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>
105 #include "qemu_socket.h"
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
111 #if defined(__OpenBSD__)
115 #if defined(CONFIG_VDE)
116 #include <libvdeplug.h>
121 #include <sys/timeb.h>
122 #include <mmsystem.h>
123 #define getopt_long_only getopt_long
124 #define memalign(align, size) malloc(size)
131 #endif /* CONFIG_SDL */
135 #define main qemu_main
136 #endif /* CONFIG_COCOA */
140 #include "exec-all.h"
142 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
145 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
147 #define SMBD_COMMAND "/usr/sbin/smbd"
150 //#define DEBUG_UNUSED_IOPORT
151 //#define DEBUG_IOPORT
154 #define DEFAULT_RAM_SIZE 144
156 #define DEFAULT_RAM_SIZE 128
159 /* Max number of USB devices that can be specified on the commandline. */
160 #define MAX_USB_CMDLINE 8
162 /* XXX: use a two level table to limit memory usage */
163 #define MAX_IOPORTS 65536
165 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
166 const char *bios_name
= NULL
;
167 void *ioport_opaque
[MAX_IOPORTS
];
168 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
169 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
170 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
171 to store the VM snapshots */
172 DriveInfo drives_table
[MAX_DRIVES
+1];
174 /* point to the block driver where the snapshots are managed */
175 BlockDriverState
*bs_snapshots
;
177 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
178 static DisplayState display_state
;
181 const char* keyboard_layout
= NULL
;
182 int64_t ticks_per_sec
;
184 int pit_min_timer_count
= 0;
186 NICInfo nd_table
[MAX_NICS
];
188 static int rtc_utc
= 1;
189 static int rtc_date_offset
= -1; /* -1 means no change */
190 int cirrus_vga_enabled
= 1;
191 int vmsvga_enabled
= 0;
193 int graphic_width
= 1024;
194 int graphic_height
= 768;
195 int graphic_depth
= 8;
197 int graphic_width
= 800;
198 int graphic_height
= 600;
199 int graphic_depth
= 15;
204 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
205 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
207 int win2k_install_hack
= 0;
210 static VLANState
*first_vlan
;
212 const char *vnc_display
;
213 #if defined(TARGET_SPARC)
215 #elif defined(TARGET_I386)
220 int acpi_enabled
= 1;
225 int graphic_rotate
= 0;
227 const char *option_rom
[MAX_OPTION_ROMS
];
229 int semihosting_enabled
= 0;
234 const char *qemu_name
;
237 unsigned int nb_prom_envs
= 0;
238 const char *prom_envs
[MAX_PROM_ENVS
];
244 } drives_opt
[MAX_DRIVES
];
246 static CPUState
*cur_cpu
;
247 static CPUState
*next_cpu
;
248 static int event_pending
= 1;
249 /* Conversion factor from emulated instructions to virtual clock ticks. */
250 static int icount_time_shift
;
251 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
252 #define MAX_ICOUNT_SHIFT 10
253 /* Compensate for varying guest execution speed. */
254 static int64_t qemu_icount_bias
;
255 QEMUTimer
*icount_rt_timer
;
256 QEMUTimer
*icount_vm_timer
;
258 uint8_t qemu_uuid
[16];
260 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
262 /***********************************************************/
263 /* x86 ISA bus support */
265 target_phys_addr_t isa_mem_base
= 0;
268 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
269 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
271 static uint32_t ioport_read(int index
, uint32_t address
)
273 static IOPortReadFunc
*default_func
[3] = {
274 default_ioport_readb
,
275 default_ioport_readw
,
278 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
280 func
= default_func
[index
];
281 return func(ioport_opaque
[address
], address
);
284 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
286 static IOPortWriteFunc
*default_func
[3] = {
287 default_ioport_writeb
,
288 default_ioport_writew
,
289 default_ioport_writel
291 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
293 func
= default_func
[index
];
294 func(ioport_opaque
[address
], address
, data
);
297 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
299 #ifdef DEBUG_UNUSED_IOPORT
300 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
305 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
307 #ifdef DEBUG_UNUSED_IOPORT
308 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
312 /* default is to make two byte accesses */
313 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
316 data
= ioport_read(0, address
);
317 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
318 data
|= ioport_read(0, address
) << 8;
322 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
324 ioport_write(0, address
, data
& 0xff);
325 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
326 ioport_write(0, address
, (data
>> 8) & 0xff);
329 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
331 #ifdef DEBUG_UNUSED_IOPORT
332 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
337 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
339 #ifdef DEBUG_UNUSED_IOPORT
340 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
344 /* size is the word size in byte */
345 int register_ioport_read(int start
, int length
, int size
,
346 IOPortReadFunc
*func
, void *opaque
)
352 } else if (size
== 2) {
354 } else if (size
== 4) {
357 hw_error("register_ioport_read: invalid size");
360 for(i
= start
; i
< start
+ length
; i
+= size
) {
361 ioport_read_table
[bsize
][i
] = func
;
362 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
363 hw_error("register_ioport_read: invalid opaque");
364 ioport_opaque
[i
] = opaque
;
369 /* size is the word size in byte */
370 int register_ioport_write(int start
, int length
, int size
,
371 IOPortWriteFunc
*func
, void *opaque
)
377 } else if (size
== 2) {
379 } else if (size
== 4) {
382 hw_error("register_ioport_write: invalid size");
385 for(i
= start
; i
< start
+ length
; i
+= size
) {
386 ioport_write_table
[bsize
][i
] = func
;
387 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
388 hw_error("register_ioport_write: invalid opaque");
389 ioport_opaque
[i
] = opaque
;
394 void isa_unassign_ioport(int start
, int length
)
398 for(i
= start
; i
< start
+ length
; i
++) {
399 ioport_read_table
[0][i
] = default_ioport_readb
;
400 ioport_read_table
[1][i
] = default_ioport_readw
;
401 ioport_read_table
[2][i
] = default_ioport_readl
;
403 ioport_write_table
[0][i
] = default_ioport_writeb
;
404 ioport_write_table
[1][i
] = default_ioport_writew
;
405 ioport_write_table
[2][i
] = default_ioport_writel
;
409 /***********************************************************/
411 void cpu_outb(CPUState
*env
, int addr
, int val
)
414 if (loglevel
& CPU_LOG_IOPORT
)
415 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
417 ioport_write(0, addr
, val
);
420 env
->last_io_time
= cpu_get_time_fast();
424 void cpu_outw(CPUState
*env
, int addr
, int val
)
427 if (loglevel
& CPU_LOG_IOPORT
)
428 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
430 ioport_write(1, addr
, val
);
433 env
->last_io_time
= cpu_get_time_fast();
437 void cpu_outl(CPUState
*env
, int addr
, int val
)
440 if (loglevel
& CPU_LOG_IOPORT
)
441 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
443 ioport_write(2, addr
, val
);
446 env
->last_io_time
= cpu_get_time_fast();
450 int cpu_inb(CPUState
*env
, int addr
)
453 val
= ioport_read(0, addr
);
455 if (loglevel
& CPU_LOG_IOPORT
)
456 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
460 env
->last_io_time
= cpu_get_time_fast();
465 int cpu_inw(CPUState
*env
, int addr
)
468 val
= ioport_read(1, addr
);
470 if (loglevel
& CPU_LOG_IOPORT
)
471 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
475 env
->last_io_time
= cpu_get_time_fast();
480 int cpu_inl(CPUState
*env
, int addr
)
483 val
= ioport_read(2, addr
);
485 if (loglevel
& CPU_LOG_IOPORT
)
486 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
490 env
->last_io_time
= cpu_get_time_fast();
495 /***********************************************************/
496 void hw_error(const char *fmt
, ...)
502 fprintf(stderr
, "qemu: hardware error: ");
503 vfprintf(stderr
, fmt
, ap
);
504 fprintf(stderr
, "\n");
505 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
506 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
508 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
510 cpu_dump_state(env
, stderr
, fprintf
, 0);
517 /***********************************************************/
520 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
521 static void *qemu_put_kbd_event_opaque
;
522 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
523 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
525 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
527 qemu_put_kbd_event_opaque
= opaque
;
528 qemu_put_kbd_event
= func
;
531 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
532 void *opaque
, int absolute
,
535 QEMUPutMouseEntry
*s
, *cursor
;
537 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
541 s
->qemu_put_mouse_event
= func
;
542 s
->qemu_put_mouse_event_opaque
= opaque
;
543 s
->qemu_put_mouse_event_absolute
= absolute
;
544 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
547 if (!qemu_put_mouse_event_head
) {
548 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
552 cursor
= qemu_put_mouse_event_head
;
553 while (cursor
->next
!= NULL
)
554 cursor
= cursor
->next
;
557 qemu_put_mouse_event_current
= s
;
562 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
564 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
566 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
569 cursor
= qemu_put_mouse_event_head
;
570 while (cursor
!= NULL
&& cursor
!= entry
) {
572 cursor
= cursor
->next
;
575 if (cursor
== NULL
) // does not exist or list empty
577 else if (prev
== NULL
) { // entry is head
578 qemu_put_mouse_event_head
= cursor
->next
;
579 if (qemu_put_mouse_event_current
== entry
)
580 qemu_put_mouse_event_current
= cursor
->next
;
581 qemu_free(entry
->qemu_put_mouse_event_name
);
586 prev
->next
= entry
->next
;
588 if (qemu_put_mouse_event_current
== entry
)
589 qemu_put_mouse_event_current
= prev
;
591 qemu_free(entry
->qemu_put_mouse_event_name
);
595 void kbd_put_keycode(int keycode
)
597 if (qemu_put_kbd_event
) {
598 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
602 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
604 QEMUPutMouseEvent
*mouse_event
;
605 void *mouse_event_opaque
;
608 if (!qemu_put_mouse_event_current
) {
613 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
615 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
618 if (graphic_rotate
) {
619 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
622 width
= graphic_width
- 1;
623 mouse_event(mouse_event_opaque
,
624 width
- dy
, dx
, dz
, buttons_state
);
626 mouse_event(mouse_event_opaque
,
627 dx
, dy
, dz
, buttons_state
);
631 int kbd_mouse_is_absolute(void)
633 if (!qemu_put_mouse_event_current
)
636 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
639 void do_info_mice(void)
641 QEMUPutMouseEntry
*cursor
;
644 if (!qemu_put_mouse_event_head
) {
645 term_printf("No mouse devices connected\n");
649 term_printf("Mouse devices available:\n");
650 cursor
= qemu_put_mouse_event_head
;
651 while (cursor
!= NULL
) {
652 term_printf("%c Mouse #%d: %s\n",
653 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
654 index
, cursor
->qemu_put_mouse_event_name
);
656 cursor
= cursor
->next
;
660 void do_mouse_set(int index
)
662 QEMUPutMouseEntry
*cursor
;
665 if (!qemu_put_mouse_event_head
) {
666 term_printf("No mouse devices connected\n");
670 cursor
= qemu_put_mouse_event_head
;
671 while (cursor
!= NULL
&& index
!= i
) {
673 cursor
= cursor
->next
;
677 qemu_put_mouse_event_current
= cursor
;
679 term_printf("Mouse at given index not found\n");
682 /* compute with 96 bit intermediate result: (a*b)/c */
683 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
688 #ifdef WORDS_BIGENDIAN
698 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
699 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
702 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
706 /***********************************************************/
707 /* real time host monotonic timer */
709 #define QEMU_TIMER_BASE 1000000000LL
713 static int64_t clock_freq
;
715 static void init_get_clock(void)
719 ret
= QueryPerformanceFrequency(&freq
);
721 fprintf(stderr
, "Could not calibrate ticks\n");
724 clock_freq
= freq
.QuadPart
;
727 static int64_t get_clock(void)
730 QueryPerformanceCounter(&ti
);
731 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
736 static int use_rt_clock
;
738 static void init_get_clock(void)
741 #if defined(__linux__)
744 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
751 static int64_t get_clock(void)
753 #if defined(__linux__)
756 clock_gettime(CLOCK_MONOTONIC
, &ts
);
757 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
761 /* XXX: using gettimeofday leads to problems if the date
762 changes, so it should be avoided. */
764 gettimeofday(&tv
, NULL
);
765 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
770 /* Return the virtual CPU time, based on the instruction counter. */
771 static int64_t cpu_get_icount(void)
774 CPUState
*env
= cpu_single_env
;;
775 icount
= qemu_icount
;
778 fprintf(stderr
, "Bad clock read\n");
779 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
781 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
784 /***********************************************************/
785 /* guest cycle counter */
787 static int64_t cpu_ticks_prev
;
788 static int64_t cpu_ticks_offset
;
789 static int64_t cpu_clock_offset
;
790 static int cpu_ticks_enabled
;
792 /* return the host CPU cycle counter and handle stop/restart */
793 int64_t cpu_get_ticks(void)
796 return cpu_get_icount();
798 if (!cpu_ticks_enabled
) {
799 return cpu_ticks_offset
;
802 ticks
= cpu_get_real_ticks();
803 if (cpu_ticks_prev
> ticks
) {
804 /* Note: non increasing ticks may happen if the host uses
806 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
808 cpu_ticks_prev
= ticks
;
809 return ticks
+ cpu_ticks_offset
;
813 /* return the host CPU monotonic timer and handle stop/restart */
814 static int64_t cpu_get_clock(void)
817 if (!cpu_ticks_enabled
) {
818 return cpu_clock_offset
;
821 return ti
+ cpu_clock_offset
;
825 /* enable cpu_get_ticks() */
826 void cpu_enable_ticks(void)
828 if (!cpu_ticks_enabled
) {
829 cpu_ticks_offset
-= cpu_get_real_ticks();
830 cpu_clock_offset
-= get_clock();
831 cpu_ticks_enabled
= 1;
835 /* disable cpu_get_ticks() : the clock is stopped. You must not call
836 cpu_get_ticks() after that. */
837 void cpu_disable_ticks(void)
839 if (cpu_ticks_enabled
) {
840 cpu_ticks_offset
= cpu_get_ticks();
841 cpu_clock_offset
= cpu_get_clock();
842 cpu_ticks_enabled
= 0;
846 /***********************************************************/
849 #define QEMU_TIMER_REALTIME 0
850 #define QEMU_TIMER_VIRTUAL 1
854 /* XXX: add frequency */
862 struct QEMUTimer
*next
;
865 struct qemu_alarm_timer
{
869 int (*start
)(struct qemu_alarm_timer
*t
);
870 void (*stop
)(struct qemu_alarm_timer
*t
);
871 void (*rearm
)(struct qemu_alarm_timer
*t
);
875 #define ALARM_FLAG_DYNTICKS 0x1
876 #define ALARM_FLAG_EXPIRED 0x2
878 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
880 return t
->flags
& ALARM_FLAG_DYNTICKS
;
883 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
885 if (!alarm_has_dynticks(t
))
891 /* TODO: MIN_TIMER_REARM_US should be optimized */
892 #define MIN_TIMER_REARM_US 250
894 static struct qemu_alarm_timer
*alarm_timer
;
898 struct qemu_alarm_win32
{
902 } alarm_win32_data
= {0, NULL
, -1};
904 static int win32_start_timer(struct qemu_alarm_timer
*t
);
905 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
906 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
910 static int unix_start_timer(struct qemu_alarm_timer
*t
);
911 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
915 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
916 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
917 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
919 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
920 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
922 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
923 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
925 #endif /* __linux__ */
929 /* Correlation between real and virtual time is always going to be
930 fairly approximate, so ignore small variation.
931 When the guest is idle real and virtual time will be aligned in
933 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
935 static void icount_adjust(void)
940 static int64_t last_delta
;
941 /* If the VM is not running, then do nothing. */
945 cur_time
= cpu_get_clock();
946 cur_icount
= qemu_get_clock(vm_clock
);
947 delta
= cur_icount
- cur_time
;
948 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
950 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
951 && icount_time_shift
> 0) {
952 /* The guest is getting too far ahead. Slow time down. */
956 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
957 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
958 /* The guest is getting too far behind. Speed time up. */
962 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
965 static void icount_adjust_rt(void * opaque
)
967 qemu_mod_timer(icount_rt_timer
,
968 qemu_get_clock(rt_clock
) + 1000);
972 static void icount_adjust_vm(void * opaque
)
974 qemu_mod_timer(icount_vm_timer
,
975 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
979 static void init_icount_adjust(void)
981 /* Have both realtime and virtual time triggers for speed adjustment.
982 The realtime trigger catches emulated time passing too slowly,
983 the virtual time trigger catches emulated time passing too fast.
984 Realtime triggers occur even when idle, so use them less frequently
986 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
987 qemu_mod_timer(icount_rt_timer
,
988 qemu_get_clock(rt_clock
) + 1000);
989 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
990 qemu_mod_timer(icount_vm_timer
,
991 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
994 static struct qemu_alarm_timer alarm_timers
[] = {
997 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
998 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
999 /* HPET - if available - is preferred */
1000 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1001 /* ...otherwise try RTC */
1002 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1004 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1006 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1007 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1008 {"win32", 0, win32_start_timer
,
1009 win32_stop_timer
, NULL
, &alarm_win32_data
},
1014 static void show_available_alarms(void)
1018 printf("Available alarm timers, in order of precedence:\n");
1019 for (i
= 0; alarm_timers
[i
].name
; i
++)
1020 printf("%s\n", alarm_timers
[i
].name
);
1023 static void configure_alarms(char const *opt
)
1027 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1030 struct qemu_alarm_timer tmp
;
1032 if (!strcmp(opt
, "?")) {
1033 show_available_alarms();
1039 /* Reorder the array */
1040 name
= strtok(arg
, ",");
1042 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1043 if (!strcmp(alarm_timers
[i
].name
, name
))
1048 fprintf(stderr
, "Unknown clock %s\n", name
);
1057 tmp
= alarm_timers
[i
];
1058 alarm_timers
[i
] = alarm_timers
[cur
];
1059 alarm_timers
[cur
] = tmp
;
1063 name
= strtok(NULL
, ",");
1069 /* Disable remaining timers */
1070 for (i
= cur
; i
< count
; i
++)
1071 alarm_timers
[i
].name
= NULL
;
1073 show_available_alarms();
1078 QEMUClock
*rt_clock
;
1079 QEMUClock
*vm_clock
;
1081 static QEMUTimer
*active_timers
[2];
1083 static QEMUClock
*qemu_new_clock(int type
)
1086 clock
= qemu_mallocz(sizeof(QEMUClock
));
1093 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1097 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1100 ts
->opaque
= opaque
;
1104 void qemu_free_timer(QEMUTimer
*ts
)
1109 /* stop a timer, but do not dealloc it */
1110 void qemu_del_timer(QEMUTimer
*ts
)
1114 /* NOTE: this code must be signal safe because
1115 qemu_timer_expired() can be called from a signal. */
1116 pt
= &active_timers
[ts
->clock
->type
];
1129 /* modify the current timer so that it will be fired when current_time
1130 >= expire_time. The corresponding callback will be called. */
1131 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1137 /* add the timer in the sorted list */
1138 /* NOTE: this code must be signal safe because
1139 qemu_timer_expired() can be called from a signal. */
1140 pt
= &active_timers
[ts
->clock
->type
];
1145 if (t
->expire_time
> expire_time
)
1149 ts
->expire_time
= expire_time
;
1153 /* Rearm if necessary */
1154 if (pt
== &active_timers
[ts
->clock
->type
]) {
1155 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1156 qemu_rearm_alarm_timer(alarm_timer
);
1158 /* Interrupt execution to force deadline recalculation. */
1159 if (use_icount
&& cpu_single_env
) {
1160 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1165 int qemu_timer_pending(QEMUTimer
*ts
)
1168 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1175 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1179 return (timer_head
->expire_time
<= current_time
);
1182 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1188 if (!ts
|| ts
->expire_time
> current_time
)
1190 /* remove timer from the list before calling the callback */
1191 *ptimer_head
= ts
->next
;
1194 /* run the callback (the timer list can be modified) */
1199 int64_t qemu_get_clock(QEMUClock
*clock
)
1201 switch(clock
->type
) {
1202 case QEMU_TIMER_REALTIME
:
1203 return get_clock() / 1000000;
1205 case QEMU_TIMER_VIRTUAL
:
1207 return cpu_get_icount();
1209 return cpu_get_clock();
1214 static void init_timers(void)
1217 ticks_per_sec
= QEMU_TIMER_BASE
;
1218 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1219 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1223 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1225 uint64_t expire_time
;
1227 if (qemu_timer_pending(ts
)) {
1228 expire_time
= ts
->expire_time
;
1232 qemu_put_be64(f
, expire_time
);
1235 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1237 uint64_t expire_time
;
1239 expire_time
= qemu_get_be64(f
);
1240 if (expire_time
!= -1) {
1241 qemu_mod_timer(ts
, expire_time
);
1247 static void timer_save(QEMUFile
*f
, void *opaque
)
1249 if (cpu_ticks_enabled
) {
1250 hw_error("cannot save state if virtual timers are running");
1252 qemu_put_be64(f
, cpu_ticks_offset
);
1253 qemu_put_be64(f
, ticks_per_sec
);
1254 qemu_put_be64(f
, cpu_clock_offset
);
1257 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1259 if (version_id
!= 1 && version_id
!= 2)
1261 if (cpu_ticks_enabled
) {
1264 cpu_ticks_offset
=qemu_get_be64(f
);
1265 ticks_per_sec
=qemu_get_be64(f
);
1266 if (version_id
== 2) {
1267 cpu_clock_offset
=qemu_get_be64(f
);
1273 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1274 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1276 static void host_alarm_handler(int host_signum
)
1280 #define DISP_FREQ 1000
1282 static int64_t delta_min
= INT64_MAX
;
1283 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1285 ti
= qemu_get_clock(vm_clock
);
1286 if (last_clock
!= 0) {
1287 delta
= ti
- last_clock
;
1288 if (delta
< delta_min
)
1290 if (delta
> delta_max
)
1293 if (++count
== DISP_FREQ
) {
1294 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1295 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1296 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1297 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1298 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1300 delta_min
= INT64_MAX
;
1308 if (alarm_has_dynticks(alarm_timer
) ||
1310 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1311 qemu_get_clock(vm_clock
))) ||
1312 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1313 qemu_get_clock(rt_clock
))) {
1315 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1316 SetEvent(data
->host_alarm
);
1318 CPUState
*env
= next_cpu
;
1320 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1323 /* stop the currently executing cpu because a timer occured */
1324 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1326 if (env
->kqemu_enabled
) {
1327 kqemu_cpu_interrupt(env
);
1335 static int64_t qemu_next_deadline(void)
1339 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1340 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1341 qemu_get_clock(vm_clock
);
1343 /* To avoid problems with overflow limit this to 2^32. */
1353 #if defined(__linux__) || defined(_WIN32)
1354 static uint64_t qemu_next_deadline_dyntick(void)
1362 delta
= (qemu_next_deadline() + 999) / 1000;
1364 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1365 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1366 qemu_get_clock(rt_clock
))*1000;
1367 if (rtdelta
< delta
)
1371 if (delta
< MIN_TIMER_REARM_US
)
1372 delta
= MIN_TIMER_REARM_US
;
1380 #if defined(__linux__)
1382 #define RTC_FREQ 1024
1384 static void enable_sigio_timer(int fd
)
1386 struct sigaction act
;
1389 sigfillset(&act
.sa_mask
);
1391 act
.sa_handler
= host_alarm_handler
;
1393 sigaction(SIGIO
, &act
, NULL
);
1394 fcntl(fd
, F_SETFL
, O_ASYNC
);
1395 fcntl(fd
, F_SETOWN
, getpid());
1398 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1400 struct hpet_info info
;
1403 fd
= open("/dev/hpet", O_RDONLY
);
1408 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1410 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1411 "error, but for better emulation accuracy type:\n"
1412 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1416 /* Check capabilities */
1417 r
= ioctl(fd
, HPET_INFO
, &info
);
1421 /* Enable periodic mode */
1422 r
= ioctl(fd
, HPET_EPI
, 0);
1423 if (info
.hi_flags
&& (r
< 0))
1426 /* Enable interrupt */
1427 r
= ioctl(fd
, HPET_IE_ON
, 0);
1431 enable_sigio_timer(fd
);
1432 t
->priv
= (void *)(long)fd
;
1440 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1442 int fd
= (long)t
->priv
;
1447 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1450 unsigned long current_rtc_freq
= 0;
1452 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1455 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1456 if (current_rtc_freq
!= RTC_FREQ
&&
1457 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1458 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1459 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1460 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1463 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1469 enable_sigio_timer(rtc_fd
);
1471 t
->priv
= (void *)(long)rtc_fd
;
1476 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1478 int rtc_fd
= (long)t
->priv
;
1483 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1487 struct sigaction act
;
1489 sigfillset(&act
.sa_mask
);
1491 act
.sa_handler
= host_alarm_handler
;
1493 sigaction(SIGALRM
, &act
, NULL
);
1495 ev
.sigev_value
.sival_int
= 0;
1496 ev
.sigev_notify
= SIGEV_SIGNAL
;
1497 ev
.sigev_signo
= SIGALRM
;
1499 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1500 perror("timer_create");
1502 /* disable dynticks */
1503 fprintf(stderr
, "Dynamic Ticks disabled\n");
1508 t
->priv
= (void *)host_timer
;
1513 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1515 timer_t host_timer
= (timer_t
)t
->priv
;
1517 timer_delete(host_timer
);
1520 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1522 timer_t host_timer
= (timer_t
)t
->priv
;
1523 struct itimerspec timeout
;
1524 int64_t nearest_delta_us
= INT64_MAX
;
1527 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1528 !active_timers
[QEMU_TIMER_VIRTUAL
])
1531 nearest_delta_us
= qemu_next_deadline_dyntick();
1533 /* check whether a timer is already running */
1534 if (timer_gettime(host_timer
, &timeout
)) {
1536 fprintf(stderr
, "Internal timer error: aborting\n");
1539 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1540 if (current_us
&& current_us
<= nearest_delta_us
)
1543 timeout
.it_interval
.tv_sec
= 0;
1544 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1545 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1546 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1547 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1549 fprintf(stderr
, "Internal timer error: aborting\n");
1554 #endif /* defined(__linux__) */
1556 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1558 struct sigaction act
;
1559 struct itimerval itv
;
1563 sigfillset(&act
.sa_mask
);
1565 act
.sa_handler
= host_alarm_handler
;
1567 sigaction(SIGALRM
, &act
, NULL
);
1569 itv
.it_interval
.tv_sec
= 0;
1570 /* for i386 kernel 2.6 to get 1 ms */
1571 itv
.it_interval
.tv_usec
= 999;
1572 itv
.it_value
.tv_sec
= 0;
1573 itv
.it_value
.tv_usec
= 10 * 1000;
1575 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1582 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1584 struct itimerval itv
;
1586 memset(&itv
, 0, sizeof(itv
));
1587 setitimer(ITIMER_REAL
, &itv
, NULL
);
1590 #endif /* !defined(_WIN32) */
1594 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1597 struct qemu_alarm_win32
*data
= t
->priv
;
1600 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1601 if (!data
->host_alarm
) {
1602 perror("Failed CreateEvent");
1606 memset(&tc
, 0, sizeof(tc
));
1607 timeGetDevCaps(&tc
, sizeof(tc
));
1609 if (data
->period
< tc
.wPeriodMin
)
1610 data
->period
= tc
.wPeriodMin
;
1612 timeBeginPeriod(data
->period
);
1614 flags
= TIME_CALLBACK_FUNCTION
;
1615 if (alarm_has_dynticks(t
))
1616 flags
|= TIME_ONESHOT
;
1618 flags
|= TIME_PERIODIC
;
1620 data
->timerId
= timeSetEvent(1, // interval (ms)
1621 data
->period
, // resolution
1622 host_alarm_handler
, // function
1623 (DWORD
)t
, // parameter
1626 if (!data
->timerId
) {
1627 perror("Failed to initialize win32 alarm timer");
1629 timeEndPeriod(data
->period
);
1630 CloseHandle(data
->host_alarm
);
1634 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1639 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1641 struct qemu_alarm_win32
*data
= t
->priv
;
1643 timeKillEvent(data
->timerId
);
1644 timeEndPeriod(data
->period
);
1646 CloseHandle(data
->host_alarm
);
1649 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1651 struct qemu_alarm_win32
*data
= t
->priv
;
1652 uint64_t nearest_delta_us
;
1654 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1655 !active_timers
[QEMU_TIMER_VIRTUAL
])
1658 nearest_delta_us
= qemu_next_deadline_dyntick();
1659 nearest_delta_us
/= 1000;
1661 timeKillEvent(data
->timerId
);
1663 data
->timerId
= timeSetEvent(1,
1667 TIME_ONESHOT
| TIME_PERIODIC
);
1669 if (!data
->timerId
) {
1670 perror("Failed to re-arm win32 alarm timer");
1672 timeEndPeriod(data
->period
);
1673 CloseHandle(data
->host_alarm
);
1680 static void init_timer_alarm(void)
1682 struct qemu_alarm_timer
*t
;
1685 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1686 t
= &alarm_timers
[i
];
1694 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1695 fprintf(stderr
, "Terminating\n");
1702 static void quit_timers(void)
1704 alarm_timer
->stop(alarm_timer
);
1708 /***********************************************************/
1709 /* host time/date access */
1710 void qemu_get_timedate(struct tm
*tm
, int offset
)
1717 if (rtc_date_offset
== -1) {
1721 ret
= localtime(&ti
);
1723 ti
-= rtc_date_offset
;
1727 memcpy(tm
, ret
, sizeof(struct tm
));
1730 int qemu_timedate_diff(struct tm
*tm
)
1734 if (rtc_date_offset
== -1)
1736 seconds
= mktimegm(tm
);
1738 seconds
= mktime(tm
);
1740 seconds
= mktimegm(tm
) + rtc_date_offset
;
1742 return seconds
- time(NULL
);
1745 /***********************************************************/
1746 /* character device */
1748 static void qemu_chr_event(CharDriverState
*s
, int event
)
1752 s
->chr_event(s
->handler_opaque
, event
);
1755 static void qemu_chr_reset_bh(void *opaque
)
1757 CharDriverState
*s
= opaque
;
1758 qemu_chr_event(s
, CHR_EVENT_RESET
);
1759 qemu_bh_delete(s
->bh
);
1763 void qemu_chr_reset(CharDriverState
*s
)
1765 if (s
->bh
== NULL
) {
1766 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1767 qemu_bh_schedule(s
->bh
);
1771 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1773 return s
->chr_write(s
, buf
, len
);
1776 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1780 return s
->chr_ioctl(s
, cmd
, arg
);
1783 int qemu_chr_can_read(CharDriverState
*s
)
1785 if (!s
->chr_can_read
)
1787 return s
->chr_can_read(s
->handler_opaque
);
1790 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1792 s
->chr_read(s
->handler_opaque
, buf
, len
);
1795 void qemu_chr_accept_input(CharDriverState
*s
)
1797 if (s
->chr_accept_input
)
1798 s
->chr_accept_input(s
);
1801 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1806 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1807 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1811 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1813 if (s
->chr_send_event
)
1814 s
->chr_send_event(s
, event
);
1817 void qemu_chr_add_handlers(CharDriverState
*s
,
1818 IOCanRWHandler
*fd_can_read
,
1819 IOReadHandler
*fd_read
,
1820 IOEventHandler
*fd_event
,
1823 s
->chr_can_read
= fd_can_read
;
1824 s
->chr_read
= fd_read
;
1825 s
->chr_event
= fd_event
;
1826 s
->handler_opaque
= opaque
;
1827 if (s
->chr_update_read_handler
)
1828 s
->chr_update_read_handler(s
);
1831 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1836 static CharDriverState
*qemu_chr_open_null(void)
1838 CharDriverState
*chr
;
1840 chr
= qemu_mallocz(sizeof(CharDriverState
));
1843 chr
->chr_write
= null_chr_write
;
1847 /* MUX driver for serial I/O splitting */
1848 static int term_timestamps
;
1849 static int64_t term_timestamps_start
;
1851 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1852 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1854 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1855 IOReadHandler
*chr_read
[MAX_MUX
];
1856 IOEventHandler
*chr_event
[MAX_MUX
];
1857 void *ext_opaque
[MAX_MUX
];
1858 CharDriverState
*drv
;
1859 unsigned char buffer
[MUX_BUFFER_SIZE
];
1863 int term_got_escape
;
1868 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1870 MuxDriver
*d
= chr
->opaque
;
1872 if (!term_timestamps
) {
1873 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1878 for(i
= 0; i
< len
; i
++) {
1879 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1880 if (buf
[i
] == '\n') {
1886 if (term_timestamps_start
== -1)
1887 term_timestamps_start
= ti
;
1888 ti
-= term_timestamps_start
;
1889 secs
= ti
/ 1000000000;
1890 snprintf(buf1
, sizeof(buf1
),
1891 "[%02d:%02d:%02d.%03d] ",
1895 (int)((ti
/ 1000000) % 1000));
1896 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1903 static const char * const mux_help
[] = {
1904 "% h print this help\n\r",
1905 "% x exit emulator\n\r",
1906 "% s save disk data back to file (if -snapshot)\n\r",
1907 "% t toggle console timestamps\n\r"
1908 "% b send break (magic sysrq)\n\r",
1909 "% c switch between console and monitor\n\r",
1914 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1915 static void mux_print_help(CharDriverState
*chr
)
1918 char ebuf
[15] = "Escape-Char";
1919 char cbuf
[50] = "\n\r";
1921 if (term_escape_char
> 0 && term_escape_char
< 26) {
1922 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1923 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1925 snprintf(cbuf
, sizeof(cbuf
),
1926 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1929 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1930 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1931 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1932 if (mux_help
[i
][j
] == '%')
1933 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1935 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1940 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1942 if (d
->term_got_escape
) {
1943 d
->term_got_escape
= 0;
1944 if (ch
== term_escape_char
)
1949 mux_print_help(chr
);
1953 const char *term
= "QEMU: Terminated\n\r";
1954 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1961 for (i
= 0; i
< nb_drives
; i
++) {
1962 bdrv_commit(drives_table
[i
].bdrv
);
1967 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1970 /* Switch to the next registered device */
1972 if (chr
->focus
>= d
->mux_cnt
)
1976 term_timestamps
= !term_timestamps
;
1977 term_timestamps_start
= -1;
1980 } else if (ch
== term_escape_char
) {
1981 d
->term_got_escape
= 1;
1989 static void mux_chr_accept_input(CharDriverState
*chr
)
1992 MuxDriver
*d
= chr
->opaque
;
1994 while (d
->prod
!= d
->cons
&&
1995 d
->chr_can_read
[m
] &&
1996 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1997 d
->chr_read
[m
](d
->ext_opaque
[m
],
1998 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2002 static int mux_chr_can_read(void *opaque
)
2004 CharDriverState
*chr
= opaque
;
2005 MuxDriver
*d
= chr
->opaque
;
2007 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2009 if (d
->chr_can_read
[chr
->focus
])
2010 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2014 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2016 CharDriverState
*chr
= opaque
;
2017 MuxDriver
*d
= chr
->opaque
;
2021 mux_chr_accept_input (opaque
);
2023 for(i
= 0; i
< size
; i
++)
2024 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2025 if (d
->prod
== d
->cons
&&
2026 d
->chr_can_read
[m
] &&
2027 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2028 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2030 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2034 static void mux_chr_event(void *opaque
, int event
)
2036 CharDriverState
*chr
= opaque
;
2037 MuxDriver
*d
= chr
->opaque
;
2040 /* Send the event to all registered listeners */
2041 for (i
= 0; i
< d
->mux_cnt
; i
++)
2042 if (d
->chr_event
[i
])
2043 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2046 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2048 MuxDriver
*d
= chr
->opaque
;
2050 if (d
->mux_cnt
>= MAX_MUX
) {
2051 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2054 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2055 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2056 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2057 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2058 /* Fix up the real driver with mux routines */
2059 if (d
->mux_cnt
== 0) {
2060 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2061 mux_chr_event
, chr
);
2063 chr
->focus
= d
->mux_cnt
;
2067 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2069 CharDriverState
*chr
;
2072 chr
= qemu_mallocz(sizeof(CharDriverState
));
2075 d
= qemu_mallocz(sizeof(MuxDriver
));
2084 chr
->chr_write
= mux_chr_write
;
2085 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2086 chr
->chr_accept_input
= mux_chr_accept_input
;
2093 static void socket_cleanup(void)
2098 static int socket_init(void)
2103 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2105 err
= WSAGetLastError();
2106 fprintf(stderr
, "WSAStartup: %d\n", err
);
2109 atexit(socket_cleanup
);
2113 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2119 ret
= send(fd
, buf
, len
, 0);
2122 errno
= WSAGetLastError();
2123 if (errno
!= WSAEWOULDBLOCK
) {
2126 } else if (ret
== 0) {
2138 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2144 ret
= write(fd
, buf
, len
);
2146 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2148 } else if (ret
== 0) {
2158 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2160 return unix_write(fd
, buf
, len1
);
2162 #endif /* !_WIN32 */
2171 #define STDIO_MAX_CLIENTS 1
2172 static int stdio_nb_clients
= 0;
2174 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2176 FDCharDriver
*s
= chr
->opaque
;
2177 return unix_write(s
->fd_out
, buf
, len
);
2180 static int fd_chr_read_poll(void *opaque
)
2182 CharDriverState
*chr
= opaque
;
2183 FDCharDriver
*s
= chr
->opaque
;
2185 s
->max_size
= qemu_chr_can_read(chr
);
2189 static void fd_chr_read(void *opaque
)
2191 CharDriverState
*chr
= opaque
;
2192 FDCharDriver
*s
= chr
->opaque
;
2197 if (len
> s
->max_size
)
2201 size
= read(s
->fd_in
, buf
, len
);
2203 /* FD has been closed. Remove it from the active list. */
2204 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2208 qemu_chr_read(chr
, buf
, size
);
2212 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2214 FDCharDriver
*s
= chr
->opaque
;
2216 if (s
->fd_in
>= 0) {
2217 if (nographic
&& s
->fd_in
== 0) {
2219 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2220 fd_chr_read
, NULL
, chr
);
2225 static void fd_chr_close(struct CharDriverState
*chr
)
2227 FDCharDriver
*s
= chr
->opaque
;
2229 if (s
->fd_in
>= 0) {
2230 if (nographic
&& s
->fd_in
== 0) {
2232 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2239 /* open a character device to a unix fd */
2240 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2242 CharDriverState
*chr
;
2245 chr
= qemu_mallocz(sizeof(CharDriverState
));
2248 s
= qemu_mallocz(sizeof(FDCharDriver
));
2256 chr
->chr_write
= fd_chr_write
;
2257 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2258 chr
->chr_close
= fd_chr_close
;
2260 qemu_chr_reset(chr
);
2265 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2269 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2272 return qemu_chr_open_fd(-1, fd_out
);
2275 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2278 char filename_in
[256], filename_out
[256];
2280 snprintf(filename_in
, 256, "%s.in", filename
);
2281 snprintf(filename_out
, 256, "%s.out", filename
);
2282 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2283 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2284 if (fd_in
< 0 || fd_out
< 0) {
2289 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2293 return qemu_chr_open_fd(fd_in
, fd_out
);
2297 /* for STDIO, we handle the case where several clients use it
2300 #define TERM_FIFO_MAX_SIZE 1
2302 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2303 static int term_fifo_size
;
2305 static int stdio_read_poll(void *opaque
)
2307 CharDriverState
*chr
= opaque
;
2309 /* try to flush the queue if needed */
2310 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2311 qemu_chr_read(chr
, term_fifo
, 1);
2314 /* see if we can absorb more chars */
2315 if (term_fifo_size
== 0)
2321 static void stdio_read(void *opaque
)
2325 CharDriverState
*chr
= opaque
;
2327 size
= read(0, buf
, 1);
2329 /* stdin has been closed. Remove it from the active list. */
2330 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2334 if (qemu_chr_can_read(chr
) > 0) {
2335 qemu_chr_read(chr
, buf
, 1);
2336 } else if (term_fifo_size
== 0) {
2337 term_fifo
[term_fifo_size
++] = buf
[0];
2342 /* init terminal so that we can grab keys */
2343 static struct termios oldtty
;
2344 static int old_fd0_flags
;
2345 static int term_atexit_done
;
2347 static void term_exit(void)
2349 tcsetattr (0, TCSANOW
, &oldtty
);
2350 fcntl(0, F_SETFL
, old_fd0_flags
);
2353 static void term_init(void)
2357 tcgetattr (0, &tty
);
2359 old_fd0_flags
= fcntl(0, F_GETFL
);
2361 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2362 |INLCR
|IGNCR
|ICRNL
|IXON
);
2363 tty
.c_oflag
|= OPOST
;
2364 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2365 /* if graphical mode, we allow Ctrl-C handling */
2367 tty
.c_lflag
&= ~ISIG
;
2368 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2371 tty
.c_cc
[VTIME
] = 0;
2373 tcsetattr (0, TCSANOW
, &tty
);
2375 if (!term_atexit_done
++)
2378 fcntl(0, F_SETFL
, O_NONBLOCK
);
2381 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2385 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2389 static CharDriverState
*qemu_chr_open_stdio(void)
2391 CharDriverState
*chr
;
2393 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2395 chr
= qemu_chr_open_fd(0, 1);
2396 chr
->chr_close
= qemu_chr_close_stdio
;
2397 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2405 /* Once Solaris has openpty(), this is going to be removed. */
2406 int openpty(int *amaster
, int *aslave
, char *name
,
2407 struct termios
*termp
, struct winsize
*winp
)
2410 int mfd
= -1, sfd
= -1;
2412 *amaster
= *aslave
= -1;
2414 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2418 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2421 if ((slave
= ptsname(mfd
)) == NULL
)
2424 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2427 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2428 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2436 ioctl(sfd
, TIOCSWINSZ
, winp
);
2447 void cfmakeraw (struct termios
*termios_p
)
2449 termios_p
->c_iflag
&=
2450 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2451 termios_p
->c_oflag
&= ~OPOST
;
2452 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2453 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2454 termios_p
->c_cflag
|= CS8
;
2456 termios_p
->c_cc
[VMIN
] = 0;
2457 termios_p
->c_cc
[VTIME
] = 0;
2461 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2462 || defined(__NetBSD__) || defined(__OpenBSD__)
2472 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2473 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2475 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2477 PtyCharDriver
*s
= chr
->opaque
;
2479 if (!s
->connected
) {
2480 /* guest sends data, check for (re-)connect */
2481 pty_chr_update_read_handler(chr
);
2484 return unix_write(s
->fd
, buf
, len
);
2487 static int pty_chr_read_poll(void *opaque
)
2489 CharDriverState
*chr
= opaque
;
2490 PtyCharDriver
*s
= chr
->opaque
;
2492 s
->read_bytes
= qemu_chr_can_read(chr
);
2493 return s
->read_bytes
;
2496 static void pty_chr_read(void *opaque
)
2498 CharDriverState
*chr
= opaque
;
2499 PtyCharDriver
*s
= chr
->opaque
;
2504 if (len
> s
->read_bytes
)
2505 len
= s
->read_bytes
;
2508 size
= read(s
->fd
, buf
, len
);
2509 if ((size
== -1 && errno
== EIO
) ||
2511 pty_chr_state(chr
, 0);
2515 pty_chr_state(chr
, 1);
2516 qemu_chr_read(chr
, buf
, size
);
2520 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2522 PtyCharDriver
*s
= chr
->opaque
;
2524 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2525 pty_chr_read
, NULL
, chr
);
2528 * Short timeout here: just need wait long enougth that qemu makes
2529 * it through the poll loop once. When reconnected we want a
2530 * short timeout so we notice it almost instantly. Otherwise
2531 * read() gives us -EIO instantly, making pty_chr_state() reset the
2532 * timeout to the normal (much longer) poll interval before the
2535 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2538 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2540 PtyCharDriver
*s
= chr
->opaque
;
2543 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2546 /* (re-)connect poll interval for idle guests: once per second.
2547 * We check more frequently in case the guests sends data to
2548 * the virtual device linked to our pty. */
2549 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2552 qemu_chr_reset(chr
);
2557 static void pty_chr_timer(void *opaque
)
2559 struct CharDriverState
*chr
= opaque
;
2560 PtyCharDriver
*s
= chr
->opaque
;
2565 /* If we arrive here without polling being cleared due
2566 * read returning -EIO, then we are (re-)connected */
2567 pty_chr_state(chr
, 1);
2572 pty_chr_update_read_handler(chr
);
2575 static void pty_chr_close(struct CharDriverState
*chr
)
2577 PtyCharDriver
*s
= chr
->opaque
;
2579 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2584 static CharDriverState
*qemu_chr_open_pty(void)
2586 CharDriverState
*chr
;
2590 #if defined(__OpenBSD__)
2591 char pty_name
[PATH_MAX
];
2592 #define q_ptsname(x) pty_name
2594 char *pty_name
= NULL
;
2595 #define q_ptsname(x) ptsname(x)
2598 chr
= qemu_mallocz(sizeof(CharDriverState
));
2601 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2607 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2611 /* Set raw attributes on the pty. */
2613 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2616 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2619 chr
->chr_write
= pty_chr_write
;
2620 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2621 chr
->chr_close
= pty_chr_close
;
2623 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2628 static void tty_serial_init(int fd
, int speed
,
2629 int parity
, int data_bits
, int stop_bits
)
2635 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2636 speed
, parity
, data_bits
, stop_bits
);
2638 tcgetattr (fd
, &tty
);
2641 if (speed
<= 50 * MARGIN
)
2643 else if (speed
<= 75 * MARGIN
)
2645 else if (speed
<= 300 * MARGIN
)
2647 else if (speed
<= 600 * MARGIN
)
2649 else if (speed
<= 1200 * MARGIN
)
2651 else if (speed
<= 2400 * MARGIN
)
2653 else if (speed
<= 4800 * MARGIN
)
2655 else if (speed
<= 9600 * MARGIN
)
2657 else if (speed
<= 19200 * MARGIN
)
2659 else if (speed
<= 38400 * MARGIN
)
2661 else if (speed
<= 57600 * MARGIN
)
2663 else if (speed
<= 115200 * MARGIN
)
2668 cfsetispeed(&tty
, spd
);
2669 cfsetospeed(&tty
, spd
);
2671 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2672 |INLCR
|IGNCR
|ICRNL
|IXON
);
2673 tty
.c_oflag
|= OPOST
;
2674 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2675 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2696 tty
.c_cflag
|= PARENB
;
2699 tty
.c_cflag
|= PARENB
| PARODD
;
2703 tty
.c_cflag
|= CSTOPB
;
2705 tcsetattr (fd
, TCSANOW
, &tty
);
2708 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2710 FDCharDriver
*s
= chr
->opaque
;
2713 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2715 QEMUSerialSetParams
*ssp
= arg
;
2716 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2717 ssp
->data_bits
, ssp
->stop_bits
);
2720 case CHR_IOCTL_SERIAL_SET_BREAK
:
2722 int enable
= *(int *)arg
;
2724 tcsendbreak(s
->fd_in
, 1);
2727 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2730 int *targ
= (int *)arg
;
2731 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2733 if (sarg
| TIOCM_CTS
)
2734 *targ
|= CHR_TIOCM_CTS
;
2735 if (sarg
| TIOCM_CAR
)
2736 *targ
|= CHR_TIOCM_CAR
;
2737 if (sarg
| TIOCM_DSR
)
2738 *targ
|= CHR_TIOCM_DSR
;
2739 if (sarg
| TIOCM_RI
)
2740 *targ
|= CHR_TIOCM_RI
;
2741 if (sarg
| TIOCM_DTR
)
2742 *targ
|= CHR_TIOCM_DTR
;
2743 if (sarg
| TIOCM_RTS
)
2744 *targ
|= CHR_TIOCM_RTS
;
2747 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2749 int sarg
= *(int *)arg
;
2751 if (sarg
| CHR_TIOCM_DTR
)
2753 if (sarg
| CHR_TIOCM_RTS
)
2755 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2764 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2766 CharDriverState
*chr
;
2769 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2770 tty_serial_init(fd
, 115200, 'N', 8, 1);
2771 chr
= qemu_chr_open_fd(fd
, fd
);
2776 chr
->chr_ioctl
= tty_serial_ioctl
;
2777 qemu_chr_reset(chr
);
2780 #else /* ! __linux__ && ! __sun__ */
2781 static CharDriverState
*qemu_chr_open_pty(void)
2785 #endif /* __linux__ || __sun__ */
2787 #if defined(__linux__)
2791 } ParallelCharDriver
;
2793 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2795 if (s
->mode
!= mode
) {
2797 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2804 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2806 ParallelCharDriver
*drv
= chr
->opaque
;
2811 case CHR_IOCTL_PP_READ_DATA
:
2812 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2814 *(uint8_t *)arg
= b
;
2816 case CHR_IOCTL_PP_WRITE_DATA
:
2817 b
= *(uint8_t *)arg
;
2818 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2821 case CHR_IOCTL_PP_READ_CONTROL
:
2822 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2824 /* Linux gives only the lowest bits, and no way to know data
2825 direction! For better compatibility set the fixed upper
2827 *(uint8_t *)arg
= b
| 0xc0;
2829 case CHR_IOCTL_PP_WRITE_CONTROL
:
2830 b
= *(uint8_t *)arg
;
2831 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2834 case CHR_IOCTL_PP_READ_STATUS
:
2835 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2837 *(uint8_t *)arg
= b
;
2839 case CHR_IOCTL_PP_DATA_DIR
:
2840 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2843 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2844 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2845 struct ParallelIOArg
*parg
= arg
;
2846 int n
= read(fd
, parg
->buffer
, parg
->count
);
2847 if (n
!= parg
->count
) {
2852 case CHR_IOCTL_PP_EPP_READ
:
2853 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2854 struct ParallelIOArg
*parg
= arg
;
2855 int n
= read(fd
, parg
->buffer
, parg
->count
);
2856 if (n
!= parg
->count
) {
2861 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2862 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2863 struct ParallelIOArg
*parg
= arg
;
2864 int n
= write(fd
, parg
->buffer
, parg
->count
);
2865 if (n
!= parg
->count
) {
2870 case CHR_IOCTL_PP_EPP_WRITE
:
2871 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2872 struct ParallelIOArg
*parg
= arg
;
2873 int n
= write(fd
, parg
->buffer
, parg
->count
);
2874 if (n
!= parg
->count
) {
2885 static void pp_close(CharDriverState
*chr
)
2887 ParallelCharDriver
*drv
= chr
->opaque
;
2890 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2891 ioctl(fd
, PPRELEASE
);
2896 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2898 CharDriverState
*chr
;
2899 ParallelCharDriver
*drv
;
2902 TFR(fd
= open(filename
, O_RDWR
));
2906 if (ioctl(fd
, PPCLAIM
) < 0) {
2911 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2917 drv
->mode
= IEEE1284_MODE_COMPAT
;
2919 chr
= qemu_mallocz(sizeof(CharDriverState
));
2925 chr
->chr_write
= null_chr_write
;
2926 chr
->chr_ioctl
= pp_ioctl
;
2927 chr
->chr_close
= pp_close
;
2930 qemu_chr_reset(chr
);
2934 #endif /* __linux__ */
2940 HANDLE hcom
, hrecv
, hsend
;
2941 OVERLAPPED orecv
, osend
;
2946 #define NSENDBUF 2048
2947 #define NRECVBUF 2048
2948 #define MAXCONNECT 1
2949 #define NTIMEOUT 5000
2951 static int win_chr_poll(void *opaque
);
2952 static int win_chr_pipe_poll(void *opaque
);
2954 static void win_chr_close(CharDriverState
*chr
)
2956 WinCharState
*s
= chr
->opaque
;
2959 CloseHandle(s
->hsend
);
2963 CloseHandle(s
->hrecv
);
2967 CloseHandle(s
->hcom
);
2971 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2973 qemu_del_polling_cb(win_chr_poll
, chr
);
2976 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2978 WinCharState
*s
= chr
->opaque
;
2980 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2985 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2987 fprintf(stderr
, "Failed CreateEvent\n");
2990 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2992 fprintf(stderr
, "Failed CreateEvent\n");
2996 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2997 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2998 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2999 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3004 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3005 fprintf(stderr
, "Failed SetupComm\n");
3009 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3010 size
= sizeof(COMMCONFIG
);
3011 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3012 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3013 CommConfigDialog(filename
, NULL
, &comcfg
);
3015 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3016 fprintf(stderr
, "Failed SetCommState\n");
3020 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3021 fprintf(stderr
, "Failed SetCommMask\n");
3025 cto
.ReadIntervalTimeout
= MAXDWORD
;
3026 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3027 fprintf(stderr
, "Failed SetCommTimeouts\n");
3031 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3032 fprintf(stderr
, "Failed ClearCommError\n");
3035 qemu_add_polling_cb(win_chr_poll
, chr
);
3043 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3045 WinCharState
*s
= chr
->opaque
;
3046 DWORD len
, ret
, size
, err
;
3049 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3050 s
->osend
.hEvent
= s
->hsend
;
3053 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3055 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3057 err
= GetLastError();
3058 if (err
== ERROR_IO_PENDING
) {
3059 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3077 static int win_chr_read_poll(CharDriverState
*chr
)
3079 WinCharState
*s
= chr
->opaque
;
3081 s
->max_size
= qemu_chr_can_read(chr
);
3085 static void win_chr_readfile(CharDriverState
*chr
)
3087 WinCharState
*s
= chr
->opaque
;
3092 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3093 s
->orecv
.hEvent
= s
->hrecv
;
3094 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3096 err
= GetLastError();
3097 if (err
== ERROR_IO_PENDING
) {
3098 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3103 qemu_chr_read(chr
, buf
, size
);
3107 static void win_chr_read(CharDriverState
*chr
)
3109 WinCharState
*s
= chr
->opaque
;
3111 if (s
->len
> s
->max_size
)
3112 s
->len
= s
->max_size
;
3116 win_chr_readfile(chr
);
3119 static int win_chr_poll(void *opaque
)
3121 CharDriverState
*chr
= opaque
;
3122 WinCharState
*s
= chr
->opaque
;
3126 ClearCommError(s
->hcom
, &comerr
, &status
);
3127 if (status
.cbInQue
> 0) {
3128 s
->len
= status
.cbInQue
;
3129 win_chr_read_poll(chr
);
3136 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3138 CharDriverState
*chr
;
3141 chr
= qemu_mallocz(sizeof(CharDriverState
));
3144 s
= qemu_mallocz(sizeof(WinCharState
));
3150 chr
->chr_write
= win_chr_write
;
3151 chr
->chr_close
= win_chr_close
;
3153 if (win_chr_init(chr
, filename
) < 0) {
3158 qemu_chr_reset(chr
);
3162 static int win_chr_pipe_poll(void *opaque
)
3164 CharDriverState
*chr
= opaque
;
3165 WinCharState
*s
= chr
->opaque
;
3168 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3171 win_chr_read_poll(chr
);
3178 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3180 WinCharState
*s
= chr
->opaque
;
3188 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3190 fprintf(stderr
, "Failed CreateEvent\n");
3193 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3195 fprintf(stderr
, "Failed CreateEvent\n");
3199 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3200 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3201 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3203 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3204 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3205 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3210 ZeroMemory(&ov
, sizeof(ov
));
3211 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3212 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3214 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3218 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3220 fprintf(stderr
, "Failed GetOverlappedResult\n");
3222 CloseHandle(ov
.hEvent
);
3229 CloseHandle(ov
.hEvent
);
3232 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3241 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3243 CharDriverState
*chr
;
3246 chr
= qemu_mallocz(sizeof(CharDriverState
));
3249 s
= qemu_mallocz(sizeof(WinCharState
));
3255 chr
->chr_write
= win_chr_write
;
3256 chr
->chr_close
= win_chr_close
;
3258 if (win_chr_pipe_init(chr
, filename
) < 0) {
3263 qemu_chr_reset(chr
);
3267 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3269 CharDriverState
*chr
;
3272 chr
= qemu_mallocz(sizeof(CharDriverState
));
3275 s
= qemu_mallocz(sizeof(WinCharState
));
3282 chr
->chr_write
= win_chr_write
;
3283 qemu_chr_reset(chr
);
3287 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3289 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3292 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3296 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3297 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3298 if (fd_out
== INVALID_HANDLE_VALUE
)
3301 return qemu_chr_open_win_file(fd_out
);
3303 #endif /* !_WIN32 */
3305 /***********************************************************/
3306 /* UDP Net console */
3310 struct sockaddr_in daddr
;
3317 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3319 NetCharDriver
*s
= chr
->opaque
;
3321 return sendto(s
->fd
, buf
, len
, 0,
3322 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3325 static int udp_chr_read_poll(void *opaque
)
3327 CharDriverState
*chr
= opaque
;
3328 NetCharDriver
*s
= chr
->opaque
;
3330 s
->max_size
= qemu_chr_can_read(chr
);
3332 /* If there were any stray characters in the queue process them
3335 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3336 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3338 s
->max_size
= qemu_chr_can_read(chr
);
3343 static void udp_chr_read(void *opaque
)
3345 CharDriverState
*chr
= opaque
;
3346 NetCharDriver
*s
= chr
->opaque
;
3348 if (s
->max_size
== 0)
3350 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3351 s
->bufptr
= s
->bufcnt
;
3356 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3357 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3359 s
->max_size
= qemu_chr_can_read(chr
);
3363 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3365 NetCharDriver
*s
= chr
->opaque
;
3368 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3369 udp_chr_read
, NULL
, chr
);
3373 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3375 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3377 int parse_host_src_port(struct sockaddr_in
*haddr
,
3378 struct sockaddr_in
*saddr
,
3381 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3383 CharDriverState
*chr
= NULL
;
3384 NetCharDriver
*s
= NULL
;
3386 struct sockaddr_in saddr
;
3388 chr
= qemu_mallocz(sizeof(CharDriverState
));
3391 s
= qemu_mallocz(sizeof(NetCharDriver
));
3395 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3397 perror("socket(PF_INET, SOCK_DGRAM)");
3401 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3402 printf("Could not parse: %s\n", def
);
3406 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3416 chr
->chr_write
= udp_chr_write
;
3417 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3430 /***********************************************************/
3431 /* TCP Net console */
3442 static void tcp_chr_accept(void *opaque
);
3444 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3446 TCPCharDriver
*s
= chr
->opaque
;
3448 return send_all(s
->fd
, buf
, len
);
3450 /* XXX: indicate an error ? */
3455 static int tcp_chr_read_poll(void *opaque
)
3457 CharDriverState
*chr
= opaque
;
3458 TCPCharDriver
*s
= chr
->opaque
;
3461 s
->max_size
= qemu_chr_can_read(chr
);
3466 #define IAC_BREAK 243
3467 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3469 uint8_t *buf
, int *size
)
3471 /* Handle any telnet client's basic IAC options to satisfy char by
3472 * char mode with no echo. All IAC options will be removed from
3473 * the buf and the do_telnetopt variable will be used to track the
3474 * state of the width of the IAC information.
3476 * IAC commands come in sets of 3 bytes with the exception of the
3477 * "IAC BREAK" command and the double IAC.
3483 for (i
= 0; i
< *size
; i
++) {
3484 if (s
->do_telnetopt
> 1) {
3485 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3486 /* Double IAC means send an IAC */
3490 s
->do_telnetopt
= 1;
3492 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3493 /* Handle IAC break commands by sending a serial break */
3494 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3499 if (s
->do_telnetopt
>= 4) {
3500 s
->do_telnetopt
= 1;
3503 if ((unsigned char)buf
[i
] == IAC
) {
3504 s
->do_telnetopt
= 2;
3515 static void tcp_chr_read(void *opaque
)
3517 CharDriverState
*chr
= opaque
;
3518 TCPCharDriver
*s
= chr
->opaque
;
3522 if (!s
->connected
|| s
->max_size
<= 0)
3525 if (len
> s
->max_size
)
3527 size
= recv(s
->fd
, buf
, len
, 0);
3529 /* connection closed */
3531 if (s
->listen_fd
>= 0) {
3532 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3534 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3537 } else if (size
> 0) {
3538 if (s
->do_telnetopt
)
3539 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3541 qemu_chr_read(chr
, buf
, size
);
3545 static void tcp_chr_connect(void *opaque
)
3547 CharDriverState
*chr
= opaque
;
3548 TCPCharDriver
*s
= chr
->opaque
;
3551 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3552 tcp_chr_read
, NULL
, chr
);
3553 qemu_chr_reset(chr
);
3556 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3557 static void tcp_chr_telnet_init(int fd
)
3560 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3561 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3562 send(fd
, (char *)buf
, 3, 0);
3563 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3564 send(fd
, (char *)buf
, 3, 0);
3565 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3566 send(fd
, (char *)buf
, 3, 0);
3567 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3568 send(fd
, (char *)buf
, 3, 0);
3571 static void socket_set_nodelay(int fd
)
3574 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3577 static void tcp_chr_accept(void *opaque
)
3579 CharDriverState
*chr
= opaque
;
3580 TCPCharDriver
*s
= chr
->opaque
;
3581 struct sockaddr_in saddr
;
3583 struct sockaddr_un uaddr
;
3585 struct sockaddr
*addr
;
3592 len
= sizeof(uaddr
);
3593 addr
= (struct sockaddr
*)&uaddr
;
3597 len
= sizeof(saddr
);
3598 addr
= (struct sockaddr
*)&saddr
;
3600 fd
= accept(s
->listen_fd
, addr
, &len
);
3601 if (fd
< 0 && errno
!= EINTR
) {
3603 } else if (fd
>= 0) {
3604 if (s
->do_telnetopt
)
3605 tcp_chr_telnet_init(fd
);
3609 socket_set_nonblock(fd
);
3611 socket_set_nodelay(fd
);
3613 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3614 tcp_chr_connect(chr
);
3617 static void tcp_chr_close(CharDriverState
*chr
)
3619 TCPCharDriver
*s
= chr
->opaque
;
3622 if (s
->listen_fd
>= 0)
3623 closesocket(s
->listen_fd
);
3627 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3631 CharDriverState
*chr
= NULL
;
3632 TCPCharDriver
*s
= NULL
;
3633 int fd
= -1, ret
, err
, val
;
3635 int is_waitconnect
= 1;
3638 struct sockaddr_in saddr
;
3640 struct sockaddr_un uaddr
;
3642 struct sockaddr
*addr
;
3647 addr
= (struct sockaddr
*)&uaddr
;
3648 addrlen
= sizeof(uaddr
);
3649 if (parse_unix_path(&uaddr
, host_str
) < 0)
3654 addr
= (struct sockaddr
*)&saddr
;
3655 addrlen
= sizeof(saddr
);
3656 if (parse_host_port(&saddr
, host_str
) < 0)
3661 while((ptr
= strchr(ptr
,','))) {
3663 if (!strncmp(ptr
,"server",6)) {
3665 } else if (!strncmp(ptr
,"nowait",6)) {
3667 } else if (!strncmp(ptr
,"nodelay",6)) {
3670 printf("Unknown option: %s\n", ptr
);
3677 chr
= qemu_mallocz(sizeof(CharDriverState
));
3680 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3686 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3689 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3694 if (!is_waitconnect
)
3695 socket_set_nonblock(fd
);
3700 s
->is_unix
= is_unix
;
3701 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3704 chr
->chr_write
= tcp_chr_write
;
3705 chr
->chr_close
= tcp_chr_close
;
3708 /* allow fast reuse */
3712 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3718 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3721 ret
= bind(fd
, addr
, addrlen
);
3725 ret
= listen(fd
, 0);
3730 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3732 s
->do_telnetopt
= 1;
3735 ret
= connect(fd
, addr
, addrlen
);
3737 err
= socket_error();
3738 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3739 } else if (err
== EINPROGRESS
) {
3742 } else if (err
== WSAEALREADY
) {
3754 socket_set_nodelay(fd
);
3756 tcp_chr_connect(chr
);
3758 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3761 if (is_listen
&& is_waitconnect
) {
3762 printf("QEMU waiting for connection on: %s\n", host_str
);
3763 tcp_chr_accept(chr
);
3764 socket_set_nonblock(s
->listen_fd
);
3776 CharDriverState
*qemu_chr_open(const char *filename
)
3780 if (!strcmp(filename
, "vc")) {
3781 return text_console_init(&display_state
, 0);
3782 } else if (strstart(filename
, "vc:", &p
)) {
3783 return text_console_init(&display_state
, p
);
3784 } else if (!strcmp(filename
, "null")) {
3785 return qemu_chr_open_null();
3787 if (strstart(filename
, "tcp:", &p
)) {
3788 return qemu_chr_open_tcp(p
, 0, 0);
3790 if (strstart(filename
, "telnet:", &p
)) {
3791 return qemu_chr_open_tcp(p
, 1, 0);
3793 if (strstart(filename
, "udp:", &p
)) {
3794 return qemu_chr_open_udp(p
);
3796 if (strstart(filename
, "mon:", &p
)) {
3797 CharDriverState
*drv
= qemu_chr_open(p
);
3799 drv
= qemu_chr_open_mux(drv
);
3800 monitor_init(drv
, !nographic
);
3803 printf("Unable to open driver: %s\n", p
);
3807 if (strstart(filename
, "unix:", &p
)) {
3808 return qemu_chr_open_tcp(p
, 0, 1);
3809 } else if (strstart(filename
, "file:", &p
)) {
3810 return qemu_chr_open_file_out(p
);
3811 } else if (strstart(filename
, "pipe:", &p
)) {
3812 return qemu_chr_open_pipe(p
);
3813 } else if (!strcmp(filename
, "pty")) {
3814 return qemu_chr_open_pty();
3815 } else if (!strcmp(filename
, "stdio")) {
3816 return qemu_chr_open_stdio();
3818 #if defined(__linux__)
3819 if (strstart(filename
, "/dev/parport", NULL
)) {
3820 return qemu_chr_open_pp(filename
);
3823 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3824 || defined(__NetBSD__) || defined(__OpenBSD__)
3825 if (strstart(filename
, "/dev/", NULL
)) {
3826 return qemu_chr_open_tty(filename
);
3830 if (strstart(filename
, "COM", NULL
)) {
3831 return qemu_chr_open_win(filename
);
3833 if (strstart(filename
, "pipe:", &p
)) {
3834 return qemu_chr_open_win_pipe(p
);
3836 if (strstart(filename
, "con:", NULL
)) {
3837 return qemu_chr_open_win_con(filename
);
3839 if (strstart(filename
, "file:", &p
)) {
3840 return qemu_chr_open_win_file_out(p
);
3843 #ifdef CONFIG_BRLAPI
3844 if (!strcmp(filename
, "braille")) {
3845 return chr_baum_init();
3853 void qemu_chr_close(CharDriverState
*chr
)
3856 chr
->chr_close(chr
);
3860 /***********************************************************/
3861 /* network device redirectors */
3863 __attribute__ (( unused
))
3864 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3868 for(i
=0;i
<size
;i
+=16) {
3872 fprintf(f
, "%08x ", i
);
3875 fprintf(f
, " %02x", buf
[i
+j
]);
3880 for(j
=0;j
<len
;j
++) {
3882 if (c
< ' ' || c
> '~')
3884 fprintf(f
, "%c", c
);
3890 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3897 offset
= strtol(p
, &last_char
, 0);
3898 if (0 == errno
&& '\0' == *last_char
&&
3899 offset
>= 0 && offset
<= 0xFFFFFF) {
3900 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3901 macaddr
[4] = (offset
& 0xFF00) >> 8;
3902 macaddr
[5] = offset
& 0xFF;
3905 for(i
= 0; i
< 6; i
++) {
3906 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3911 if (*p
!= ':' && *p
!= '-')
3922 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3927 p1
= strchr(p
, sep
);
3933 if (len
> buf_size
- 1)
3935 memcpy(buf
, p
, len
);
3942 int parse_host_src_port(struct sockaddr_in
*haddr
,
3943 struct sockaddr_in
*saddr
,
3944 const char *input_str
)
3946 char *str
= strdup(input_str
);
3947 char *host_str
= str
;
3949 const char *src_str2
;
3953 * Chop off any extra arguments at the end of the string which
3954 * would start with a comma, then fill in the src port information
3955 * if it was provided else use the "any address" and "any port".
3957 if ((ptr
= strchr(str
,',')))
3960 if ((src_str
= strchr(input_str
,'@'))) {
3965 if (parse_host_port(haddr
, host_str
) < 0)
3969 if (!src_str
|| *src_str
== '\0')
3972 if (parse_host_port(saddr
, src_str2
) < 0)
3983 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3991 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3993 saddr
->sin_family
= AF_INET
;
3994 if (buf
[0] == '\0') {
3995 saddr
->sin_addr
.s_addr
= 0;
3997 if (isdigit(buf
[0])) {
3998 if (!inet_aton(buf
, &saddr
->sin_addr
))
4001 if ((he
= gethostbyname(buf
)) == NULL
)
4003 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4006 port
= strtol(p
, (char **)&r
, 0);
4009 saddr
->sin_port
= htons(port
);
4014 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4019 len
= MIN(108, strlen(str
));
4020 p
= strchr(str
, ',');
4022 len
= MIN(len
, p
- str
);
4024 memset(uaddr
, 0, sizeof(*uaddr
));
4026 uaddr
->sun_family
= AF_UNIX
;
4027 memcpy(uaddr
->sun_path
, str
, len
);
4033 /* find or alloc a new VLAN */
4034 VLANState
*qemu_find_vlan(int id
)
4036 VLANState
**pvlan
, *vlan
;
4037 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4041 vlan
= qemu_mallocz(sizeof(VLANState
));
4046 pvlan
= &first_vlan
;
4047 while (*pvlan
!= NULL
)
4048 pvlan
= &(*pvlan
)->next
;
4053 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4054 IOReadHandler
*fd_read
,
4055 IOCanRWHandler
*fd_can_read
,
4058 VLANClientState
*vc
, **pvc
;
4059 vc
= qemu_mallocz(sizeof(VLANClientState
));
4062 vc
->fd_read
= fd_read
;
4063 vc
->fd_can_read
= fd_can_read
;
4064 vc
->opaque
= opaque
;
4068 pvc
= &vlan
->first_client
;
4069 while (*pvc
!= NULL
)
4070 pvc
= &(*pvc
)->next
;
4075 void qemu_del_vlan_client(VLANClientState
*vc
)
4077 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4079 while (*pvc
!= NULL
)
4085 pvc
= &(*pvc
)->next
;
4088 int qemu_can_send_packet(VLANClientState
*vc1
)
4090 VLANState
*vlan
= vc1
->vlan
;
4091 VLANClientState
*vc
;
4093 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4095 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4102 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4104 VLANState
*vlan
= vc1
->vlan
;
4105 VLANClientState
*vc
;
4108 printf("vlan %d send:\n", vlan
->id
);
4109 hex_dump(stdout
, buf
, size
);
4111 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4113 vc
->fd_read(vc
->opaque
, buf
, size
);
4118 #if defined(CONFIG_SLIRP)
4120 /* slirp network adapter */
4122 static int slirp_inited
;
4123 static VLANClientState
*slirp_vc
;
4125 int slirp_can_output(void)
4127 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4130 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4133 printf("slirp output:\n");
4134 hex_dump(stdout
, pkt
, pkt_len
);
4138 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4141 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4144 printf("slirp input:\n");
4145 hex_dump(stdout
, buf
, size
);
4147 slirp_input(buf
, size
);
4150 static int net_slirp_init(VLANState
*vlan
)
4152 if (!slirp_inited
) {
4156 slirp_vc
= qemu_new_vlan_client(vlan
,
4157 slirp_receive
, NULL
, NULL
);
4158 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4162 static void net_slirp_redir(const char *redir_str
)
4167 struct in_addr guest_addr
;
4168 int host_port
, guest_port
;
4170 if (!slirp_inited
) {
4176 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4178 if (!strcmp(buf
, "tcp")) {
4180 } else if (!strcmp(buf
, "udp")) {
4186 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4188 host_port
= strtol(buf
, &r
, 0);
4192 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4194 if (buf
[0] == '\0') {
4195 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4197 if (!inet_aton(buf
, &guest_addr
))
4200 guest_port
= strtol(p
, &r
, 0);
4204 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4205 fprintf(stderr
, "qemu: could not set up redirection\n");
4210 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4218 static void erase_dir(char *dir_name
)
4222 char filename
[1024];
4224 /* erase all the files in the directory */
4225 if ((d
= opendir(dir_name
)) != 0) {
4230 if (strcmp(de
->d_name
, ".") != 0 &&
4231 strcmp(de
->d_name
, "..") != 0) {
4232 snprintf(filename
, sizeof(filename
), "%s/%s",
4233 smb_dir
, de
->d_name
);
4234 if (unlink(filename
) != 0) /* is it a directory? */
4235 erase_dir(filename
);
4243 /* automatic user mode samba server configuration */
4244 static void smb_exit(void)
4249 /* automatic user mode samba server configuration */
4250 static void net_slirp_smb(const char *exported_dir
)
4252 char smb_conf
[1024];
4253 char smb_cmdline
[1024];
4256 if (!slirp_inited
) {
4261 /* XXX: better tmp dir construction */
4262 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4263 if (mkdir(smb_dir
, 0700) < 0) {
4264 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4267 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4269 f
= fopen(smb_conf
, "w");
4271 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4278 "socket address=127.0.0.1\n"
4279 "pid directory=%s\n"
4280 "lock directory=%s\n"
4281 "log file=%s/log.smbd\n"
4282 "smb passwd file=%s/smbpasswd\n"
4283 "security = share\n"
4298 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4299 SMBD_COMMAND
, smb_conf
);
4301 slirp_add_exec(0, smb_cmdline
, 4, 139);
4304 #endif /* !defined(_WIN32) */
4305 void do_info_slirp(void)
4310 #endif /* CONFIG_SLIRP */
4312 #if !defined(_WIN32)
4314 typedef struct TAPState
{
4315 VLANClientState
*vc
;
4317 char down_script
[1024];
4320 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4322 TAPState
*s
= opaque
;
4325 ret
= write(s
->fd
, buf
, size
);
4326 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4333 static void tap_send(void *opaque
)
4335 TAPState
*s
= opaque
;
4342 sbuf
.maxlen
= sizeof(buf
);
4344 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4346 size
= read(s
->fd
, buf
, sizeof(buf
));
4349 qemu_send_packet(s
->vc
, buf
, size
);
4355 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4359 s
= qemu_mallocz(sizeof(TAPState
));
4363 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4364 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4365 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4369 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4370 static int tap_open(char *ifname
, int ifname_size
)
4376 TFR(fd
= open("/dev/tap", O_RDWR
));
4378 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4383 dev
= devname(s
.st_rdev
, S_IFCHR
);
4384 pstrcpy(ifname
, ifname_size
, dev
);
4386 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4389 #elif defined(__sun__)
4390 #define TUNNEWPPA (('T'<<16) | 0x0001)
4392 * Allocate TAP device, returns opened fd.
4393 * Stores dev name in the first arg(must be large enough).
4395 int tap_alloc(char *dev
, size_t dev_size
)
4397 int tap_fd
, if_fd
, ppa
= -1;
4398 static int ip_fd
= 0;
4401 static int arp_fd
= 0;
4402 int ip_muxid
, arp_muxid
;
4403 struct strioctl strioc_if
, strioc_ppa
;
4404 int link_type
= I_PLINK
;;
4406 char actual_name
[32] = "";
4408 memset(&ifr
, 0x0, sizeof(ifr
));
4412 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4416 /* Check if IP device was opened */
4420 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4422 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4426 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4428 syslog(LOG_ERR
, "Can't open /dev/tap");
4432 /* Assign a new PPA and get its unit number. */
4433 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4434 strioc_ppa
.ic_timout
= 0;
4435 strioc_ppa
.ic_len
= sizeof(ppa
);
4436 strioc_ppa
.ic_dp
= (char *)&ppa
;
4437 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4438 syslog (LOG_ERR
, "Can't assign new interface");
4440 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4442 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4445 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4446 syslog(LOG_ERR
, "Can't push IP module");
4450 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4451 syslog(LOG_ERR
, "Can't get flags\n");
4453 snprintf (actual_name
, 32, "tap%d", ppa
);
4454 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4457 /* Assign ppa according to the unit number returned by tun device */
4459 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4460 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4461 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4462 syslog (LOG_ERR
, "Can't get flags\n");
4463 /* Push arp module to if_fd */
4464 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4465 syslog (LOG_ERR
, "Can't push ARP module (2)");
4467 /* Push arp module to ip_fd */
4468 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4469 syslog (LOG_ERR
, "I_POP failed\n");
4470 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4471 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4473 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4475 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4477 /* Set ifname to arp */
4478 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4479 strioc_if
.ic_timout
= 0;
4480 strioc_if
.ic_len
= sizeof(ifr
);
4481 strioc_if
.ic_dp
= (char *)&ifr
;
4482 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4483 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4486 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4487 syslog(LOG_ERR
, "Can't link TAP device to IP");
4491 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4492 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4496 memset(&ifr
, 0x0, sizeof(ifr
));
4497 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4498 ifr
.lifr_ip_muxid
= ip_muxid
;
4499 ifr
.lifr_arp_muxid
= arp_muxid
;
4501 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4503 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4504 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4505 syslog (LOG_ERR
, "Can't set multiplexor id");
4508 snprintf(dev
, dev_size
, "tap%d", ppa
);
4512 static int tap_open(char *ifname
, int ifname_size
)
4516 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4517 fprintf(stderr
, "Cannot allocate TAP device\n");
4520 pstrcpy(ifname
, ifname_size
, dev
);
4521 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4525 static int tap_open(char *ifname
, int ifname_size
)
4530 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4532 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4535 memset(&ifr
, 0, sizeof(ifr
));
4536 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4537 if (ifname
[0] != '\0')
4538 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4540 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4541 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4543 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4547 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4548 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4553 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4559 /* try to launch network script */
4563 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4564 for (i
= 0; i
< open_max
; i
++)
4565 if (i
!= STDIN_FILENO
&&
4566 i
!= STDOUT_FILENO
&&
4567 i
!= STDERR_FILENO
&&
4572 *parg
++ = (char *)setup_script
;
4573 *parg
++ = (char *)ifname
;
4575 execv(setup_script
, args
);
4578 while (waitpid(pid
, &status
, 0) != pid
);
4579 if (!WIFEXITED(status
) ||
4580 WEXITSTATUS(status
) != 0) {
4581 fprintf(stderr
, "%s: could not launch network script\n",
4589 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4590 const char *setup_script
, const char *down_script
)
4596 if (ifname1
!= NULL
)
4597 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4600 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4604 if (!setup_script
|| !strcmp(setup_script
, "no"))
4606 if (setup_script
[0] != '\0') {
4607 if (launch_script(setup_script
, ifname
, fd
))
4610 s
= net_tap_fd_init(vlan
, fd
);
4613 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4614 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4615 if (down_script
&& strcmp(down_script
, "no"))
4616 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4620 #endif /* !_WIN32 */
4622 #if defined(CONFIG_VDE)
4623 typedef struct VDEState
{
4624 VLANClientState
*vc
;
4628 static void vde_to_qemu(void *opaque
)
4630 VDEState
*s
= opaque
;
4634 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4636 qemu_send_packet(s
->vc
, buf
, size
);
4640 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4642 VDEState
*s
= opaque
;
4645 ret
= vde_send(s
->vde
, buf
, size
, 0);
4646 if (ret
< 0 && errno
== EINTR
) {
4653 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4654 const char *group
, int mode
)
4657 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4658 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4660 struct vde_open_args args
= {
4662 .group
= init_group
,
4666 s
= qemu_mallocz(sizeof(VDEState
));
4669 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4674 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4675 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4676 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4677 sock
, vde_datafd(s
->vde
));
4682 /* network connection */
4683 typedef struct NetSocketState
{
4684 VLANClientState
*vc
;
4686 int state
; /* 0 = getting length, 1 = getting data */
4690 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4693 typedef struct NetSocketListenState
{
4696 } NetSocketListenState
;
4698 /* XXX: we consider we can send the whole packet without blocking */
4699 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4701 NetSocketState
*s
= opaque
;
4705 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4706 send_all(s
->fd
, buf
, size
);
4709 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4711 NetSocketState
*s
= opaque
;
4712 sendto(s
->fd
, buf
, size
, 0,
4713 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4716 static void net_socket_send(void *opaque
)
4718 NetSocketState
*s
= opaque
;
4723 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4725 err
= socket_error();
4726 if (err
!= EWOULDBLOCK
)
4728 } else if (size
== 0) {
4729 /* end of connection */
4731 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4737 /* reassemble a packet from the network */
4743 memcpy(s
->buf
+ s
->index
, buf
, l
);
4747 if (s
->index
== 4) {
4749 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4755 l
= s
->packet_len
- s
->index
;
4758 memcpy(s
->buf
+ s
->index
, buf
, l
);
4762 if (s
->index
>= s
->packet_len
) {
4763 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4772 static void net_socket_send_dgram(void *opaque
)
4774 NetSocketState
*s
= opaque
;
4777 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4781 /* end of connection */
4782 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4785 qemu_send_packet(s
->vc
, s
->buf
, size
);
4788 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4793 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4794 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4795 inet_ntoa(mcastaddr
->sin_addr
),
4796 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4800 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4802 perror("socket(PF_INET, SOCK_DGRAM)");
4807 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4808 (const char *)&val
, sizeof(val
));
4810 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4814 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4820 /* Add host to multicast group */
4821 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4822 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4824 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4825 (const char *)&imr
, sizeof(struct ip_mreq
));
4827 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4831 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4833 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4834 (const char *)&val
, sizeof(val
));
4836 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4840 socket_set_nonblock(fd
);
4848 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4851 struct sockaddr_in saddr
;
4853 socklen_t saddr_len
;
4856 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4857 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4858 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4862 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4864 if (saddr
.sin_addr
.s_addr
==0) {
4865 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4869 /* clone dgram socket */
4870 newfd
= net_socket_mcast_create(&saddr
);
4872 /* error already reported by net_socket_mcast_create() */
4876 /* clone newfd to fd, close newfd */
4881 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4882 fd
, strerror(errno
));
4887 s
= qemu_mallocz(sizeof(NetSocketState
));
4892 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4893 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4895 /* mcast: save bound address as dst */
4896 if (is_connected
) s
->dgram_dst
=saddr
;
4898 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4899 "socket: fd=%d (%s mcast=%s:%d)",
4900 fd
, is_connected
? "cloned" : "",
4901 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4905 static void net_socket_connect(void *opaque
)
4907 NetSocketState
*s
= opaque
;
4908 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4911 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4915 s
= qemu_mallocz(sizeof(NetSocketState
));
4919 s
->vc
= qemu_new_vlan_client(vlan
,
4920 net_socket_receive
, NULL
, s
);
4921 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4922 "socket: fd=%d", fd
);
4924 net_socket_connect(s
);
4926 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4931 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4934 int so_type
=-1, optlen
=sizeof(so_type
);
4936 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4937 (socklen_t
*)&optlen
)< 0) {
4938 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4943 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4945 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4947 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4948 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4949 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4954 static void net_socket_accept(void *opaque
)
4956 NetSocketListenState
*s
= opaque
;
4958 struct sockaddr_in saddr
;
4963 len
= sizeof(saddr
);
4964 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4965 if (fd
< 0 && errno
!= EINTR
) {
4967 } else if (fd
>= 0) {
4971 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4975 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4976 "socket: connection from %s:%d",
4977 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4981 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4983 NetSocketListenState
*s
;
4985 struct sockaddr_in saddr
;
4987 if (parse_host_port(&saddr
, host_str
) < 0)
4990 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4994 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4999 socket_set_nonblock(fd
);
5001 /* allow fast reuse */
5003 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5005 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5010 ret
= listen(fd
, 0);
5017 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5021 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5024 int fd
, connected
, ret
, err
;
5025 struct sockaddr_in saddr
;
5027 if (parse_host_port(&saddr
, host_str
) < 0)
5030 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5035 socket_set_nonblock(fd
);
5039 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5041 err
= socket_error();
5042 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5043 } else if (err
== EINPROGRESS
) {
5046 } else if (err
== WSAEALREADY
) {
5059 s
= net_socket_fd_init(vlan
, fd
, connected
);
5062 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5063 "socket: connect to %s:%d",
5064 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5068 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5072 struct sockaddr_in saddr
;
5074 if (parse_host_port(&saddr
, host_str
) < 0)
5078 fd
= net_socket_mcast_create(&saddr
);
5082 s
= net_socket_fd_init(vlan
, fd
, 0);
5086 s
->dgram_dst
= saddr
;
5088 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5089 "socket: mcast=%s:%d",
5090 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5095 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5100 while (*p
!= '\0' && *p
!= '=') {
5101 if (q
&& (q
- buf
) < buf_size
- 1)
5111 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5116 while (*p
!= '\0') {
5118 if (*(p
+ 1) != ',')
5122 if (q
&& (q
- buf
) < buf_size
- 1)
5132 static int get_param_value(char *buf
, int buf_size
,
5133 const char *tag
, const char *str
)
5140 p
= get_opt_name(option
, sizeof(option
), p
);
5144 if (!strcmp(tag
, option
)) {
5145 (void)get_opt_value(buf
, buf_size
, p
);
5148 p
= get_opt_value(NULL
, 0, p
);
5157 static int check_params(char *buf
, int buf_size
,
5158 const char * const *params
, const char *str
)
5165 p
= get_opt_name(buf
, buf_size
, p
);
5169 for(i
= 0; params
[i
] != NULL
; i
++)
5170 if (!strcmp(params
[i
], buf
))
5172 if (params
[i
] == NULL
)
5174 p
= get_opt_value(NULL
, 0, p
);
5182 static int net_client_init(const char *device
, const char *p
)
5189 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5190 vlan_id
= strtol(buf
, NULL
, 0);
5192 vlan
= qemu_find_vlan(vlan_id
);
5194 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5197 if (!strcmp(device
, "nic")) {
5201 if (nb_nics
>= MAX_NICS
) {
5202 fprintf(stderr
, "Too Many NICs\n");
5205 nd
= &nd_table
[nb_nics
];
5206 macaddr
= nd
->macaddr
;
5212 macaddr
[5] = 0x56 + nb_nics
;
5214 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5215 if (parse_macaddr(macaddr
, buf
) < 0) {
5216 fprintf(stderr
, "invalid syntax for ethernet address\n");
5220 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5221 nd
->model
= strdup(buf
);
5225 vlan
->nb_guest_devs
++;
5228 if (!strcmp(device
, "none")) {
5229 /* does nothing. It is needed to signal that no network cards
5234 if (!strcmp(device
, "user")) {
5235 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5236 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5238 vlan
->nb_host_devs
++;
5239 ret
= net_slirp_init(vlan
);
5243 if (!strcmp(device
, "tap")) {
5245 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5246 fprintf(stderr
, "tap: no interface name\n");
5249 vlan
->nb_host_devs
++;
5250 ret
= tap_win32_init(vlan
, ifname
);
5253 if (!strcmp(device
, "tap")) {
5255 char setup_script
[1024], down_script
[1024];
5257 vlan
->nb_host_devs
++;
5258 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5259 fd
= strtol(buf
, NULL
, 0);
5260 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5262 if (net_tap_fd_init(vlan
, fd
))
5265 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5268 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5269 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5271 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5272 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5274 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5278 if (!strcmp(device
, "socket")) {
5279 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5281 fd
= strtol(buf
, NULL
, 0);
5283 if (net_socket_fd_init(vlan
, fd
, 1))
5285 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5286 ret
= net_socket_listen_init(vlan
, buf
);
5287 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5288 ret
= net_socket_connect_init(vlan
, buf
);
5289 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5290 ret
= net_socket_mcast_init(vlan
, buf
);
5292 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5295 vlan
->nb_host_devs
++;
5298 if (!strcmp(device
, "vde")) {
5299 char vde_sock
[1024], vde_group
[512];
5300 int vde_port
, vde_mode
;
5301 vlan
->nb_host_devs
++;
5302 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5305 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5306 vde_port
= strtol(buf
, NULL
, 10);
5310 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5311 vde_group
[0] = '\0';
5313 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5314 vde_mode
= strtol(buf
, NULL
, 8);
5318 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5322 fprintf(stderr
, "Unknown network device: %s\n", device
);
5326 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5332 static int net_client_parse(const char *str
)
5340 while (*p
!= '\0' && *p
!= ',') {
5341 if ((q
- device
) < sizeof(device
) - 1)
5349 return net_client_init(device
, p
);
5352 void do_info_network(void)
5355 VLANClientState
*vc
;
5357 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5358 term_printf("VLAN %d devices:\n", vlan
->id
);
5359 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5360 term_printf(" %s\n", vc
->info_str
);
5364 #define HD_ALIAS "index=%d,media=disk"
5366 #define CDROM_ALIAS "index=1,media=cdrom"
5368 #define CDROM_ALIAS "index=2,media=cdrom"
5370 #define FD_ALIAS "index=%d,if=floppy"
5371 #define PFLASH_ALIAS "if=pflash"
5372 #define MTD_ALIAS "if=mtd"
5373 #define SD_ALIAS "index=0,if=sd"
5375 static int drive_add(const char *file
, const char *fmt
, ...)
5379 if (nb_drives_opt
>= MAX_DRIVES
) {
5380 fprintf(stderr
, "qemu: too many drives\n");
5384 drives_opt
[nb_drives_opt
].file
= file
;
5386 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5387 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5390 return nb_drives_opt
++;
5393 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5397 /* seek interface, bus and unit */
5399 for (index
= 0; index
< nb_drives
; index
++)
5400 if (drives_table
[index
].type
== type
&&
5401 drives_table
[index
].bus
== bus
&&
5402 drives_table
[index
].unit
== unit
)
5408 int drive_get_max_bus(BlockInterfaceType type
)
5414 for (index
= 0; index
< nb_drives
; index
++) {
5415 if(drives_table
[index
].type
== type
&&
5416 drives_table
[index
].bus
> max_bus
)
5417 max_bus
= drives_table
[index
].bus
;
5422 static void bdrv_format_print(void *opaque
, const char *name
)
5424 fprintf(stderr
, " %s", name
);
5427 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5428 QEMUMachine
*machine
)
5433 const char *mediastr
= "";
5434 BlockInterfaceType type
;
5435 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5436 int bus_id
, unit_id
;
5437 int cyls
, heads
, secs
, translation
;
5438 BlockDriverState
*bdrv
;
5439 BlockDriver
*drv
= NULL
;
5444 char *str
= arg
->opt
;
5445 static const char * const params
[] = { "bus", "unit", "if", "index",
5446 "cyls", "heads", "secs", "trans",
5447 "media", "snapshot", "file",
5448 "cache", "format", NULL
};
5450 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5451 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5457 cyls
= heads
= secs
= 0;
5460 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5464 if (machine
->use_scsi
) {
5466 max_devs
= MAX_SCSI_DEVS
;
5467 pstrcpy(devname
, sizeof(devname
), "scsi");
5470 max_devs
= MAX_IDE_DEVS
;
5471 pstrcpy(devname
, sizeof(devname
), "ide");
5475 /* extract parameters */
5477 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5478 bus_id
= strtol(buf
, NULL
, 0);
5480 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5485 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5486 unit_id
= strtol(buf
, NULL
, 0);
5488 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5493 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5494 pstrcpy(devname
, sizeof(devname
), buf
);
5495 if (!strcmp(buf
, "ide")) {
5497 max_devs
= MAX_IDE_DEVS
;
5498 } else if (!strcmp(buf
, "scsi")) {
5500 max_devs
= MAX_SCSI_DEVS
;
5501 } else if (!strcmp(buf
, "floppy")) {
5504 } else if (!strcmp(buf
, "pflash")) {
5507 } else if (!strcmp(buf
, "mtd")) {
5510 } else if (!strcmp(buf
, "sd")) {
5514 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5519 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5520 index
= strtol(buf
, NULL
, 0);
5522 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5527 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5528 cyls
= strtol(buf
, NULL
, 0);
5531 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5532 heads
= strtol(buf
, NULL
, 0);
5535 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5536 secs
= strtol(buf
, NULL
, 0);
5539 if (cyls
|| heads
|| secs
) {
5540 if (cyls
< 1 || cyls
> 16383) {
5541 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5544 if (heads
< 1 || heads
> 16) {
5545 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5548 if (secs
< 1 || secs
> 63) {
5549 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5554 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5557 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5561 if (!strcmp(buf
, "none"))
5562 translation
= BIOS_ATA_TRANSLATION_NONE
;
5563 else if (!strcmp(buf
, "lba"))
5564 translation
= BIOS_ATA_TRANSLATION_LBA
;
5565 else if (!strcmp(buf
, "auto"))
5566 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5568 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5573 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5574 if (!strcmp(buf
, "disk")) {
5576 } else if (!strcmp(buf
, "cdrom")) {
5577 if (cyls
|| secs
|| heads
) {
5579 "qemu: '%s' invalid physical CHS format\n", str
);
5582 media
= MEDIA_CDROM
;
5584 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5589 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5590 if (!strcmp(buf
, "on"))
5592 else if (!strcmp(buf
, "off"))
5595 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5600 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5601 if (!strcmp(buf
, "off"))
5603 else if (!strcmp(buf
, "on"))
5606 fprintf(stderr
, "qemu: invalid cache option\n");
5611 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5612 if (strcmp(buf
, "?") == 0) {
5613 fprintf(stderr
, "qemu: Supported formats:");
5614 bdrv_iterate_format(bdrv_format_print
, NULL
);
5615 fprintf(stderr
, "\n");
5618 drv
= bdrv_find_format(buf
);
5620 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5625 if (arg
->file
== NULL
)
5626 get_param_value(file
, sizeof(file
), "file", str
);
5628 pstrcpy(file
, sizeof(file
), arg
->file
);
5630 /* compute bus and unit according index */
5633 if (bus_id
!= 0 || unit_id
!= -1) {
5635 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5643 unit_id
= index
% max_devs
;
5644 bus_id
= index
/ max_devs
;
5648 /* if user doesn't specify a unit_id,
5649 * try to find the first free
5652 if (unit_id
== -1) {
5654 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5656 if (max_devs
&& unit_id
>= max_devs
) {
5657 unit_id
-= max_devs
;
5665 if (max_devs
&& unit_id
>= max_devs
) {
5666 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5667 str
, unit_id
, max_devs
- 1);
5672 * ignore multiple definitions
5675 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5680 if (type
== IF_IDE
|| type
== IF_SCSI
)
5681 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5683 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5684 devname
, bus_id
, mediastr
, unit_id
);
5686 snprintf(buf
, sizeof(buf
), "%s%s%i",
5687 devname
, mediastr
, unit_id
);
5688 bdrv
= bdrv_new(buf
);
5689 drives_table
[nb_drives
].bdrv
= bdrv
;
5690 drives_table
[nb_drives
].type
= type
;
5691 drives_table
[nb_drives
].bus
= bus_id
;
5692 drives_table
[nb_drives
].unit
= unit_id
;
5701 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5702 bdrv_set_translation_hint(bdrv
, translation
);
5706 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5711 /* FIXME: This isn't really a floppy, but it's a reasonable
5714 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5724 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5726 bdrv_flags
|= BDRV_O_DIRECT
;
5727 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5728 fprintf(stderr
, "qemu: could not open disk image %s\n",
5735 /***********************************************************/
5738 static USBPort
*used_usb_ports
;
5739 static USBPort
*free_usb_ports
;
5741 /* ??? Maybe change this to register a hub to keep track of the topology. */
5742 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5743 usb_attachfn attach
)
5745 port
->opaque
= opaque
;
5746 port
->index
= index
;
5747 port
->attach
= attach
;
5748 port
->next
= free_usb_ports
;
5749 free_usb_ports
= port
;
5752 int usb_device_add_dev(USBDevice
*dev
)
5756 /* Find a USB port to add the device to. */
5757 port
= free_usb_ports
;
5761 /* Create a new hub and chain it on. */
5762 free_usb_ports
= NULL
;
5763 port
->next
= used_usb_ports
;
5764 used_usb_ports
= port
;
5766 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5767 usb_attach(port
, hub
);
5768 port
= free_usb_ports
;
5771 free_usb_ports
= port
->next
;
5772 port
->next
= used_usb_ports
;
5773 used_usb_ports
= port
;
5774 usb_attach(port
, dev
);
5778 static int usb_device_add(const char *devname
)
5783 if (!free_usb_ports
)
5786 if (strstart(devname
, "host:", &p
)) {
5787 dev
= usb_host_device_open(p
);
5788 } else if (!strcmp(devname
, "mouse")) {
5789 dev
= usb_mouse_init();
5790 } else if (!strcmp(devname
, "tablet")) {
5791 dev
= usb_tablet_init();
5792 } else if (!strcmp(devname
, "keyboard")) {
5793 dev
= usb_keyboard_init();
5794 } else if (strstart(devname
, "disk:", &p
)) {
5795 dev
= usb_msd_init(p
);
5796 } else if (!strcmp(devname
, "wacom-tablet")) {
5797 dev
= usb_wacom_init();
5798 } else if (strstart(devname
, "serial:", &p
)) {
5799 dev
= usb_serial_init(p
);
5800 #ifdef CONFIG_BRLAPI
5801 } else if (!strcmp(devname
, "braille")) {
5802 dev
= usb_baum_init();
5804 } else if (strstart(devname
, "net:", &p
)) {
5807 if (net_client_init("nic", p
) < 0)
5809 nd_table
[nic
].model
= "usb";
5810 dev
= usb_net_init(&nd_table
[nic
]);
5817 return usb_device_add_dev(dev
);
5820 int usb_device_del_addr(int bus_num
, int addr
)
5826 if (!used_usb_ports
)
5832 lastp
= &used_usb_ports
;
5833 port
= used_usb_ports
;
5834 while (port
&& port
->dev
->addr
!= addr
) {
5835 lastp
= &port
->next
;
5843 *lastp
= port
->next
;
5844 usb_attach(port
, NULL
);
5845 dev
->handle_destroy(dev
);
5846 port
->next
= free_usb_ports
;
5847 free_usb_ports
= port
;
5851 static int usb_device_del(const char *devname
)
5856 if (strstart(devname
, "host:", &p
))
5857 return usb_host_device_close(p
);
5859 if (!used_usb_ports
)
5862 p
= strchr(devname
, '.');
5865 bus_num
= strtoul(devname
, NULL
, 0);
5866 addr
= strtoul(p
+ 1, NULL
, 0);
5868 return usb_device_del_addr(bus_num
, addr
);
5871 void do_usb_add(const char *devname
)
5873 usb_device_add(devname
);
5876 void do_usb_del(const char *devname
)
5878 usb_device_del(devname
);
5885 const char *speed_str
;
5888 term_printf("USB support not enabled\n");
5892 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5896 switch(dev
->speed
) {
5900 case USB_SPEED_FULL
:
5903 case USB_SPEED_HIGH
:
5910 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5911 0, dev
->addr
, speed_str
, dev
->devname
);
5915 /***********************************************************/
5916 /* PCMCIA/Cardbus */
5918 static struct pcmcia_socket_entry_s
{
5919 struct pcmcia_socket_s
*socket
;
5920 struct pcmcia_socket_entry_s
*next
;
5921 } *pcmcia_sockets
= 0;
5923 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5925 struct pcmcia_socket_entry_s
*entry
;
5927 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5928 entry
->socket
= socket
;
5929 entry
->next
= pcmcia_sockets
;
5930 pcmcia_sockets
= entry
;
5933 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5935 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5937 ptr
= &pcmcia_sockets
;
5938 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5939 if (entry
->socket
== socket
) {
5945 void pcmcia_info(void)
5947 struct pcmcia_socket_entry_s
*iter
;
5948 if (!pcmcia_sockets
)
5949 term_printf("No PCMCIA sockets\n");
5951 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5952 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5953 iter
->socket
->attached
? iter
->socket
->card_string
:
5957 /***********************************************************/
5960 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5964 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5968 static void dumb_refresh(DisplayState
*ds
)
5970 #if defined(CONFIG_SDL)
5975 static void dumb_display_init(DisplayState
*ds
)
5980 ds
->dpy_update
= dumb_update
;
5981 ds
->dpy_resize
= dumb_resize
;
5982 ds
->dpy_refresh
= dumb_refresh
;
5983 ds
->gui_timer_interval
= 500;
5987 /***********************************************************/
5990 #define MAX_IO_HANDLERS 64
5992 typedef struct IOHandlerRecord
{
5994 IOCanRWHandler
*fd_read_poll
;
5996 IOHandler
*fd_write
;
5999 /* temporary data */
6001 struct IOHandlerRecord
*next
;
6004 static IOHandlerRecord
*first_io_handler
;
6006 /* XXX: fd_read_poll should be suppressed, but an API change is
6007 necessary in the character devices to suppress fd_can_read(). */
6008 int qemu_set_fd_handler2(int fd
,
6009 IOCanRWHandler
*fd_read_poll
,
6011 IOHandler
*fd_write
,
6014 IOHandlerRecord
**pioh
, *ioh
;
6016 if (!fd_read
&& !fd_write
) {
6017 pioh
= &first_io_handler
;
6022 if (ioh
->fd
== fd
) {
6029 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6033 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6036 ioh
->next
= first_io_handler
;
6037 first_io_handler
= ioh
;
6040 ioh
->fd_read_poll
= fd_read_poll
;
6041 ioh
->fd_read
= fd_read
;
6042 ioh
->fd_write
= fd_write
;
6043 ioh
->opaque
= opaque
;
6049 int qemu_set_fd_handler(int fd
,
6051 IOHandler
*fd_write
,
6054 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6057 /***********************************************************/
6058 /* Polling handling */
6060 typedef struct PollingEntry
{
6063 struct PollingEntry
*next
;
6066 static PollingEntry
*first_polling_entry
;
6068 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6070 PollingEntry
**ppe
, *pe
;
6071 pe
= qemu_mallocz(sizeof(PollingEntry
));
6075 pe
->opaque
= opaque
;
6076 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6081 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6083 PollingEntry
**ppe
, *pe
;
6084 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6086 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6095 /***********************************************************/
6096 /* Wait objects support */
6097 typedef struct WaitObjects
{
6099 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6100 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6101 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6104 static WaitObjects wait_objects
= {0};
6106 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6108 WaitObjects
*w
= &wait_objects
;
6110 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6112 w
->events
[w
->num
] = handle
;
6113 w
->func
[w
->num
] = func
;
6114 w
->opaque
[w
->num
] = opaque
;
6119 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6122 WaitObjects
*w
= &wait_objects
;
6125 for (i
= 0; i
< w
->num
; i
++) {
6126 if (w
->events
[i
] == handle
)
6129 w
->events
[i
] = w
->events
[i
+ 1];
6130 w
->func
[i
] = w
->func
[i
+ 1];
6131 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6139 /***********************************************************/
6140 /* savevm/loadvm support */
6142 #define IO_BUF_SIZE 32768
6146 BlockDriverState
*bs
;
6149 int64_t base_offset
;
6150 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6153 int buf_size
; /* 0 when writing */
6154 uint8_t buf
[IO_BUF_SIZE
];
6157 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6161 f
= qemu_mallocz(sizeof(QEMUFile
));
6164 if (!strcmp(mode
, "wb")) {
6166 } else if (!strcmp(mode
, "rb")) {
6171 f
->outfile
= fopen(filename
, mode
);
6183 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6187 f
= qemu_mallocz(sizeof(QEMUFile
));
6192 f
->is_writable
= is_writable
;
6193 f
->base_offset
= offset
;
6197 void qemu_fflush(QEMUFile
*f
)
6199 if (!f
->is_writable
)
6201 if (f
->buf_index
> 0) {
6203 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6204 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6206 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6207 f
->buf
, f
->buf_index
);
6209 f
->buf_offset
+= f
->buf_index
;
6214 static void qemu_fill_buffer(QEMUFile
*f
)
6221 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6222 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6226 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6227 f
->buf
, IO_BUF_SIZE
);
6233 f
->buf_offset
+= len
;
6236 void qemu_fclose(QEMUFile
*f
)
6246 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6250 l
= IO_BUF_SIZE
- f
->buf_index
;
6253 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6257 if (f
->buf_index
>= IO_BUF_SIZE
)
6262 void qemu_put_byte(QEMUFile
*f
, int v
)
6264 f
->buf
[f
->buf_index
++] = v
;
6265 if (f
->buf_index
>= IO_BUF_SIZE
)
6269 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6275 l
= f
->buf_size
- f
->buf_index
;
6277 qemu_fill_buffer(f
);
6278 l
= f
->buf_size
- f
->buf_index
;
6284 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6289 return size1
- size
;
6292 int qemu_get_byte(QEMUFile
*f
)
6294 if (f
->buf_index
>= f
->buf_size
) {
6295 qemu_fill_buffer(f
);
6296 if (f
->buf_index
>= f
->buf_size
)
6299 return f
->buf
[f
->buf_index
++];
6302 int64_t qemu_ftell(QEMUFile
*f
)
6304 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6307 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6309 if (whence
== SEEK_SET
) {
6311 } else if (whence
== SEEK_CUR
) {
6312 pos
+= qemu_ftell(f
);
6314 /* SEEK_END not supported */
6317 if (f
->is_writable
) {
6319 f
->buf_offset
= pos
;
6321 f
->buf_offset
= pos
;
6328 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6330 qemu_put_byte(f
, v
>> 8);
6331 qemu_put_byte(f
, v
);
6334 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6336 qemu_put_byte(f
, v
>> 24);
6337 qemu_put_byte(f
, v
>> 16);
6338 qemu_put_byte(f
, v
>> 8);
6339 qemu_put_byte(f
, v
);
6342 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6344 qemu_put_be32(f
, v
>> 32);
6345 qemu_put_be32(f
, v
);
6348 unsigned int qemu_get_be16(QEMUFile
*f
)
6351 v
= qemu_get_byte(f
) << 8;
6352 v
|= qemu_get_byte(f
);
6356 unsigned int qemu_get_be32(QEMUFile
*f
)
6359 v
= qemu_get_byte(f
) << 24;
6360 v
|= qemu_get_byte(f
) << 16;
6361 v
|= qemu_get_byte(f
) << 8;
6362 v
|= qemu_get_byte(f
);
6366 uint64_t qemu_get_be64(QEMUFile
*f
)
6369 v
= (uint64_t)qemu_get_be32(f
) << 32;
6370 v
|= qemu_get_be32(f
);
6374 typedef struct SaveStateEntry
{
6378 SaveStateHandler
*save_state
;
6379 LoadStateHandler
*load_state
;
6381 struct SaveStateEntry
*next
;
6384 static SaveStateEntry
*first_se
;
6386 /* TODO: Individual devices generally have very little idea about the rest
6387 of the system, so instance_id should be removed/replaced.
6388 Meanwhile pass -1 as instance_id if you do not already have a clearly
6389 distinguishing id for all instances of your device class. */
6390 int register_savevm(const char *idstr
,
6393 SaveStateHandler
*save_state
,
6394 LoadStateHandler
*load_state
,
6397 SaveStateEntry
*se
, **pse
;
6399 se
= qemu_malloc(sizeof(SaveStateEntry
));
6402 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6403 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6404 se
->version_id
= version_id
;
6405 se
->save_state
= save_state
;
6406 se
->load_state
= load_state
;
6407 se
->opaque
= opaque
;
6410 /* add at the end of list */
6412 while (*pse
!= NULL
) {
6413 if (instance_id
== -1
6414 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6415 && se
->instance_id
<= (*pse
)->instance_id
)
6416 se
->instance_id
= (*pse
)->instance_id
+ 1;
6417 pse
= &(*pse
)->next
;
6423 #define QEMU_VM_FILE_MAGIC 0x5145564d
6424 #define QEMU_VM_FILE_VERSION 0x00000002
6426 static int qemu_savevm_state(QEMUFile
*f
)
6430 int64_t cur_pos
, len_pos
, total_len_pos
;
6432 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6433 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6434 total_len_pos
= qemu_ftell(f
);
6435 qemu_put_be64(f
, 0); /* total size */
6437 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6438 if (se
->save_state
== NULL
)
6439 /* this one has a loader only, for backwards compatibility */
6443 len
= strlen(se
->idstr
);
6444 qemu_put_byte(f
, len
);
6445 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6447 qemu_put_be32(f
, se
->instance_id
);
6448 qemu_put_be32(f
, se
->version_id
);
6450 /* record size: filled later */
6451 len_pos
= qemu_ftell(f
);
6452 qemu_put_be32(f
, 0);
6453 se
->save_state(f
, se
->opaque
);
6455 /* fill record size */
6456 cur_pos
= qemu_ftell(f
);
6457 len
= cur_pos
- len_pos
- 4;
6458 qemu_fseek(f
, len_pos
, SEEK_SET
);
6459 qemu_put_be32(f
, len
);
6460 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6462 cur_pos
= qemu_ftell(f
);
6463 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6464 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6465 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6471 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6475 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6476 if (!strcmp(se
->idstr
, idstr
) &&
6477 instance_id
== se
->instance_id
)
6483 static int qemu_loadvm_state(QEMUFile
*f
)
6486 int len
, ret
, instance_id
, record_len
, version_id
;
6487 int64_t total_len
, end_pos
, cur_pos
;
6491 v
= qemu_get_be32(f
);
6492 if (v
!= QEMU_VM_FILE_MAGIC
)
6494 v
= qemu_get_be32(f
);
6495 if (v
!= QEMU_VM_FILE_VERSION
) {
6500 total_len
= qemu_get_be64(f
);
6501 end_pos
= total_len
+ qemu_ftell(f
);
6503 if (qemu_ftell(f
) >= end_pos
)
6505 len
= qemu_get_byte(f
);
6506 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6508 instance_id
= qemu_get_be32(f
);
6509 version_id
= qemu_get_be32(f
);
6510 record_len
= qemu_get_be32(f
);
6512 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6513 idstr
, instance_id
, version_id
, record_len
);
6515 cur_pos
= qemu_ftell(f
);
6516 se
= find_se(idstr
, instance_id
);
6518 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6519 instance_id
, idstr
);
6521 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6523 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6524 instance_id
, idstr
);
6527 /* always seek to exact end of record */
6528 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6535 /* device can contain snapshots */
6536 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6539 !bdrv_is_removable(bs
) &&
6540 !bdrv_is_read_only(bs
));
6543 /* device must be snapshots in order to have a reliable snapshot */
6544 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6547 !bdrv_is_removable(bs
) &&
6548 !bdrv_is_read_only(bs
));
6551 static BlockDriverState
*get_bs_snapshots(void)
6553 BlockDriverState
*bs
;
6557 return bs_snapshots
;
6558 for(i
= 0; i
<= nb_drives
; i
++) {
6559 bs
= drives_table
[i
].bdrv
;
6560 if (bdrv_can_snapshot(bs
))
6569 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6572 QEMUSnapshotInfo
*sn_tab
, *sn
;
6576 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6579 for(i
= 0; i
< nb_sns
; i
++) {
6581 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6591 void do_savevm(const char *name
)
6593 BlockDriverState
*bs
, *bs1
;
6594 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6595 int must_delete
, ret
, i
;
6596 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6598 int saved_vm_running
;
6605 bs
= get_bs_snapshots();
6607 term_printf("No block device can accept snapshots\n");
6611 /* ??? Should this occur after vm_stop? */
6614 saved_vm_running
= vm_running
;
6619 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6624 memset(sn
, 0, sizeof(*sn
));
6626 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6627 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6630 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6633 /* fill auxiliary fields */
6636 sn
->date_sec
= tb
.time
;
6637 sn
->date_nsec
= tb
.millitm
* 1000000;
6639 gettimeofday(&tv
, NULL
);
6640 sn
->date_sec
= tv
.tv_sec
;
6641 sn
->date_nsec
= tv
.tv_usec
* 1000;
6643 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6645 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6646 term_printf("Device %s does not support VM state snapshots\n",
6647 bdrv_get_device_name(bs
));
6651 /* save the VM state */
6652 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6654 term_printf("Could not open VM state file\n");
6657 ret
= qemu_savevm_state(f
);
6658 sn
->vm_state_size
= qemu_ftell(f
);
6661 term_printf("Error %d while writing VM\n", ret
);
6665 /* create the snapshots */
6667 for(i
= 0; i
< nb_drives
; i
++) {
6668 bs1
= drives_table
[i
].bdrv
;
6669 if (bdrv_has_snapshot(bs1
)) {
6671 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6673 term_printf("Error while deleting snapshot on '%s'\n",
6674 bdrv_get_device_name(bs1
));
6677 ret
= bdrv_snapshot_create(bs1
, sn
);
6679 term_printf("Error while creating snapshot on '%s'\n",
6680 bdrv_get_device_name(bs1
));
6686 if (saved_vm_running
)
6690 void do_loadvm(const char *name
)
6692 BlockDriverState
*bs
, *bs1
;
6693 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6696 int saved_vm_running
;
6698 bs
= get_bs_snapshots();
6700 term_printf("No block device supports snapshots\n");
6704 /* Flush all IO requests so they don't interfere with the new state. */
6707 saved_vm_running
= vm_running
;
6710 for(i
= 0; i
<= nb_drives
; i
++) {
6711 bs1
= drives_table
[i
].bdrv
;
6712 if (bdrv_has_snapshot(bs1
)) {
6713 ret
= bdrv_snapshot_goto(bs1
, name
);
6716 term_printf("Warning: ");
6719 term_printf("Snapshots not supported on device '%s'\n",
6720 bdrv_get_device_name(bs1
));
6723 term_printf("Could not find snapshot '%s' on device '%s'\n",
6724 name
, bdrv_get_device_name(bs1
));
6727 term_printf("Error %d while activating snapshot on '%s'\n",
6728 ret
, bdrv_get_device_name(bs1
));
6731 /* fatal on snapshot block device */
6738 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6739 term_printf("Device %s does not support VM state snapshots\n",
6740 bdrv_get_device_name(bs
));
6744 /* restore the VM state */
6745 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6747 term_printf("Could not open VM state file\n");
6750 ret
= qemu_loadvm_state(f
);
6753 term_printf("Error %d while loading VM state\n", ret
);
6756 if (saved_vm_running
)
6760 void do_delvm(const char *name
)
6762 BlockDriverState
*bs
, *bs1
;
6765 bs
= get_bs_snapshots();
6767 term_printf("No block device supports snapshots\n");
6771 for(i
= 0; i
<= nb_drives
; i
++) {
6772 bs1
= drives_table
[i
].bdrv
;
6773 if (bdrv_has_snapshot(bs1
)) {
6774 ret
= bdrv_snapshot_delete(bs1
, name
);
6776 if (ret
== -ENOTSUP
)
6777 term_printf("Snapshots not supported on device '%s'\n",
6778 bdrv_get_device_name(bs1
));
6780 term_printf("Error %d while deleting snapshot on '%s'\n",
6781 ret
, bdrv_get_device_name(bs1
));
6787 void do_info_snapshots(void)
6789 BlockDriverState
*bs
, *bs1
;
6790 QEMUSnapshotInfo
*sn_tab
, *sn
;
6794 bs
= get_bs_snapshots();
6796 term_printf("No available block device supports snapshots\n");
6799 term_printf("Snapshot devices:");
6800 for(i
= 0; i
<= nb_drives
; i
++) {
6801 bs1
= drives_table
[i
].bdrv
;
6802 if (bdrv_has_snapshot(bs1
)) {
6804 term_printf(" %s", bdrv_get_device_name(bs1
));
6809 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6811 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6814 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6815 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6816 for(i
= 0; i
< nb_sns
; i
++) {
6818 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6823 /***********************************************************/
6824 /* ram save/restore */
6826 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6830 v
= qemu_get_byte(f
);
6833 if (qemu_get_buffer(f
, buf
, len
) != len
)
6837 v
= qemu_get_byte(f
);
6838 memset(buf
, v
, len
);
6846 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6851 if (qemu_get_be32(f
) != phys_ram_size
)
6853 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6854 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6861 #define BDRV_HASH_BLOCK_SIZE 1024
6862 #define IOBUF_SIZE 4096
6863 #define RAM_CBLOCK_MAGIC 0xfabe
6865 typedef struct RamCompressState
{
6868 uint8_t buf
[IOBUF_SIZE
];
6871 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6874 memset(s
, 0, sizeof(*s
));
6876 ret
= deflateInit2(&s
->zstream
, 1,
6878 9, Z_DEFAULT_STRATEGY
);
6881 s
->zstream
.avail_out
= IOBUF_SIZE
;
6882 s
->zstream
.next_out
= s
->buf
;
6886 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6888 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6889 qemu_put_be16(s
->f
, len
);
6890 qemu_put_buffer(s
->f
, buf
, len
);
6893 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6897 s
->zstream
.avail_in
= len
;
6898 s
->zstream
.next_in
= (uint8_t *)buf
;
6899 while (s
->zstream
.avail_in
> 0) {
6900 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6903 if (s
->zstream
.avail_out
== 0) {
6904 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6905 s
->zstream
.avail_out
= IOBUF_SIZE
;
6906 s
->zstream
.next_out
= s
->buf
;
6912 static void ram_compress_close(RamCompressState
*s
)
6916 /* compress last bytes */
6918 ret
= deflate(&s
->zstream
, Z_FINISH
);
6919 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6920 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6922 ram_put_cblock(s
, s
->buf
, len
);
6924 s
->zstream
.avail_out
= IOBUF_SIZE
;
6925 s
->zstream
.next_out
= s
->buf
;
6926 if (ret
== Z_STREAM_END
)
6933 deflateEnd(&s
->zstream
);
6936 typedef struct RamDecompressState
{
6939 uint8_t buf
[IOBUF_SIZE
];
6940 } RamDecompressState
;
6942 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6945 memset(s
, 0, sizeof(*s
));
6947 ret
= inflateInit(&s
->zstream
);
6953 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6957 s
->zstream
.avail_out
= len
;
6958 s
->zstream
.next_out
= buf
;
6959 while (s
->zstream
.avail_out
> 0) {
6960 if (s
->zstream
.avail_in
== 0) {
6961 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6963 clen
= qemu_get_be16(s
->f
);
6964 if (clen
> IOBUF_SIZE
)
6966 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6967 s
->zstream
.avail_in
= clen
;
6968 s
->zstream
.next_in
= s
->buf
;
6970 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6971 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6978 static void ram_decompress_close(RamDecompressState
*s
)
6980 inflateEnd(&s
->zstream
);
6983 static void ram_save(QEMUFile
*f
, void *opaque
)
6986 RamCompressState s1
, *s
= &s1
;
6989 qemu_put_be32(f
, phys_ram_size
);
6990 if (ram_compress_open(s
, f
) < 0)
6992 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6994 if (tight_savevm_enabled
) {
6998 /* find if the memory block is available on a virtual
7001 for(j
= 0; j
< nb_drives
; j
++) {
7002 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7004 BDRV_HASH_BLOCK_SIZE
);
7005 if (sector_num
>= 0)
7009 goto normal_compress
;
7012 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7013 ram_compress_buf(s
, buf
, 10);
7019 ram_compress_buf(s
, buf
, 1);
7020 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7023 ram_compress_close(s
);
7026 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7028 RamDecompressState s1
, *s
= &s1
;
7032 if (version_id
== 1)
7033 return ram_load_v1(f
, opaque
);
7034 if (version_id
!= 2)
7036 if (qemu_get_be32(f
) != phys_ram_size
)
7038 if (ram_decompress_open(s
, f
) < 0)
7040 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7041 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7042 fprintf(stderr
, "Error while reading ram block header\n");
7046 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7047 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7056 ram_decompress_buf(s
, buf
+ 1, 9);
7058 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7059 if (bs_index
>= nb_drives
) {
7060 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7063 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7065 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7066 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7067 bs_index
, sector_num
);
7074 printf("Error block header\n");
7078 ram_decompress_close(s
);
7082 /***********************************************************/
7083 /* bottom halves (can be seen as timers which expire ASAP) */
7092 static QEMUBH
*first_bh
= NULL
;
7094 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7097 bh
= qemu_mallocz(sizeof(QEMUBH
));
7101 bh
->opaque
= opaque
;
7105 int qemu_bh_poll(void)
7124 void qemu_bh_schedule(QEMUBH
*bh
)
7126 CPUState
*env
= cpu_single_env
;
7130 bh
->next
= first_bh
;
7133 /* stop the currently executing CPU to execute the BH ASAP */
7135 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7139 void qemu_bh_cancel(QEMUBH
*bh
)
7142 if (bh
->scheduled
) {
7145 pbh
= &(*pbh
)->next
;
7151 void qemu_bh_delete(QEMUBH
*bh
)
7157 /***********************************************************/
7158 /* machine registration */
7160 QEMUMachine
*first_machine
= NULL
;
7162 int qemu_register_machine(QEMUMachine
*m
)
7165 pm
= &first_machine
;
7173 static QEMUMachine
*find_machine(const char *name
)
7177 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7178 if (!strcmp(m
->name
, name
))
7184 /***********************************************************/
7185 /* main execution loop */
7187 static void gui_update(void *opaque
)
7189 DisplayState
*ds
= opaque
;
7190 ds
->dpy_refresh(ds
);
7191 qemu_mod_timer(ds
->gui_timer
,
7192 (ds
->gui_timer_interval
?
7193 ds
->gui_timer_interval
:
7194 GUI_REFRESH_INTERVAL
)
7195 + qemu_get_clock(rt_clock
));
7198 struct vm_change_state_entry
{
7199 VMChangeStateHandler
*cb
;
7201 LIST_ENTRY (vm_change_state_entry
) entries
;
7204 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7206 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7209 VMChangeStateEntry
*e
;
7211 e
= qemu_mallocz(sizeof (*e
));
7217 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7221 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7223 LIST_REMOVE (e
, entries
);
7227 static void vm_state_notify(int running
)
7229 VMChangeStateEntry
*e
;
7231 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7232 e
->cb(e
->opaque
, running
);
7236 /* XXX: support several handlers */
7237 static VMStopHandler
*vm_stop_cb
;
7238 static void *vm_stop_opaque
;
7240 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7243 vm_stop_opaque
= opaque
;
7247 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7258 qemu_rearm_alarm_timer(alarm_timer
);
7262 void vm_stop(int reason
)
7265 cpu_disable_ticks();
7269 vm_stop_cb(vm_stop_opaque
, reason
);
7276 /* reset/shutdown handler */
7278 typedef struct QEMUResetEntry
{
7279 QEMUResetHandler
*func
;
7281 struct QEMUResetEntry
*next
;
7284 static QEMUResetEntry
*first_reset_entry
;
7285 static int reset_requested
;
7286 static int shutdown_requested
;
7287 static int powerdown_requested
;
7289 int qemu_shutdown_requested(void)
7291 int r
= shutdown_requested
;
7292 shutdown_requested
= 0;
7296 int qemu_reset_requested(void)
7298 int r
= reset_requested
;
7299 reset_requested
= 0;
7303 int qemu_powerdown_requested(void)
7305 int r
= powerdown_requested
;
7306 powerdown_requested
= 0;
7310 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7312 QEMUResetEntry
**pre
, *re
;
7314 pre
= &first_reset_entry
;
7315 while (*pre
!= NULL
)
7316 pre
= &(*pre
)->next
;
7317 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7319 re
->opaque
= opaque
;
7324 void qemu_system_reset(void)
7328 /* reset all devices */
7329 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7330 re
->func(re
->opaque
);
7334 void qemu_system_reset_request(void)
7337 shutdown_requested
= 1;
7339 reset_requested
= 1;
7342 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7345 void qemu_system_shutdown_request(void)
7347 shutdown_requested
= 1;
7349 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7352 void qemu_system_powerdown_request(void)
7354 powerdown_requested
= 1;
7356 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7359 void main_loop_wait(int timeout
)
7361 IOHandlerRecord
*ioh
;
7362 fd_set rfds
, wfds
, xfds
;
7371 /* XXX: need to suppress polling by better using win32 events */
7373 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7374 ret
|= pe
->func(pe
->opaque
);
7379 WaitObjects
*w
= &wait_objects
;
7381 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7382 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7383 if (w
->func
[ret
- WAIT_OBJECT_0
])
7384 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7386 /* Check for additional signaled events */
7387 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7389 /* Check if event is signaled */
7390 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7391 if(ret2
== WAIT_OBJECT_0
) {
7393 w
->func
[i
](w
->opaque
[i
]);
7394 } else if (ret2
== WAIT_TIMEOUT
) {
7396 err
= GetLastError();
7397 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7400 } else if (ret
== WAIT_TIMEOUT
) {
7402 err
= GetLastError();
7403 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7407 /* poll any events */
7408 /* XXX: separate device handlers from system ones */
7413 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7417 (!ioh
->fd_read_poll
||
7418 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7419 FD_SET(ioh
->fd
, &rfds
);
7423 if (ioh
->fd_write
) {
7424 FD_SET(ioh
->fd
, &wfds
);
7434 tv
.tv_usec
= timeout
* 1000;
7436 #if defined(CONFIG_SLIRP)
7438 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7441 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7443 IOHandlerRecord
**pioh
;
7445 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7446 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7447 ioh
->fd_read(ioh
->opaque
);
7449 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7450 ioh
->fd_write(ioh
->opaque
);
7454 /* remove deleted IO handlers */
7455 pioh
= &first_io_handler
;
7465 #if defined(CONFIG_SLIRP)
7472 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7477 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7478 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7479 qemu_get_clock(vm_clock
));
7480 /* run dma transfers, if any */
7484 /* real time timers */
7485 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7486 qemu_get_clock(rt_clock
));
7488 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7489 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7490 qemu_rearm_alarm_timer(alarm_timer
);
7493 /* Check bottom-halves last in case any of the earlier events triggered
7499 static int main_loop(void)
7502 #ifdef CONFIG_PROFILER
7507 cur_cpu
= first_cpu
;
7508 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7515 #ifdef CONFIG_PROFILER
7516 ti
= profile_getclock();
7521 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7522 env
->icount_decr
.u16
.low
= 0;
7523 env
->icount_extra
= 0;
7524 count
= qemu_next_deadline();
7525 count
= (count
+ (1 << icount_time_shift
) - 1)
7526 >> icount_time_shift
;
7527 qemu_icount
+= count
;
7528 decr
= (count
> 0xffff) ? 0xffff : count
;
7530 env
->icount_decr
.u16
.low
= decr
;
7531 env
->icount_extra
= count
;
7533 ret
= cpu_exec(env
);
7534 #ifdef CONFIG_PROFILER
7535 qemu_time
+= profile_getclock() - ti
;
7538 /* Fold pending instructions back into the
7539 instruction counter, and clear the interrupt flag. */
7540 qemu_icount
-= (env
->icount_decr
.u16
.low
7541 + env
->icount_extra
);
7542 env
->icount_decr
.u32
= 0;
7543 env
->icount_extra
= 0;
7545 next_cpu
= env
->next_cpu
?: first_cpu
;
7546 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7547 ret
= EXCP_INTERRUPT
;
7551 if (ret
== EXCP_HLT
) {
7552 /* Give the next CPU a chance to run. */
7556 if (ret
!= EXCP_HALTED
)
7558 /* all CPUs are halted ? */
7564 if (shutdown_requested
) {
7565 ret
= EXCP_INTERRUPT
;
7573 if (reset_requested
) {
7574 reset_requested
= 0;
7575 qemu_system_reset();
7576 ret
= EXCP_INTERRUPT
;
7578 if (powerdown_requested
) {
7579 powerdown_requested
= 0;
7580 qemu_system_powerdown();
7581 ret
= EXCP_INTERRUPT
;
7583 if (unlikely(ret
== EXCP_DEBUG
)) {
7584 vm_stop(EXCP_DEBUG
);
7586 /* If all cpus are halted then wait until the next IRQ */
7587 /* XXX: use timeout computed from timers */
7588 if (ret
== EXCP_HALTED
) {
7592 /* Advance virtual time to the next event. */
7593 if (use_icount
== 1) {
7594 /* When not using an adaptive execution frequency
7595 we tend to get badly out of sync with real time,
7596 so just delay for a reasonable amount of time. */
7599 delta
= cpu_get_icount() - cpu_get_clock();
7602 /* If virtual time is ahead of real time then just
7604 timeout
= (delta
/ 1000000) + 1;
7606 /* Wait for either IO to occur or the next
7608 add
= qemu_next_deadline();
7609 /* We advance the timer before checking for IO.
7610 Limit the amount we advance so that early IO
7611 activity won't get the guest too far ahead. */
7615 add
= (add
+ (1 << icount_time_shift
) - 1)
7616 >> icount_time_shift
;
7618 timeout
= delta
/ 1000000;
7629 if (shutdown_requested
)
7633 #ifdef CONFIG_PROFILER
7634 ti
= profile_getclock();
7636 main_loop_wait(timeout
);
7637 #ifdef CONFIG_PROFILER
7638 dev_time
+= profile_getclock() - ti
;
7641 cpu_disable_ticks();
7645 static void help(int exitcode
)
7647 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7648 "usage: %s [options] [disk_image]\n"
7650 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7652 "Standard options:\n"
7653 "-M machine select emulated machine (-M ? for list)\n"
7654 "-cpu cpu select CPU (-cpu ? for list)\n"
7655 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7656 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7657 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7658 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7659 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7660 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7661 " [,cache=on|off][,format=f]\n"
7662 " use 'file' as a drive image\n"
7663 "-mtdblock file use 'file' as on-board Flash memory image\n"
7664 "-sd file use 'file' as SecureDigital card image\n"
7665 "-pflash file use 'file' as a parallel flash image\n"
7666 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7667 "-snapshot write to temporary files instead of disk image files\n"
7669 "-no-frame open SDL window without a frame and window decorations\n"
7670 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7671 "-no-quit disable SDL window close capability\n"
7674 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7676 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7677 "-smp n set the number of CPUs to 'n' [default=1]\n"
7678 "-nographic disable graphical output and redirect serial I/Os to console\n"
7679 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7681 "-k language use keyboard layout (for example \"fr\" for French)\n"
7684 "-audio-help print list of audio drivers and their options\n"
7685 "-soundhw c1,... enable audio support\n"
7686 " and only specified sound cards (comma separated list)\n"
7687 " use -soundhw ? to get the list of supported cards\n"
7688 " use -soundhw all to enable all of them\n"
7690 "-vga [std|cirrus|vmware]\n"
7691 " select video card type\n"
7692 "-localtime set the real time clock to local time [default=utc]\n"
7693 "-full-screen start in full screen\n"
7695 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7697 "-usb enable the USB driver (will be the default soon)\n"
7698 "-usbdevice name add the host or guest USB device 'name'\n"
7699 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7700 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7702 "-name string set the name of the guest\n"
7703 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
7705 "Network options:\n"
7706 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7707 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7709 "-net user[,vlan=n][,hostname=host]\n"
7710 " connect the user mode network stack to VLAN 'n' and send\n"
7711 " hostname 'host' to DHCP clients\n"
7714 "-net tap[,vlan=n],ifname=name\n"
7715 " connect the host TAP network interface to VLAN 'n'\n"
7717 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7718 " connect the host TAP network interface to VLAN 'n' and use the\n"
7719 " network scripts 'file' (default=%s)\n"
7720 " and 'dfile' (default=%s);\n"
7721 " use '[down]script=no' to disable script execution;\n"
7722 " use 'fd=h' to connect to an already opened TAP interface\n"
7724 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7725 " connect the vlan 'n' to another VLAN using a socket connection\n"
7726 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7727 " connect the vlan 'n' to multicast maddr and port\n"
7729 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7730 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7731 " on host and listening for incoming connections on 'socketpath'.\n"
7732 " Use group 'groupname' and mode 'octalmode' to change default\n"
7733 " ownership and permissions for communication port.\n"
7735 "-net none use it alone to have zero network devices; if no -net option\n"
7736 " is provided, the default is '-net nic -net user'\n"
7739 "-tftp dir allow tftp access to files in dir [-net user]\n"
7740 "-bootp file advertise file in BOOTP replies\n"
7742 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7744 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7745 " redirect TCP or UDP connections from host to guest [-net user]\n"
7748 "Linux boot specific:\n"
7749 "-kernel bzImage use 'bzImage' as kernel image\n"
7750 "-append cmdline use 'cmdline' as kernel command line\n"
7751 "-initrd file use 'file' as initial ram disk\n"
7753 "Debug/Expert options:\n"
7754 "-monitor dev redirect the monitor to char device 'dev'\n"
7755 "-serial dev redirect the serial port to char device 'dev'\n"
7756 "-parallel dev redirect the parallel port to char device 'dev'\n"
7757 "-pidfile file Write PID to 'file'\n"
7758 "-S freeze CPU at startup (use 'c' to start execution)\n"
7759 "-s wait gdb connection to port\n"
7760 "-p port set gdb connection port [default=%s]\n"
7761 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7762 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7763 " translation (t=none or lba) (usually qemu can guess them)\n"
7764 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7766 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7767 "-no-kqemu disable KQEMU kernel module usage\n"
7770 "-no-acpi disable ACPI\n"
7772 #ifdef CONFIG_CURSES
7773 "-curses use a curses/ncurses interface instead of SDL\n"
7775 "-no-reboot exit instead of rebooting\n"
7776 "-no-shutdown stop before shutdown\n"
7777 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7778 "-vnc display start a VNC server on display\n"
7780 "-daemonize daemonize QEMU after initializing\n"
7782 "-option-rom rom load a file, rom, into the option ROM space\n"
7784 "-prom-env variable=value set OpenBIOS nvram variables\n"
7786 "-clock force the use of the given methods for timer alarm.\n"
7787 " To see what timers are available use -clock ?\n"
7788 "-startdate select initial date of the clock\n"
7789 "-icount [N|auto]\n"
7790 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7792 "During emulation, the following keys are useful:\n"
7793 "ctrl-alt-f toggle full screen\n"
7794 "ctrl-alt-n switch to virtual console 'n'\n"
7795 "ctrl-alt toggle mouse and keyboard grab\n"
7797 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7802 DEFAULT_NETWORK_SCRIPT
,
7803 DEFAULT_NETWORK_DOWN_SCRIPT
,
7805 DEFAULT_GDBSTUB_PORT
,
7810 #define HAS_ARG 0x0001
7825 QEMU_OPTION_mtdblock
,
7829 QEMU_OPTION_snapshot
,
7831 QEMU_OPTION_no_fd_bootchk
,
7834 QEMU_OPTION_nographic
,
7835 QEMU_OPTION_portrait
,
7837 QEMU_OPTION_audio_help
,
7838 QEMU_OPTION_soundhw
,
7859 QEMU_OPTION_localtime
,
7863 QEMU_OPTION_monitor
,
7865 QEMU_OPTION_parallel
,
7867 QEMU_OPTION_full_screen
,
7868 QEMU_OPTION_no_frame
,
7869 QEMU_OPTION_alt_grab
,
7870 QEMU_OPTION_no_quit
,
7871 QEMU_OPTION_pidfile
,
7872 QEMU_OPTION_no_kqemu
,
7873 QEMU_OPTION_kernel_kqemu
,
7874 QEMU_OPTION_win2k_hack
,
7876 QEMU_OPTION_usbdevice
,
7879 QEMU_OPTION_no_acpi
,
7881 QEMU_OPTION_no_reboot
,
7882 QEMU_OPTION_no_shutdown
,
7883 QEMU_OPTION_show_cursor
,
7884 QEMU_OPTION_daemonize
,
7885 QEMU_OPTION_option_rom
,
7886 QEMU_OPTION_semihosting
,
7888 QEMU_OPTION_prom_env
,
7889 QEMU_OPTION_old_param
,
7891 QEMU_OPTION_startdate
,
7892 QEMU_OPTION_tb_size
,
7897 typedef struct QEMUOption
{
7903 const QEMUOption qemu_options
[] = {
7904 { "h", 0, QEMU_OPTION_h
},
7905 { "help", 0, QEMU_OPTION_h
},
7907 { "M", HAS_ARG
, QEMU_OPTION_M
},
7908 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7909 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7910 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7911 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7912 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7913 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7914 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7915 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7916 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7917 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7918 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7919 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7920 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7921 { "snapshot", 0, QEMU_OPTION_snapshot
},
7923 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7925 { "m", HAS_ARG
, QEMU_OPTION_m
},
7926 { "nographic", 0, QEMU_OPTION_nographic
},
7927 { "portrait", 0, QEMU_OPTION_portrait
},
7928 { "k", HAS_ARG
, QEMU_OPTION_k
},
7930 { "audio-help", 0, QEMU_OPTION_audio_help
},
7931 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7934 { "net", HAS_ARG
, QEMU_OPTION_net
},
7936 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7937 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7939 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7941 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7944 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7945 { "append", HAS_ARG
, QEMU_OPTION_append
},
7946 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7948 { "S", 0, QEMU_OPTION_S
},
7949 { "s", 0, QEMU_OPTION_s
},
7950 { "p", HAS_ARG
, QEMU_OPTION_p
},
7951 { "d", HAS_ARG
, QEMU_OPTION_d
},
7952 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7953 { "L", HAS_ARG
, QEMU_OPTION_L
},
7954 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7956 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7957 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7959 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7960 { "g", 1, QEMU_OPTION_g
},
7962 { "localtime", 0, QEMU_OPTION_localtime
},
7963 { "vga", HAS_ARG
, QEMU_OPTION_vga
},
7964 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7965 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7966 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7967 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7968 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7969 { "full-screen", 0, QEMU_OPTION_full_screen
},
7971 { "no-frame", 0, QEMU_OPTION_no_frame
},
7972 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7973 { "no-quit", 0, QEMU_OPTION_no_quit
},
7975 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7976 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7977 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7978 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7979 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7980 #ifdef CONFIG_CURSES
7981 { "curses", 0, QEMU_OPTION_curses
},
7983 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
7985 /* temporary options */
7986 { "usb", 0, QEMU_OPTION_usb
},
7987 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7988 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7989 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7990 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7991 { "daemonize", 0, QEMU_OPTION_daemonize
},
7992 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7993 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7994 { "semihosting", 0, QEMU_OPTION_semihosting
},
7996 { "name", HAS_ARG
, QEMU_OPTION_name
},
7997 #if defined(TARGET_SPARC)
7998 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8000 #if defined(TARGET_ARM)
8001 { "old-param", 0, QEMU_OPTION_old_param
},
8003 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8004 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8005 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8006 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8010 /* password input */
8012 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8017 if (!bdrv_is_encrypted(bs
))
8020 term_printf("%s is encrypted.\n", name
);
8021 for(i
= 0; i
< 3; i
++) {
8022 monitor_readline("Password: ", 1, password
, sizeof(password
));
8023 if (bdrv_set_key(bs
, password
) == 0)
8025 term_printf("invalid password\n");
8030 static BlockDriverState
*get_bdrv(int index
)
8032 if (index
> nb_drives
)
8034 return drives_table
[index
].bdrv
;
8037 static void read_passwords(void)
8039 BlockDriverState
*bs
;
8042 for(i
= 0; i
< 6; i
++) {
8045 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8050 struct soundhw soundhw
[] = {
8051 #ifdef HAS_AUDIO_CHOICE
8052 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8058 { .init_isa
= pcspk_audio_init
}
8063 "Creative Sound Blaster 16",
8066 { .init_isa
= SB16_init
}
8069 #ifdef CONFIG_CS4231A
8075 { .init_isa
= cs4231a_init
}
8083 "Yamaha YMF262 (OPL3)",
8085 "Yamaha YM3812 (OPL2)",
8089 { .init_isa
= Adlib_init
}
8096 "Gravis Ultrasound GF1",
8099 { .init_isa
= GUS_init
}
8106 "Intel 82801AA AC97 Audio",
8109 { .init_pci
= ac97_init
}
8115 "ENSONIQ AudioPCI ES1370",
8118 { .init_pci
= es1370_init
}
8122 { NULL
, NULL
, 0, 0, { NULL
} }
8125 static void select_soundhw (const char *optarg
)
8129 if (*optarg
== '?') {
8132 printf ("Valid sound card names (comma separated):\n");
8133 for (c
= soundhw
; c
->name
; ++c
) {
8134 printf ("%-11s %s\n", c
->name
, c
->descr
);
8136 printf ("\n-soundhw all will enable all of the above\n");
8137 exit (*optarg
!= '?');
8145 if (!strcmp (optarg
, "all")) {
8146 for (c
= soundhw
; c
->name
; ++c
) {
8154 e
= strchr (p
, ',');
8155 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8157 for (c
= soundhw
; c
->name
; ++c
) {
8158 if (!strncmp (c
->name
, p
, l
)) {
8167 "Unknown sound card name (too big to show)\n");
8170 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8175 p
+= l
+ (e
!= NULL
);
8179 goto show_valid_cards
;
8184 static void select_vgahw (const char *p
)
8188 if (strstart(p
, "std", &opts
)) {
8189 cirrus_vga_enabled
= 0;
8191 } else if (strstart(p
, "cirrus", &opts
)) {
8192 cirrus_vga_enabled
= 1;
8194 } else if (strstart(p
, "vmware", &opts
)) {
8195 cirrus_vga_enabled
= 0;
8199 fprintf(stderr
, "Unknown vga type: %s\n", p
);
8203 const char *nextopt
;
8205 if (strstart(opts
, ",retrace=", &nextopt
)) {
8207 if (strstart(opts
, "dumb", &nextopt
))
8208 vga_retrace_method
= VGA_RETRACE_DUMB
;
8209 else if (strstart(opts
, "precise", &nextopt
))
8210 vga_retrace_method
= VGA_RETRACE_PRECISE
;
8211 else goto invalid_vga
;
8212 } else goto invalid_vga
;
8218 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8220 exit(STATUS_CONTROL_C_EXIT
);
8225 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8229 if(strlen(str
) != 36)
8232 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8233 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8234 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8242 #define MAX_NET_CLIENTS 32
8246 static void termsig_handler(int signal
)
8248 qemu_system_shutdown_request();
8251 static void termsig_setup(void)
8253 struct sigaction act
;
8255 memset(&act
, 0, sizeof(act
));
8256 act
.sa_handler
= termsig_handler
;
8257 sigaction(SIGINT
, &act
, NULL
);
8258 sigaction(SIGHUP
, &act
, NULL
);
8259 sigaction(SIGTERM
, &act
, NULL
);
8264 int main(int argc
, char **argv
)
8266 #ifdef CONFIG_GDBSTUB
8268 const char *gdbstub_port
;
8270 uint32_t boot_devices_bitmap
= 0;
8272 int snapshot
, linux_boot
, net_boot
;
8273 const char *initrd_filename
;
8274 const char *kernel_filename
, *kernel_cmdline
;
8275 const char *boot_devices
= "";
8276 DisplayState
*ds
= &display_state
;
8277 int cyls
, heads
, secs
, translation
;
8278 const char *net_clients
[MAX_NET_CLIENTS
];
8282 const char *r
, *optarg
;
8283 CharDriverState
*monitor_hd
;
8284 const char *monitor_device
;
8285 const char *serial_devices
[MAX_SERIAL_PORTS
];
8286 int serial_device_index
;
8287 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8288 int parallel_device_index
;
8289 const char *loadvm
= NULL
;
8290 QEMUMachine
*machine
;
8291 const char *cpu_model
;
8292 const char *usb_devices
[MAX_USB_CMDLINE
];
8293 int usb_devices_index
;
8296 const char *pid_file
= NULL
;
8299 LIST_INIT (&vm_change_state_head
);
8302 struct sigaction act
;
8303 sigfillset(&act
.sa_mask
);
8305 act
.sa_handler
= SIG_IGN
;
8306 sigaction(SIGPIPE
, &act
, NULL
);
8309 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8310 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8311 QEMU to run on a single CPU */
8316 h
= GetCurrentProcess();
8317 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8318 for(i
= 0; i
< 32; i
++) {
8319 if (mask
& (1 << i
))
8324 SetProcessAffinityMask(h
, mask
);
8330 register_machines();
8331 machine
= first_machine
;
8333 initrd_filename
= NULL
;
8335 vga_ram_size
= VGA_RAM_SIZE
;
8336 #ifdef CONFIG_GDBSTUB
8338 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8343 kernel_filename
= NULL
;
8344 kernel_cmdline
= "";
8345 cyls
= heads
= secs
= 0;
8346 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8347 monitor_device
= "vc";
8349 serial_devices
[0] = "vc:80Cx24C";
8350 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8351 serial_devices
[i
] = NULL
;
8352 serial_device_index
= 0;
8354 parallel_devices
[0] = "vc:640x480";
8355 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8356 parallel_devices
[i
] = NULL
;
8357 parallel_device_index
= 0;
8359 usb_devices_index
= 0;
8376 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8378 const QEMUOption
*popt
;
8381 /* Treat --foo the same as -foo. */
8384 popt
= qemu_options
;
8387 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8391 if (!strcmp(popt
->name
, r
+ 1))
8395 if (popt
->flags
& HAS_ARG
) {
8396 if (optind
>= argc
) {
8397 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8401 optarg
= argv
[optind
++];
8406 switch(popt
->index
) {
8408 machine
= find_machine(optarg
);
8411 printf("Supported machines are:\n");
8412 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8413 printf("%-10s %s%s\n",
8415 m
== first_machine
? " (default)" : "");
8417 exit(*optarg
!= '?');
8420 case QEMU_OPTION_cpu
:
8421 /* hw initialization will check this */
8422 if (*optarg
== '?') {
8423 /* XXX: implement xxx_cpu_list for targets that still miss it */
8424 #if defined(cpu_list)
8425 cpu_list(stdout
, &fprintf
);
8432 case QEMU_OPTION_initrd
:
8433 initrd_filename
= optarg
;
8435 case QEMU_OPTION_hda
:
8437 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8439 hda_index
= drive_add(optarg
, HD_ALIAS
8440 ",cyls=%d,heads=%d,secs=%d%s",
8441 0, cyls
, heads
, secs
,
8442 translation
== BIOS_ATA_TRANSLATION_LBA
?
8444 translation
== BIOS_ATA_TRANSLATION_NONE
?
8445 ",trans=none" : "");
8447 case QEMU_OPTION_hdb
:
8448 case QEMU_OPTION_hdc
:
8449 case QEMU_OPTION_hdd
:
8450 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8452 case QEMU_OPTION_drive
:
8453 drive_add(NULL
, "%s", optarg
);
8455 case QEMU_OPTION_mtdblock
:
8456 drive_add(optarg
, MTD_ALIAS
);
8458 case QEMU_OPTION_sd
:
8459 drive_add(optarg
, SD_ALIAS
);
8461 case QEMU_OPTION_pflash
:
8462 drive_add(optarg
, PFLASH_ALIAS
);
8464 case QEMU_OPTION_snapshot
:
8467 case QEMU_OPTION_hdachs
:
8471 cyls
= strtol(p
, (char **)&p
, 0);
8472 if (cyls
< 1 || cyls
> 16383)
8477 heads
= strtol(p
, (char **)&p
, 0);
8478 if (heads
< 1 || heads
> 16)
8483 secs
= strtol(p
, (char **)&p
, 0);
8484 if (secs
< 1 || secs
> 63)
8488 if (!strcmp(p
, "none"))
8489 translation
= BIOS_ATA_TRANSLATION_NONE
;
8490 else if (!strcmp(p
, "lba"))
8491 translation
= BIOS_ATA_TRANSLATION_LBA
;
8492 else if (!strcmp(p
, "auto"))
8493 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8496 } else if (*p
!= '\0') {
8498 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8501 if (hda_index
!= -1)
8502 snprintf(drives_opt
[hda_index
].opt
,
8503 sizeof(drives_opt
[hda_index
].opt
),
8504 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8505 0, cyls
, heads
, secs
,
8506 translation
== BIOS_ATA_TRANSLATION_LBA
?
8508 translation
== BIOS_ATA_TRANSLATION_NONE
?
8509 ",trans=none" : "");
8512 case QEMU_OPTION_nographic
:
8515 #ifdef CONFIG_CURSES
8516 case QEMU_OPTION_curses
:
8520 case QEMU_OPTION_portrait
:
8523 case QEMU_OPTION_kernel
:
8524 kernel_filename
= optarg
;
8526 case QEMU_OPTION_append
:
8527 kernel_cmdline
= optarg
;
8529 case QEMU_OPTION_cdrom
:
8530 drive_add(optarg
, CDROM_ALIAS
);
8532 case QEMU_OPTION_boot
:
8533 boot_devices
= optarg
;
8534 /* We just do some generic consistency checks */
8536 /* Could easily be extended to 64 devices if needed */
8539 boot_devices_bitmap
= 0;
8540 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8541 /* Allowed boot devices are:
8542 * a b : floppy disk drives
8543 * c ... f : IDE disk drives
8544 * g ... m : machine implementation dependant drives
8545 * n ... p : network devices
8546 * It's up to each machine implementation to check
8547 * if the given boot devices match the actual hardware
8548 * implementation and firmware features.
8550 if (*p
< 'a' || *p
> 'q') {
8551 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8554 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8556 "Boot device '%c' was given twice\n",*p
);
8559 boot_devices_bitmap
|= 1 << (*p
- 'a');
8563 case QEMU_OPTION_fda
:
8564 case QEMU_OPTION_fdb
:
8565 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8568 case QEMU_OPTION_no_fd_bootchk
:
8572 case QEMU_OPTION_net
:
8573 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8574 fprintf(stderr
, "qemu: too many network clients\n");
8577 net_clients
[nb_net_clients
] = optarg
;
8581 case QEMU_OPTION_tftp
:
8582 tftp_prefix
= optarg
;
8584 case QEMU_OPTION_bootp
:
8585 bootp_filename
= optarg
;
8588 case QEMU_OPTION_smb
:
8589 net_slirp_smb(optarg
);
8592 case QEMU_OPTION_redir
:
8593 net_slirp_redir(optarg
);
8597 case QEMU_OPTION_audio_help
:
8601 case QEMU_OPTION_soundhw
:
8602 select_soundhw (optarg
);
8608 case QEMU_OPTION_m
: {
8612 value
= strtoul(optarg
, &ptr
, 10);
8614 case 0: case 'M': case 'm':
8621 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8625 /* On 32-bit hosts, QEMU is limited by virtual address space */
8626 if (value
> (2047 << 20)
8628 && HOST_LONG_BITS
== 32
8631 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8634 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8635 fprintf(stderr
, "qemu: ram size too large\n");
8646 mask
= cpu_str_to_log_mask(optarg
);
8648 printf("Log items (comma separated):\n");
8649 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8650 printf("%-10s %s\n", item
->name
, item
->help
);
8657 #ifdef CONFIG_GDBSTUB
8662 gdbstub_port
= optarg
;
8668 case QEMU_OPTION_bios
:
8675 keyboard_layout
= optarg
;
8677 case QEMU_OPTION_localtime
:
8680 case QEMU_OPTION_vga
:
8681 select_vgahw (optarg
);
8688 w
= strtol(p
, (char **)&p
, 10);
8691 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8697 h
= strtol(p
, (char **)&p
, 10);
8702 depth
= strtol(p
, (char **)&p
, 10);
8703 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8704 depth
!= 24 && depth
!= 32)
8706 } else if (*p
== '\0') {
8707 depth
= graphic_depth
;
8714 graphic_depth
= depth
;
8717 case QEMU_OPTION_echr
:
8720 term_escape_char
= strtol(optarg
, &r
, 0);
8722 printf("Bad argument to echr\n");
8725 case QEMU_OPTION_monitor
:
8726 monitor_device
= optarg
;
8728 case QEMU_OPTION_serial
:
8729 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8730 fprintf(stderr
, "qemu: too many serial ports\n");
8733 serial_devices
[serial_device_index
] = optarg
;
8734 serial_device_index
++;
8736 case QEMU_OPTION_parallel
:
8737 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8738 fprintf(stderr
, "qemu: too many parallel ports\n");
8741 parallel_devices
[parallel_device_index
] = optarg
;
8742 parallel_device_index
++;
8744 case QEMU_OPTION_loadvm
:
8747 case QEMU_OPTION_full_screen
:
8751 case QEMU_OPTION_no_frame
:
8754 case QEMU_OPTION_alt_grab
:
8757 case QEMU_OPTION_no_quit
:
8761 case QEMU_OPTION_pidfile
:
8765 case QEMU_OPTION_win2k_hack
:
8766 win2k_install_hack
= 1;
8770 case QEMU_OPTION_no_kqemu
:
8773 case QEMU_OPTION_kernel_kqemu
:
8777 case QEMU_OPTION_usb
:
8780 case QEMU_OPTION_usbdevice
:
8782 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8783 fprintf(stderr
, "Too many USB devices\n");
8786 usb_devices
[usb_devices_index
] = optarg
;
8787 usb_devices_index
++;
8789 case QEMU_OPTION_smp
:
8790 smp_cpus
= atoi(optarg
);
8791 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8792 fprintf(stderr
, "Invalid number of CPUs\n");
8796 case QEMU_OPTION_vnc
:
8797 vnc_display
= optarg
;
8799 case QEMU_OPTION_no_acpi
:
8802 case QEMU_OPTION_no_reboot
:
8805 case QEMU_OPTION_no_shutdown
:
8808 case QEMU_OPTION_show_cursor
:
8811 case QEMU_OPTION_uuid
:
8812 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
8813 fprintf(stderr
, "Fail to parse UUID string."
8814 " Wrong format.\n");
8818 case QEMU_OPTION_daemonize
:
8821 case QEMU_OPTION_option_rom
:
8822 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8823 fprintf(stderr
, "Too many option ROMs\n");
8826 option_rom
[nb_option_roms
] = optarg
;
8829 case QEMU_OPTION_semihosting
:
8830 semihosting_enabled
= 1;
8832 case QEMU_OPTION_name
:
8836 case QEMU_OPTION_prom_env
:
8837 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8838 fprintf(stderr
, "Too many prom variables\n");
8841 prom_envs
[nb_prom_envs
] = optarg
;
8846 case QEMU_OPTION_old_param
:
8850 case QEMU_OPTION_clock
:
8851 configure_alarms(optarg
);
8853 case QEMU_OPTION_startdate
:
8856 time_t rtc_start_date
;
8857 if (!strcmp(optarg
, "now")) {
8858 rtc_date_offset
= -1;
8860 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8868 } else if (sscanf(optarg
, "%d-%d-%d",
8871 &tm
.tm_mday
) == 3) {
8880 rtc_start_date
= mktimegm(&tm
);
8881 if (rtc_start_date
== -1) {
8883 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8884 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8887 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8891 case QEMU_OPTION_tb_size
:
8892 tb_size
= strtol(optarg
, NULL
, 0);
8896 case QEMU_OPTION_icount
:
8898 if (strcmp(optarg
, "auto") == 0) {
8899 icount_time_shift
= -1;
8901 icount_time_shift
= strtol(optarg
, NULL
, 0);
8909 if (serial_device_index
== 0)
8910 serial_devices
[0] = "stdio";
8911 if (parallel_device_index
== 0)
8912 parallel_devices
[0] = "null";
8913 if (strncmp(monitor_device
, "vc", 2) == 0)
8914 monitor_device
= "stdio";
8921 if (pipe(fds
) == -1)
8932 len
= read(fds
[0], &status
, 1);
8933 if (len
== -1 && (errno
== EINTR
))
8938 else if (status
== 1) {
8939 fprintf(stderr
, "Could not acquire pidfile\n");
8956 signal(SIGTSTP
, SIG_IGN
);
8957 signal(SIGTTOU
, SIG_IGN
);
8958 signal(SIGTTIN
, SIG_IGN
);
8962 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8965 write(fds
[1], &status
, 1);
8967 fprintf(stderr
, "Could not acquire pid file\n");
8975 linux_boot
= (kernel_filename
!= NULL
);
8976 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8978 if (!linux_boot
&& net_boot
== 0 &&
8979 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8982 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8983 fprintf(stderr
, "-append only allowed with -kernel option\n");
8987 if (!linux_boot
&& initrd_filename
!= NULL
) {
8988 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8992 /* boot to floppy or the default cd if no hard disk defined yet */
8993 if (!boot_devices
[0]) {
8994 boot_devices
= "cad";
8996 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9000 if (use_icount
&& icount_time_shift
< 0) {
9002 /* 125MIPS seems a reasonable initial guess at the guest speed.
9003 It will be corrected fairly quickly anyway. */
9004 icount_time_shift
= 3;
9005 init_icount_adjust();
9012 /* init network clients */
9013 if (nb_net_clients
== 0) {
9014 /* if no clients, we use a default config */
9015 net_clients
[nb_net_clients
++] = "nic";
9017 net_clients
[nb_net_clients
++] = "user";
9021 for(i
= 0;i
< nb_net_clients
; i
++) {
9022 if (net_client_parse(net_clients
[i
]) < 0)
9025 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9026 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9028 if (vlan
->nb_guest_devs
== 0)
9029 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9030 if (vlan
->nb_host_devs
== 0)
9032 "Warning: vlan %d is not connected to host network\n",
9037 /* XXX: this should be moved in the PC machine instantiation code */
9038 if (net_boot
!= 0) {
9040 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9041 const char *model
= nd_table
[i
].model
;
9043 if (net_boot
& (1 << i
)) {
9046 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9047 if (get_image_size(buf
) > 0) {
9048 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9049 fprintf(stderr
, "Too many option ROMs\n");
9052 option_rom
[nb_option_roms
] = strdup(buf
);
9059 fprintf(stderr
, "No valid PXE rom found for network device\n");
9065 /* init the memory */
9066 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9068 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9070 if (ram_size
< phys_ram_size
) {
9071 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9072 machine
->name
, (unsigned long long) phys_ram_size
);
9076 phys_ram_size
= ram_size
;
9078 ram_size
= phys_ram_size
;
9081 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9083 phys_ram_size
+= ram_size
;
9086 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9087 if (!phys_ram_base
) {
9088 fprintf(stderr
, "Could not allocate physical memory\n");
9092 /* init the dynamic translator */
9093 cpu_exec_init_all(tb_size
* 1024 * 1024);
9097 /* we always create the cdrom drive, even if no disk is there */
9099 if (nb_drives_opt
< MAX_DRIVES
)
9100 drive_add(NULL
, CDROM_ALIAS
);
9102 /* we always create at least one floppy */
9104 if (nb_drives_opt
< MAX_DRIVES
)
9105 drive_add(NULL
, FD_ALIAS
, 0);
9107 /* we always create one sd slot, even if no card is in it */
9109 if (nb_drives_opt
< MAX_DRIVES
)
9110 drive_add(NULL
, SD_ALIAS
);
9112 /* open the virtual block devices */
9114 for(i
= 0; i
< nb_drives_opt
; i
++)
9115 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9118 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9119 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9122 memset(&display_state
, 0, sizeof(display_state
));
9125 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9128 /* nearly nothing to do */
9129 dumb_display_init(ds
);
9130 } else if (vnc_display
!= NULL
) {
9131 vnc_display_init(ds
);
9132 if (vnc_display_open(ds
, vnc_display
) < 0)
9135 #if defined(CONFIG_CURSES)
9137 curses_display_init(ds
, full_screen
);
9141 #if defined(CONFIG_SDL)
9142 sdl_display_init(ds
, full_screen
, no_frame
);
9143 #elif defined(CONFIG_COCOA)
9144 cocoa_display_init(ds
, full_screen
);
9146 dumb_display_init(ds
);
9151 /* must be after terminal init, SDL library changes signal handlers */
9155 /* Maintain compatibility with multiple stdio monitors */
9156 if (!strcmp(monitor_device
,"stdio")) {
9157 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9158 const char *devname
= serial_devices
[i
];
9159 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9160 monitor_device
= NULL
;
9162 } else if (devname
&& !strcmp(devname
,"stdio")) {
9163 monitor_device
= NULL
;
9164 serial_devices
[i
] = "mon:stdio";
9169 if (monitor_device
) {
9170 monitor_hd
= qemu_chr_open(monitor_device
);
9172 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9175 monitor_init(monitor_hd
, !nographic
);
9178 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9179 const char *devname
= serial_devices
[i
];
9180 if (devname
&& strcmp(devname
, "none")) {
9181 serial_hds
[i
] = qemu_chr_open(devname
);
9182 if (!serial_hds
[i
]) {
9183 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9187 if (strstart(devname
, "vc", 0))
9188 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9192 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9193 const char *devname
= parallel_devices
[i
];
9194 if (devname
&& strcmp(devname
, "none")) {
9195 parallel_hds
[i
] = qemu_chr_open(devname
);
9196 if (!parallel_hds
[i
]) {
9197 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9201 if (strstart(devname
, "vc", 0))
9202 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9206 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9207 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9209 /* init USB devices */
9211 for(i
= 0; i
< usb_devices_index
; i
++) {
9212 if (usb_device_add(usb_devices
[i
]) < 0) {
9213 fprintf(stderr
, "Warning: could not add USB device %s\n",
9219 if (display_state
.dpy_refresh
) {
9220 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9221 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9224 #ifdef CONFIG_GDBSTUB
9226 /* XXX: use standard host:port notation and modify options
9228 if (gdbserver_start(gdbstub_port
) < 0) {
9229 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9240 /* XXX: simplify init */
9253 len
= write(fds
[1], &status
, 1);
9254 if (len
== -1 && (errno
== EINTR
))
9261 TFR(fd
= open("/dev/null", O_RDWR
));
9275 #if !defined(_WIN32)
9276 /* close network clients */
9277 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9278 VLANClientState
*vc
;
9280 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9281 if (vc
->fd_read
== tap_receive
) {
9283 TAPState
*s
= vc
->opaque
;
9285 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9287 launch_script(s
->down_script
, ifname
, s
->fd
);
9289 #if defined(CONFIG_VDE)
9290 if (vc
->fd_read
== vde_from_qemu
) {
9291 VDEState
*s
= vc
->opaque
;