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 (!strcmp(machine
->name
, "realview") ||
5465 !strcmp(machine
->name
, "SS-5") ||
5466 !strcmp(machine
->name
, "SS-10") ||
5467 !strcmp(machine
->name
, "SS-600MP") ||
5468 !strcmp(machine
->name
, "versatilepb") ||
5469 !strcmp(machine
->name
, "versatileab")) {
5471 max_devs
= MAX_SCSI_DEVS
;
5472 pstrcpy(devname
, sizeof(devname
), "scsi");
5475 max_devs
= MAX_IDE_DEVS
;
5476 pstrcpy(devname
, sizeof(devname
), "ide");
5480 /* extract parameters */
5482 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5483 bus_id
= strtol(buf
, NULL
, 0);
5485 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5490 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5491 unit_id
= strtol(buf
, NULL
, 0);
5493 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5498 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5499 pstrcpy(devname
, sizeof(devname
), buf
);
5500 if (!strcmp(buf
, "ide")) {
5502 max_devs
= MAX_IDE_DEVS
;
5503 } else if (!strcmp(buf
, "scsi")) {
5505 max_devs
= MAX_SCSI_DEVS
;
5506 } else if (!strcmp(buf
, "floppy")) {
5509 } else if (!strcmp(buf
, "pflash")) {
5512 } else if (!strcmp(buf
, "mtd")) {
5515 } else if (!strcmp(buf
, "sd")) {
5519 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5524 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5525 index
= strtol(buf
, NULL
, 0);
5527 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5532 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5533 cyls
= strtol(buf
, NULL
, 0);
5536 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5537 heads
= strtol(buf
, NULL
, 0);
5540 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5541 secs
= strtol(buf
, NULL
, 0);
5544 if (cyls
|| heads
|| secs
) {
5545 if (cyls
< 1 || cyls
> 16383) {
5546 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5549 if (heads
< 1 || heads
> 16) {
5550 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5553 if (secs
< 1 || secs
> 63) {
5554 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5559 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5562 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5566 if (!strcmp(buf
, "none"))
5567 translation
= BIOS_ATA_TRANSLATION_NONE
;
5568 else if (!strcmp(buf
, "lba"))
5569 translation
= BIOS_ATA_TRANSLATION_LBA
;
5570 else if (!strcmp(buf
, "auto"))
5571 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5573 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5578 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5579 if (!strcmp(buf
, "disk")) {
5581 } else if (!strcmp(buf
, "cdrom")) {
5582 if (cyls
|| secs
|| heads
) {
5584 "qemu: '%s' invalid physical CHS format\n", str
);
5587 media
= MEDIA_CDROM
;
5589 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5594 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5595 if (!strcmp(buf
, "on"))
5597 else if (!strcmp(buf
, "off"))
5600 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5605 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5606 if (!strcmp(buf
, "off"))
5608 else if (!strcmp(buf
, "on"))
5611 fprintf(stderr
, "qemu: invalid cache option\n");
5616 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5617 if (strcmp(buf
, "?") == 0) {
5618 fprintf(stderr
, "qemu: Supported formats:");
5619 bdrv_iterate_format(bdrv_format_print
, NULL
);
5620 fprintf(stderr
, "\n");
5623 drv
= bdrv_find_format(buf
);
5625 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5630 if (arg
->file
== NULL
)
5631 get_param_value(file
, sizeof(file
), "file", str
);
5633 pstrcpy(file
, sizeof(file
), arg
->file
);
5635 /* compute bus and unit according index */
5638 if (bus_id
!= 0 || unit_id
!= -1) {
5640 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5648 unit_id
= index
% max_devs
;
5649 bus_id
= index
/ max_devs
;
5653 /* if user doesn't specify a unit_id,
5654 * try to find the first free
5657 if (unit_id
== -1) {
5659 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5661 if (max_devs
&& unit_id
>= max_devs
) {
5662 unit_id
-= max_devs
;
5670 if (max_devs
&& unit_id
>= max_devs
) {
5671 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5672 str
, unit_id
, max_devs
- 1);
5677 * ignore multiple definitions
5680 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5685 if (type
== IF_IDE
|| type
== IF_SCSI
)
5686 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5688 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5689 devname
, bus_id
, mediastr
, unit_id
);
5691 snprintf(buf
, sizeof(buf
), "%s%s%i",
5692 devname
, mediastr
, unit_id
);
5693 bdrv
= bdrv_new(buf
);
5694 drives_table
[nb_drives
].bdrv
= bdrv
;
5695 drives_table
[nb_drives
].type
= type
;
5696 drives_table
[nb_drives
].bus
= bus_id
;
5697 drives_table
[nb_drives
].unit
= unit_id
;
5706 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5707 bdrv_set_translation_hint(bdrv
, translation
);
5711 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5716 /* FIXME: This isn't really a floppy, but it's a reasonable
5719 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5729 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5731 bdrv_flags
|= BDRV_O_DIRECT
;
5732 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5733 fprintf(stderr
, "qemu: could not open disk image %s\n",
5740 /***********************************************************/
5743 static USBPort
*used_usb_ports
;
5744 static USBPort
*free_usb_ports
;
5746 /* ??? Maybe change this to register a hub to keep track of the topology. */
5747 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5748 usb_attachfn attach
)
5750 port
->opaque
= opaque
;
5751 port
->index
= index
;
5752 port
->attach
= attach
;
5753 port
->next
= free_usb_ports
;
5754 free_usb_ports
= port
;
5757 int usb_device_add_dev(USBDevice
*dev
)
5761 /* Find a USB port to add the device to. */
5762 port
= free_usb_ports
;
5766 /* Create a new hub and chain it on. */
5767 free_usb_ports
= NULL
;
5768 port
->next
= used_usb_ports
;
5769 used_usb_ports
= port
;
5771 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5772 usb_attach(port
, hub
);
5773 port
= free_usb_ports
;
5776 free_usb_ports
= port
->next
;
5777 port
->next
= used_usb_ports
;
5778 used_usb_ports
= port
;
5779 usb_attach(port
, dev
);
5783 static int usb_device_add(const char *devname
)
5788 if (!free_usb_ports
)
5791 if (strstart(devname
, "host:", &p
)) {
5792 dev
= usb_host_device_open(p
);
5793 } else if (!strcmp(devname
, "mouse")) {
5794 dev
= usb_mouse_init();
5795 } else if (!strcmp(devname
, "tablet")) {
5796 dev
= usb_tablet_init();
5797 } else if (!strcmp(devname
, "keyboard")) {
5798 dev
= usb_keyboard_init();
5799 } else if (strstart(devname
, "disk:", &p
)) {
5800 dev
= usb_msd_init(p
);
5801 } else if (!strcmp(devname
, "wacom-tablet")) {
5802 dev
= usb_wacom_init();
5803 } else if (strstart(devname
, "serial:", &p
)) {
5804 dev
= usb_serial_init(p
);
5805 #ifdef CONFIG_BRLAPI
5806 } else if (!strcmp(devname
, "braille")) {
5807 dev
= usb_baum_init();
5809 } else if (strstart(devname
, "net:", &p
)) {
5812 if (net_client_init("nic", p
) < 0)
5814 nd_table
[nic
].model
= "usb";
5815 dev
= usb_net_init(&nd_table
[nic
]);
5822 return usb_device_add_dev(dev
);
5825 int usb_device_del_addr(int bus_num
, int addr
)
5831 if (!used_usb_ports
)
5837 lastp
= &used_usb_ports
;
5838 port
= used_usb_ports
;
5839 while (port
&& port
->dev
->addr
!= addr
) {
5840 lastp
= &port
->next
;
5848 *lastp
= port
->next
;
5849 usb_attach(port
, NULL
);
5850 dev
->handle_destroy(dev
);
5851 port
->next
= free_usb_ports
;
5852 free_usb_ports
= port
;
5856 static int usb_device_del(const char *devname
)
5861 if (strstart(devname
, "host:", &p
))
5862 return usb_host_device_close(p
);
5864 if (!used_usb_ports
)
5867 p
= strchr(devname
, '.');
5870 bus_num
= strtoul(devname
, NULL
, 0);
5871 addr
= strtoul(p
+ 1, NULL
, 0);
5873 return usb_device_del_addr(bus_num
, addr
);
5876 void do_usb_add(const char *devname
)
5878 usb_device_add(devname
);
5881 void do_usb_del(const char *devname
)
5883 usb_device_del(devname
);
5890 const char *speed_str
;
5893 term_printf("USB support not enabled\n");
5897 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5901 switch(dev
->speed
) {
5905 case USB_SPEED_FULL
:
5908 case USB_SPEED_HIGH
:
5915 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5916 0, dev
->addr
, speed_str
, dev
->devname
);
5920 /***********************************************************/
5921 /* PCMCIA/Cardbus */
5923 static struct pcmcia_socket_entry_s
{
5924 struct pcmcia_socket_s
*socket
;
5925 struct pcmcia_socket_entry_s
*next
;
5926 } *pcmcia_sockets
= 0;
5928 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5930 struct pcmcia_socket_entry_s
*entry
;
5932 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5933 entry
->socket
= socket
;
5934 entry
->next
= pcmcia_sockets
;
5935 pcmcia_sockets
= entry
;
5938 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5940 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5942 ptr
= &pcmcia_sockets
;
5943 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5944 if (entry
->socket
== socket
) {
5950 void pcmcia_info(void)
5952 struct pcmcia_socket_entry_s
*iter
;
5953 if (!pcmcia_sockets
)
5954 term_printf("No PCMCIA sockets\n");
5956 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5957 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5958 iter
->socket
->attached
? iter
->socket
->card_string
:
5962 /***********************************************************/
5965 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5969 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5973 static void dumb_refresh(DisplayState
*ds
)
5975 #if defined(CONFIG_SDL)
5980 static void dumb_display_init(DisplayState
*ds
)
5985 ds
->dpy_update
= dumb_update
;
5986 ds
->dpy_resize
= dumb_resize
;
5987 ds
->dpy_refresh
= dumb_refresh
;
5988 ds
->gui_timer_interval
= 500;
5992 /***********************************************************/
5995 #define MAX_IO_HANDLERS 64
5997 typedef struct IOHandlerRecord
{
5999 IOCanRWHandler
*fd_read_poll
;
6001 IOHandler
*fd_write
;
6004 /* temporary data */
6006 struct IOHandlerRecord
*next
;
6009 static IOHandlerRecord
*first_io_handler
;
6011 /* XXX: fd_read_poll should be suppressed, but an API change is
6012 necessary in the character devices to suppress fd_can_read(). */
6013 int qemu_set_fd_handler2(int fd
,
6014 IOCanRWHandler
*fd_read_poll
,
6016 IOHandler
*fd_write
,
6019 IOHandlerRecord
**pioh
, *ioh
;
6021 if (!fd_read
&& !fd_write
) {
6022 pioh
= &first_io_handler
;
6027 if (ioh
->fd
== fd
) {
6034 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6038 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6041 ioh
->next
= first_io_handler
;
6042 first_io_handler
= ioh
;
6045 ioh
->fd_read_poll
= fd_read_poll
;
6046 ioh
->fd_read
= fd_read
;
6047 ioh
->fd_write
= fd_write
;
6048 ioh
->opaque
= opaque
;
6054 int qemu_set_fd_handler(int fd
,
6056 IOHandler
*fd_write
,
6059 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6062 /***********************************************************/
6063 /* Polling handling */
6065 typedef struct PollingEntry
{
6068 struct PollingEntry
*next
;
6071 static PollingEntry
*first_polling_entry
;
6073 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6075 PollingEntry
**ppe
, *pe
;
6076 pe
= qemu_mallocz(sizeof(PollingEntry
));
6080 pe
->opaque
= opaque
;
6081 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6086 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6088 PollingEntry
**ppe
, *pe
;
6089 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6091 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6100 /***********************************************************/
6101 /* Wait objects support */
6102 typedef struct WaitObjects
{
6104 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6105 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6106 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6109 static WaitObjects wait_objects
= {0};
6111 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6113 WaitObjects
*w
= &wait_objects
;
6115 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6117 w
->events
[w
->num
] = handle
;
6118 w
->func
[w
->num
] = func
;
6119 w
->opaque
[w
->num
] = opaque
;
6124 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6127 WaitObjects
*w
= &wait_objects
;
6130 for (i
= 0; i
< w
->num
; i
++) {
6131 if (w
->events
[i
] == handle
)
6134 w
->events
[i
] = w
->events
[i
+ 1];
6135 w
->func
[i
] = w
->func
[i
+ 1];
6136 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6144 /***********************************************************/
6145 /* savevm/loadvm support */
6147 #define IO_BUF_SIZE 32768
6151 BlockDriverState
*bs
;
6154 int64_t base_offset
;
6155 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6158 int buf_size
; /* 0 when writing */
6159 uint8_t buf
[IO_BUF_SIZE
];
6162 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6166 f
= qemu_mallocz(sizeof(QEMUFile
));
6169 if (!strcmp(mode
, "wb")) {
6171 } else if (!strcmp(mode
, "rb")) {
6176 f
->outfile
= fopen(filename
, mode
);
6188 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6192 f
= qemu_mallocz(sizeof(QEMUFile
));
6197 f
->is_writable
= is_writable
;
6198 f
->base_offset
= offset
;
6202 void qemu_fflush(QEMUFile
*f
)
6204 if (!f
->is_writable
)
6206 if (f
->buf_index
> 0) {
6208 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6209 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6211 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6212 f
->buf
, f
->buf_index
);
6214 f
->buf_offset
+= f
->buf_index
;
6219 static void qemu_fill_buffer(QEMUFile
*f
)
6226 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6227 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6231 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6232 f
->buf
, IO_BUF_SIZE
);
6238 f
->buf_offset
+= len
;
6241 void qemu_fclose(QEMUFile
*f
)
6251 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6255 l
= IO_BUF_SIZE
- f
->buf_index
;
6258 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6262 if (f
->buf_index
>= IO_BUF_SIZE
)
6267 void qemu_put_byte(QEMUFile
*f
, int v
)
6269 f
->buf
[f
->buf_index
++] = v
;
6270 if (f
->buf_index
>= IO_BUF_SIZE
)
6274 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6280 l
= f
->buf_size
- f
->buf_index
;
6282 qemu_fill_buffer(f
);
6283 l
= f
->buf_size
- f
->buf_index
;
6289 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6294 return size1
- size
;
6297 int qemu_get_byte(QEMUFile
*f
)
6299 if (f
->buf_index
>= f
->buf_size
) {
6300 qemu_fill_buffer(f
);
6301 if (f
->buf_index
>= f
->buf_size
)
6304 return f
->buf
[f
->buf_index
++];
6307 int64_t qemu_ftell(QEMUFile
*f
)
6309 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6312 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6314 if (whence
== SEEK_SET
) {
6316 } else if (whence
== SEEK_CUR
) {
6317 pos
+= qemu_ftell(f
);
6319 /* SEEK_END not supported */
6322 if (f
->is_writable
) {
6324 f
->buf_offset
= pos
;
6326 f
->buf_offset
= pos
;
6333 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6335 qemu_put_byte(f
, v
>> 8);
6336 qemu_put_byte(f
, v
);
6339 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6341 qemu_put_byte(f
, v
>> 24);
6342 qemu_put_byte(f
, v
>> 16);
6343 qemu_put_byte(f
, v
>> 8);
6344 qemu_put_byte(f
, v
);
6347 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6349 qemu_put_be32(f
, v
>> 32);
6350 qemu_put_be32(f
, v
);
6353 unsigned int qemu_get_be16(QEMUFile
*f
)
6356 v
= qemu_get_byte(f
) << 8;
6357 v
|= qemu_get_byte(f
);
6361 unsigned int qemu_get_be32(QEMUFile
*f
)
6364 v
= qemu_get_byte(f
) << 24;
6365 v
|= qemu_get_byte(f
) << 16;
6366 v
|= qemu_get_byte(f
) << 8;
6367 v
|= qemu_get_byte(f
);
6371 uint64_t qemu_get_be64(QEMUFile
*f
)
6374 v
= (uint64_t)qemu_get_be32(f
) << 32;
6375 v
|= qemu_get_be32(f
);
6379 typedef struct SaveStateEntry
{
6383 SaveStateHandler
*save_state
;
6384 LoadStateHandler
*load_state
;
6386 struct SaveStateEntry
*next
;
6389 static SaveStateEntry
*first_se
;
6391 /* TODO: Individual devices generally have very little idea about the rest
6392 of the system, so instance_id should be removed/replaced.
6393 Meanwhile pass -1 as instance_id if you do not already have a clearly
6394 distinguishing id for all instances of your device class. */
6395 int register_savevm(const char *idstr
,
6398 SaveStateHandler
*save_state
,
6399 LoadStateHandler
*load_state
,
6402 SaveStateEntry
*se
, **pse
;
6404 se
= qemu_malloc(sizeof(SaveStateEntry
));
6407 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6408 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6409 se
->version_id
= version_id
;
6410 se
->save_state
= save_state
;
6411 se
->load_state
= load_state
;
6412 se
->opaque
= opaque
;
6415 /* add at the end of list */
6417 while (*pse
!= NULL
) {
6418 if (instance_id
== -1
6419 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6420 && se
->instance_id
<= (*pse
)->instance_id
)
6421 se
->instance_id
= (*pse
)->instance_id
+ 1;
6422 pse
= &(*pse
)->next
;
6428 #define QEMU_VM_FILE_MAGIC 0x5145564d
6429 #define QEMU_VM_FILE_VERSION 0x00000002
6431 static int qemu_savevm_state(QEMUFile
*f
)
6435 int64_t cur_pos
, len_pos
, total_len_pos
;
6437 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6438 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6439 total_len_pos
= qemu_ftell(f
);
6440 qemu_put_be64(f
, 0); /* total size */
6442 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6443 if (se
->save_state
== NULL
)
6444 /* this one has a loader only, for backwards compatibility */
6448 len
= strlen(se
->idstr
);
6449 qemu_put_byte(f
, len
);
6450 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6452 qemu_put_be32(f
, se
->instance_id
);
6453 qemu_put_be32(f
, se
->version_id
);
6455 /* record size: filled later */
6456 len_pos
= qemu_ftell(f
);
6457 qemu_put_be32(f
, 0);
6458 se
->save_state(f
, se
->opaque
);
6460 /* fill record size */
6461 cur_pos
= qemu_ftell(f
);
6462 len
= cur_pos
- len_pos
- 4;
6463 qemu_fseek(f
, len_pos
, SEEK_SET
);
6464 qemu_put_be32(f
, len
);
6465 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6467 cur_pos
= qemu_ftell(f
);
6468 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6469 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6470 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6476 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6480 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6481 if (!strcmp(se
->idstr
, idstr
) &&
6482 instance_id
== se
->instance_id
)
6488 static int qemu_loadvm_state(QEMUFile
*f
)
6491 int len
, ret
, instance_id
, record_len
, version_id
;
6492 int64_t total_len
, end_pos
, cur_pos
;
6496 v
= qemu_get_be32(f
);
6497 if (v
!= QEMU_VM_FILE_MAGIC
)
6499 v
= qemu_get_be32(f
);
6500 if (v
!= QEMU_VM_FILE_VERSION
) {
6505 total_len
= qemu_get_be64(f
);
6506 end_pos
= total_len
+ qemu_ftell(f
);
6508 if (qemu_ftell(f
) >= end_pos
)
6510 len
= qemu_get_byte(f
);
6511 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6513 instance_id
= qemu_get_be32(f
);
6514 version_id
= qemu_get_be32(f
);
6515 record_len
= qemu_get_be32(f
);
6517 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6518 idstr
, instance_id
, version_id
, record_len
);
6520 cur_pos
= qemu_ftell(f
);
6521 se
= find_se(idstr
, instance_id
);
6523 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6524 instance_id
, idstr
);
6526 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6528 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6529 instance_id
, idstr
);
6532 /* always seek to exact end of record */
6533 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6540 /* device can contain snapshots */
6541 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6544 !bdrv_is_removable(bs
) &&
6545 !bdrv_is_read_only(bs
));
6548 /* device must be snapshots in order to have a reliable snapshot */
6549 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6552 !bdrv_is_removable(bs
) &&
6553 !bdrv_is_read_only(bs
));
6556 static BlockDriverState
*get_bs_snapshots(void)
6558 BlockDriverState
*bs
;
6562 return bs_snapshots
;
6563 for(i
= 0; i
<= nb_drives
; i
++) {
6564 bs
= drives_table
[i
].bdrv
;
6565 if (bdrv_can_snapshot(bs
))
6574 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6577 QEMUSnapshotInfo
*sn_tab
, *sn
;
6581 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6584 for(i
= 0; i
< nb_sns
; i
++) {
6586 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6596 void do_savevm(const char *name
)
6598 BlockDriverState
*bs
, *bs1
;
6599 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6600 int must_delete
, ret
, i
;
6601 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6603 int saved_vm_running
;
6610 bs
= get_bs_snapshots();
6612 term_printf("No block device can accept snapshots\n");
6616 /* ??? Should this occur after vm_stop? */
6619 saved_vm_running
= vm_running
;
6624 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6629 memset(sn
, 0, sizeof(*sn
));
6631 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6632 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6635 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6638 /* fill auxiliary fields */
6641 sn
->date_sec
= tb
.time
;
6642 sn
->date_nsec
= tb
.millitm
* 1000000;
6644 gettimeofday(&tv
, NULL
);
6645 sn
->date_sec
= tv
.tv_sec
;
6646 sn
->date_nsec
= tv
.tv_usec
* 1000;
6648 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6650 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6651 term_printf("Device %s does not support VM state snapshots\n",
6652 bdrv_get_device_name(bs
));
6656 /* save the VM state */
6657 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6659 term_printf("Could not open VM state file\n");
6662 ret
= qemu_savevm_state(f
);
6663 sn
->vm_state_size
= qemu_ftell(f
);
6666 term_printf("Error %d while writing VM\n", ret
);
6670 /* create the snapshots */
6672 for(i
= 0; i
< nb_drives
; i
++) {
6673 bs1
= drives_table
[i
].bdrv
;
6674 if (bdrv_has_snapshot(bs1
)) {
6676 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6678 term_printf("Error while deleting snapshot on '%s'\n",
6679 bdrv_get_device_name(bs1
));
6682 ret
= bdrv_snapshot_create(bs1
, sn
);
6684 term_printf("Error while creating snapshot on '%s'\n",
6685 bdrv_get_device_name(bs1
));
6691 if (saved_vm_running
)
6695 void do_loadvm(const char *name
)
6697 BlockDriverState
*bs
, *bs1
;
6698 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6701 int saved_vm_running
;
6703 bs
= get_bs_snapshots();
6705 term_printf("No block device supports snapshots\n");
6709 /* Flush all IO requests so they don't interfere with the new state. */
6712 saved_vm_running
= vm_running
;
6715 for(i
= 0; i
<= nb_drives
; i
++) {
6716 bs1
= drives_table
[i
].bdrv
;
6717 if (bdrv_has_snapshot(bs1
)) {
6718 ret
= bdrv_snapshot_goto(bs1
, name
);
6721 term_printf("Warning: ");
6724 term_printf("Snapshots not supported on device '%s'\n",
6725 bdrv_get_device_name(bs1
));
6728 term_printf("Could not find snapshot '%s' on device '%s'\n",
6729 name
, bdrv_get_device_name(bs1
));
6732 term_printf("Error %d while activating snapshot on '%s'\n",
6733 ret
, bdrv_get_device_name(bs1
));
6736 /* fatal on snapshot block device */
6743 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6744 term_printf("Device %s does not support VM state snapshots\n",
6745 bdrv_get_device_name(bs
));
6749 /* restore the VM state */
6750 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6752 term_printf("Could not open VM state file\n");
6755 ret
= qemu_loadvm_state(f
);
6758 term_printf("Error %d while loading VM state\n", ret
);
6761 if (saved_vm_running
)
6765 void do_delvm(const char *name
)
6767 BlockDriverState
*bs
, *bs1
;
6770 bs
= get_bs_snapshots();
6772 term_printf("No block device supports snapshots\n");
6776 for(i
= 0; i
<= nb_drives
; i
++) {
6777 bs1
= drives_table
[i
].bdrv
;
6778 if (bdrv_has_snapshot(bs1
)) {
6779 ret
= bdrv_snapshot_delete(bs1
, name
);
6781 if (ret
== -ENOTSUP
)
6782 term_printf("Snapshots not supported on device '%s'\n",
6783 bdrv_get_device_name(bs1
));
6785 term_printf("Error %d while deleting snapshot on '%s'\n",
6786 ret
, bdrv_get_device_name(bs1
));
6792 void do_info_snapshots(void)
6794 BlockDriverState
*bs
, *bs1
;
6795 QEMUSnapshotInfo
*sn_tab
, *sn
;
6799 bs
= get_bs_snapshots();
6801 term_printf("No available block device supports snapshots\n");
6804 term_printf("Snapshot devices:");
6805 for(i
= 0; i
<= nb_drives
; i
++) {
6806 bs1
= drives_table
[i
].bdrv
;
6807 if (bdrv_has_snapshot(bs1
)) {
6809 term_printf(" %s", bdrv_get_device_name(bs1
));
6814 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6816 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6819 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6820 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6821 for(i
= 0; i
< nb_sns
; i
++) {
6823 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6828 /***********************************************************/
6829 /* ram save/restore */
6831 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6835 v
= qemu_get_byte(f
);
6838 if (qemu_get_buffer(f
, buf
, len
) != len
)
6842 v
= qemu_get_byte(f
);
6843 memset(buf
, v
, len
);
6851 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6856 if (qemu_get_be32(f
) != phys_ram_size
)
6858 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6859 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6866 #define BDRV_HASH_BLOCK_SIZE 1024
6867 #define IOBUF_SIZE 4096
6868 #define RAM_CBLOCK_MAGIC 0xfabe
6870 typedef struct RamCompressState
{
6873 uint8_t buf
[IOBUF_SIZE
];
6876 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6879 memset(s
, 0, sizeof(*s
));
6881 ret
= deflateInit2(&s
->zstream
, 1,
6883 9, Z_DEFAULT_STRATEGY
);
6886 s
->zstream
.avail_out
= IOBUF_SIZE
;
6887 s
->zstream
.next_out
= s
->buf
;
6891 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6893 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6894 qemu_put_be16(s
->f
, len
);
6895 qemu_put_buffer(s
->f
, buf
, len
);
6898 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6902 s
->zstream
.avail_in
= len
;
6903 s
->zstream
.next_in
= (uint8_t *)buf
;
6904 while (s
->zstream
.avail_in
> 0) {
6905 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6908 if (s
->zstream
.avail_out
== 0) {
6909 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6910 s
->zstream
.avail_out
= IOBUF_SIZE
;
6911 s
->zstream
.next_out
= s
->buf
;
6917 static void ram_compress_close(RamCompressState
*s
)
6921 /* compress last bytes */
6923 ret
= deflate(&s
->zstream
, Z_FINISH
);
6924 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6925 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6927 ram_put_cblock(s
, s
->buf
, len
);
6929 s
->zstream
.avail_out
= IOBUF_SIZE
;
6930 s
->zstream
.next_out
= s
->buf
;
6931 if (ret
== Z_STREAM_END
)
6938 deflateEnd(&s
->zstream
);
6941 typedef struct RamDecompressState
{
6944 uint8_t buf
[IOBUF_SIZE
];
6945 } RamDecompressState
;
6947 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6950 memset(s
, 0, sizeof(*s
));
6952 ret
= inflateInit(&s
->zstream
);
6958 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6962 s
->zstream
.avail_out
= len
;
6963 s
->zstream
.next_out
= buf
;
6964 while (s
->zstream
.avail_out
> 0) {
6965 if (s
->zstream
.avail_in
== 0) {
6966 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6968 clen
= qemu_get_be16(s
->f
);
6969 if (clen
> IOBUF_SIZE
)
6971 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6972 s
->zstream
.avail_in
= clen
;
6973 s
->zstream
.next_in
= s
->buf
;
6975 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6976 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6983 static void ram_decompress_close(RamDecompressState
*s
)
6985 inflateEnd(&s
->zstream
);
6988 static void ram_save(QEMUFile
*f
, void *opaque
)
6991 RamCompressState s1
, *s
= &s1
;
6994 qemu_put_be32(f
, phys_ram_size
);
6995 if (ram_compress_open(s
, f
) < 0)
6997 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6999 if (tight_savevm_enabled
) {
7003 /* find if the memory block is available on a virtual
7006 for(j
= 0; j
< nb_drives
; j
++) {
7007 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7009 BDRV_HASH_BLOCK_SIZE
);
7010 if (sector_num
>= 0)
7014 goto normal_compress
;
7017 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7018 ram_compress_buf(s
, buf
, 10);
7024 ram_compress_buf(s
, buf
, 1);
7025 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7028 ram_compress_close(s
);
7031 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7033 RamDecompressState s1
, *s
= &s1
;
7037 if (version_id
== 1)
7038 return ram_load_v1(f
, opaque
);
7039 if (version_id
!= 2)
7041 if (qemu_get_be32(f
) != phys_ram_size
)
7043 if (ram_decompress_open(s
, f
) < 0)
7045 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7046 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7047 fprintf(stderr
, "Error while reading ram block header\n");
7051 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7052 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7061 ram_decompress_buf(s
, buf
+ 1, 9);
7063 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7064 if (bs_index
>= nb_drives
) {
7065 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7068 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7070 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7071 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7072 bs_index
, sector_num
);
7079 printf("Error block header\n");
7083 ram_decompress_close(s
);
7087 /***********************************************************/
7088 /* bottom halves (can be seen as timers which expire ASAP) */
7097 static QEMUBH
*first_bh
= NULL
;
7099 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7102 bh
= qemu_mallocz(sizeof(QEMUBH
));
7106 bh
->opaque
= opaque
;
7110 int qemu_bh_poll(void)
7129 void qemu_bh_schedule(QEMUBH
*bh
)
7131 CPUState
*env
= cpu_single_env
;
7135 bh
->next
= first_bh
;
7138 /* stop the currently executing CPU to execute the BH ASAP */
7140 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7144 void qemu_bh_cancel(QEMUBH
*bh
)
7147 if (bh
->scheduled
) {
7150 pbh
= &(*pbh
)->next
;
7156 void qemu_bh_delete(QEMUBH
*bh
)
7162 /***********************************************************/
7163 /* machine registration */
7165 QEMUMachine
*first_machine
= NULL
;
7167 int qemu_register_machine(QEMUMachine
*m
)
7170 pm
= &first_machine
;
7178 static QEMUMachine
*find_machine(const char *name
)
7182 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7183 if (!strcmp(m
->name
, name
))
7189 /***********************************************************/
7190 /* main execution loop */
7192 static void gui_update(void *opaque
)
7194 DisplayState
*ds
= opaque
;
7195 ds
->dpy_refresh(ds
);
7196 qemu_mod_timer(ds
->gui_timer
,
7197 (ds
->gui_timer_interval
?
7198 ds
->gui_timer_interval
:
7199 GUI_REFRESH_INTERVAL
)
7200 + qemu_get_clock(rt_clock
));
7203 struct vm_change_state_entry
{
7204 VMChangeStateHandler
*cb
;
7206 LIST_ENTRY (vm_change_state_entry
) entries
;
7209 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7211 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7214 VMChangeStateEntry
*e
;
7216 e
= qemu_mallocz(sizeof (*e
));
7222 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7226 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7228 LIST_REMOVE (e
, entries
);
7232 static void vm_state_notify(int running
)
7234 VMChangeStateEntry
*e
;
7236 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7237 e
->cb(e
->opaque
, running
);
7241 /* XXX: support several handlers */
7242 static VMStopHandler
*vm_stop_cb
;
7243 static void *vm_stop_opaque
;
7245 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7248 vm_stop_opaque
= opaque
;
7252 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7263 qemu_rearm_alarm_timer(alarm_timer
);
7267 void vm_stop(int reason
)
7270 cpu_disable_ticks();
7274 vm_stop_cb(vm_stop_opaque
, reason
);
7281 /* reset/shutdown handler */
7283 typedef struct QEMUResetEntry
{
7284 QEMUResetHandler
*func
;
7286 struct QEMUResetEntry
*next
;
7289 static QEMUResetEntry
*first_reset_entry
;
7290 static int reset_requested
;
7291 static int shutdown_requested
;
7292 static int powerdown_requested
;
7294 int qemu_shutdown_requested(void)
7296 int r
= shutdown_requested
;
7297 shutdown_requested
= 0;
7301 int qemu_reset_requested(void)
7303 int r
= reset_requested
;
7304 reset_requested
= 0;
7308 int qemu_powerdown_requested(void)
7310 int r
= powerdown_requested
;
7311 powerdown_requested
= 0;
7315 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7317 QEMUResetEntry
**pre
, *re
;
7319 pre
= &first_reset_entry
;
7320 while (*pre
!= NULL
)
7321 pre
= &(*pre
)->next
;
7322 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7324 re
->opaque
= opaque
;
7329 void qemu_system_reset(void)
7333 /* reset all devices */
7334 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7335 re
->func(re
->opaque
);
7339 void qemu_system_reset_request(void)
7342 shutdown_requested
= 1;
7344 reset_requested
= 1;
7347 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7350 void qemu_system_shutdown_request(void)
7352 shutdown_requested
= 1;
7354 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7357 void qemu_system_powerdown_request(void)
7359 powerdown_requested
= 1;
7361 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7364 void main_loop_wait(int timeout
)
7366 IOHandlerRecord
*ioh
;
7367 fd_set rfds
, wfds
, xfds
;
7376 /* XXX: need to suppress polling by better using win32 events */
7378 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7379 ret
|= pe
->func(pe
->opaque
);
7384 WaitObjects
*w
= &wait_objects
;
7386 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7387 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7388 if (w
->func
[ret
- WAIT_OBJECT_0
])
7389 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7391 /* Check for additional signaled events */
7392 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7394 /* Check if event is signaled */
7395 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7396 if(ret2
== WAIT_OBJECT_0
) {
7398 w
->func
[i
](w
->opaque
[i
]);
7399 } else if (ret2
== WAIT_TIMEOUT
) {
7401 err
= GetLastError();
7402 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7405 } else if (ret
== WAIT_TIMEOUT
) {
7407 err
= GetLastError();
7408 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7412 /* poll any events */
7413 /* XXX: separate device handlers from system ones */
7418 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7422 (!ioh
->fd_read_poll
||
7423 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7424 FD_SET(ioh
->fd
, &rfds
);
7428 if (ioh
->fd_write
) {
7429 FD_SET(ioh
->fd
, &wfds
);
7439 tv
.tv_usec
= timeout
* 1000;
7441 #if defined(CONFIG_SLIRP)
7443 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7446 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7448 IOHandlerRecord
**pioh
;
7450 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7451 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7452 ioh
->fd_read(ioh
->opaque
);
7454 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7455 ioh
->fd_write(ioh
->opaque
);
7459 /* remove deleted IO handlers */
7460 pioh
= &first_io_handler
;
7470 #if defined(CONFIG_SLIRP)
7477 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7482 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7483 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7484 qemu_get_clock(vm_clock
));
7485 /* run dma transfers, if any */
7489 /* real time timers */
7490 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7491 qemu_get_clock(rt_clock
));
7493 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7494 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7495 qemu_rearm_alarm_timer(alarm_timer
);
7498 /* Check bottom-halves last in case any of the earlier events triggered
7504 static int main_loop(void)
7507 #ifdef CONFIG_PROFILER
7512 cur_cpu
= first_cpu
;
7513 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7520 #ifdef CONFIG_PROFILER
7521 ti
= profile_getclock();
7526 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7527 env
->icount_decr
.u16
.low
= 0;
7528 env
->icount_extra
= 0;
7529 count
= qemu_next_deadline();
7530 count
= (count
+ (1 << icount_time_shift
) - 1)
7531 >> icount_time_shift
;
7532 qemu_icount
+= count
;
7533 decr
= (count
> 0xffff) ? 0xffff : count
;
7535 env
->icount_decr
.u16
.low
= decr
;
7536 env
->icount_extra
= count
;
7538 ret
= cpu_exec(env
);
7539 #ifdef CONFIG_PROFILER
7540 qemu_time
+= profile_getclock() - ti
;
7543 /* Fold pending instructions back into the
7544 instruction counter, and clear the interrupt flag. */
7545 qemu_icount
-= (env
->icount_decr
.u16
.low
7546 + env
->icount_extra
);
7547 env
->icount_decr
.u32
= 0;
7548 env
->icount_extra
= 0;
7550 next_cpu
= env
->next_cpu
?: first_cpu
;
7551 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7552 ret
= EXCP_INTERRUPT
;
7556 if (ret
== EXCP_HLT
) {
7557 /* Give the next CPU a chance to run. */
7561 if (ret
!= EXCP_HALTED
)
7563 /* all CPUs are halted ? */
7569 if (shutdown_requested
) {
7570 ret
= EXCP_INTERRUPT
;
7578 if (reset_requested
) {
7579 reset_requested
= 0;
7580 qemu_system_reset();
7581 ret
= EXCP_INTERRUPT
;
7583 if (powerdown_requested
) {
7584 powerdown_requested
= 0;
7585 qemu_system_powerdown();
7586 ret
= EXCP_INTERRUPT
;
7588 if (unlikely(ret
== EXCP_DEBUG
)) {
7589 vm_stop(EXCP_DEBUG
);
7591 /* If all cpus are halted then wait until the next IRQ */
7592 /* XXX: use timeout computed from timers */
7593 if (ret
== EXCP_HALTED
) {
7597 /* Advance virtual time to the next event. */
7598 if (use_icount
== 1) {
7599 /* When not using an adaptive execution frequency
7600 we tend to get badly out of sync with real time,
7601 so just delay for a reasonable amount of time. */
7604 delta
= cpu_get_icount() - cpu_get_clock();
7607 /* If virtual time is ahead of real time then just
7609 timeout
= (delta
/ 1000000) + 1;
7611 /* Wait for either IO to occur or the next
7613 add
= qemu_next_deadline();
7614 /* We advance the timer before checking for IO.
7615 Limit the amount we advance so that early IO
7616 activity won't get the guest too far ahead. */
7620 add
= (add
+ (1 << icount_time_shift
) - 1)
7621 >> icount_time_shift
;
7623 timeout
= delta
/ 1000000;
7634 if (shutdown_requested
)
7638 #ifdef CONFIG_PROFILER
7639 ti
= profile_getclock();
7641 main_loop_wait(timeout
);
7642 #ifdef CONFIG_PROFILER
7643 dev_time
+= profile_getclock() - ti
;
7646 cpu_disable_ticks();
7650 static void help(int exitcode
)
7652 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7653 "usage: %s [options] [disk_image]\n"
7655 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7657 "Standard options:\n"
7658 "-M machine select emulated machine (-M ? for list)\n"
7659 "-cpu cpu select CPU (-cpu ? for list)\n"
7660 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7661 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7662 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7663 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7664 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7665 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7666 " [,cache=on|off][,format=f]\n"
7667 " use 'file' as a drive image\n"
7668 "-mtdblock file use 'file' as on-board Flash memory image\n"
7669 "-sd file use 'file' as SecureDigital card image\n"
7670 "-pflash file use 'file' as a parallel flash image\n"
7671 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7672 "-snapshot write to temporary files instead of disk image files\n"
7674 "-no-frame open SDL window without a frame and window decorations\n"
7675 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7676 "-no-quit disable SDL window close capability\n"
7679 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7681 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7682 "-smp n set the number of CPUs to 'n' [default=1]\n"
7683 "-nographic disable graphical output and redirect serial I/Os to console\n"
7684 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7686 "-k language use keyboard layout (for example \"fr\" for French)\n"
7689 "-audio-help print list of audio drivers and their options\n"
7690 "-soundhw c1,... enable audio support\n"
7691 " and only specified sound cards (comma separated list)\n"
7692 " use -soundhw ? to get the list of supported cards\n"
7693 " use -soundhw all to enable all of them\n"
7695 "-vga [std|cirrus|vmware]\n"
7696 " select video card type\n"
7697 "-localtime set the real time clock to local time [default=utc]\n"
7698 "-full-screen start in full screen\n"
7700 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7702 "-usb enable the USB driver (will be the default soon)\n"
7703 "-usbdevice name add the host or guest USB device 'name'\n"
7704 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7705 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7707 "-name string set the name of the guest\n"
7708 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
7710 "Network options:\n"
7711 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7712 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7714 "-net user[,vlan=n][,hostname=host]\n"
7715 " connect the user mode network stack to VLAN 'n' and send\n"
7716 " hostname 'host' to DHCP clients\n"
7719 "-net tap[,vlan=n],ifname=name\n"
7720 " connect the host TAP network interface to VLAN 'n'\n"
7722 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7723 " connect the host TAP network interface to VLAN 'n' and use the\n"
7724 " network scripts 'file' (default=%s)\n"
7725 " and 'dfile' (default=%s);\n"
7726 " use '[down]script=no' to disable script execution;\n"
7727 " use 'fd=h' to connect to an already opened TAP interface\n"
7729 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7730 " connect the vlan 'n' to another VLAN using a socket connection\n"
7731 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7732 " connect the vlan 'n' to multicast maddr and port\n"
7734 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7735 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7736 " on host and listening for incoming connections on 'socketpath'.\n"
7737 " Use group 'groupname' and mode 'octalmode' to change default\n"
7738 " ownership and permissions for communication port.\n"
7740 "-net none use it alone to have zero network devices; if no -net option\n"
7741 " is provided, the default is '-net nic -net user'\n"
7744 "-tftp dir allow tftp access to files in dir [-net user]\n"
7745 "-bootp file advertise file in BOOTP replies\n"
7747 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7749 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7750 " redirect TCP or UDP connections from host to guest [-net user]\n"
7753 "Linux boot specific:\n"
7754 "-kernel bzImage use 'bzImage' as kernel image\n"
7755 "-append cmdline use 'cmdline' as kernel command line\n"
7756 "-initrd file use 'file' as initial ram disk\n"
7758 "Debug/Expert options:\n"
7759 "-monitor dev redirect the monitor to char device 'dev'\n"
7760 "-serial dev redirect the serial port to char device 'dev'\n"
7761 "-parallel dev redirect the parallel port to char device 'dev'\n"
7762 "-pidfile file Write PID to 'file'\n"
7763 "-S freeze CPU at startup (use 'c' to start execution)\n"
7764 "-s wait gdb connection to port\n"
7765 "-p port set gdb connection port [default=%s]\n"
7766 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7767 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7768 " translation (t=none or lba) (usually qemu can guess them)\n"
7769 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7771 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7772 "-no-kqemu disable KQEMU kernel module usage\n"
7775 "-no-acpi disable ACPI\n"
7777 #ifdef CONFIG_CURSES
7778 "-curses use a curses/ncurses interface instead of SDL\n"
7780 "-no-reboot exit instead of rebooting\n"
7781 "-no-shutdown stop before shutdown\n"
7782 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7783 "-vnc display start a VNC server on display\n"
7785 "-daemonize daemonize QEMU after initializing\n"
7787 "-option-rom rom load a file, rom, into the option ROM space\n"
7789 "-prom-env variable=value set OpenBIOS nvram variables\n"
7791 "-clock force the use of the given methods for timer alarm.\n"
7792 " To see what timers are available use -clock ?\n"
7793 "-startdate select initial date of the clock\n"
7794 "-icount [N|auto]\n"
7795 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7797 "During emulation, the following keys are useful:\n"
7798 "ctrl-alt-f toggle full screen\n"
7799 "ctrl-alt-n switch to virtual console 'n'\n"
7800 "ctrl-alt toggle mouse and keyboard grab\n"
7802 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7807 DEFAULT_NETWORK_SCRIPT
,
7808 DEFAULT_NETWORK_DOWN_SCRIPT
,
7810 DEFAULT_GDBSTUB_PORT
,
7815 #define HAS_ARG 0x0001
7830 QEMU_OPTION_mtdblock
,
7834 QEMU_OPTION_snapshot
,
7836 QEMU_OPTION_no_fd_bootchk
,
7839 QEMU_OPTION_nographic
,
7840 QEMU_OPTION_portrait
,
7842 QEMU_OPTION_audio_help
,
7843 QEMU_OPTION_soundhw
,
7864 QEMU_OPTION_localtime
,
7868 QEMU_OPTION_monitor
,
7870 QEMU_OPTION_parallel
,
7872 QEMU_OPTION_full_screen
,
7873 QEMU_OPTION_no_frame
,
7874 QEMU_OPTION_alt_grab
,
7875 QEMU_OPTION_no_quit
,
7876 QEMU_OPTION_pidfile
,
7877 QEMU_OPTION_no_kqemu
,
7878 QEMU_OPTION_kernel_kqemu
,
7879 QEMU_OPTION_win2k_hack
,
7881 QEMU_OPTION_usbdevice
,
7884 QEMU_OPTION_no_acpi
,
7886 QEMU_OPTION_no_reboot
,
7887 QEMU_OPTION_no_shutdown
,
7888 QEMU_OPTION_show_cursor
,
7889 QEMU_OPTION_daemonize
,
7890 QEMU_OPTION_option_rom
,
7891 QEMU_OPTION_semihosting
,
7893 QEMU_OPTION_prom_env
,
7894 QEMU_OPTION_old_param
,
7896 QEMU_OPTION_startdate
,
7897 QEMU_OPTION_tb_size
,
7902 typedef struct QEMUOption
{
7908 const QEMUOption qemu_options
[] = {
7909 { "h", 0, QEMU_OPTION_h
},
7910 { "help", 0, QEMU_OPTION_h
},
7912 { "M", HAS_ARG
, QEMU_OPTION_M
},
7913 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7914 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7915 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7916 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7917 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7918 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7919 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7920 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7921 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7922 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7923 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7924 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7925 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7926 { "snapshot", 0, QEMU_OPTION_snapshot
},
7928 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7930 { "m", HAS_ARG
, QEMU_OPTION_m
},
7931 { "nographic", 0, QEMU_OPTION_nographic
},
7932 { "portrait", 0, QEMU_OPTION_portrait
},
7933 { "k", HAS_ARG
, QEMU_OPTION_k
},
7935 { "audio-help", 0, QEMU_OPTION_audio_help
},
7936 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7939 { "net", HAS_ARG
, QEMU_OPTION_net
},
7941 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7942 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7944 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7946 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7949 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7950 { "append", HAS_ARG
, QEMU_OPTION_append
},
7951 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7953 { "S", 0, QEMU_OPTION_S
},
7954 { "s", 0, QEMU_OPTION_s
},
7955 { "p", HAS_ARG
, QEMU_OPTION_p
},
7956 { "d", HAS_ARG
, QEMU_OPTION_d
},
7957 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7958 { "L", HAS_ARG
, QEMU_OPTION_L
},
7959 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7961 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7962 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7964 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7965 { "g", 1, QEMU_OPTION_g
},
7967 { "localtime", 0, QEMU_OPTION_localtime
},
7968 { "vga", HAS_ARG
, QEMU_OPTION_vga
},
7969 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7970 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7971 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7972 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7973 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7974 { "full-screen", 0, QEMU_OPTION_full_screen
},
7976 { "no-frame", 0, QEMU_OPTION_no_frame
},
7977 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7978 { "no-quit", 0, QEMU_OPTION_no_quit
},
7980 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7981 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7982 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7983 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7984 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7985 #ifdef CONFIG_CURSES
7986 { "curses", 0, QEMU_OPTION_curses
},
7988 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
7990 /* temporary options */
7991 { "usb", 0, QEMU_OPTION_usb
},
7992 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7993 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7994 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7995 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7996 { "daemonize", 0, QEMU_OPTION_daemonize
},
7997 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7998 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7999 { "semihosting", 0, QEMU_OPTION_semihosting
},
8001 { "name", HAS_ARG
, QEMU_OPTION_name
},
8002 #if defined(TARGET_SPARC)
8003 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8005 #if defined(TARGET_ARM)
8006 { "old-param", 0, QEMU_OPTION_old_param
},
8008 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8009 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8010 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8011 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8015 /* password input */
8017 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8022 if (!bdrv_is_encrypted(bs
))
8025 term_printf("%s is encrypted.\n", name
);
8026 for(i
= 0; i
< 3; i
++) {
8027 monitor_readline("Password: ", 1, password
, sizeof(password
));
8028 if (bdrv_set_key(bs
, password
) == 0)
8030 term_printf("invalid password\n");
8035 static BlockDriverState
*get_bdrv(int index
)
8037 if (index
> nb_drives
)
8039 return drives_table
[index
].bdrv
;
8042 static void read_passwords(void)
8044 BlockDriverState
*bs
;
8047 for(i
= 0; i
< 6; i
++) {
8050 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8055 struct soundhw soundhw
[] = {
8056 #ifdef HAS_AUDIO_CHOICE
8057 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8063 { .init_isa
= pcspk_audio_init
}
8068 "Creative Sound Blaster 16",
8071 { .init_isa
= SB16_init
}
8074 #ifdef CONFIG_CS4231A
8080 { .init_isa
= cs4231a_init
}
8088 "Yamaha YMF262 (OPL3)",
8090 "Yamaha YM3812 (OPL2)",
8094 { .init_isa
= Adlib_init
}
8101 "Gravis Ultrasound GF1",
8104 { .init_isa
= GUS_init
}
8111 "Intel 82801AA AC97 Audio",
8114 { .init_pci
= ac97_init
}
8120 "ENSONIQ AudioPCI ES1370",
8123 { .init_pci
= es1370_init
}
8127 { NULL
, NULL
, 0, 0, { NULL
} }
8130 static void select_soundhw (const char *optarg
)
8134 if (*optarg
== '?') {
8137 printf ("Valid sound card names (comma separated):\n");
8138 for (c
= soundhw
; c
->name
; ++c
) {
8139 printf ("%-11s %s\n", c
->name
, c
->descr
);
8141 printf ("\n-soundhw all will enable all of the above\n");
8142 exit (*optarg
!= '?');
8150 if (!strcmp (optarg
, "all")) {
8151 for (c
= soundhw
; c
->name
; ++c
) {
8159 e
= strchr (p
, ',');
8160 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8162 for (c
= soundhw
; c
->name
; ++c
) {
8163 if (!strncmp (c
->name
, p
, l
)) {
8172 "Unknown sound card name (too big to show)\n");
8175 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8180 p
+= l
+ (e
!= NULL
);
8184 goto show_valid_cards
;
8189 static void select_vgahw (const char *p
)
8193 if (strstart(p
, "std", &opts
)) {
8194 cirrus_vga_enabled
= 0;
8196 } else if (strstart(p
, "cirrus", &opts
)) {
8197 cirrus_vga_enabled
= 1;
8199 } else if (strstart(p
, "vmware", &opts
)) {
8200 cirrus_vga_enabled
= 0;
8204 fprintf(stderr
, "Unknown vga type: %s\n", p
);
8208 const char *nextopt
;
8210 if (strstart(opts
, ",retrace=", &nextopt
)) {
8212 if (strstart(opts
, "dumb", &nextopt
))
8213 vga_retrace_method
= VGA_RETRACE_DUMB
;
8214 else if (strstart(opts
, "precise", &nextopt
))
8215 vga_retrace_method
= VGA_RETRACE_PRECISE
;
8216 else goto invalid_vga
;
8217 } else goto invalid_vga
;
8223 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8225 exit(STATUS_CONTROL_C_EXIT
);
8230 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8234 if(strlen(str
) != 36)
8237 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8238 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8239 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8247 #define MAX_NET_CLIENTS 32
8251 static void termsig_handler(int signal
)
8253 qemu_system_shutdown_request();
8256 static void termsig_setup(void)
8258 struct sigaction act
;
8260 memset(&act
, 0, sizeof(act
));
8261 act
.sa_handler
= termsig_handler
;
8262 sigaction(SIGINT
, &act
, NULL
);
8263 sigaction(SIGHUP
, &act
, NULL
);
8264 sigaction(SIGTERM
, &act
, NULL
);
8269 int main(int argc
, char **argv
)
8271 #ifdef CONFIG_GDBSTUB
8273 const char *gdbstub_port
;
8275 uint32_t boot_devices_bitmap
= 0;
8277 int snapshot
, linux_boot
, net_boot
;
8278 const char *initrd_filename
;
8279 const char *kernel_filename
, *kernel_cmdline
;
8280 const char *boot_devices
= "";
8281 DisplayState
*ds
= &display_state
;
8282 int cyls
, heads
, secs
, translation
;
8283 const char *net_clients
[MAX_NET_CLIENTS
];
8287 const char *r
, *optarg
;
8288 CharDriverState
*monitor_hd
;
8289 const char *monitor_device
;
8290 const char *serial_devices
[MAX_SERIAL_PORTS
];
8291 int serial_device_index
;
8292 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8293 int parallel_device_index
;
8294 const char *loadvm
= NULL
;
8295 QEMUMachine
*machine
;
8296 const char *cpu_model
;
8297 const char *usb_devices
[MAX_USB_CMDLINE
];
8298 int usb_devices_index
;
8301 const char *pid_file
= NULL
;
8304 LIST_INIT (&vm_change_state_head
);
8307 struct sigaction act
;
8308 sigfillset(&act
.sa_mask
);
8310 act
.sa_handler
= SIG_IGN
;
8311 sigaction(SIGPIPE
, &act
, NULL
);
8314 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8315 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8316 QEMU to run on a single CPU */
8321 h
= GetCurrentProcess();
8322 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8323 for(i
= 0; i
< 32; i
++) {
8324 if (mask
& (1 << i
))
8329 SetProcessAffinityMask(h
, mask
);
8335 register_machines();
8336 machine
= first_machine
;
8338 initrd_filename
= NULL
;
8340 vga_ram_size
= VGA_RAM_SIZE
;
8341 #ifdef CONFIG_GDBSTUB
8343 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8348 kernel_filename
= NULL
;
8349 kernel_cmdline
= "";
8350 cyls
= heads
= secs
= 0;
8351 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8352 monitor_device
= "vc";
8354 serial_devices
[0] = "vc:80Cx24C";
8355 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8356 serial_devices
[i
] = NULL
;
8357 serial_device_index
= 0;
8359 parallel_devices
[0] = "vc:640x480";
8360 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8361 parallel_devices
[i
] = NULL
;
8362 parallel_device_index
= 0;
8364 usb_devices_index
= 0;
8381 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8383 const QEMUOption
*popt
;
8386 /* Treat --foo the same as -foo. */
8389 popt
= qemu_options
;
8392 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8396 if (!strcmp(popt
->name
, r
+ 1))
8400 if (popt
->flags
& HAS_ARG
) {
8401 if (optind
>= argc
) {
8402 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8406 optarg
= argv
[optind
++];
8411 switch(popt
->index
) {
8413 machine
= find_machine(optarg
);
8416 printf("Supported machines are:\n");
8417 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8418 printf("%-10s %s%s\n",
8420 m
== first_machine
? " (default)" : "");
8422 exit(*optarg
!= '?');
8425 case QEMU_OPTION_cpu
:
8426 /* hw initialization will check this */
8427 if (*optarg
== '?') {
8428 /* XXX: implement xxx_cpu_list for targets that still miss it */
8429 #if defined(cpu_list)
8430 cpu_list(stdout
, &fprintf
);
8437 case QEMU_OPTION_initrd
:
8438 initrd_filename
= optarg
;
8440 case QEMU_OPTION_hda
:
8442 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8444 hda_index
= drive_add(optarg
, HD_ALIAS
8445 ",cyls=%d,heads=%d,secs=%d%s",
8446 0, cyls
, heads
, secs
,
8447 translation
== BIOS_ATA_TRANSLATION_LBA
?
8449 translation
== BIOS_ATA_TRANSLATION_NONE
?
8450 ",trans=none" : "");
8452 case QEMU_OPTION_hdb
:
8453 case QEMU_OPTION_hdc
:
8454 case QEMU_OPTION_hdd
:
8455 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8457 case QEMU_OPTION_drive
:
8458 drive_add(NULL
, "%s", optarg
);
8460 case QEMU_OPTION_mtdblock
:
8461 drive_add(optarg
, MTD_ALIAS
);
8463 case QEMU_OPTION_sd
:
8464 drive_add(optarg
, SD_ALIAS
);
8466 case QEMU_OPTION_pflash
:
8467 drive_add(optarg
, PFLASH_ALIAS
);
8469 case QEMU_OPTION_snapshot
:
8472 case QEMU_OPTION_hdachs
:
8476 cyls
= strtol(p
, (char **)&p
, 0);
8477 if (cyls
< 1 || cyls
> 16383)
8482 heads
= strtol(p
, (char **)&p
, 0);
8483 if (heads
< 1 || heads
> 16)
8488 secs
= strtol(p
, (char **)&p
, 0);
8489 if (secs
< 1 || secs
> 63)
8493 if (!strcmp(p
, "none"))
8494 translation
= BIOS_ATA_TRANSLATION_NONE
;
8495 else if (!strcmp(p
, "lba"))
8496 translation
= BIOS_ATA_TRANSLATION_LBA
;
8497 else if (!strcmp(p
, "auto"))
8498 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8501 } else if (*p
!= '\0') {
8503 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8506 if (hda_index
!= -1)
8507 snprintf(drives_opt
[hda_index
].opt
,
8508 sizeof(drives_opt
[hda_index
].opt
),
8509 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8510 0, cyls
, heads
, secs
,
8511 translation
== BIOS_ATA_TRANSLATION_LBA
?
8513 translation
== BIOS_ATA_TRANSLATION_NONE
?
8514 ",trans=none" : "");
8517 case QEMU_OPTION_nographic
:
8520 #ifdef CONFIG_CURSES
8521 case QEMU_OPTION_curses
:
8525 case QEMU_OPTION_portrait
:
8528 case QEMU_OPTION_kernel
:
8529 kernel_filename
= optarg
;
8531 case QEMU_OPTION_append
:
8532 kernel_cmdline
= optarg
;
8534 case QEMU_OPTION_cdrom
:
8535 drive_add(optarg
, CDROM_ALIAS
);
8537 case QEMU_OPTION_boot
:
8538 boot_devices
= optarg
;
8539 /* We just do some generic consistency checks */
8541 /* Could easily be extended to 64 devices if needed */
8544 boot_devices_bitmap
= 0;
8545 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8546 /* Allowed boot devices are:
8547 * a b : floppy disk drives
8548 * c ... f : IDE disk drives
8549 * g ... m : machine implementation dependant drives
8550 * n ... p : network devices
8551 * It's up to each machine implementation to check
8552 * if the given boot devices match the actual hardware
8553 * implementation and firmware features.
8555 if (*p
< 'a' || *p
> 'q') {
8556 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8559 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8561 "Boot device '%c' was given twice\n",*p
);
8564 boot_devices_bitmap
|= 1 << (*p
- 'a');
8568 case QEMU_OPTION_fda
:
8569 case QEMU_OPTION_fdb
:
8570 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8573 case QEMU_OPTION_no_fd_bootchk
:
8577 case QEMU_OPTION_net
:
8578 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8579 fprintf(stderr
, "qemu: too many network clients\n");
8582 net_clients
[nb_net_clients
] = optarg
;
8586 case QEMU_OPTION_tftp
:
8587 tftp_prefix
= optarg
;
8589 case QEMU_OPTION_bootp
:
8590 bootp_filename
= optarg
;
8593 case QEMU_OPTION_smb
:
8594 net_slirp_smb(optarg
);
8597 case QEMU_OPTION_redir
:
8598 net_slirp_redir(optarg
);
8602 case QEMU_OPTION_audio_help
:
8606 case QEMU_OPTION_soundhw
:
8607 select_soundhw (optarg
);
8613 case QEMU_OPTION_m
: {
8617 value
= strtoul(optarg
, &ptr
, 10);
8619 case 0: case 'M': case 'm':
8626 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8630 /* On 32-bit hosts, QEMU is limited by virtual address space */
8631 if (value
> (2047 << 20)
8633 && HOST_LONG_BITS
== 32
8636 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8639 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8640 fprintf(stderr
, "qemu: ram size too large\n");
8651 mask
= cpu_str_to_log_mask(optarg
);
8653 printf("Log items (comma separated):\n");
8654 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8655 printf("%-10s %s\n", item
->name
, item
->help
);
8662 #ifdef CONFIG_GDBSTUB
8667 gdbstub_port
= optarg
;
8673 case QEMU_OPTION_bios
:
8680 keyboard_layout
= optarg
;
8682 case QEMU_OPTION_localtime
:
8685 case QEMU_OPTION_vga
:
8686 select_vgahw (optarg
);
8693 w
= strtol(p
, (char **)&p
, 10);
8696 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8702 h
= strtol(p
, (char **)&p
, 10);
8707 depth
= strtol(p
, (char **)&p
, 10);
8708 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8709 depth
!= 24 && depth
!= 32)
8711 } else if (*p
== '\0') {
8712 depth
= graphic_depth
;
8719 graphic_depth
= depth
;
8722 case QEMU_OPTION_echr
:
8725 term_escape_char
= strtol(optarg
, &r
, 0);
8727 printf("Bad argument to echr\n");
8730 case QEMU_OPTION_monitor
:
8731 monitor_device
= optarg
;
8733 case QEMU_OPTION_serial
:
8734 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8735 fprintf(stderr
, "qemu: too many serial ports\n");
8738 serial_devices
[serial_device_index
] = optarg
;
8739 serial_device_index
++;
8741 case QEMU_OPTION_parallel
:
8742 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8743 fprintf(stderr
, "qemu: too many parallel ports\n");
8746 parallel_devices
[parallel_device_index
] = optarg
;
8747 parallel_device_index
++;
8749 case QEMU_OPTION_loadvm
:
8752 case QEMU_OPTION_full_screen
:
8756 case QEMU_OPTION_no_frame
:
8759 case QEMU_OPTION_alt_grab
:
8762 case QEMU_OPTION_no_quit
:
8766 case QEMU_OPTION_pidfile
:
8770 case QEMU_OPTION_win2k_hack
:
8771 win2k_install_hack
= 1;
8775 case QEMU_OPTION_no_kqemu
:
8778 case QEMU_OPTION_kernel_kqemu
:
8782 case QEMU_OPTION_usb
:
8785 case QEMU_OPTION_usbdevice
:
8787 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8788 fprintf(stderr
, "Too many USB devices\n");
8791 usb_devices
[usb_devices_index
] = optarg
;
8792 usb_devices_index
++;
8794 case QEMU_OPTION_smp
:
8795 smp_cpus
= atoi(optarg
);
8796 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8797 fprintf(stderr
, "Invalid number of CPUs\n");
8801 case QEMU_OPTION_vnc
:
8802 vnc_display
= optarg
;
8804 case QEMU_OPTION_no_acpi
:
8807 case QEMU_OPTION_no_reboot
:
8810 case QEMU_OPTION_no_shutdown
:
8813 case QEMU_OPTION_show_cursor
:
8816 case QEMU_OPTION_uuid
:
8817 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
8818 fprintf(stderr
, "Fail to parse UUID string."
8819 " Wrong format.\n");
8823 case QEMU_OPTION_daemonize
:
8826 case QEMU_OPTION_option_rom
:
8827 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8828 fprintf(stderr
, "Too many option ROMs\n");
8831 option_rom
[nb_option_roms
] = optarg
;
8834 case QEMU_OPTION_semihosting
:
8835 semihosting_enabled
= 1;
8837 case QEMU_OPTION_name
:
8841 case QEMU_OPTION_prom_env
:
8842 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8843 fprintf(stderr
, "Too many prom variables\n");
8846 prom_envs
[nb_prom_envs
] = optarg
;
8851 case QEMU_OPTION_old_param
:
8855 case QEMU_OPTION_clock
:
8856 configure_alarms(optarg
);
8858 case QEMU_OPTION_startdate
:
8861 time_t rtc_start_date
;
8862 if (!strcmp(optarg
, "now")) {
8863 rtc_date_offset
= -1;
8865 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8873 } else if (sscanf(optarg
, "%d-%d-%d",
8876 &tm
.tm_mday
) == 3) {
8885 rtc_start_date
= mktimegm(&tm
);
8886 if (rtc_start_date
== -1) {
8888 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8889 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8892 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8896 case QEMU_OPTION_tb_size
:
8897 tb_size
= strtol(optarg
, NULL
, 0);
8901 case QEMU_OPTION_icount
:
8903 if (strcmp(optarg
, "auto") == 0) {
8904 icount_time_shift
= -1;
8906 icount_time_shift
= strtol(optarg
, NULL
, 0);
8914 if (serial_device_index
== 0)
8915 serial_devices
[0] = "stdio";
8916 if (parallel_device_index
== 0)
8917 parallel_devices
[0] = "null";
8918 if (strncmp(monitor_device
, "vc", 2) == 0)
8919 monitor_device
= "stdio";
8926 if (pipe(fds
) == -1)
8937 len
= read(fds
[0], &status
, 1);
8938 if (len
== -1 && (errno
== EINTR
))
8943 else if (status
== 1) {
8944 fprintf(stderr
, "Could not acquire pidfile\n");
8961 signal(SIGTSTP
, SIG_IGN
);
8962 signal(SIGTTOU
, SIG_IGN
);
8963 signal(SIGTTIN
, SIG_IGN
);
8967 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8970 write(fds
[1], &status
, 1);
8972 fprintf(stderr
, "Could not acquire pid file\n");
8980 linux_boot
= (kernel_filename
!= NULL
);
8981 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8983 if (!linux_boot
&& net_boot
== 0 &&
8984 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8987 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8988 fprintf(stderr
, "-append only allowed with -kernel option\n");
8992 if (!linux_boot
&& initrd_filename
!= NULL
) {
8993 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8997 /* boot to floppy or the default cd if no hard disk defined yet */
8998 if (!boot_devices
[0]) {
8999 boot_devices
= "cad";
9001 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9005 if (use_icount
&& icount_time_shift
< 0) {
9007 /* 125MIPS seems a reasonable initial guess at the guest speed.
9008 It will be corrected fairly quickly anyway. */
9009 icount_time_shift
= 3;
9010 init_icount_adjust();
9017 /* init network clients */
9018 if (nb_net_clients
== 0) {
9019 /* if no clients, we use a default config */
9020 net_clients
[nb_net_clients
++] = "nic";
9022 net_clients
[nb_net_clients
++] = "user";
9026 for(i
= 0;i
< nb_net_clients
; i
++) {
9027 if (net_client_parse(net_clients
[i
]) < 0)
9030 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9031 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9033 if (vlan
->nb_guest_devs
== 0)
9034 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9035 if (vlan
->nb_host_devs
== 0)
9037 "Warning: vlan %d is not connected to host network\n",
9042 /* XXX: this should be moved in the PC machine instantiation code */
9043 if (net_boot
!= 0) {
9045 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9046 const char *model
= nd_table
[i
].model
;
9048 if (net_boot
& (1 << i
)) {
9051 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9052 if (get_image_size(buf
) > 0) {
9053 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9054 fprintf(stderr
, "Too many option ROMs\n");
9057 option_rom
[nb_option_roms
] = strdup(buf
);
9064 fprintf(stderr
, "No valid PXE rom found for network device\n");
9070 /* init the memory */
9071 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9073 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9075 if (ram_size
< phys_ram_size
) {
9076 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9077 machine
->name
, (unsigned long long) phys_ram_size
);
9081 phys_ram_size
= ram_size
;
9083 ram_size
= phys_ram_size
;
9086 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9088 phys_ram_size
+= ram_size
;
9091 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9092 if (!phys_ram_base
) {
9093 fprintf(stderr
, "Could not allocate physical memory\n");
9097 /* init the dynamic translator */
9098 cpu_exec_init_all(tb_size
* 1024 * 1024);
9102 /* we always create the cdrom drive, even if no disk is there */
9104 if (nb_drives_opt
< MAX_DRIVES
)
9105 drive_add(NULL
, CDROM_ALIAS
);
9107 /* we always create at least one floppy */
9109 if (nb_drives_opt
< MAX_DRIVES
)
9110 drive_add(NULL
, FD_ALIAS
, 0);
9112 /* we always create one sd slot, even if no card is in it */
9114 if (nb_drives_opt
< MAX_DRIVES
)
9115 drive_add(NULL
, SD_ALIAS
);
9117 /* open the virtual block devices */
9119 for(i
= 0; i
< nb_drives_opt
; i
++)
9120 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9123 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9124 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9127 memset(&display_state
, 0, sizeof(display_state
));
9130 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9133 /* nearly nothing to do */
9134 dumb_display_init(ds
);
9135 } else if (vnc_display
!= NULL
) {
9136 vnc_display_init(ds
);
9137 if (vnc_display_open(ds
, vnc_display
) < 0)
9140 #if defined(CONFIG_CURSES)
9142 curses_display_init(ds
, full_screen
);
9146 #if defined(CONFIG_SDL)
9147 sdl_display_init(ds
, full_screen
, no_frame
);
9148 #elif defined(CONFIG_COCOA)
9149 cocoa_display_init(ds
, full_screen
);
9151 dumb_display_init(ds
);
9156 /* must be after terminal init, SDL library changes signal handlers */
9160 /* Maintain compatibility with multiple stdio monitors */
9161 if (!strcmp(monitor_device
,"stdio")) {
9162 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9163 const char *devname
= serial_devices
[i
];
9164 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9165 monitor_device
= NULL
;
9167 } else if (devname
&& !strcmp(devname
,"stdio")) {
9168 monitor_device
= NULL
;
9169 serial_devices
[i
] = "mon:stdio";
9174 if (monitor_device
) {
9175 monitor_hd
= qemu_chr_open(monitor_device
);
9177 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9180 monitor_init(monitor_hd
, !nographic
);
9183 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9184 const char *devname
= serial_devices
[i
];
9185 if (devname
&& strcmp(devname
, "none")) {
9186 serial_hds
[i
] = qemu_chr_open(devname
);
9187 if (!serial_hds
[i
]) {
9188 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9192 if (strstart(devname
, "vc", 0))
9193 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9197 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9198 const char *devname
= parallel_devices
[i
];
9199 if (devname
&& strcmp(devname
, "none")) {
9200 parallel_hds
[i
] = qemu_chr_open(devname
);
9201 if (!parallel_hds
[i
]) {
9202 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9206 if (strstart(devname
, "vc", 0))
9207 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9211 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9212 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9214 /* init USB devices */
9216 for(i
= 0; i
< usb_devices_index
; i
++) {
9217 if (usb_device_add(usb_devices
[i
]) < 0) {
9218 fprintf(stderr
, "Warning: could not add USB device %s\n",
9224 if (display_state
.dpy_refresh
) {
9225 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9226 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9229 #ifdef CONFIG_GDBSTUB
9231 /* XXX: use standard host:port notation and modify options
9233 if (gdbserver_start(gdbstub_port
) < 0) {
9234 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9245 /* XXX: simplify init */
9258 len
= write(fds
[1], &status
, 1);
9259 if (len
== -1 && (errno
== EINTR
))
9266 TFR(fd
= open("/dev/null", O_RDWR
));
9280 #if !defined(_WIN32)
9281 /* close network clients */
9282 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9283 VLANClientState
*vc
;
9285 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9286 if (vc
->fd_read
== tap_receive
) {
9288 TAPState
*s
= vc
->opaque
;
9290 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9292 launch_script(s
->down_script
, ifname
, s
->fd
);
9294 #if defined(CONFIG_VDE)
9295 if (vc
->fd_read
== vde_from_qemu
) {
9296 VDEState
*s
= vc
->opaque
;