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"
37 #include "qemu-timer.h"
38 #include "qemu-char.h"
40 #include "audio/audio.h"
51 #include <sys/times.h>
56 #include <sys/ioctl.h>
57 #include <sys/socket.h>
58 #include <netinet/in.h>
61 #include <sys/select.h>
62 #include <arpa/inet.h>
65 #if !defined(__APPLE__) && !defined(__OpenBSD__)
71 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
72 #include <freebsd/stdlib.h>
76 #include <linux/if_tun.h>
79 #include <linux/rtc.h>
81 /* For the benefit of older linux systems which don't supply it,
82 we use a local copy of hpet.h. */
83 /* #include <linux/hpet.h> */
86 #include <linux/ppdev.h>
87 #include <linux/parport.h>
91 #include <sys/ethernet.h>
92 #include <sys/sockio.h>
93 #include <netinet/arp.h>
94 #include <netinet/in.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_icmp.h> // must come after ip.h
98 #include <netinet/udp.h>
99 #include <netinet/tcp.h>
107 #include "qemu_socket.h"
109 #if defined(CONFIG_SLIRP)
110 #include "libslirp.h"
113 #if defined(__OpenBSD__)
117 #if defined(CONFIG_VDE)
118 #include <libvdeplug.h>
123 #include <sys/timeb.h>
124 #include <mmsystem.h>
125 #define getopt_long_only getopt_long
126 #define memalign(align, size) malloc(size)
133 #endif /* CONFIG_SDL */
137 #define main qemu_main
138 #endif /* CONFIG_COCOA */
142 #include "exec-all.h"
144 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
145 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
147 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
149 #define SMBD_COMMAND "/usr/sbin/smbd"
152 //#define DEBUG_UNUSED_IOPORT
153 //#define DEBUG_IOPORT
156 #define DEFAULT_RAM_SIZE 144
158 #define DEFAULT_RAM_SIZE 128
161 /* Max number of USB devices that can be specified on the commandline. */
162 #define MAX_USB_CMDLINE 8
164 /* XXX: use a two level table to limit memory usage */
165 #define MAX_IOPORTS 65536
167 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
168 const char *bios_name
= NULL
;
169 static void *ioport_opaque
[MAX_IOPORTS
];
170 static IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
171 static IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
172 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
173 to store the VM snapshots */
174 DriveInfo drives_table
[MAX_DRIVES
+1];
176 /* point to the block driver where the snapshots are managed */
177 static BlockDriverState
*bs_snapshots
;
178 static int vga_ram_size
;
179 enum vga_retrace_method vga_retrace_method
= VGA_RETRACE_DUMB
;
180 static DisplayState display_state
;
183 const char* keyboard_layout
= NULL
;
184 int64_t ticks_per_sec
;
187 NICInfo nd_table
[MAX_NICS
];
189 static int rtc_utc
= 1;
190 static int rtc_date_offset
= -1; /* -1 means no change */
191 int cirrus_vga_enabled
= 1;
192 int vmsvga_enabled
= 0;
194 int graphic_width
= 1024;
195 int graphic_height
= 768;
196 int graphic_depth
= 8;
198 int graphic_width
= 800;
199 int graphic_height
= 600;
200 int graphic_depth
= 15;
202 static int full_screen
= 0;
203 static int no_frame
= 0;
205 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
206 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
208 int win2k_install_hack
= 0;
211 static VLANState
*first_vlan
;
213 const char *vnc_display
;
214 #if defined(TARGET_SPARC)
216 #elif defined(TARGET_I386)
221 int acpi_enabled
= 1;
226 int graphic_rotate
= 0;
228 const char *option_rom
[MAX_OPTION_ROMS
];
230 int semihosting_enabled
= 0;
235 const char *qemu_name
;
238 unsigned int nb_prom_envs
= 0;
239 const char *prom_envs
[MAX_PROM_ENVS
];
241 static int nb_drives_opt
;
242 static struct drive_opt
{
245 } drives_opt
[MAX_DRIVES
];
247 static CPUState
*cur_cpu
;
248 static CPUState
*next_cpu
;
249 static int event_pending
= 1;
250 /* Conversion factor from emulated instructions to virtual clock ticks. */
251 static int icount_time_shift
;
252 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
253 #define MAX_ICOUNT_SHIFT 10
254 /* Compensate for varying guest execution speed. */
255 static int64_t qemu_icount_bias
;
256 static QEMUTimer
*icount_rt_timer
;
257 static QEMUTimer
*icount_vm_timer
;
259 uint8_t qemu_uuid
[16];
261 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
263 /***********************************************************/
264 /* x86 ISA bus support */
266 target_phys_addr_t isa_mem_base
= 0;
269 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
270 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
272 static uint32_t ioport_read(int index
, uint32_t address
)
274 static IOPortReadFunc
*default_func
[3] = {
275 default_ioport_readb
,
276 default_ioport_readw
,
279 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
281 func
= default_func
[index
];
282 return func(ioport_opaque
[address
], address
);
285 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
287 static IOPortWriteFunc
*default_func
[3] = {
288 default_ioport_writeb
,
289 default_ioport_writew
,
290 default_ioport_writel
292 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
294 func
= default_func
[index
];
295 func(ioport_opaque
[address
], address
, data
);
298 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
300 #ifdef DEBUG_UNUSED_IOPORT
301 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
306 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
308 #ifdef DEBUG_UNUSED_IOPORT
309 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
313 /* default is to make two byte accesses */
314 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
317 data
= ioport_read(0, address
);
318 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
319 data
|= ioport_read(0, address
) << 8;
323 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
325 ioport_write(0, address
, data
& 0xff);
326 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
327 ioport_write(0, address
, (data
>> 8) & 0xff);
330 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
332 #ifdef DEBUG_UNUSED_IOPORT
333 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
338 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
340 #ifdef DEBUG_UNUSED_IOPORT
341 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
345 /* size is the word size in byte */
346 int register_ioport_read(int start
, int length
, int size
,
347 IOPortReadFunc
*func
, void *opaque
)
353 } else if (size
== 2) {
355 } else if (size
== 4) {
358 hw_error("register_ioport_read: invalid size");
361 for(i
= start
; i
< start
+ length
; i
+= size
) {
362 ioport_read_table
[bsize
][i
] = func
;
363 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque
[i
] = opaque
;
370 /* size is the word size in byte */
371 int register_ioport_write(int start
, int length
, int size
,
372 IOPortWriteFunc
*func
, void *opaque
)
378 } else if (size
== 2) {
380 } else if (size
== 4) {
383 hw_error("register_ioport_write: invalid size");
386 for(i
= start
; i
< start
+ length
; i
+= size
) {
387 ioport_write_table
[bsize
][i
] = func
;
388 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque
[i
] = opaque
;
395 void isa_unassign_ioport(int start
, int length
)
399 for(i
= start
; i
< start
+ length
; i
++) {
400 ioport_read_table
[0][i
] = default_ioport_readb
;
401 ioport_read_table
[1][i
] = default_ioport_readw
;
402 ioport_read_table
[2][i
] = default_ioport_readl
;
404 ioport_write_table
[0][i
] = default_ioport_writeb
;
405 ioport_write_table
[1][i
] = default_ioport_writew
;
406 ioport_write_table
[2][i
] = default_ioport_writel
;
410 /***********************************************************/
412 void cpu_outb(CPUState
*env
, int addr
, int val
)
415 if (loglevel
& CPU_LOG_IOPORT
)
416 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
418 ioport_write(0, addr
, val
);
421 env
->last_io_time
= cpu_get_time_fast();
425 void cpu_outw(CPUState
*env
, int addr
, int val
)
428 if (loglevel
& CPU_LOG_IOPORT
)
429 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
431 ioport_write(1, addr
, val
);
434 env
->last_io_time
= cpu_get_time_fast();
438 void cpu_outl(CPUState
*env
, int addr
, int val
)
441 if (loglevel
& CPU_LOG_IOPORT
)
442 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
444 ioport_write(2, addr
, val
);
447 env
->last_io_time
= cpu_get_time_fast();
451 int cpu_inb(CPUState
*env
, int addr
)
454 val
= ioport_read(0, addr
);
456 if (loglevel
& CPU_LOG_IOPORT
)
457 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
461 env
->last_io_time
= cpu_get_time_fast();
466 int cpu_inw(CPUState
*env
, int addr
)
469 val
= ioport_read(1, addr
);
471 if (loglevel
& CPU_LOG_IOPORT
)
472 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
476 env
->last_io_time
= cpu_get_time_fast();
481 int cpu_inl(CPUState
*env
, int addr
)
484 val
= ioport_read(2, addr
);
486 if (loglevel
& CPU_LOG_IOPORT
)
487 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
491 env
->last_io_time
= cpu_get_time_fast();
496 /***********************************************************/
497 void hw_error(const char *fmt
, ...)
503 fprintf(stderr
, "qemu: hardware error: ");
504 vfprintf(stderr
, fmt
, ap
);
505 fprintf(stderr
, "\n");
506 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
507 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
509 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
511 cpu_dump_state(env
, stderr
, fprintf
, 0);
518 /***********************************************************/
521 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
522 static void *qemu_put_kbd_event_opaque
;
523 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
524 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
526 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
528 qemu_put_kbd_event_opaque
= opaque
;
529 qemu_put_kbd_event
= func
;
532 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
533 void *opaque
, int absolute
,
536 QEMUPutMouseEntry
*s
, *cursor
;
538 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
542 s
->qemu_put_mouse_event
= func
;
543 s
->qemu_put_mouse_event_opaque
= opaque
;
544 s
->qemu_put_mouse_event_absolute
= absolute
;
545 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
548 if (!qemu_put_mouse_event_head
) {
549 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
553 cursor
= qemu_put_mouse_event_head
;
554 while (cursor
->next
!= NULL
)
555 cursor
= cursor
->next
;
558 qemu_put_mouse_event_current
= s
;
563 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
565 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
567 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
570 cursor
= qemu_put_mouse_event_head
;
571 while (cursor
!= NULL
&& cursor
!= entry
) {
573 cursor
= cursor
->next
;
576 if (cursor
== NULL
) // does not exist or list empty
578 else if (prev
== NULL
) { // entry is head
579 qemu_put_mouse_event_head
= cursor
->next
;
580 if (qemu_put_mouse_event_current
== entry
)
581 qemu_put_mouse_event_current
= cursor
->next
;
582 qemu_free(entry
->qemu_put_mouse_event_name
);
587 prev
->next
= entry
->next
;
589 if (qemu_put_mouse_event_current
== entry
)
590 qemu_put_mouse_event_current
= prev
;
592 qemu_free(entry
->qemu_put_mouse_event_name
);
596 void kbd_put_keycode(int keycode
)
598 if (qemu_put_kbd_event
) {
599 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
603 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
605 QEMUPutMouseEvent
*mouse_event
;
606 void *mouse_event_opaque
;
609 if (!qemu_put_mouse_event_current
) {
614 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
616 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
619 if (graphic_rotate
) {
620 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
623 width
= graphic_width
- 1;
624 mouse_event(mouse_event_opaque
,
625 width
- dy
, dx
, dz
, buttons_state
);
627 mouse_event(mouse_event_opaque
,
628 dx
, dy
, dz
, buttons_state
);
632 int kbd_mouse_is_absolute(void)
634 if (!qemu_put_mouse_event_current
)
637 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
640 void do_info_mice(void)
642 QEMUPutMouseEntry
*cursor
;
645 if (!qemu_put_mouse_event_head
) {
646 term_printf("No mouse devices connected\n");
650 term_printf("Mouse devices available:\n");
651 cursor
= qemu_put_mouse_event_head
;
652 while (cursor
!= NULL
) {
653 term_printf("%c Mouse #%d: %s\n",
654 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
655 index
, cursor
->qemu_put_mouse_event_name
);
657 cursor
= cursor
->next
;
661 void do_mouse_set(int index
)
663 QEMUPutMouseEntry
*cursor
;
666 if (!qemu_put_mouse_event_head
) {
667 term_printf("No mouse devices connected\n");
671 cursor
= qemu_put_mouse_event_head
;
672 while (cursor
!= NULL
&& index
!= i
) {
674 cursor
= cursor
->next
;
678 qemu_put_mouse_event_current
= cursor
;
680 term_printf("Mouse at given index not found\n");
683 /* compute with 96 bit intermediate result: (a*b)/c */
684 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
689 #ifdef WORDS_BIGENDIAN
699 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
700 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
703 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
707 /***********************************************************/
708 /* real time host monotonic timer */
710 #define QEMU_TIMER_BASE 1000000000LL
714 static int64_t clock_freq
;
716 static void init_get_clock(void)
720 ret
= QueryPerformanceFrequency(&freq
);
722 fprintf(stderr
, "Could not calibrate ticks\n");
725 clock_freq
= freq
.QuadPart
;
728 static int64_t get_clock(void)
731 QueryPerformanceCounter(&ti
);
732 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
737 static int use_rt_clock
;
739 static void init_get_clock(void)
742 #if defined(__linux__)
745 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
752 static int64_t get_clock(void)
754 #if defined(__linux__)
757 clock_gettime(CLOCK_MONOTONIC
, &ts
);
758 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
762 /* XXX: using gettimeofday leads to problems if the date
763 changes, so it should be avoided. */
765 gettimeofday(&tv
, NULL
);
766 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
771 /* Return the virtual CPU time, based on the instruction counter. */
772 static int64_t cpu_get_icount(void)
775 CPUState
*env
= cpu_single_env
;;
776 icount
= qemu_icount
;
779 fprintf(stderr
, "Bad clock read\n");
780 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
782 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
785 /***********************************************************/
786 /* guest cycle counter */
788 static int64_t cpu_ticks_prev
;
789 static int64_t cpu_ticks_offset
;
790 static int64_t cpu_clock_offset
;
791 static int cpu_ticks_enabled
;
793 /* return the host CPU cycle counter and handle stop/restart */
794 int64_t cpu_get_ticks(void)
797 return cpu_get_icount();
799 if (!cpu_ticks_enabled
) {
800 return cpu_ticks_offset
;
803 ticks
= cpu_get_real_ticks();
804 if (cpu_ticks_prev
> ticks
) {
805 /* Note: non increasing ticks may happen if the host uses
807 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
809 cpu_ticks_prev
= ticks
;
810 return ticks
+ cpu_ticks_offset
;
814 /* return the host CPU monotonic timer and handle stop/restart */
815 static int64_t cpu_get_clock(void)
818 if (!cpu_ticks_enabled
) {
819 return cpu_clock_offset
;
822 return ti
+ cpu_clock_offset
;
826 /* enable cpu_get_ticks() */
827 void cpu_enable_ticks(void)
829 if (!cpu_ticks_enabled
) {
830 cpu_ticks_offset
-= cpu_get_real_ticks();
831 cpu_clock_offset
-= get_clock();
832 cpu_ticks_enabled
= 1;
836 /* disable cpu_get_ticks() : the clock is stopped. You must not call
837 cpu_get_ticks() after that. */
838 void cpu_disable_ticks(void)
840 if (cpu_ticks_enabled
) {
841 cpu_ticks_offset
= cpu_get_ticks();
842 cpu_clock_offset
= cpu_get_clock();
843 cpu_ticks_enabled
= 0;
847 /***********************************************************/
850 #define QEMU_TIMER_REALTIME 0
851 #define QEMU_TIMER_VIRTUAL 1
855 /* XXX: add frequency */
863 struct QEMUTimer
*next
;
866 struct qemu_alarm_timer
{
870 int (*start
)(struct qemu_alarm_timer
*t
);
871 void (*stop
)(struct qemu_alarm_timer
*t
);
872 void (*rearm
)(struct qemu_alarm_timer
*t
);
876 #define ALARM_FLAG_DYNTICKS 0x1
877 #define ALARM_FLAG_EXPIRED 0x2
879 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
881 return t
->flags
& ALARM_FLAG_DYNTICKS
;
884 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
886 if (!alarm_has_dynticks(t
))
892 /* TODO: MIN_TIMER_REARM_US should be optimized */
893 #define MIN_TIMER_REARM_US 250
895 static struct qemu_alarm_timer
*alarm_timer
;
899 struct qemu_alarm_win32
{
903 } alarm_win32_data
= {0, NULL
, -1};
905 static int win32_start_timer(struct qemu_alarm_timer
*t
);
906 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
907 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
911 static int unix_start_timer(struct qemu_alarm_timer
*t
);
912 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
916 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
917 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
918 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
920 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
921 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
923 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
924 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
926 #endif /* __linux__ */
930 /* Correlation between real and virtual time is always going to be
931 fairly approximate, so ignore small variation.
932 When the guest is idle real and virtual time will be aligned in
934 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
936 static void icount_adjust(void)
941 static int64_t last_delta
;
942 /* If the VM is not running, then do nothing. */
946 cur_time
= cpu_get_clock();
947 cur_icount
= qemu_get_clock(vm_clock
);
948 delta
= cur_icount
- cur_time
;
949 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
951 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
952 && icount_time_shift
> 0) {
953 /* The guest is getting too far ahead. Slow time down. */
957 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
958 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
959 /* The guest is getting too far behind. Speed time up. */
963 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
966 static void icount_adjust_rt(void * opaque
)
968 qemu_mod_timer(icount_rt_timer
,
969 qemu_get_clock(rt_clock
) + 1000);
973 static void icount_adjust_vm(void * opaque
)
975 qemu_mod_timer(icount_vm_timer
,
976 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
980 static void init_icount_adjust(void)
982 /* Have both realtime and virtual time triggers for speed adjustment.
983 The realtime trigger catches emulated time passing too slowly,
984 the virtual time trigger catches emulated time passing too fast.
985 Realtime triggers occur even when idle, so use them less frequently
987 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
988 qemu_mod_timer(icount_rt_timer
,
989 qemu_get_clock(rt_clock
) + 1000);
990 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
991 qemu_mod_timer(icount_vm_timer
,
992 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
995 static struct qemu_alarm_timer alarm_timers
[] = {
998 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
999 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1000 /* HPET - if available - is preferred */
1001 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1002 /* ...otherwise try RTC */
1003 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1005 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1007 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1008 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1009 {"win32", 0, win32_start_timer
,
1010 win32_stop_timer
, NULL
, &alarm_win32_data
},
1015 static void show_available_alarms(void)
1019 printf("Available alarm timers, in order of precedence:\n");
1020 for (i
= 0; alarm_timers
[i
].name
; i
++)
1021 printf("%s\n", alarm_timers
[i
].name
);
1024 static void configure_alarms(char const *opt
)
1028 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1031 struct qemu_alarm_timer tmp
;
1033 if (!strcmp(opt
, "?")) {
1034 show_available_alarms();
1040 /* Reorder the array */
1041 name
= strtok(arg
, ",");
1043 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1044 if (!strcmp(alarm_timers
[i
].name
, name
))
1049 fprintf(stderr
, "Unknown clock %s\n", name
);
1058 tmp
= alarm_timers
[i
];
1059 alarm_timers
[i
] = alarm_timers
[cur
];
1060 alarm_timers
[cur
] = tmp
;
1064 name
= strtok(NULL
, ",");
1070 /* Disable remaining timers */
1071 for (i
= cur
; i
< count
; i
++)
1072 alarm_timers
[i
].name
= NULL
;
1074 show_available_alarms();
1079 QEMUClock
*rt_clock
;
1080 QEMUClock
*vm_clock
;
1082 static QEMUTimer
*active_timers
[2];
1084 static QEMUClock
*qemu_new_clock(int type
)
1087 clock
= qemu_mallocz(sizeof(QEMUClock
));
1094 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1098 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1101 ts
->opaque
= opaque
;
1105 void qemu_free_timer(QEMUTimer
*ts
)
1110 /* stop a timer, but do not dealloc it */
1111 void qemu_del_timer(QEMUTimer
*ts
)
1115 /* NOTE: this code must be signal safe because
1116 qemu_timer_expired() can be called from a signal. */
1117 pt
= &active_timers
[ts
->clock
->type
];
1130 /* modify the current timer so that it will be fired when current_time
1131 >= expire_time. The corresponding callback will be called. */
1132 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1138 /* add the timer in the sorted list */
1139 /* NOTE: this code must be signal safe because
1140 qemu_timer_expired() can be called from a signal. */
1141 pt
= &active_timers
[ts
->clock
->type
];
1146 if (t
->expire_time
> expire_time
)
1150 ts
->expire_time
= expire_time
;
1154 /* Rearm if necessary */
1155 if (pt
== &active_timers
[ts
->clock
->type
]) {
1156 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1157 qemu_rearm_alarm_timer(alarm_timer
);
1159 /* Interrupt execution to force deadline recalculation. */
1160 if (use_icount
&& cpu_single_env
) {
1161 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1166 int qemu_timer_pending(QEMUTimer
*ts
)
1169 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1176 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1180 return (timer_head
->expire_time
<= current_time
);
1183 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1189 if (!ts
|| ts
->expire_time
> current_time
)
1191 /* remove timer from the list before calling the callback */
1192 *ptimer_head
= ts
->next
;
1195 /* run the callback (the timer list can be modified) */
1200 int64_t qemu_get_clock(QEMUClock
*clock
)
1202 switch(clock
->type
) {
1203 case QEMU_TIMER_REALTIME
:
1204 return get_clock() / 1000000;
1206 case QEMU_TIMER_VIRTUAL
:
1208 return cpu_get_icount();
1210 return cpu_get_clock();
1215 static void init_timers(void)
1218 ticks_per_sec
= QEMU_TIMER_BASE
;
1219 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1220 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1224 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1226 uint64_t expire_time
;
1228 if (qemu_timer_pending(ts
)) {
1229 expire_time
= ts
->expire_time
;
1233 qemu_put_be64(f
, expire_time
);
1236 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1238 uint64_t expire_time
;
1240 expire_time
= qemu_get_be64(f
);
1241 if (expire_time
!= -1) {
1242 qemu_mod_timer(ts
, expire_time
);
1248 static void timer_save(QEMUFile
*f
, void *opaque
)
1250 if (cpu_ticks_enabled
) {
1251 hw_error("cannot save state if virtual timers are running");
1253 qemu_put_be64(f
, cpu_ticks_offset
);
1254 qemu_put_be64(f
, ticks_per_sec
);
1255 qemu_put_be64(f
, cpu_clock_offset
);
1258 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1260 if (version_id
!= 1 && version_id
!= 2)
1262 if (cpu_ticks_enabled
) {
1265 cpu_ticks_offset
=qemu_get_be64(f
);
1266 ticks_per_sec
=qemu_get_be64(f
);
1267 if (version_id
== 2) {
1268 cpu_clock_offset
=qemu_get_be64(f
);
1274 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1275 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1277 static void host_alarm_handler(int host_signum
)
1281 #define DISP_FREQ 1000
1283 static int64_t delta_min
= INT64_MAX
;
1284 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1286 ti
= qemu_get_clock(vm_clock
);
1287 if (last_clock
!= 0) {
1288 delta
= ti
- last_clock
;
1289 if (delta
< delta_min
)
1291 if (delta
> delta_max
)
1294 if (++count
== DISP_FREQ
) {
1295 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1296 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1297 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1298 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1299 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1301 delta_min
= INT64_MAX
;
1309 if (alarm_has_dynticks(alarm_timer
) ||
1311 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1312 qemu_get_clock(vm_clock
))) ||
1313 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1314 qemu_get_clock(rt_clock
))) {
1316 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1317 SetEvent(data
->host_alarm
);
1319 CPUState
*env
= next_cpu
;
1321 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1324 /* stop the currently executing cpu because a timer occured */
1325 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1327 if (env
->kqemu_enabled
) {
1328 kqemu_cpu_interrupt(env
);
1336 static int64_t qemu_next_deadline(void)
1340 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1341 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1342 qemu_get_clock(vm_clock
);
1344 /* To avoid problems with overflow limit this to 2^32. */
1354 #if defined(__linux__) || defined(_WIN32)
1355 static uint64_t qemu_next_deadline_dyntick(void)
1363 delta
= (qemu_next_deadline() + 999) / 1000;
1365 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1366 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1367 qemu_get_clock(rt_clock
))*1000;
1368 if (rtdelta
< delta
)
1372 if (delta
< MIN_TIMER_REARM_US
)
1373 delta
= MIN_TIMER_REARM_US
;
1381 #if defined(__linux__)
1383 #define RTC_FREQ 1024
1385 static void enable_sigio_timer(int fd
)
1387 struct sigaction act
;
1390 sigfillset(&act
.sa_mask
);
1392 act
.sa_handler
= host_alarm_handler
;
1394 sigaction(SIGIO
, &act
, NULL
);
1395 fcntl(fd
, F_SETFL
, O_ASYNC
);
1396 fcntl(fd
, F_SETOWN
, getpid());
1399 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1401 struct hpet_info info
;
1404 fd
= open("/dev/hpet", O_RDONLY
);
1409 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1411 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1412 "error, but for better emulation accuracy type:\n"
1413 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1417 /* Check capabilities */
1418 r
= ioctl(fd
, HPET_INFO
, &info
);
1422 /* Enable periodic mode */
1423 r
= ioctl(fd
, HPET_EPI
, 0);
1424 if (info
.hi_flags
&& (r
< 0))
1427 /* Enable interrupt */
1428 r
= ioctl(fd
, HPET_IE_ON
, 0);
1432 enable_sigio_timer(fd
);
1433 t
->priv
= (void *)(long)fd
;
1441 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1443 int fd
= (long)t
->priv
;
1448 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1451 unsigned long current_rtc_freq
= 0;
1453 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1456 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1457 if (current_rtc_freq
!= RTC_FREQ
&&
1458 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1459 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1460 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1461 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1464 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1470 enable_sigio_timer(rtc_fd
);
1472 t
->priv
= (void *)(long)rtc_fd
;
1477 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1479 int rtc_fd
= (long)t
->priv
;
1484 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1488 struct sigaction act
;
1490 sigfillset(&act
.sa_mask
);
1492 act
.sa_handler
= host_alarm_handler
;
1494 sigaction(SIGALRM
, &act
, NULL
);
1496 ev
.sigev_value
.sival_int
= 0;
1497 ev
.sigev_notify
= SIGEV_SIGNAL
;
1498 ev
.sigev_signo
= SIGALRM
;
1500 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1501 perror("timer_create");
1503 /* disable dynticks */
1504 fprintf(stderr
, "Dynamic Ticks disabled\n");
1509 t
->priv
= (void *)host_timer
;
1514 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1516 timer_t host_timer
= (timer_t
)t
->priv
;
1518 timer_delete(host_timer
);
1521 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1523 timer_t host_timer
= (timer_t
)t
->priv
;
1524 struct itimerspec timeout
;
1525 int64_t nearest_delta_us
= INT64_MAX
;
1528 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1529 !active_timers
[QEMU_TIMER_VIRTUAL
])
1532 nearest_delta_us
= qemu_next_deadline_dyntick();
1534 /* check whether a timer is already running */
1535 if (timer_gettime(host_timer
, &timeout
)) {
1537 fprintf(stderr
, "Internal timer error: aborting\n");
1540 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1541 if (current_us
&& current_us
<= nearest_delta_us
)
1544 timeout
.it_interval
.tv_sec
= 0;
1545 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1546 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1547 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1548 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1550 fprintf(stderr
, "Internal timer error: aborting\n");
1555 #endif /* defined(__linux__) */
1557 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1559 struct sigaction act
;
1560 struct itimerval itv
;
1564 sigfillset(&act
.sa_mask
);
1566 act
.sa_handler
= host_alarm_handler
;
1568 sigaction(SIGALRM
, &act
, NULL
);
1570 itv
.it_interval
.tv_sec
= 0;
1571 /* for i386 kernel 2.6 to get 1 ms */
1572 itv
.it_interval
.tv_usec
= 999;
1573 itv
.it_value
.tv_sec
= 0;
1574 itv
.it_value
.tv_usec
= 10 * 1000;
1576 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1583 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1585 struct itimerval itv
;
1587 memset(&itv
, 0, sizeof(itv
));
1588 setitimer(ITIMER_REAL
, &itv
, NULL
);
1591 #endif /* !defined(_WIN32) */
1595 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1598 struct qemu_alarm_win32
*data
= t
->priv
;
1601 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1602 if (!data
->host_alarm
) {
1603 perror("Failed CreateEvent");
1607 memset(&tc
, 0, sizeof(tc
));
1608 timeGetDevCaps(&tc
, sizeof(tc
));
1610 if (data
->period
< tc
.wPeriodMin
)
1611 data
->period
= tc
.wPeriodMin
;
1613 timeBeginPeriod(data
->period
);
1615 flags
= TIME_CALLBACK_FUNCTION
;
1616 if (alarm_has_dynticks(t
))
1617 flags
|= TIME_ONESHOT
;
1619 flags
|= TIME_PERIODIC
;
1621 data
->timerId
= timeSetEvent(1, // interval (ms)
1622 data
->period
, // resolution
1623 host_alarm_handler
, // function
1624 (DWORD
)t
, // parameter
1627 if (!data
->timerId
) {
1628 perror("Failed to initialize win32 alarm timer");
1630 timeEndPeriod(data
->period
);
1631 CloseHandle(data
->host_alarm
);
1635 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1640 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1642 struct qemu_alarm_win32
*data
= t
->priv
;
1644 timeKillEvent(data
->timerId
);
1645 timeEndPeriod(data
->period
);
1647 CloseHandle(data
->host_alarm
);
1650 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1652 struct qemu_alarm_win32
*data
= t
->priv
;
1653 uint64_t nearest_delta_us
;
1655 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1656 !active_timers
[QEMU_TIMER_VIRTUAL
])
1659 nearest_delta_us
= qemu_next_deadline_dyntick();
1660 nearest_delta_us
/= 1000;
1662 timeKillEvent(data
->timerId
);
1664 data
->timerId
= timeSetEvent(1,
1668 TIME_ONESHOT
| TIME_PERIODIC
);
1670 if (!data
->timerId
) {
1671 perror("Failed to re-arm win32 alarm timer");
1673 timeEndPeriod(data
->period
);
1674 CloseHandle(data
->host_alarm
);
1681 static void init_timer_alarm(void)
1683 struct qemu_alarm_timer
*t
= NULL
;
1686 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1687 t
= &alarm_timers
[i
];
1695 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1696 fprintf(stderr
, "Terminating\n");
1703 static void quit_timers(void)
1705 alarm_timer
->stop(alarm_timer
);
1709 /***********************************************************/
1710 /* host time/date access */
1711 void qemu_get_timedate(struct tm
*tm
, int offset
)
1718 if (rtc_date_offset
== -1) {
1722 ret
= localtime(&ti
);
1724 ti
-= rtc_date_offset
;
1728 memcpy(tm
, ret
, sizeof(struct tm
));
1731 int qemu_timedate_diff(struct tm
*tm
)
1735 if (rtc_date_offset
== -1)
1737 seconds
= mktimegm(tm
);
1739 seconds
= mktime(tm
);
1741 seconds
= mktimegm(tm
) + rtc_date_offset
;
1743 return seconds
- time(NULL
);
1746 /***********************************************************/
1747 /* character device */
1749 static void qemu_chr_event(CharDriverState
*s
, int event
)
1753 s
->chr_event(s
->handler_opaque
, event
);
1756 static void qemu_chr_reset_bh(void *opaque
)
1758 CharDriverState
*s
= opaque
;
1759 qemu_chr_event(s
, CHR_EVENT_RESET
);
1760 qemu_bh_delete(s
->bh
);
1764 void qemu_chr_reset(CharDriverState
*s
)
1766 if (s
->bh
== NULL
) {
1767 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1768 qemu_bh_schedule(s
->bh
);
1772 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1774 return s
->chr_write(s
, buf
, len
);
1777 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1781 return s
->chr_ioctl(s
, cmd
, arg
);
1784 int qemu_chr_can_read(CharDriverState
*s
)
1786 if (!s
->chr_can_read
)
1788 return s
->chr_can_read(s
->handler_opaque
);
1791 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1793 s
->chr_read(s
->handler_opaque
, buf
, len
);
1796 void qemu_chr_accept_input(CharDriverState
*s
)
1798 if (s
->chr_accept_input
)
1799 s
->chr_accept_input(s
);
1802 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1807 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1808 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1812 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1814 if (s
->chr_send_event
)
1815 s
->chr_send_event(s
, event
);
1818 void qemu_chr_add_handlers(CharDriverState
*s
,
1819 IOCanRWHandler
*fd_can_read
,
1820 IOReadHandler
*fd_read
,
1821 IOEventHandler
*fd_event
,
1824 s
->chr_can_read
= fd_can_read
;
1825 s
->chr_read
= fd_read
;
1826 s
->chr_event
= fd_event
;
1827 s
->handler_opaque
= opaque
;
1828 if (s
->chr_update_read_handler
)
1829 s
->chr_update_read_handler(s
);
1832 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1837 static CharDriverState
*qemu_chr_open_null(void)
1839 CharDriverState
*chr
;
1841 chr
= qemu_mallocz(sizeof(CharDriverState
));
1844 chr
->chr_write
= null_chr_write
;
1848 /* MUX driver for serial I/O splitting */
1849 static int term_timestamps
;
1850 static int64_t term_timestamps_start
;
1852 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1853 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1855 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1856 IOReadHandler
*chr_read
[MAX_MUX
];
1857 IOEventHandler
*chr_event
[MAX_MUX
];
1858 void *ext_opaque
[MAX_MUX
];
1859 CharDriverState
*drv
;
1860 unsigned char buffer
[MUX_BUFFER_SIZE
];
1864 int term_got_escape
;
1869 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1871 MuxDriver
*d
= chr
->opaque
;
1873 if (!term_timestamps
) {
1874 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1879 for(i
= 0; i
< len
; i
++) {
1880 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1881 if (buf
[i
] == '\n') {
1887 if (term_timestamps_start
== -1)
1888 term_timestamps_start
= ti
;
1889 ti
-= term_timestamps_start
;
1890 secs
= ti
/ 1000000000;
1891 snprintf(buf1
, sizeof(buf1
),
1892 "[%02d:%02d:%02d.%03d] ",
1896 (int)((ti
/ 1000000) % 1000));
1897 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1904 static const char * const mux_help
[] = {
1905 "% h print this help\n\r",
1906 "% x exit emulator\n\r",
1907 "% s save disk data back to file (if -snapshot)\n\r",
1908 "% t toggle console timestamps\n\r"
1909 "% b send break (magic sysrq)\n\r",
1910 "% c switch between console and monitor\n\r",
1915 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1916 static void mux_print_help(CharDriverState
*chr
)
1919 char ebuf
[15] = "Escape-Char";
1920 char cbuf
[50] = "\n\r";
1922 if (term_escape_char
> 0 && term_escape_char
< 26) {
1923 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1924 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1926 snprintf(cbuf
, sizeof(cbuf
),
1927 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1930 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1931 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1932 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1933 if (mux_help
[i
][j
] == '%')
1934 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1936 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1941 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1943 if (d
->term_got_escape
) {
1944 d
->term_got_escape
= 0;
1945 if (ch
== term_escape_char
)
1950 mux_print_help(chr
);
1954 const char *term
= "QEMU: Terminated\n\r";
1955 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1962 for (i
= 0; i
< nb_drives
; i
++) {
1963 bdrv_commit(drives_table
[i
].bdrv
);
1968 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1971 /* Switch to the next registered device */
1973 if (chr
->focus
>= d
->mux_cnt
)
1977 term_timestamps
= !term_timestamps
;
1978 term_timestamps_start
= -1;
1981 } else if (ch
== term_escape_char
) {
1982 d
->term_got_escape
= 1;
1990 static void mux_chr_accept_input(CharDriverState
*chr
)
1993 MuxDriver
*d
= chr
->opaque
;
1995 while (d
->prod
!= d
->cons
&&
1996 d
->chr_can_read
[m
] &&
1997 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1998 d
->chr_read
[m
](d
->ext_opaque
[m
],
1999 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2003 static int mux_chr_can_read(void *opaque
)
2005 CharDriverState
*chr
= opaque
;
2006 MuxDriver
*d
= chr
->opaque
;
2008 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2010 if (d
->chr_can_read
[chr
->focus
])
2011 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2015 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2017 CharDriverState
*chr
= opaque
;
2018 MuxDriver
*d
= chr
->opaque
;
2022 mux_chr_accept_input (opaque
);
2024 for(i
= 0; i
< size
; i
++)
2025 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2026 if (d
->prod
== d
->cons
&&
2027 d
->chr_can_read
[m
] &&
2028 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2029 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2031 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2035 static void mux_chr_event(void *opaque
, int event
)
2037 CharDriverState
*chr
= opaque
;
2038 MuxDriver
*d
= chr
->opaque
;
2041 /* Send the event to all registered listeners */
2042 for (i
= 0; i
< d
->mux_cnt
; i
++)
2043 if (d
->chr_event
[i
])
2044 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2047 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2049 MuxDriver
*d
= chr
->opaque
;
2051 if (d
->mux_cnt
>= MAX_MUX
) {
2052 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2055 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2056 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2057 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2058 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2059 /* Fix up the real driver with mux routines */
2060 if (d
->mux_cnt
== 0) {
2061 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2062 mux_chr_event
, chr
);
2064 chr
->focus
= d
->mux_cnt
;
2068 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2070 CharDriverState
*chr
;
2073 chr
= qemu_mallocz(sizeof(CharDriverState
));
2076 d
= qemu_mallocz(sizeof(MuxDriver
));
2085 chr
->chr_write
= mux_chr_write
;
2086 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2087 chr
->chr_accept_input
= mux_chr_accept_input
;
2094 static void socket_cleanup(void)
2099 static int socket_init(void)
2104 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2106 err
= WSAGetLastError();
2107 fprintf(stderr
, "WSAStartup: %d\n", err
);
2110 atexit(socket_cleanup
);
2114 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2120 ret
= send(fd
, buf
, len
, 0);
2123 errno
= WSAGetLastError();
2124 if (errno
!= WSAEWOULDBLOCK
) {
2127 } else if (ret
== 0) {
2139 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2145 ret
= write(fd
, buf
, len
);
2147 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2149 } else if (ret
== 0) {
2159 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2161 return unix_write(fd
, buf
, len1
);
2163 #endif /* !_WIN32 */
2172 #define STDIO_MAX_CLIENTS 1
2173 static int stdio_nb_clients
= 0;
2175 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2177 FDCharDriver
*s
= chr
->opaque
;
2178 return unix_write(s
->fd_out
, buf
, len
);
2181 static int fd_chr_read_poll(void *opaque
)
2183 CharDriverState
*chr
= opaque
;
2184 FDCharDriver
*s
= chr
->opaque
;
2186 s
->max_size
= qemu_chr_can_read(chr
);
2190 static void fd_chr_read(void *opaque
)
2192 CharDriverState
*chr
= opaque
;
2193 FDCharDriver
*s
= chr
->opaque
;
2198 if (len
> s
->max_size
)
2202 size
= read(s
->fd_in
, buf
, len
);
2204 /* FD has been closed. Remove it from the active list. */
2205 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2209 qemu_chr_read(chr
, buf
, size
);
2213 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2215 FDCharDriver
*s
= chr
->opaque
;
2217 if (s
->fd_in
>= 0) {
2218 if (nographic
&& s
->fd_in
== 0) {
2220 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2221 fd_chr_read
, NULL
, chr
);
2226 static void fd_chr_close(struct CharDriverState
*chr
)
2228 FDCharDriver
*s
= chr
->opaque
;
2230 if (s
->fd_in
>= 0) {
2231 if (nographic
&& s
->fd_in
== 0) {
2233 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2240 /* open a character device to a unix fd */
2241 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2243 CharDriverState
*chr
;
2246 chr
= qemu_mallocz(sizeof(CharDriverState
));
2249 s
= qemu_mallocz(sizeof(FDCharDriver
));
2257 chr
->chr_write
= fd_chr_write
;
2258 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2259 chr
->chr_close
= fd_chr_close
;
2261 qemu_chr_reset(chr
);
2266 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2270 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2273 return qemu_chr_open_fd(-1, fd_out
);
2276 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2279 char filename_in
[256], filename_out
[256];
2281 snprintf(filename_in
, 256, "%s.in", filename
);
2282 snprintf(filename_out
, 256, "%s.out", filename
);
2283 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2284 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2285 if (fd_in
< 0 || fd_out
< 0) {
2290 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2294 return qemu_chr_open_fd(fd_in
, fd_out
);
2298 /* for STDIO, we handle the case where several clients use it
2301 #define TERM_FIFO_MAX_SIZE 1
2303 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2304 static int term_fifo_size
;
2306 static int stdio_read_poll(void *opaque
)
2308 CharDriverState
*chr
= opaque
;
2310 /* try to flush the queue if needed */
2311 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2312 qemu_chr_read(chr
, term_fifo
, 1);
2315 /* see if we can absorb more chars */
2316 if (term_fifo_size
== 0)
2322 static void stdio_read(void *opaque
)
2326 CharDriverState
*chr
= opaque
;
2328 size
= read(0, buf
, 1);
2330 /* stdin has been closed. Remove it from the active list. */
2331 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2335 if (qemu_chr_can_read(chr
) > 0) {
2336 qemu_chr_read(chr
, buf
, 1);
2337 } else if (term_fifo_size
== 0) {
2338 term_fifo
[term_fifo_size
++] = buf
[0];
2343 /* init terminal so that we can grab keys */
2344 static struct termios oldtty
;
2345 static int old_fd0_flags
;
2346 static int term_atexit_done
;
2348 static void term_exit(void)
2350 tcsetattr (0, TCSANOW
, &oldtty
);
2351 fcntl(0, F_SETFL
, old_fd0_flags
);
2354 static void term_init(void)
2358 tcgetattr (0, &tty
);
2360 old_fd0_flags
= fcntl(0, F_GETFL
);
2362 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2363 |INLCR
|IGNCR
|ICRNL
|IXON
);
2364 tty
.c_oflag
|= OPOST
;
2365 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2366 /* if graphical mode, we allow Ctrl-C handling */
2368 tty
.c_lflag
&= ~ISIG
;
2369 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2372 tty
.c_cc
[VTIME
] = 0;
2374 tcsetattr (0, TCSANOW
, &tty
);
2376 if (!term_atexit_done
++)
2379 fcntl(0, F_SETFL
, O_NONBLOCK
);
2382 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2386 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2390 static CharDriverState
*qemu_chr_open_stdio(void)
2392 CharDriverState
*chr
;
2394 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2396 chr
= qemu_chr_open_fd(0, 1);
2397 chr
->chr_close
= qemu_chr_close_stdio
;
2398 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2406 /* Once Solaris has openpty(), this is going to be removed. */
2407 int openpty(int *amaster
, int *aslave
, char *name
,
2408 struct termios
*termp
, struct winsize
*winp
)
2411 int mfd
= -1, sfd
= -1;
2413 *amaster
= *aslave
= -1;
2415 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2419 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2422 if ((slave
= ptsname(mfd
)) == NULL
)
2425 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2428 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2429 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2437 ioctl(sfd
, TIOCSWINSZ
, winp
);
2448 void cfmakeraw (struct termios
*termios_p
)
2450 termios_p
->c_iflag
&=
2451 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2452 termios_p
->c_oflag
&= ~OPOST
;
2453 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2454 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2455 termios_p
->c_cflag
|= CS8
;
2457 termios_p
->c_cc
[VMIN
] = 0;
2458 termios_p
->c_cc
[VTIME
] = 0;
2462 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2463 || defined(__NetBSD__) || defined(__OpenBSD__)
2473 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2474 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2476 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2478 PtyCharDriver
*s
= chr
->opaque
;
2480 if (!s
->connected
) {
2481 /* guest sends data, check for (re-)connect */
2482 pty_chr_update_read_handler(chr
);
2485 return unix_write(s
->fd
, buf
, len
);
2488 static int pty_chr_read_poll(void *opaque
)
2490 CharDriverState
*chr
= opaque
;
2491 PtyCharDriver
*s
= chr
->opaque
;
2493 s
->read_bytes
= qemu_chr_can_read(chr
);
2494 return s
->read_bytes
;
2497 static void pty_chr_read(void *opaque
)
2499 CharDriverState
*chr
= opaque
;
2500 PtyCharDriver
*s
= chr
->opaque
;
2505 if (len
> s
->read_bytes
)
2506 len
= s
->read_bytes
;
2509 size
= read(s
->fd
, buf
, len
);
2510 if ((size
== -1 && errno
== EIO
) ||
2512 pty_chr_state(chr
, 0);
2516 pty_chr_state(chr
, 1);
2517 qemu_chr_read(chr
, buf
, size
);
2521 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2523 PtyCharDriver
*s
= chr
->opaque
;
2525 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2526 pty_chr_read
, NULL
, chr
);
2529 * Short timeout here: just need wait long enougth that qemu makes
2530 * it through the poll loop once. When reconnected we want a
2531 * short timeout so we notice it almost instantly. Otherwise
2532 * read() gives us -EIO instantly, making pty_chr_state() reset the
2533 * timeout to the normal (much longer) poll interval before the
2536 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2539 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2541 PtyCharDriver
*s
= chr
->opaque
;
2544 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2547 /* (re-)connect poll interval for idle guests: once per second.
2548 * We check more frequently in case the guests sends data to
2549 * the virtual device linked to our pty. */
2550 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2553 qemu_chr_reset(chr
);
2558 static void pty_chr_timer(void *opaque
)
2560 struct CharDriverState
*chr
= opaque
;
2561 PtyCharDriver
*s
= chr
->opaque
;
2566 /* If we arrive here without polling being cleared due
2567 * read returning -EIO, then we are (re-)connected */
2568 pty_chr_state(chr
, 1);
2573 pty_chr_update_read_handler(chr
);
2576 static void pty_chr_close(struct CharDriverState
*chr
)
2578 PtyCharDriver
*s
= chr
->opaque
;
2580 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2585 static CharDriverState
*qemu_chr_open_pty(void)
2587 CharDriverState
*chr
;
2591 #if defined(__OpenBSD__)
2592 char pty_name
[PATH_MAX
];
2593 #define q_ptsname(x) pty_name
2595 char *pty_name
= NULL
;
2596 #define q_ptsname(x) ptsname(x)
2599 chr
= qemu_mallocz(sizeof(CharDriverState
));
2602 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2608 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2612 /* Set raw attributes on the pty. */
2614 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2617 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2620 chr
->chr_write
= pty_chr_write
;
2621 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2622 chr
->chr_close
= pty_chr_close
;
2624 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2629 static void tty_serial_init(int fd
, int speed
,
2630 int parity
, int data_bits
, int stop_bits
)
2636 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2637 speed
, parity
, data_bits
, stop_bits
);
2639 tcgetattr (fd
, &tty
);
2642 if (speed
<= 50 * MARGIN
)
2644 else if (speed
<= 75 * MARGIN
)
2646 else if (speed
<= 300 * MARGIN
)
2648 else if (speed
<= 600 * MARGIN
)
2650 else if (speed
<= 1200 * MARGIN
)
2652 else if (speed
<= 2400 * MARGIN
)
2654 else if (speed
<= 4800 * MARGIN
)
2656 else if (speed
<= 9600 * MARGIN
)
2658 else if (speed
<= 19200 * MARGIN
)
2660 else if (speed
<= 38400 * MARGIN
)
2662 else if (speed
<= 57600 * MARGIN
)
2664 else if (speed
<= 115200 * MARGIN
)
2669 cfsetispeed(&tty
, spd
);
2670 cfsetospeed(&tty
, spd
);
2672 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2673 |INLCR
|IGNCR
|ICRNL
|IXON
);
2674 tty
.c_oflag
|= OPOST
;
2675 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2676 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2697 tty
.c_cflag
|= PARENB
;
2700 tty
.c_cflag
|= PARENB
| PARODD
;
2704 tty
.c_cflag
|= CSTOPB
;
2706 tcsetattr (fd
, TCSANOW
, &tty
);
2709 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2711 FDCharDriver
*s
= chr
->opaque
;
2714 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2716 QEMUSerialSetParams
*ssp
= arg
;
2717 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2718 ssp
->data_bits
, ssp
->stop_bits
);
2721 case CHR_IOCTL_SERIAL_SET_BREAK
:
2723 int enable
= *(int *)arg
;
2725 tcsendbreak(s
->fd_in
, 1);
2728 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2731 int *targ
= (int *)arg
;
2732 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2734 if (sarg
| TIOCM_CTS
)
2735 *targ
|= CHR_TIOCM_CTS
;
2736 if (sarg
| TIOCM_CAR
)
2737 *targ
|= CHR_TIOCM_CAR
;
2738 if (sarg
| TIOCM_DSR
)
2739 *targ
|= CHR_TIOCM_DSR
;
2740 if (sarg
| TIOCM_RI
)
2741 *targ
|= CHR_TIOCM_RI
;
2742 if (sarg
| TIOCM_DTR
)
2743 *targ
|= CHR_TIOCM_DTR
;
2744 if (sarg
| TIOCM_RTS
)
2745 *targ
|= CHR_TIOCM_RTS
;
2748 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2750 int sarg
= *(int *)arg
;
2752 if (sarg
| CHR_TIOCM_DTR
)
2754 if (sarg
| CHR_TIOCM_RTS
)
2756 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2765 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2767 CharDriverState
*chr
;
2770 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2771 tty_serial_init(fd
, 115200, 'N', 8, 1);
2772 chr
= qemu_chr_open_fd(fd
, fd
);
2777 chr
->chr_ioctl
= tty_serial_ioctl
;
2778 qemu_chr_reset(chr
);
2781 #else /* ! __linux__ && ! __sun__ */
2782 static CharDriverState
*qemu_chr_open_pty(void)
2786 #endif /* __linux__ || __sun__ */
2788 #if defined(__linux__)
2792 } ParallelCharDriver
;
2794 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2796 if (s
->mode
!= mode
) {
2798 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2805 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2807 ParallelCharDriver
*drv
= chr
->opaque
;
2812 case CHR_IOCTL_PP_READ_DATA
:
2813 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2815 *(uint8_t *)arg
= b
;
2817 case CHR_IOCTL_PP_WRITE_DATA
:
2818 b
= *(uint8_t *)arg
;
2819 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2822 case CHR_IOCTL_PP_READ_CONTROL
:
2823 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2825 /* Linux gives only the lowest bits, and no way to know data
2826 direction! For better compatibility set the fixed upper
2828 *(uint8_t *)arg
= b
| 0xc0;
2830 case CHR_IOCTL_PP_WRITE_CONTROL
:
2831 b
= *(uint8_t *)arg
;
2832 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2835 case CHR_IOCTL_PP_READ_STATUS
:
2836 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2838 *(uint8_t *)arg
= b
;
2840 case CHR_IOCTL_PP_DATA_DIR
:
2841 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2844 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2845 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2846 struct ParallelIOArg
*parg
= arg
;
2847 int n
= read(fd
, parg
->buffer
, parg
->count
);
2848 if (n
!= parg
->count
) {
2853 case CHR_IOCTL_PP_EPP_READ
:
2854 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2855 struct ParallelIOArg
*parg
= arg
;
2856 int n
= read(fd
, parg
->buffer
, parg
->count
);
2857 if (n
!= parg
->count
) {
2862 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2863 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2864 struct ParallelIOArg
*parg
= arg
;
2865 int n
= write(fd
, parg
->buffer
, parg
->count
);
2866 if (n
!= parg
->count
) {
2871 case CHR_IOCTL_PP_EPP_WRITE
:
2872 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2873 struct ParallelIOArg
*parg
= arg
;
2874 int n
= write(fd
, parg
->buffer
, parg
->count
);
2875 if (n
!= parg
->count
) {
2886 static void pp_close(CharDriverState
*chr
)
2888 ParallelCharDriver
*drv
= chr
->opaque
;
2891 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2892 ioctl(fd
, PPRELEASE
);
2897 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2899 CharDriverState
*chr
;
2900 ParallelCharDriver
*drv
;
2903 TFR(fd
= open(filename
, O_RDWR
));
2907 if (ioctl(fd
, PPCLAIM
) < 0) {
2912 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2918 drv
->mode
= IEEE1284_MODE_COMPAT
;
2920 chr
= qemu_mallocz(sizeof(CharDriverState
));
2926 chr
->chr_write
= null_chr_write
;
2927 chr
->chr_ioctl
= pp_ioctl
;
2928 chr
->chr_close
= pp_close
;
2931 qemu_chr_reset(chr
);
2935 #endif /* __linux__ */
2941 HANDLE hcom
, hrecv
, hsend
;
2942 OVERLAPPED orecv
, osend
;
2947 #define NSENDBUF 2048
2948 #define NRECVBUF 2048
2949 #define MAXCONNECT 1
2950 #define NTIMEOUT 5000
2952 static int win_chr_poll(void *opaque
);
2953 static int win_chr_pipe_poll(void *opaque
);
2955 static void win_chr_close(CharDriverState
*chr
)
2957 WinCharState
*s
= chr
->opaque
;
2960 CloseHandle(s
->hsend
);
2964 CloseHandle(s
->hrecv
);
2968 CloseHandle(s
->hcom
);
2972 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2974 qemu_del_polling_cb(win_chr_poll
, chr
);
2977 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2979 WinCharState
*s
= chr
->opaque
;
2981 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2986 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2988 fprintf(stderr
, "Failed CreateEvent\n");
2991 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2993 fprintf(stderr
, "Failed CreateEvent\n");
2997 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2998 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2999 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3000 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3005 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3006 fprintf(stderr
, "Failed SetupComm\n");
3010 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3011 size
= sizeof(COMMCONFIG
);
3012 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3013 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3014 CommConfigDialog(filename
, NULL
, &comcfg
);
3016 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3017 fprintf(stderr
, "Failed SetCommState\n");
3021 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3022 fprintf(stderr
, "Failed SetCommMask\n");
3026 cto
.ReadIntervalTimeout
= MAXDWORD
;
3027 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3028 fprintf(stderr
, "Failed SetCommTimeouts\n");
3032 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3033 fprintf(stderr
, "Failed ClearCommError\n");
3036 qemu_add_polling_cb(win_chr_poll
, chr
);
3044 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3046 WinCharState
*s
= chr
->opaque
;
3047 DWORD len
, ret
, size
, err
;
3050 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3051 s
->osend
.hEvent
= s
->hsend
;
3054 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3056 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3058 err
= GetLastError();
3059 if (err
== ERROR_IO_PENDING
) {
3060 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3078 static int win_chr_read_poll(CharDriverState
*chr
)
3080 WinCharState
*s
= chr
->opaque
;
3082 s
->max_size
= qemu_chr_can_read(chr
);
3086 static void win_chr_readfile(CharDriverState
*chr
)
3088 WinCharState
*s
= chr
->opaque
;
3093 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3094 s
->orecv
.hEvent
= s
->hrecv
;
3095 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3097 err
= GetLastError();
3098 if (err
== ERROR_IO_PENDING
) {
3099 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3104 qemu_chr_read(chr
, buf
, size
);
3108 static void win_chr_read(CharDriverState
*chr
)
3110 WinCharState
*s
= chr
->opaque
;
3112 if (s
->len
> s
->max_size
)
3113 s
->len
= s
->max_size
;
3117 win_chr_readfile(chr
);
3120 static int win_chr_poll(void *opaque
)
3122 CharDriverState
*chr
= opaque
;
3123 WinCharState
*s
= chr
->opaque
;
3127 ClearCommError(s
->hcom
, &comerr
, &status
);
3128 if (status
.cbInQue
> 0) {
3129 s
->len
= status
.cbInQue
;
3130 win_chr_read_poll(chr
);
3137 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3139 CharDriverState
*chr
;
3142 chr
= qemu_mallocz(sizeof(CharDriverState
));
3145 s
= qemu_mallocz(sizeof(WinCharState
));
3151 chr
->chr_write
= win_chr_write
;
3152 chr
->chr_close
= win_chr_close
;
3154 if (win_chr_init(chr
, filename
) < 0) {
3159 qemu_chr_reset(chr
);
3163 static int win_chr_pipe_poll(void *opaque
)
3165 CharDriverState
*chr
= opaque
;
3166 WinCharState
*s
= chr
->opaque
;
3169 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3172 win_chr_read_poll(chr
);
3179 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3181 WinCharState
*s
= chr
->opaque
;
3189 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3191 fprintf(stderr
, "Failed CreateEvent\n");
3194 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3196 fprintf(stderr
, "Failed CreateEvent\n");
3200 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3201 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3202 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3204 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3205 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3206 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3211 ZeroMemory(&ov
, sizeof(ov
));
3212 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3213 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3215 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3219 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3221 fprintf(stderr
, "Failed GetOverlappedResult\n");
3223 CloseHandle(ov
.hEvent
);
3230 CloseHandle(ov
.hEvent
);
3233 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3242 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3244 CharDriverState
*chr
;
3247 chr
= qemu_mallocz(sizeof(CharDriverState
));
3250 s
= qemu_mallocz(sizeof(WinCharState
));
3256 chr
->chr_write
= win_chr_write
;
3257 chr
->chr_close
= win_chr_close
;
3259 if (win_chr_pipe_init(chr
, filename
) < 0) {
3264 qemu_chr_reset(chr
);
3268 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3270 CharDriverState
*chr
;
3273 chr
= qemu_mallocz(sizeof(CharDriverState
));
3276 s
= qemu_mallocz(sizeof(WinCharState
));
3283 chr
->chr_write
= win_chr_write
;
3284 qemu_chr_reset(chr
);
3288 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3290 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3293 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3297 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3298 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3299 if (fd_out
== INVALID_HANDLE_VALUE
)
3302 return qemu_chr_open_win_file(fd_out
);
3304 #endif /* !_WIN32 */
3306 /***********************************************************/
3307 /* UDP Net console */
3311 struct sockaddr_in daddr
;
3318 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3320 NetCharDriver
*s
= chr
->opaque
;
3322 return sendto(s
->fd
, buf
, len
, 0,
3323 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3326 static int udp_chr_read_poll(void *opaque
)
3328 CharDriverState
*chr
= opaque
;
3329 NetCharDriver
*s
= chr
->opaque
;
3331 s
->max_size
= qemu_chr_can_read(chr
);
3333 /* If there were any stray characters in the queue process them
3336 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3337 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3339 s
->max_size
= qemu_chr_can_read(chr
);
3344 static void udp_chr_read(void *opaque
)
3346 CharDriverState
*chr
= opaque
;
3347 NetCharDriver
*s
= chr
->opaque
;
3349 if (s
->max_size
== 0)
3351 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3352 s
->bufptr
= s
->bufcnt
;
3357 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3358 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3360 s
->max_size
= qemu_chr_can_read(chr
);
3364 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3366 NetCharDriver
*s
= chr
->opaque
;
3369 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3370 udp_chr_read
, NULL
, chr
);
3374 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3376 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3378 int parse_host_src_port(struct sockaddr_in
*haddr
,
3379 struct sockaddr_in
*saddr
,
3382 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3384 CharDriverState
*chr
= NULL
;
3385 NetCharDriver
*s
= NULL
;
3387 struct sockaddr_in saddr
;
3389 chr
= qemu_mallocz(sizeof(CharDriverState
));
3392 s
= qemu_mallocz(sizeof(NetCharDriver
));
3396 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3398 perror("socket(PF_INET, SOCK_DGRAM)");
3402 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3403 printf("Could not parse: %s\n", def
);
3407 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3417 chr
->chr_write
= udp_chr_write
;
3418 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3431 /***********************************************************/
3432 /* TCP Net console */
3443 static void tcp_chr_accept(void *opaque
);
3445 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3447 TCPCharDriver
*s
= chr
->opaque
;
3449 return send_all(s
->fd
, buf
, len
);
3451 /* XXX: indicate an error ? */
3456 static int tcp_chr_read_poll(void *opaque
)
3458 CharDriverState
*chr
= opaque
;
3459 TCPCharDriver
*s
= chr
->opaque
;
3462 s
->max_size
= qemu_chr_can_read(chr
);
3467 #define IAC_BREAK 243
3468 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3470 uint8_t *buf
, int *size
)
3472 /* Handle any telnet client's basic IAC options to satisfy char by
3473 * char mode with no echo. All IAC options will be removed from
3474 * the buf and the do_telnetopt variable will be used to track the
3475 * state of the width of the IAC information.
3477 * IAC commands come in sets of 3 bytes with the exception of the
3478 * "IAC BREAK" command and the double IAC.
3484 for (i
= 0; i
< *size
; i
++) {
3485 if (s
->do_telnetopt
> 1) {
3486 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3487 /* Double IAC means send an IAC */
3491 s
->do_telnetopt
= 1;
3493 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3494 /* Handle IAC break commands by sending a serial break */
3495 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3500 if (s
->do_telnetopt
>= 4) {
3501 s
->do_telnetopt
= 1;
3504 if ((unsigned char)buf
[i
] == IAC
) {
3505 s
->do_telnetopt
= 2;
3516 static void tcp_chr_read(void *opaque
)
3518 CharDriverState
*chr
= opaque
;
3519 TCPCharDriver
*s
= chr
->opaque
;
3523 if (!s
->connected
|| s
->max_size
<= 0)
3526 if (len
> s
->max_size
)
3528 size
= recv(s
->fd
, buf
, len
, 0);
3530 /* connection closed */
3532 if (s
->listen_fd
>= 0) {
3533 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3535 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3538 } else if (size
> 0) {
3539 if (s
->do_telnetopt
)
3540 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3542 qemu_chr_read(chr
, buf
, size
);
3546 static void tcp_chr_connect(void *opaque
)
3548 CharDriverState
*chr
= opaque
;
3549 TCPCharDriver
*s
= chr
->opaque
;
3552 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3553 tcp_chr_read
, NULL
, chr
);
3554 qemu_chr_reset(chr
);
3557 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3558 static void tcp_chr_telnet_init(int fd
)
3561 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3562 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3563 send(fd
, (char *)buf
, 3, 0);
3564 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3565 send(fd
, (char *)buf
, 3, 0);
3566 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3567 send(fd
, (char *)buf
, 3, 0);
3568 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3569 send(fd
, (char *)buf
, 3, 0);
3572 static void socket_set_nodelay(int fd
)
3575 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3578 static void tcp_chr_accept(void *opaque
)
3580 CharDriverState
*chr
= opaque
;
3581 TCPCharDriver
*s
= chr
->opaque
;
3582 struct sockaddr_in saddr
;
3584 struct sockaddr_un uaddr
;
3586 struct sockaddr
*addr
;
3593 len
= sizeof(uaddr
);
3594 addr
= (struct sockaddr
*)&uaddr
;
3598 len
= sizeof(saddr
);
3599 addr
= (struct sockaddr
*)&saddr
;
3601 fd
= accept(s
->listen_fd
, addr
, &len
);
3602 if (fd
< 0 && errno
!= EINTR
) {
3604 } else if (fd
>= 0) {
3605 if (s
->do_telnetopt
)
3606 tcp_chr_telnet_init(fd
);
3610 socket_set_nonblock(fd
);
3612 socket_set_nodelay(fd
);
3614 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3615 tcp_chr_connect(chr
);
3618 static void tcp_chr_close(CharDriverState
*chr
)
3620 TCPCharDriver
*s
= chr
->opaque
;
3623 if (s
->listen_fd
>= 0)
3624 closesocket(s
->listen_fd
);
3628 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3632 CharDriverState
*chr
= NULL
;
3633 TCPCharDriver
*s
= NULL
;
3634 int fd
= -1, ret
, err
, val
;
3636 int is_waitconnect
= 1;
3639 struct sockaddr_in saddr
;
3641 struct sockaddr_un uaddr
;
3643 struct sockaddr
*addr
;
3648 addr
= (struct sockaddr
*)&uaddr
;
3649 addrlen
= sizeof(uaddr
);
3650 if (parse_unix_path(&uaddr
, host_str
) < 0)
3655 addr
= (struct sockaddr
*)&saddr
;
3656 addrlen
= sizeof(saddr
);
3657 if (parse_host_port(&saddr
, host_str
) < 0)
3662 while((ptr
= strchr(ptr
,','))) {
3664 if (!strncmp(ptr
,"server",6)) {
3666 } else if (!strncmp(ptr
,"nowait",6)) {
3668 } else if (!strncmp(ptr
,"nodelay",6)) {
3671 printf("Unknown option: %s\n", ptr
);
3678 chr
= qemu_mallocz(sizeof(CharDriverState
));
3681 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3687 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3690 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3695 if (!is_waitconnect
)
3696 socket_set_nonblock(fd
);
3701 s
->is_unix
= is_unix
;
3702 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3705 chr
->chr_write
= tcp_chr_write
;
3706 chr
->chr_close
= tcp_chr_close
;
3709 /* allow fast reuse */
3713 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3719 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3722 ret
= bind(fd
, addr
, addrlen
);
3726 ret
= listen(fd
, 0);
3731 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3733 s
->do_telnetopt
= 1;
3736 ret
= connect(fd
, addr
, addrlen
);
3738 err
= socket_error();
3739 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3740 } else if (err
== EINPROGRESS
) {
3743 } else if (err
== WSAEALREADY
) {
3755 socket_set_nodelay(fd
);
3757 tcp_chr_connect(chr
);
3759 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3762 if (is_listen
&& is_waitconnect
) {
3763 printf("QEMU waiting for connection on: %s\n", host_str
);
3764 tcp_chr_accept(chr
);
3765 socket_set_nonblock(s
->listen_fd
);
3777 CharDriverState
*qemu_chr_open(const char *filename
)
3781 if (!strcmp(filename
, "vc")) {
3782 return text_console_init(&display_state
, 0);
3783 } else if (strstart(filename
, "vc:", &p
)) {
3784 return text_console_init(&display_state
, p
);
3785 } else if (!strcmp(filename
, "null")) {
3786 return qemu_chr_open_null();
3788 if (strstart(filename
, "tcp:", &p
)) {
3789 return qemu_chr_open_tcp(p
, 0, 0);
3791 if (strstart(filename
, "telnet:", &p
)) {
3792 return qemu_chr_open_tcp(p
, 1, 0);
3794 if (strstart(filename
, "udp:", &p
)) {
3795 return qemu_chr_open_udp(p
);
3797 if (strstart(filename
, "mon:", &p
)) {
3798 CharDriverState
*drv
= qemu_chr_open(p
);
3800 drv
= qemu_chr_open_mux(drv
);
3801 monitor_init(drv
, !nographic
);
3804 printf("Unable to open driver: %s\n", p
);
3808 if (strstart(filename
, "unix:", &p
)) {
3809 return qemu_chr_open_tcp(p
, 0, 1);
3810 } else if (strstart(filename
, "file:", &p
)) {
3811 return qemu_chr_open_file_out(p
);
3812 } else if (strstart(filename
, "pipe:", &p
)) {
3813 return qemu_chr_open_pipe(p
);
3814 } else if (!strcmp(filename
, "pty")) {
3815 return qemu_chr_open_pty();
3816 } else if (!strcmp(filename
, "stdio")) {
3817 return qemu_chr_open_stdio();
3819 #if defined(__linux__)
3820 if (strstart(filename
, "/dev/parport", NULL
)) {
3821 return qemu_chr_open_pp(filename
);
3824 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3825 || defined(__NetBSD__) || defined(__OpenBSD__)
3826 if (strstart(filename
, "/dev/", NULL
)) {
3827 return qemu_chr_open_tty(filename
);
3831 if (strstart(filename
, "COM", NULL
)) {
3832 return qemu_chr_open_win(filename
);
3834 if (strstart(filename
, "pipe:", &p
)) {
3835 return qemu_chr_open_win_pipe(p
);
3837 if (strstart(filename
, "con:", NULL
)) {
3838 return qemu_chr_open_win_con(filename
);
3840 if (strstart(filename
, "file:", &p
)) {
3841 return qemu_chr_open_win_file_out(p
);
3844 #ifdef CONFIG_BRLAPI
3845 if (!strcmp(filename
, "braille")) {
3846 return chr_baum_init();
3854 void qemu_chr_close(CharDriverState
*chr
)
3857 chr
->chr_close(chr
);
3861 /***********************************************************/
3862 /* network device redirectors */
3864 __attribute__ (( unused
))
3865 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3869 for(i
=0;i
<size
;i
+=16) {
3873 fprintf(f
, "%08x ", i
);
3876 fprintf(f
, " %02x", buf
[i
+j
]);
3881 for(j
=0;j
<len
;j
++) {
3883 if (c
< ' ' || c
> '~')
3885 fprintf(f
, "%c", c
);
3891 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3898 offset
= strtol(p
, &last_char
, 0);
3899 if (0 == errno
&& '\0' == *last_char
&&
3900 offset
>= 0 && offset
<= 0xFFFFFF) {
3901 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3902 macaddr
[4] = (offset
& 0xFF00) >> 8;
3903 macaddr
[5] = offset
& 0xFF;
3906 for(i
= 0; i
< 6; i
++) {
3907 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3912 if (*p
!= ':' && *p
!= '-')
3923 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3928 p1
= strchr(p
, sep
);
3934 if (len
> buf_size
- 1)
3936 memcpy(buf
, p
, len
);
3943 int parse_host_src_port(struct sockaddr_in
*haddr
,
3944 struct sockaddr_in
*saddr
,
3945 const char *input_str
)
3947 char *str
= strdup(input_str
);
3948 char *host_str
= str
;
3950 const char *src_str2
;
3954 * Chop off any extra arguments at the end of the string which
3955 * would start with a comma, then fill in the src port information
3956 * if it was provided else use the "any address" and "any port".
3958 if ((ptr
= strchr(str
,',')))
3961 if ((src_str
= strchr(input_str
,'@'))) {
3966 if (parse_host_port(haddr
, host_str
) < 0)
3970 if (!src_str
|| *src_str
== '\0')
3973 if (parse_host_port(saddr
, src_str2
) < 0)
3984 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3992 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3994 saddr
->sin_family
= AF_INET
;
3995 if (buf
[0] == '\0') {
3996 saddr
->sin_addr
.s_addr
= 0;
3998 if (isdigit(buf
[0])) {
3999 if (!inet_aton(buf
, &saddr
->sin_addr
))
4002 if ((he
= gethostbyname(buf
)) == NULL
)
4004 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4007 port
= strtol(p
, (char **)&r
, 0);
4010 saddr
->sin_port
= htons(port
);
4015 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4020 len
= MIN(108, strlen(str
));
4021 p
= strchr(str
, ',');
4023 len
= MIN(len
, p
- str
);
4025 memset(uaddr
, 0, sizeof(*uaddr
));
4027 uaddr
->sun_family
= AF_UNIX
;
4028 memcpy(uaddr
->sun_path
, str
, len
);
4034 /* find or alloc a new VLAN */
4035 VLANState
*qemu_find_vlan(int id
)
4037 VLANState
**pvlan
, *vlan
;
4038 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4042 vlan
= qemu_mallocz(sizeof(VLANState
));
4047 pvlan
= &first_vlan
;
4048 while (*pvlan
!= NULL
)
4049 pvlan
= &(*pvlan
)->next
;
4054 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4055 IOReadHandler
*fd_read
,
4056 IOCanRWHandler
*fd_can_read
,
4059 VLANClientState
*vc
, **pvc
;
4060 vc
= qemu_mallocz(sizeof(VLANClientState
));
4063 vc
->fd_read
= fd_read
;
4064 vc
->fd_can_read
= fd_can_read
;
4065 vc
->opaque
= opaque
;
4069 pvc
= &vlan
->first_client
;
4070 while (*pvc
!= NULL
)
4071 pvc
= &(*pvc
)->next
;
4076 void qemu_del_vlan_client(VLANClientState
*vc
)
4078 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4080 while (*pvc
!= NULL
)
4086 pvc
= &(*pvc
)->next
;
4089 int qemu_can_send_packet(VLANClientState
*vc1
)
4091 VLANState
*vlan
= vc1
->vlan
;
4092 VLANClientState
*vc
;
4094 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4096 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4103 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4105 VLANState
*vlan
= vc1
->vlan
;
4106 VLANClientState
*vc
;
4109 printf("vlan %d send:\n", vlan
->id
);
4110 hex_dump(stdout
, buf
, size
);
4112 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4114 vc
->fd_read(vc
->opaque
, buf
, size
);
4119 #if defined(CONFIG_SLIRP)
4121 /* slirp network adapter */
4123 static int slirp_inited
;
4124 static VLANClientState
*slirp_vc
;
4126 int slirp_can_output(void)
4128 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4131 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4134 printf("slirp output:\n");
4135 hex_dump(stdout
, pkt
, pkt_len
);
4139 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4142 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4145 printf("slirp input:\n");
4146 hex_dump(stdout
, buf
, size
);
4148 slirp_input(buf
, size
);
4151 static int net_slirp_init(VLANState
*vlan
)
4153 if (!slirp_inited
) {
4157 slirp_vc
= qemu_new_vlan_client(vlan
,
4158 slirp_receive
, NULL
, NULL
);
4159 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4163 static void net_slirp_redir(const char *redir_str
)
4168 struct in_addr guest_addr
;
4169 int host_port
, guest_port
;
4171 if (!slirp_inited
) {
4177 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4179 if (!strcmp(buf
, "tcp")) {
4181 } else if (!strcmp(buf
, "udp")) {
4187 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4189 host_port
= strtol(buf
, &r
, 0);
4193 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4195 if (buf
[0] == '\0') {
4196 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4198 if (!inet_aton(buf
, &guest_addr
))
4201 guest_port
= strtol(p
, &r
, 0);
4205 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4206 fprintf(stderr
, "qemu: could not set up redirection\n");
4211 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4217 static char smb_dir
[1024];
4219 static void erase_dir(char *dir_name
)
4223 char filename
[1024];
4225 /* erase all the files in the directory */
4226 if ((d
= opendir(dir_name
)) != 0) {
4231 if (strcmp(de
->d_name
, ".") != 0 &&
4232 strcmp(de
->d_name
, "..") != 0) {
4233 snprintf(filename
, sizeof(filename
), "%s/%s",
4234 smb_dir
, de
->d_name
);
4235 if (unlink(filename
) != 0) /* is it a directory? */
4236 erase_dir(filename
);
4244 /* automatic user mode samba server configuration */
4245 static void smb_exit(void)
4250 /* automatic user mode samba server configuration */
4251 static void net_slirp_smb(const char *exported_dir
)
4253 char smb_conf
[1024];
4254 char smb_cmdline
[1024];
4257 if (!slirp_inited
) {
4262 /* XXX: better tmp dir construction */
4263 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4264 if (mkdir(smb_dir
, 0700) < 0) {
4265 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4268 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4270 f
= fopen(smb_conf
, "w");
4272 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4279 "socket address=127.0.0.1\n"
4280 "pid directory=%s\n"
4281 "lock directory=%s\n"
4282 "log file=%s/log.smbd\n"
4283 "smb passwd file=%s/smbpasswd\n"
4284 "security = share\n"
4299 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4300 SMBD_COMMAND
, smb_conf
);
4302 slirp_add_exec(0, smb_cmdline
, 4, 139);
4305 #endif /* !defined(_WIN32) */
4306 void do_info_slirp(void)
4311 #endif /* CONFIG_SLIRP */
4313 #if !defined(_WIN32)
4315 typedef struct TAPState
{
4316 VLANClientState
*vc
;
4318 char down_script
[1024];
4321 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4323 TAPState
*s
= opaque
;
4326 ret
= write(s
->fd
, buf
, size
);
4327 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4334 static void tap_send(void *opaque
)
4336 TAPState
*s
= opaque
;
4343 sbuf
.maxlen
= sizeof(buf
);
4345 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4347 size
= read(s
->fd
, buf
, sizeof(buf
));
4350 qemu_send_packet(s
->vc
, buf
, size
);
4356 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4360 s
= qemu_mallocz(sizeof(TAPState
));
4364 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4365 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4366 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4370 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4371 static int tap_open(char *ifname
, int ifname_size
)
4377 TFR(fd
= open("/dev/tap", O_RDWR
));
4379 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4384 dev
= devname(s
.st_rdev
, S_IFCHR
);
4385 pstrcpy(ifname
, ifname_size
, dev
);
4387 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4390 #elif defined(__sun__)
4391 #define TUNNEWPPA (('T'<<16) | 0x0001)
4393 * Allocate TAP device, returns opened fd.
4394 * Stores dev name in the first arg(must be large enough).
4396 int tap_alloc(char *dev
, size_t dev_size
)
4398 int tap_fd
, if_fd
, ppa
= -1;
4399 static int ip_fd
= 0;
4402 static int arp_fd
= 0;
4403 int ip_muxid
, arp_muxid
;
4404 struct strioctl strioc_if
, strioc_ppa
;
4405 int link_type
= I_PLINK
;;
4407 char actual_name
[32] = "";
4409 memset(&ifr
, 0x0, sizeof(ifr
));
4413 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4417 /* Check if IP device was opened */
4421 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4423 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4427 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4429 syslog(LOG_ERR
, "Can't open /dev/tap");
4433 /* Assign a new PPA and get its unit number. */
4434 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4435 strioc_ppa
.ic_timout
= 0;
4436 strioc_ppa
.ic_len
= sizeof(ppa
);
4437 strioc_ppa
.ic_dp
= (char *)&ppa
;
4438 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4439 syslog (LOG_ERR
, "Can't assign new interface");
4441 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4443 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4446 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4447 syslog(LOG_ERR
, "Can't push IP module");
4451 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4452 syslog(LOG_ERR
, "Can't get flags\n");
4454 snprintf (actual_name
, 32, "tap%d", ppa
);
4455 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4458 /* Assign ppa according to the unit number returned by tun device */
4460 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4461 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4462 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4463 syslog (LOG_ERR
, "Can't get flags\n");
4464 /* Push arp module to if_fd */
4465 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4466 syslog (LOG_ERR
, "Can't push ARP module (2)");
4468 /* Push arp module to ip_fd */
4469 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4470 syslog (LOG_ERR
, "I_POP failed\n");
4471 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4472 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4474 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4476 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4478 /* Set ifname to arp */
4479 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4480 strioc_if
.ic_timout
= 0;
4481 strioc_if
.ic_len
= sizeof(ifr
);
4482 strioc_if
.ic_dp
= (char *)&ifr
;
4483 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4484 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4487 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4488 syslog(LOG_ERR
, "Can't link TAP device to IP");
4492 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4493 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4497 memset(&ifr
, 0x0, sizeof(ifr
));
4498 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4499 ifr
.lifr_ip_muxid
= ip_muxid
;
4500 ifr
.lifr_arp_muxid
= arp_muxid
;
4502 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4504 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4505 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4506 syslog (LOG_ERR
, "Can't set multiplexor id");
4509 snprintf(dev
, dev_size
, "tap%d", ppa
);
4513 static int tap_open(char *ifname
, int ifname_size
)
4517 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4518 fprintf(stderr
, "Cannot allocate TAP device\n");
4521 pstrcpy(ifname
, ifname_size
, dev
);
4522 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4526 static int tap_open(char *ifname
, int ifname_size
)
4531 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4533 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4536 memset(&ifr
, 0, sizeof(ifr
));
4537 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4538 if (ifname
[0] != '\0')
4539 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4541 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4542 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4544 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4548 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4549 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4554 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4560 /* try to launch network script */
4564 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4565 for (i
= 0; i
< open_max
; i
++)
4566 if (i
!= STDIN_FILENO
&&
4567 i
!= STDOUT_FILENO
&&
4568 i
!= STDERR_FILENO
&&
4573 *parg
++ = (char *)setup_script
;
4574 *parg
++ = (char *)ifname
;
4576 execv(setup_script
, args
);
4579 while (waitpid(pid
, &status
, 0) != pid
);
4580 if (!WIFEXITED(status
) ||
4581 WEXITSTATUS(status
) != 0) {
4582 fprintf(stderr
, "%s: could not launch network script\n",
4590 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4591 const char *setup_script
, const char *down_script
)
4597 if (ifname1
!= NULL
)
4598 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4601 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4605 if (!setup_script
|| !strcmp(setup_script
, "no"))
4607 if (setup_script
[0] != '\0') {
4608 if (launch_script(setup_script
, ifname
, fd
))
4611 s
= net_tap_fd_init(vlan
, fd
);
4614 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4615 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4616 if (down_script
&& strcmp(down_script
, "no"))
4617 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4621 #endif /* !_WIN32 */
4623 #if defined(CONFIG_VDE)
4624 typedef struct VDEState
{
4625 VLANClientState
*vc
;
4629 static void vde_to_qemu(void *opaque
)
4631 VDEState
*s
= opaque
;
4635 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4637 qemu_send_packet(s
->vc
, buf
, size
);
4641 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4643 VDEState
*s
= opaque
;
4646 ret
= vde_send(s
->vde
, buf
, size
, 0);
4647 if (ret
< 0 && errno
== EINTR
) {
4654 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4655 const char *group
, int mode
)
4658 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4659 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4661 struct vde_open_args args
= {
4663 .group
= init_group
,
4667 s
= qemu_mallocz(sizeof(VDEState
));
4670 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4675 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4676 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4677 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4678 sock
, vde_datafd(s
->vde
));
4683 /* network connection */
4684 typedef struct NetSocketState
{
4685 VLANClientState
*vc
;
4687 int state
; /* 0 = getting length, 1 = getting data */
4691 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4694 typedef struct NetSocketListenState
{
4697 } NetSocketListenState
;
4699 /* XXX: we consider we can send the whole packet without blocking */
4700 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4702 NetSocketState
*s
= opaque
;
4706 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4707 send_all(s
->fd
, buf
, size
);
4710 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4712 NetSocketState
*s
= opaque
;
4713 sendto(s
->fd
, buf
, size
, 0,
4714 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4717 static void net_socket_send(void *opaque
)
4719 NetSocketState
*s
= opaque
;
4724 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4726 err
= socket_error();
4727 if (err
!= EWOULDBLOCK
)
4729 } else if (size
== 0) {
4730 /* end of connection */
4732 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4738 /* reassemble a packet from the network */
4744 memcpy(s
->buf
+ s
->index
, buf
, l
);
4748 if (s
->index
== 4) {
4750 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4756 l
= s
->packet_len
- s
->index
;
4759 memcpy(s
->buf
+ s
->index
, buf
, l
);
4763 if (s
->index
>= s
->packet_len
) {
4764 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4773 static void net_socket_send_dgram(void *opaque
)
4775 NetSocketState
*s
= opaque
;
4778 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4782 /* end of connection */
4783 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4786 qemu_send_packet(s
->vc
, s
->buf
, size
);
4789 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4794 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4795 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4796 inet_ntoa(mcastaddr
->sin_addr
),
4797 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4801 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4803 perror("socket(PF_INET, SOCK_DGRAM)");
4808 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4809 (const char *)&val
, sizeof(val
));
4811 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4815 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4821 /* Add host to multicast group */
4822 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4823 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4825 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4826 (const char *)&imr
, sizeof(struct ip_mreq
));
4828 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4832 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4834 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4835 (const char *)&val
, sizeof(val
));
4837 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4841 socket_set_nonblock(fd
);
4849 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4852 struct sockaddr_in saddr
;
4854 socklen_t saddr_len
;
4857 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4858 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4859 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4863 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4865 if (saddr
.sin_addr
.s_addr
==0) {
4866 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4870 /* clone dgram socket */
4871 newfd
= net_socket_mcast_create(&saddr
);
4873 /* error already reported by net_socket_mcast_create() */
4877 /* clone newfd to fd, close newfd */
4882 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4883 fd
, strerror(errno
));
4888 s
= qemu_mallocz(sizeof(NetSocketState
));
4893 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4894 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4896 /* mcast: save bound address as dst */
4897 if (is_connected
) s
->dgram_dst
=saddr
;
4899 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4900 "socket: fd=%d (%s mcast=%s:%d)",
4901 fd
, is_connected
? "cloned" : "",
4902 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4906 static void net_socket_connect(void *opaque
)
4908 NetSocketState
*s
= opaque
;
4909 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4912 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4916 s
= qemu_mallocz(sizeof(NetSocketState
));
4920 s
->vc
= qemu_new_vlan_client(vlan
,
4921 net_socket_receive
, NULL
, s
);
4922 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4923 "socket: fd=%d", fd
);
4925 net_socket_connect(s
);
4927 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4932 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4935 int so_type
=-1, optlen
=sizeof(so_type
);
4937 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4938 (socklen_t
*)&optlen
)< 0) {
4939 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4944 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4946 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4948 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4949 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4950 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4955 static void net_socket_accept(void *opaque
)
4957 NetSocketListenState
*s
= opaque
;
4959 struct sockaddr_in saddr
;
4964 len
= sizeof(saddr
);
4965 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4966 if (fd
< 0 && errno
!= EINTR
) {
4968 } else if (fd
>= 0) {
4972 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4976 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4977 "socket: connection from %s:%d",
4978 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4982 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4984 NetSocketListenState
*s
;
4986 struct sockaddr_in saddr
;
4988 if (parse_host_port(&saddr
, host_str
) < 0)
4991 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4995 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5000 socket_set_nonblock(fd
);
5002 /* allow fast reuse */
5004 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5006 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5011 ret
= listen(fd
, 0);
5018 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5022 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5025 int fd
, connected
, ret
, err
;
5026 struct sockaddr_in saddr
;
5028 if (parse_host_port(&saddr
, host_str
) < 0)
5031 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5036 socket_set_nonblock(fd
);
5040 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5042 err
= socket_error();
5043 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5044 } else if (err
== EINPROGRESS
) {
5047 } else if (err
== WSAEALREADY
) {
5060 s
= net_socket_fd_init(vlan
, fd
, connected
);
5063 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5064 "socket: connect to %s:%d",
5065 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5069 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5073 struct sockaddr_in saddr
;
5075 if (parse_host_port(&saddr
, host_str
) < 0)
5079 fd
= net_socket_mcast_create(&saddr
);
5083 s
= net_socket_fd_init(vlan
, fd
, 0);
5087 s
->dgram_dst
= saddr
;
5089 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5090 "socket: mcast=%s:%d",
5091 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5096 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5101 while (*p
!= '\0' && *p
!= '=') {
5102 if (q
&& (q
- buf
) < buf_size
- 1)
5112 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5117 while (*p
!= '\0') {
5119 if (*(p
+ 1) != ',')
5123 if (q
&& (q
- buf
) < buf_size
- 1)
5133 static int get_param_value(char *buf
, int buf_size
,
5134 const char *tag
, const char *str
)
5141 p
= get_opt_name(option
, sizeof(option
), p
);
5145 if (!strcmp(tag
, option
)) {
5146 (void)get_opt_value(buf
, buf_size
, p
);
5149 p
= get_opt_value(NULL
, 0, p
);
5158 static int check_params(char *buf
, int buf_size
,
5159 const char * const *params
, const char *str
)
5166 p
= get_opt_name(buf
, buf_size
, p
);
5170 for(i
= 0; params
[i
] != NULL
; i
++)
5171 if (!strcmp(params
[i
], buf
))
5173 if (params
[i
] == NULL
)
5175 p
= get_opt_value(NULL
, 0, p
);
5183 static int net_client_init(const char *device
, const char *p
)
5190 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5191 vlan_id
= strtol(buf
, NULL
, 0);
5193 vlan
= qemu_find_vlan(vlan_id
);
5195 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5198 if (!strcmp(device
, "nic")) {
5202 if (nb_nics
>= MAX_NICS
) {
5203 fprintf(stderr
, "Too Many NICs\n");
5206 nd
= &nd_table
[nb_nics
];
5207 macaddr
= nd
->macaddr
;
5213 macaddr
[5] = 0x56 + nb_nics
;
5215 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5216 if (parse_macaddr(macaddr
, buf
) < 0) {
5217 fprintf(stderr
, "invalid syntax for ethernet address\n");
5221 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5222 nd
->model
= strdup(buf
);
5226 vlan
->nb_guest_devs
++;
5229 if (!strcmp(device
, "none")) {
5230 /* does nothing. It is needed to signal that no network cards
5235 if (!strcmp(device
, "user")) {
5236 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5237 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5239 vlan
->nb_host_devs
++;
5240 ret
= net_slirp_init(vlan
);
5244 if (!strcmp(device
, "tap")) {
5246 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5247 fprintf(stderr
, "tap: no interface name\n");
5250 vlan
->nb_host_devs
++;
5251 ret
= tap_win32_init(vlan
, ifname
);
5254 if (!strcmp(device
, "tap")) {
5256 char setup_script
[1024], down_script
[1024];
5258 vlan
->nb_host_devs
++;
5259 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5260 fd
= strtol(buf
, NULL
, 0);
5261 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5263 if (net_tap_fd_init(vlan
, fd
))
5266 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5269 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5270 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5272 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5273 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5275 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5279 if (!strcmp(device
, "socket")) {
5280 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5282 fd
= strtol(buf
, NULL
, 0);
5284 if (net_socket_fd_init(vlan
, fd
, 1))
5286 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5287 ret
= net_socket_listen_init(vlan
, buf
);
5288 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5289 ret
= net_socket_connect_init(vlan
, buf
);
5290 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5291 ret
= net_socket_mcast_init(vlan
, buf
);
5293 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5296 vlan
->nb_host_devs
++;
5299 if (!strcmp(device
, "vde")) {
5300 char vde_sock
[1024], vde_group
[512];
5301 int vde_port
, vde_mode
;
5302 vlan
->nb_host_devs
++;
5303 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5306 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5307 vde_port
= strtol(buf
, NULL
, 10);
5311 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5312 vde_group
[0] = '\0';
5314 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5315 vde_mode
= strtol(buf
, NULL
, 8);
5319 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5323 fprintf(stderr
, "Unknown network device: %s\n", device
);
5327 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5333 static int net_client_parse(const char *str
)
5341 while (*p
!= '\0' && *p
!= ',') {
5342 if ((q
- device
) < sizeof(device
) - 1)
5350 return net_client_init(device
, p
);
5353 void do_info_network(void)
5356 VLANClientState
*vc
;
5358 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5359 term_printf("VLAN %d devices:\n", vlan
->id
);
5360 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5361 term_printf(" %s\n", vc
->info_str
);
5365 /***********************************************************/
5366 /* Bluetooth support */
5369 static struct HCIInfo
*hci_table
[MAX_NICS
];
5370 static struct bt_vlan_s
{
5371 struct bt_scatternet_s net
;
5373 struct bt_vlan_s
*next
;
5376 /* find or alloc a new bluetooth "VLAN" */
5377 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
5379 struct bt_vlan_s
**pvlan
, *vlan
;
5380 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5384 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
5386 pvlan
= &first_bt_vlan
;
5387 while (*pvlan
!= NULL
)
5388 pvlan
= &(*pvlan
)->next
;
5393 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
5397 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
5402 static struct HCIInfo null_hci
= {
5403 .cmd_send
= null_hci_send
,
5404 .sco_send
= null_hci_send
,
5405 .acl_send
= null_hci_send
,
5406 .bdaddr_set
= null_hci_addr_set
,
5409 struct HCIInfo
*qemu_next_hci(void)
5411 if (cur_hci
== nb_hcis
)
5414 return hci_table
[cur_hci
++];
5417 /***********************************************************/
5418 /* QEMU Block devices */
5420 #define HD_ALIAS "index=%d,media=disk"
5422 #define CDROM_ALIAS "index=1,media=cdrom"
5424 #define CDROM_ALIAS "index=2,media=cdrom"
5426 #define FD_ALIAS "index=%d,if=floppy"
5427 #define PFLASH_ALIAS "if=pflash"
5428 #define MTD_ALIAS "if=mtd"
5429 #define SD_ALIAS "index=0,if=sd"
5431 static int drive_add(const char *file
, const char *fmt
, ...)
5435 if (nb_drives_opt
>= MAX_DRIVES
) {
5436 fprintf(stderr
, "qemu: too many drives\n");
5440 drives_opt
[nb_drives_opt
].file
= file
;
5442 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5443 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5446 return nb_drives_opt
++;
5449 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5453 /* seek interface, bus and unit */
5455 for (index
= 0; index
< nb_drives
; index
++)
5456 if (drives_table
[index
].type
== type
&&
5457 drives_table
[index
].bus
== bus
&&
5458 drives_table
[index
].unit
== unit
)
5464 int drive_get_max_bus(BlockInterfaceType type
)
5470 for (index
= 0; index
< nb_drives
; index
++) {
5471 if(drives_table
[index
].type
== type
&&
5472 drives_table
[index
].bus
> max_bus
)
5473 max_bus
= drives_table
[index
].bus
;
5478 static void bdrv_format_print(void *opaque
, const char *name
)
5480 fprintf(stderr
, " %s", name
);
5483 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5484 QEMUMachine
*machine
)
5489 const char *mediastr
= "";
5490 BlockInterfaceType type
;
5491 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5492 int bus_id
, unit_id
;
5493 int cyls
, heads
, secs
, translation
;
5494 BlockDriverState
*bdrv
;
5495 BlockDriver
*drv
= NULL
;
5500 char *str
= arg
->opt
;
5501 static const char * const params
[] = { "bus", "unit", "if", "index",
5502 "cyls", "heads", "secs", "trans",
5503 "media", "snapshot", "file",
5504 "cache", "format", NULL
};
5506 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5507 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5513 cyls
= heads
= secs
= 0;
5516 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5520 if (machine
->use_scsi
) {
5522 max_devs
= MAX_SCSI_DEVS
;
5523 pstrcpy(devname
, sizeof(devname
), "scsi");
5526 max_devs
= MAX_IDE_DEVS
;
5527 pstrcpy(devname
, sizeof(devname
), "ide");
5531 /* extract parameters */
5533 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5534 bus_id
= strtol(buf
, NULL
, 0);
5536 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5541 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5542 unit_id
= strtol(buf
, NULL
, 0);
5544 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5549 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5550 pstrcpy(devname
, sizeof(devname
), buf
);
5551 if (!strcmp(buf
, "ide")) {
5553 max_devs
= MAX_IDE_DEVS
;
5554 } else if (!strcmp(buf
, "scsi")) {
5556 max_devs
= MAX_SCSI_DEVS
;
5557 } else if (!strcmp(buf
, "floppy")) {
5560 } else if (!strcmp(buf
, "pflash")) {
5563 } else if (!strcmp(buf
, "mtd")) {
5566 } else if (!strcmp(buf
, "sd")) {
5570 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5575 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5576 index
= strtol(buf
, NULL
, 0);
5578 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5583 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5584 cyls
= strtol(buf
, NULL
, 0);
5587 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5588 heads
= strtol(buf
, NULL
, 0);
5591 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5592 secs
= strtol(buf
, NULL
, 0);
5595 if (cyls
|| heads
|| secs
) {
5596 if (cyls
< 1 || cyls
> 16383) {
5597 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5600 if (heads
< 1 || heads
> 16) {
5601 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5604 if (secs
< 1 || secs
> 63) {
5605 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5610 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5613 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5617 if (!strcmp(buf
, "none"))
5618 translation
= BIOS_ATA_TRANSLATION_NONE
;
5619 else if (!strcmp(buf
, "lba"))
5620 translation
= BIOS_ATA_TRANSLATION_LBA
;
5621 else if (!strcmp(buf
, "auto"))
5622 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5624 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5629 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5630 if (!strcmp(buf
, "disk")) {
5632 } else if (!strcmp(buf
, "cdrom")) {
5633 if (cyls
|| secs
|| heads
) {
5635 "qemu: '%s' invalid physical CHS format\n", str
);
5638 media
= MEDIA_CDROM
;
5640 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5645 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5646 if (!strcmp(buf
, "on"))
5648 else if (!strcmp(buf
, "off"))
5651 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5656 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5657 if (!strcmp(buf
, "off"))
5659 else if (!strcmp(buf
, "on"))
5662 fprintf(stderr
, "qemu: invalid cache option\n");
5667 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5668 if (strcmp(buf
, "?") == 0) {
5669 fprintf(stderr
, "qemu: Supported formats:");
5670 bdrv_iterate_format(bdrv_format_print
, NULL
);
5671 fprintf(stderr
, "\n");
5674 drv
= bdrv_find_format(buf
);
5676 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5681 if (arg
->file
== NULL
)
5682 get_param_value(file
, sizeof(file
), "file", str
);
5684 pstrcpy(file
, sizeof(file
), arg
->file
);
5686 /* compute bus and unit according index */
5689 if (bus_id
!= 0 || unit_id
!= -1) {
5691 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5699 unit_id
= index
% max_devs
;
5700 bus_id
= index
/ max_devs
;
5704 /* if user doesn't specify a unit_id,
5705 * try to find the first free
5708 if (unit_id
== -1) {
5710 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5712 if (max_devs
&& unit_id
>= max_devs
) {
5713 unit_id
-= max_devs
;
5721 if (max_devs
&& unit_id
>= max_devs
) {
5722 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5723 str
, unit_id
, max_devs
- 1);
5728 * ignore multiple definitions
5731 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5736 if (type
== IF_IDE
|| type
== IF_SCSI
)
5737 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5739 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5740 devname
, bus_id
, mediastr
, unit_id
);
5742 snprintf(buf
, sizeof(buf
), "%s%s%i",
5743 devname
, mediastr
, unit_id
);
5744 bdrv
= bdrv_new(buf
);
5745 drives_table
[nb_drives
].bdrv
= bdrv
;
5746 drives_table
[nb_drives
].type
= type
;
5747 drives_table
[nb_drives
].bus
= bus_id
;
5748 drives_table
[nb_drives
].unit
= unit_id
;
5757 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5758 bdrv_set_translation_hint(bdrv
, translation
);
5762 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5767 /* FIXME: This isn't really a floppy, but it's a reasonable
5770 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5780 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5782 bdrv_flags
|= BDRV_O_DIRECT
;
5783 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5784 fprintf(stderr
, "qemu: could not open disk image %s\n",
5791 /***********************************************************/
5794 static USBPort
*used_usb_ports
;
5795 static USBPort
*free_usb_ports
;
5797 /* ??? Maybe change this to register a hub to keep track of the topology. */
5798 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5799 usb_attachfn attach
)
5801 port
->opaque
= opaque
;
5802 port
->index
= index
;
5803 port
->attach
= attach
;
5804 port
->next
= free_usb_ports
;
5805 free_usb_ports
= port
;
5808 int usb_device_add_dev(USBDevice
*dev
)
5812 /* Find a USB port to add the device to. */
5813 port
= free_usb_ports
;
5817 /* Create a new hub and chain it on. */
5818 free_usb_ports
= NULL
;
5819 port
->next
= used_usb_ports
;
5820 used_usb_ports
= port
;
5822 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5823 usb_attach(port
, hub
);
5824 port
= free_usb_ports
;
5827 free_usb_ports
= port
->next
;
5828 port
->next
= used_usb_ports
;
5829 used_usb_ports
= port
;
5830 usb_attach(port
, dev
);
5834 static int usb_device_add(const char *devname
)
5839 if (!free_usb_ports
)
5842 if (strstart(devname
, "host:", &p
)) {
5843 dev
= usb_host_device_open(p
);
5844 } else if (!strcmp(devname
, "mouse")) {
5845 dev
= usb_mouse_init();
5846 } else if (!strcmp(devname
, "tablet")) {
5847 dev
= usb_tablet_init();
5848 } else if (!strcmp(devname
, "keyboard")) {
5849 dev
= usb_keyboard_init();
5850 } else if (strstart(devname
, "disk:", &p
)) {
5851 dev
= usb_msd_init(p
);
5852 } else if (!strcmp(devname
, "wacom-tablet")) {
5853 dev
= usb_wacom_init();
5854 } else if (strstart(devname
, "serial:", &p
)) {
5855 dev
= usb_serial_init(p
);
5856 #ifdef CONFIG_BRLAPI
5857 } else if (!strcmp(devname
, "braille")) {
5858 dev
= usb_baum_init();
5860 } else if (strstart(devname
, "net:", &p
)) {
5863 if (net_client_init("nic", p
) < 0)
5865 nd_table
[nic
].model
= "usb";
5866 dev
= usb_net_init(&nd_table
[nic
]);
5873 return usb_device_add_dev(dev
);
5876 int usb_device_del_addr(int bus_num
, int addr
)
5882 if (!used_usb_ports
)
5888 lastp
= &used_usb_ports
;
5889 port
= used_usb_ports
;
5890 while (port
&& port
->dev
->addr
!= addr
) {
5891 lastp
= &port
->next
;
5899 *lastp
= port
->next
;
5900 usb_attach(port
, NULL
);
5901 dev
->handle_destroy(dev
);
5902 port
->next
= free_usb_ports
;
5903 free_usb_ports
= port
;
5907 static int usb_device_del(const char *devname
)
5912 if (strstart(devname
, "host:", &p
))
5913 return usb_host_device_close(p
);
5915 if (!used_usb_ports
)
5918 p
= strchr(devname
, '.');
5921 bus_num
= strtoul(devname
, NULL
, 0);
5922 addr
= strtoul(p
+ 1, NULL
, 0);
5924 return usb_device_del_addr(bus_num
, addr
);
5927 void do_usb_add(const char *devname
)
5929 usb_device_add(devname
);
5932 void do_usb_del(const char *devname
)
5934 usb_device_del(devname
);
5941 const char *speed_str
;
5944 term_printf("USB support not enabled\n");
5948 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5952 switch(dev
->speed
) {
5956 case USB_SPEED_FULL
:
5959 case USB_SPEED_HIGH
:
5966 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5967 0, dev
->addr
, speed_str
, dev
->devname
);
5971 /***********************************************************/
5972 /* PCMCIA/Cardbus */
5974 static struct pcmcia_socket_entry_s
{
5975 struct pcmcia_socket_s
*socket
;
5976 struct pcmcia_socket_entry_s
*next
;
5977 } *pcmcia_sockets
= 0;
5979 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5981 struct pcmcia_socket_entry_s
*entry
;
5983 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5984 entry
->socket
= socket
;
5985 entry
->next
= pcmcia_sockets
;
5986 pcmcia_sockets
= entry
;
5989 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5991 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5993 ptr
= &pcmcia_sockets
;
5994 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5995 if (entry
->socket
== socket
) {
6001 void pcmcia_info(void)
6003 struct pcmcia_socket_entry_s
*iter
;
6004 if (!pcmcia_sockets
)
6005 term_printf("No PCMCIA sockets\n");
6007 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6008 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6009 iter
->socket
->attached
? iter
->socket
->card_string
:
6013 /***********************************************************/
6016 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6020 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6024 static void dumb_refresh(DisplayState
*ds
)
6026 #if defined(CONFIG_SDL)
6031 static void dumb_display_init(DisplayState
*ds
)
6036 ds
->dpy_update
= dumb_update
;
6037 ds
->dpy_resize
= dumb_resize
;
6038 ds
->dpy_refresh
= dumb_refresh
;
6039 ds
->gui_timer_interval
= 500;
6043 /***********************************************************/
6046 #define MAX_IO_HANDLERS 64
6048 typedef struct IOHandlerRecord
{
6050 IOCanRWHandler
*fd_read_poll
;
6052 IOHandler
*fd_write
;
6055 /* temporary data */
6057 struct IOHandlerRecord
*next
;
6060 static IOHandlerRecord
*first_io_handler
;
6062 /* XXX: fd_read_poll should be suppressed, but an API change is
6063 necessary in the character devices to suppress fd_can_read(). */
6064 int qemu_set_fd_handler2(int fd
,
6065 IOCanRWHandler
*fd_read_poll
,
6067 IOHandler
*fd_write
,
6070 IOHandlerRecord
**pioh
, *ioh
;
6072 if (!fd_read
&& !fd_write
) {
6073 pioh
= &first_io_handler
;
6078 if (ioh
->fd
== fd
) {
6085 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6089 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6092 ioh
->next
= first_io_handler
;
6093 first_io_handler
= ioh
;
6096 ioh
->fd_read_poll
= fd_read_poll
;
6097 ioh
->fd_read
= fd_read
;
6098 ioh
->fd_write
= fd_write
;
6099 ioh
->opaque
= opaque
;
6105 int qemu_set_fd_handler(int fd
,
6107 IOHandler
*fd_write
,
6110 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6113 /***********************************************************/
6114 /* Polling handling */
6116 typedef struct PollingEntry
{
6119 struct PollingEntry
*next
;
6122 static PollingEntry
*first_polling_entry
;
6124 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6126 PollingEntry
**ppe
, *pe
;
6127 pe
= qemu_mallocz(sizeof(PollingEntry
));
6131 pe
->opaque
= opaque
;
6132 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6137 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6139 PollingEntry
**ppe
, *pe
;
6140 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6142 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6151 /***********************************************************/
6152 /* Wait objects support */
6153 typedef struct WaitObjects
{
6155 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6156 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6157 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6160 static WaitObjects wait_objects
= {0};
6162 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6164 WaitObjects
*w
= &wait_objects
;
6166 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6168 w
->events
[w
->num
] = handle
;
6169 w
->func
[w
->num
] = func
;
6170 w
->opaque
[w
->num
] = opaque
;
6175 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6178 WaitObjects
*w
= &wait_objects
;
6181 for (i
= 0; i
< w
->num
; i
++) {
6182 if (w
->events
[i
] == handle
)
6185 w
->events
[i
] = w
->events
[i
+ 1];
6186 w
->func
[i
] = w
->func
[i
+ 1];
6187 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6195 /***********************************************************/
6196 /* savevm/loadvm support */
6198 #define IO_BUF_SIZE 32768
6201 QEMUFilePutBufferFunc
*put_buffer
;
6202 QEMUFileGetBufferFunc
*get_buffer
;
6203 QEMUFileCloseFunc
*close
;
6204 QEMUFileRateLimit
*rate_limit
;
6207 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6210 int buf_size
; /* 0 when writing */
6211 uint8_t buf
[IO_BUF_SIZE
];
6214 typedef struct QEMUFileFD
6220 static void fd_put_notify(void *opaque
)
6222 QEMUFileFD
*s
= opaque
;
6224 /* Remove writable callback and do a put notify */
6225 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
6226 qemu_file_put_notify(s
->file
);
6229 static void fd_put_buffer(void *opaque
, const uint8_t *buf
,
6230 int64_t pos
, int size
)
6232 QEMUFileFD
*s
= opaque
;
6236 len
= write(s
->fd
, buf
, size
);
6237 } while (len
== -1 && errno
== EINTR
);
6242 /* When the fd becomes writable again, register a callback to do
6245 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, fd_put_notify
, s
);
6248 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6250 QEMUFileFD
*s
= opaque
;
6254 len
= read(s
->fd
, buf
, size
);
6255 } while (len
== -1 && errno
== EINTR
);
6263 static int fd_close(void *opaque
)
6265 QEMUFileFD
*s
= opaque
;
6270 QEMUFile
*qemu_fopen_fd(int fd
)
6272 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6278 s
->file
= qemu_fopen_ops(s
, fd_put_buffer
, fd_get_buffer
, fd_close
, NULL
);
6282 typedef struct QEMUFileStdio
6287 static void file_put_buffer(void *opaque
, const uint8_t *buf
,
6288 int64_t pos
, int size
)
6290 QEMUFileStdio
*s
= opaque
;
6291 fseek(s
->outfile
, pos
, SEEK_SET
);
6292 fwrite(buf
, 1, size
, s
->outfile
);
6295 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6297 QEMUFileStdio
*s
= opaque
;
6298 fseek(s
->outfile
, pos
, SEEK_SET
);
6299 return fread(buf
, 1, size
, s
->outfile
);
6302 static int file_close(void *opaque
)
6304 QEMUFileStdio
*s
= opaque
;
6310 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6314 s
= qemu_mallocz(sizeof(QEMUFileStdio
));
6318 s
->outfile
= fopen(filename
, mode
);
6322 if (!strcmp(mode
, "wb"))
6323 return qemu_fopen_ops(s
, file_put_buffer
, NULL
, file_close
, NULL
);
6324 else if (!strcmp(mode
, "rb"))
6325 return qemu_fopen_ops(s
, NULL
, file_get_buffer
, file_close
, NULL
);
6334 typedef struct QEMUFileBdrv
6336 BlockDriverState
*bs
;
6337 int64_t base_offset
;
6340 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
,
6341 int64_t pos
, int size
)
6343 QEMUFileBdrv
*s
= opaque
;
6344 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6347 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6349 QEMUFileBdrv
*s
= opaque
;
6350 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6353 static int bdrv_fclose(void *opaque
)
6355 QEMUFileBdrv
*s
= opaque
;
6360 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6364 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6369 s
->base_offset
= offset
;
6372 return qemu_fopen_ops(s
, bdrv_put_buffer
, NULL
, bdrv_fclose
, NULL
);
6374 return qemu_fopen_ops(s
, NULL
, bdrv_get_buffer
, bdrv_fclose
, NULL
);
6377 QEMUFile
*qemu_fopen_ops(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6378 QEMUFileGetBufferFunc
*get_buffer
,
6379 QEMUFileCloseFunc
*close
,
6380 QEMUFileRateLimit
*rate_limit
)
6384 f
= qemu_mallocz(sizeof(QEMUFile
));
6389 f
->put_buffer
= put_buffer
;
6390 f
->get_buffer
= get_buffer
;
6392 f
->rate_limit
= rate_limit
;
6397 void qemu_fflush(QEMUFile
*f
)
6402 if (f
->buf_index
> 0) {
6403 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6404 f
->buf_offset
+= f
->buf_index
;
6409 static void qemu_fill_buffer(QEMUFile
*f
)
6416 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6422 f
->buf_offset
+= len
;
6425 int qemu_fclose(QEMUFile
*f
)
6430 ret
= f
->close(f
->opaque
);
6435 void qemu_file_put_notify(QEMUFile
*f
)
6437 f
->put_buffer(f
->opaque
, NULL
, 0, 0);
6440 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6444 l
= IO_BUF_SIZE
- f
->buf_index
;
6447 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6451 if (f
->buf_index
>= IO_BUF_SIZE
)
6456 void qemu_put_byte(QEMUFile
*f
, int v
)
6458 f
->buf
[f
->buf_index
++] = v
;
6459 if (f
->buf_index
>= IO_BUF_SIZE
)
6463 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6469 l
= f
->buf_size
- f
->buf_index
;
6471 qemu_fill_buffer(f
);
6472 l
= f
->buf_size
- f
->buf_index
;
6478 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6483 return size1
- size
;
6486 int qemu_get_byte(QEMUFile
*f
)
6488 if (f
->buf_index
>= f
->buf_size
) {
6489 qemu_fill_buffer(f
);
6490 if (f
->buf_index
>= f
->buf_size
)
6493 return f
->buf
[f
->buf_index
++];
6496 int64_t qemu_ftell(QEMUFile
*f
)
6498 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6501 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6503 if (whence
== SEEK_SET
) {
6505 } else if (whence
== SEEK_CUR
) {
6506 pos
+= qemu_ftell(f
);
6508 /* SEEK_END not supported */
6511 if (f
->put_buffer
) {
6513 f
->buf_offset
= pos
;
6515 f
->buf_offset
= pos
;
6522 int qemu_file_rate_limit(QEMUFile
*f
)
6525 return f
->rate_limit(f
->opaque
);
6530 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6532 qemu_put_byte(f
, v
>> 8);
6533 qemu_put_byte(f
, v
);
6536 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6538 qemu_put_byte(f
, v
>> 24);
6539 qemu_put_byte(f
, v
>> 16);
6540 qemu_put_byte(f
, v
>> 8);
6541 qemu_put_byte(f
, v
);
6544 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6546 qemu_put_be32(f
, v
>> 32);
6547 qemu_put_be32(f
, v
);
6550 unsigned int qemu_get_be16(QEMUFile
*f
)
6553 v
= qemu_get_byte(f
) << 8;
6554 v
|= qemu_get_byte(f
);
6558 unsigned int qemu_get_be32(QEMUFile
*f
)
6561 v
= qemu_get_byte(f
) << 24;
6562 v
|= qemu_get_byte(f
) << 16;
6563 v
|= qemu_get_byte(f
) << 8;
6564 v
|= qemu_get_byte(f
);
6568 uint64_t qemu_get_be64(QEMUFile
*f
)
6571 v
= (uint64_t)qemu_get_be32(f
) << 32;
6572 v
|= qemu_get_be32(f
);
6576 typedef struct SaveStateEntry
{
6580 SaveStateHandler
*save_state
;
6581 LoadStateHandler
*load_state
;
6583 struct SaveStateEntry
*next
;
6586 static SaveStateEntry
*first_se
;
6588 /* TODO: Individual devices generally have very little idea about the rest
6589 of the system, so instance_id should be removed/replaced.
6590 Meanwhile pass -1 as instance_id if you do not already have a clearly
6591 distinguishing id for all instances of your device class. */
6592 int register_savevm(const char *idstr
,
6595 SaveStateHandler
*save_state
,
6596 LoadStateHandler
*load_state
,
6599 SaveStateEntry
*se
, **pse
;
6601 se
= qemu_malloc(sizeof(SaveStateEntry
));
6604 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6605 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6606 se
->version_id
= version_id
;
6607 se
->save_state
= save_state
;
6608 se
->load_state
= load_state
;
6609 se
->opaque
= opaque
;
6612 /* add at the end of list */
6614 while (*pse
!= NULL
) {
6615 if (instance_id
== -1
6616 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6617 && se
->instance_id
<= (*pse
)->instance_id
)
6618 se
->instance_id
= (*pse
)->instance_id
+ 1;
6619 pse
= &(*pse
)->next
;
6625 #define QEMU_VM_FILE_MAGIC 0x5145564d
6626 #define QEMU_VM_FILE_VERSION 0x00000002
6628 static int qemu_savevm_state(QEMUFile
*f
)
6632 int64_t cur_pos
, len_pos
, total_len_pos
;
6634 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6635 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6636 total_len_pos
= qemu_ftell(f
);
6637 qemu_put_be64(f
, 0); /* total size */
6639 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6640 if (se
->save_state
== NULL
)
6641 /* this one has a loader only, for backwards compatibility */
6645 len
= strlen(se
->idstr
);
6646 qemu_put_byte(f
, len
);
6647 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6649 qemu_put_be32(f
, se
->instance_id
);
6650 qemu_put_be32(f
, se
->version_id
);
6652 /* record size: filled later */
6653 len_pos
= qemu_ftell(f
);
6654 qemu_put_be32(f
, 0);
6655 se
->save_state(f
, se
->opaque
);
6657 /* fill record size */
6658 cur_pos
= qemu_ftell(f
);
6659 len
= cur_pos
- len_pos
- 4;
6660 qemu_fseek(f
, len_pos
, SEEK_SET
);
6661 qemu_put_be32(f
, len
);
6662 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6664 cur_pos
= qemu_ftell(f
);
6665 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6666 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6667 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6673 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6677 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6678 if (!strcmp(se
->idstr
, idstr
) &&
6679 instance_id
== se
->instance_id
)
6685 static int qemu_loadvm_state(QEMUFile
*f
)
6688 int len
, ret
, instance_id
, record_len
, version_id
;
6689 int64_t total_len
, end_pos
, cur_pos
;
6693 v
= qemu_get_be32(f
);
6694 if (v
!= QEMU_VM_FILE_MAGIC
)
6696 v
= qemu_get_be32(f
);
6697 if (v
!= QEMU_VM_FILE_VERSION
) {
6702 total_len
= qemu_get_be64(f
);
6703 end_pos
= total_len
+ qemu_ftell(f
);
6705 if (qemu_ftell(f
) >= end_pos
)
6707 len
= qemu_get_byte(f
);
6708 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6710 instance_id
= qemu_get_be32(f
);
6711 version_id
= qemu_get_be32(f
);
6712 record_len
= qemu_get_be32(f
);
6714 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6715 idstr
, instance_id
, version_id
, record_len
);
6717 cur_pos
= qemu_ftell(f
);
6718 se
= find_se(idstr
, instance_id
);
6720 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6721 instance_id
, idstr
);
6723 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6725 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6726 instance_id
, idstr
);
6729 /* always seek to exact end of record */
6730 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6737 /* device can contain snapshots */
6738 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6741 !bdrv_is_removable(bs
) &&
6742 !bdrv_is_read_only(bs
));
6745 /* device must be snapshots in order to have a reliable snapshot */
6746 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6749 !bdrv_is_removable(bs
) &&
6750 !bdrv_is_read_only(bs
));
6753 static BlockDriverState
*get_bs_snapshots(void)
6755 BlockDriverState
*bs
;
6759 return bs_snapshots
;
6760 for(i
= 0; i
<= nb_drives
; i
++) {
6761 bs
= drives_table
[i
].bdrv
;
6762 if (bdrv_can_snapshot(bs
))
6771 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6774 QEMUSnapshotInfo
*sn_tab
, *sn
;
6778 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6781 for(i
= 0; i
< nb_sns
; i
++) {
6783 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6793 void do_savevm(const char *name
)
6795 BlockDriverState
*bs
, *bs1
;
6796 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6797 int must_delete
, ret
, i
;
6798 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6800 int saved_vm_running
;
6807 bs
= get_bs_snapshots();
6809 term_printf("No block device can accept snapshots\n");
6813 /* ??? Should this occur after vm_stop? */
6816 saved_vm_running
= vm_running
;
6821 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6826 memset(sn
, 0, sizeof(*sn
));
6828 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6829 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6832 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6835 /* fill auxiliary fields */
6838 sn
->date_sec
= tb
.time
;
6839 sn
->date_nsec
= tb
.millitm
* 1000000;
6841 gettimeofday(&tv
, NULL
);
6842 sn
->date_sec
= tv
.tv_sec
;
6843 sn
->date_nsec
= tv
.tv_usec
* 1000;
6845 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6847 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6848 term_printf("Device %s does not support VM state snapshots\n",
6849 bdrv_get_device_name(bs
));
6853 /* save the VM state */
6854 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6856 term_printf("Could not open VM state file\n");
6859 ret
= qemu_savevm_state(f
);
6860 sn
->vm_state_size
= qemu_ftell(f
);
6863 term_printf("Error %d while writing VM\n", ret
);
6867 /* create the snapshots */
6869 for(i
= 0; i
< nb_drives
; i
++) {
6870 bs1
= drives_table
[i
].bdrv
;
6871 if (bdrv_has_snapshot(bs1
)) {
6873 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6875 term_printf("Error while deleting snapshot on '%s'\n",
6876 bdrv_get_device_name(bs1
));
6879 ret
= bdrv_snapshot_create(bs1
, sn
);
6881 term_printf("Error while creating snapshot on '%s'\n",
6882 bdrv_get_device_name(bs1
));
6888 if (saved_vm_running
)
6892 void do_loadvm(const char *name
)
6894 BlockDriverState
*bs
, *bs1
;
6895 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6898 int saved_vm_running
;
6900 bs
= get_bs_snapshots();
6902 term_printf("No block device supports snapshots\n");
6906 /* Flush all IO requests so they don't interfere with the new state. */
6909 saved_vm_running
= vm_running
;
6912 for(i
= 0; i
<= nb_drives
; i
++) {
6913 bs1
= drives_table
[i
].bdrv
;
6914 if (bdrv_has_snapshot(bs1
)) {
6915 ret
= bdrv_snapshot_goto(bs1
, name
);
6918 term_printf("Warning: ");
6921 term_printf("Snapshots not supported on device '%s'\n",
6922 bdrv_get_device_name(bs1
));
6925 term_printf("Could not find snapshot '%s' on device '%s'\n",
6926 name
, bdrv_get_device_name(bs1
));
6929 term_printf("Error %d while activating snapshot on '%s'\n",
6930 ret
, bdrv_get_device_name(bs1
));
6933 /* fatal on snapshot block device */
6940 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6941 term_printf("Device %s does not support VM state snapshots\n",
6942 bdrv_get_device_name(bs
));
6946 /* restore the VM state */
6947 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6949 term_printf("Could not open VM state file\n");
6952 ret
= qemu_loadvm_state(f
);
6955 term_printf("Error %d while loading VM state\n", ret
);
6958 if (saved_vm_running
)
6962 void do_delvm(const char *name
)
6964 BlockDriverState
*bs
, *bs1
;
6967 bs
= get_bs_snapshots();
6969 term_printf("No block device supports snapshots\n");
6973 for(i
= 0; i
<= nb_drives
; i
++) {
6974 bs1
= drives_table
[i
].bdrv
;
6975 if (bdrv_has_snapshot(bs1
)) {
6976 ret
= bdrv_snapshot_delete(bs1
, name
);
6978 if (ret
== -ENOTSUP
)
6979 term_printf("Snapshots not supported on device '%s'\n",
6980 bdrv_get_device_name(bs1
));
6982 term_printf("Error %d while deleting snapshot on '%s'\n",
6983 ret
, bdrv_get_device_name(bs1
));
6989 void do_info_snapshots(void)
6991 BlockDriverState
*bs
, *bs1
;
6992 QEMUSnapshotInfo
*sn_tab
, *sn
;
6996 bs
= get_bs_snapshots();
6998 term_printf("No available block device supports snapshots\n");
7001 term_printf("Snapshot devices:");
7002 for(i
= 0; i
<= nb_drives
; i
++) {
7003 bs1
= drives_table
[i
].bdrv
;
7004 if (bdrv_has_snapshot(bs1
)) {
7006 term_printf(" %s", bdrv_get_device_name(bs1
));
7011 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7013 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7016 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7017 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7018 for(i
= 0; i
< nb_sns
; i
++) {
7020 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7025 /***********************************************************/
7026 /* ram save/restore */
7028 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7032 v
= qemu_get_byte(f
);
7035 if (qemu_get_buffer(f
, buf
, len
) != len
)
7039 v
= qemu_get_byte(f
);
7040 memset(buf
, v
, len
);
7048 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7053 if (qemu_get_be32(f
) != phys_ram_size
)
7055 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7056 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7063 #define BDRV_HASH_BLOCK_SIZE 1024
7064 #define IOBUF_SIZE 4096
7065 #define RAM_CBLOCK_MAGIC 0xfabe
7067 typedef struct RamCompressState
{
7070 uint8_t buf
[IOBUF_SIZE
];
7073 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7076 memset(s
, 0, sizeof(*s
));
7078 ret
= deflateInit2(&s
->zstream
, 1,
7080 9, Z_DEFAULT_STRATEGY
);
7083 s
->zstream
.avail_out
= IOBUF_SIZE
;
7084 s
->zstream
.next_out
= s
->buf
;
7088 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7090 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7091 qemu_put_be16(s
->f
, len
);
7092 qemu_put_buffer(s
->f
, buf
, len
);
7095 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7099 s
->zstream
.avail_in
= len
;
7100 s
->zstream
.next_in
= (uint8_t *)buf
;
7101 while (s
->zstream
.avail_in
> 0) {
7102 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7105 if (s
->zstream
.avail_out
== 0) {
7106 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7107 s
->zstream
.avail_out
= IOBUF_SIZE
;
7108 s
->zstream
.next_out
= s
->buf
;
7114 static void ram_compress_close(RamCompressState
*s
)
7118 /* compress last bytes */
7120 ret
= deflate(&s
->zstream
, Z_FINISH
);
7121 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7122 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7124 ram_put_cblock(s
, s
->buf
, len
);
7126 s
->zstream
.avail_out
= IOBUF_SIZE
;
7127 s
->zstream
.next_out
= s
->buf
;
7128 if (ret
== Z_STREAM_END
)
7135 deflateEnd(&s
->zstream
);
7138 typedef struct RamDecompressState
{
7141 uint8_t buf
[IOBUF_SIZE
];
7142 } RamDecompressState
;
7144 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7147 memset(s
, 0, sizeof(*s
));
7149 ret
= inflateInit(&s
->zstream
);
7155 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7159 s
->zstream
.avail_out
= len
;
7160 s
->zstream
.next_out
= buf
;
7161 while (s
->zstream
.avail_out
> 0) {
7162 if (s
->zstream
.avail_in
== 0) {
7163 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7165 clen
= qemu_get_be16(s
->f
);
7166 if (clen
> IOBUF_SIZE
)
7168 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7169 s
->zstream
.avail_in
= clen
;
7170 s
->zstream
.next_in
= s
->buf
;
7172 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7173 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7180 static void ram_decompress_close(RamDecompressState
*s
)
7182 inflateEnd(&s
->zstream
);
7185 static void ram_save(QEMUFile
*f
, void *opaque
)
7188 RamCompressState s1
, *s
= &s1
;
7191 qemu_put_be32(f
, phys_ram_size
);
7192 if (ram_compress_open(s
, f
) < 0)
7194 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7196 if (tight_savevm_enabled
) {
7200 /* find if the memory block is available on a virtual
7203 for(j
= 0; j
< nb_drives
; j
++) {
7204 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7206 BDRV_HASH_BLOCK_SIZE
);
7207 if (sector_num
>= 0)
7211 goto normal_compress
;
7214 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7215 ram_compress_buf(s
, buf
, 10);
7221 ram_compress_buf(s
, buf
, 1);
7222 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7225 ram_compress_close(s
);
7228 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7230 RamDecompressState s1
, *s
= &s1
;
7234 if (version_id
== 1)
7235 return ram_load_v1(f
, opaque
);
7236 if (version_id
!= 2)
7238 if (qemu_get_be32(f
) != phys_ram_size
)
7240 if (ram_decompress_open(s
, f
) < 0)
7242 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7243 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7244 fprintf(stderr
, "Error while reading ram block header\n");
7248 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7249 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7258 ram_decompress_buf(s
, buf
+ 1, 9);
7260 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7261 if (bs_index
>= nb_drives
) {
7262 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7265 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7267 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7268 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7269 bs_index
, sector_num
);
7276 printf("Error block header\n");
7280 ram_decompress_close(s
);
7284 /***********************************************************/
7285 /* bottom halves (can be seen as timers which expire ASAP) */
7294 static QEMUBH
*first_bh
= NULL
;
7296 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7299 bh
= qemu_mallocz(sizeof(QEMUBH
));
7303 bh
->opaque
= opaque
;
7307 int qemu_bh_poll(void)
7326 void qemu_bh_schedule(QEMUBH
*bh
)
7328 CPUState
*env
= cpu_single_env
;
7332 bh
->next
= first_bh
;
7335 /* stop the currently executing CPU to execute the BH ASAP */
7337 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7341 void qemu_bh_cancel(QEMUBH
*bh
)
7344 if (bh
->scheduled
) {
7347 pbh
= &(*pbh
)->next
;
7353 void qemu_bh_delete(QEMUBH
*bh
)
7359 /***********************************************************/
7360 /* machine registration */
7362 QEMUMachine
*first_machine
= NULL
;
7364 int qemu_register_machine(QEMUMachine
*m
)
7367 pm
= &first_machine
;
7375 static QEMUMachine
*find_machine(const char *name
)
7379 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7380 if (!strcmp(m
->name
, name
))
7386 /***********************************************************/
7387 /* main execution loop */
7389 static void gui_update(void *opaque
)
7391 DisplayState
*ds
= opaque
;
7392 ds
->dpy_refresh(ds
);
7393 qemu_mod_timer(ds
->gui_timer
,
7394 (ds
->gui_timer_interval
?
7395 ds
->gui_timer_interval
:
7396 GUI_REFRESH_INTERVAL
)
7397 + qemu_get_clock(rt_clock
));
7400 struct vm_change_state_entry
{
7401 VMChangeStateHandler
*cb
;
7403 LIST_ENTRY (vm_change_state_entry
) entries
;
7406 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7408 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7411 VMChangeStateEntry
*e
;
7413 e
= qemu_mallocz(sizeof (*e
));
7419 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7423 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7425 LIST_REMOVE (e
, entries
);
7429 static void vm_state_notify(int running
)
7431 VMChangeStateEntry
*e
;
7433 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7434 e
->cb(e
->opaque
, running
);
7438 /* XXX: support several handlers */
7439 static VMStopHandler
*vm_stop_cb
;
7440 static void *vm_stop_opaque
;
7442 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7445 vm_stop_opaque
= opaque
;
7449 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7460 qemu_rearm_alarm_timer(alarm_timer
);
7464 void vm_stop(int reason
)
7467 cpu_disable_ticks();
7471 vm_stop_cb(vm_stop_opaque
, reason
);
7478 /* reset/shutdown handler */
7480 typedef struct QEMUResetEntry
{
7481 QEMUResetHandler
*func
;
7483 struct QEMUResetEntry
*next
;
7486 static QEMUResetEntry
*first_reset_entry
;
7487 static int reset_requested
;
7488 static int shutdown_requested
;
7489 static int powerdown_requested
;
7491 int qemu_shutdown_requested(void)
7493 int r
= shutdown_requested
;
7494 shutdown_requested
= 0;
7498 int qemu_reset_requested(void)
7500 int r
= reset_requested
;
7501 reset_requested
= 0;
7505 int qemu_powerdown_requested(void)
7507 int r
= powerdown_requested
;
7508 powerdown_requested
= 0;
7512 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7514 QEMUResetEntry
**pre
, *re
;
7516 pre
= &first_reset_entry
;
7517 while (*pre
!= NULL
)
7518 pre
= &(*pre
)->next
;
7519 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7521 re
->opaque
= opaque
;
7526 void qemu_system_reset(void)
7530 /* reset all devices */
7531 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7532 re
->func(re
->opaque
);
7536 void qemu_system_reset_request(void)
7539 shutdown_requested
= 1;
7541 reset_requested
= 1;
7544 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7547 void qemu_system_shutdown_request(void)
7549 shutdown_requested
= 1;
7551 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7554 void qemu_system_powerdown_request(void)
7556 powerdown_requested
= 1;
7558 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7561 void main_loop_wait(int timeout
)
7563 IOHandlerRecord
*ioh
;
7564 fd_set rfds
, wfds
, xfds
;
7573 /* XXX: need to suppress polling by better using win32 events */
7575 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7576 ret
|= pe
->func(pe
->opaque
);
7581 WaitObjects
*w
= &wait_objects
;
7583 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7584 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7585 if (w
->func
[ret
- WAIT_OBJECT_0
])
7586 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7588 /* Check for additional signaled events */
7589 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7591 /* Check if event is signaled */
7592 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7593 if(ret2
== WAIT_OBJECT_0
) {
7595 w
->func
[i
](w
->opaque
[i
]);
7596 } else if (ret2
== WAIT_TIMEOUT
) {
7598 err
= GetLastError();
7599 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7602 } else if (ret
== WAIT_TIMEOUT
) {
7604 err
= GetLastError();
7605 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7609 /* poll any events */
7610 /* XXX: separate device handlers from system ones */
7615 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7619 (!ioh
->fd_read_poll
||
7620 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7621 FD_SET(ioh
->fd
, &rfds
);
7625 if (ioh
->fd_write
) {
7626 FD_SET(ioh
->fd
, &wfds
);
7636 tv
.tv_usec
= timeout
* 1000;
7638 #if defined(CONFIG_SLIRP)
7640 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7643 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7645 IOHandlerRecord
**pioh
;
7647 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7648 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7649 ioh
->fd_read(ioh
->opaque
);
7651 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7652 ioh
->fd_write(ioh
->opaque
);
7656 /* remove deleted IO handlers */
7657 pioh
= &first_io_handler
;
7667 #if defined(CONFIG_SLIRP)
7674 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7679 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7680 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7681 qemu_get_clock(vm_clock
));
7682 /* run dma transfers, if any */
7686 /* real time timers */
7687 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7688 qemu_get_clock(rt_clock
));
7690 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7691 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7692 qemu_rearm_alarm_timer(alarm_timer
);
7695 /* Check bottom-halves last in case any of the earlier events triggered
7701 static int main_loop(void)
7704 #ifdef CONFIG_PROFILER
7709 cur_cpu
= first_cpu
;
7710 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7717 #ifdef CONFIG_PROFILER
7718 ti
= profile_getclock();
7723 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7724 env
->icount_decr
.u16
.low
= 0;
7725 env
->icount_extra
= 0;
7726 count
= qemu_next_deadline();
7727 count
= (count
+ (1 << icount_time_shift
) - 1)
7728 >> icount_time_shift
;
7729 qemu_icount
+= count
;
7730 decr
= (count
> 0xffff) ? 0xffff : count
;
7732 env
->icount_decr
.u16
.low
= decr
;
7733 env
->icount_extra
= count
;
7735 ret
= cpu_exec(env
);
7736 #ifdef CONFIG_PROFILER
7737 qemu_time
+= profile_getclock() - ti
;
7740 /* Fold pending instructions back into the
7741 instruction counter, and clear the interrupt flag. */
7742 qemu_icount
-= (env
->icount_decr
.u16
.low
7743 + env
->icount_extra
);
7744 env
->icount_decr
.u32
= 0;
7745 env
->icount_extra
= 0;
7747 next_cpu
= env
->next_cpu
?: first_cpu
;
7748 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7749 ret
= EXCP_INTERRUPT
;
7753 if (ret
== EXCP_HLT
) {
7754 /* Give the next CPU a chance to run. */
7758 if (ret
!= EXCP_HALTED
)
7760 /* all CPUs are halted ? */
7766 if (shutdown_requested
) {
7767 ret
= EXCP_INTERRUPT
;
7775 if (reset_requested
) {
7776 reset_requested
= 0;
7777 qemu_system_reset();
7778 ret
= EXCP_INTERRUPT
;
7780 if (powerdown_requested
) {
7781 powerdown_requested
= 0;
7782 qemu_system_powerdown();
7783 ret
= EXCP_INTERRUPT
;
7785 if (unlikely(ret
== EXCP_DEBUG
)) {
7786 vm_stop(EXCP_DEBUG
);
7788 /* If all cpus are halted then wait until the next IRQ */
7789 /* XXX: use timeout computed from timers */
7790 if (ret
== EXCP_HALTED
) {
7794 /* Advance virtual time to the next event. */
7795 if (use_icount
== 1) {
7796 /* When not using an adaptive execution frequency
7797 we tend to get badly out of sync with real time,
7798 so just delay for a reasonable amount of time. */
7801 delta
= cpu_get_icount() - cpu_get_clock();
7804 /* If virtual time is ahead of real time then just
7806 timeout
= (delta
/ 1000000) + 1;
7808 /* Wait for either IO to occur or the next
7810 add
= qemu_next_deadline();
7811 /* We advance the timer before checking for IO.
7812 Limit the amount we advance so that early IO
7813 activity won't get the guest too far ahead. */
7817 add
= (add
+ (1 << icount_time_shift
) - 1)
7818 >> icount_time_shift
;
7820 timeout
= delta
/ 1000000;
7831 if (shutdown_requested
) {
7832 ret
= EXCP_INTERRUPT
;
7837 #ifdef CONFIG_PROFILER
7838 ti
= profile_getclock();
7840 main_loop_wait(timeout
);
7841 #ifdef CONFIG_PROFILER
7842 dev_time
+= profile_getclock() - ti
;
7845 cpu_disable_ticks();
7849 static void help(int exitcode
)
7851 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7852 "usage: %s [options] [disk_image]\n"
7854 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7856 "Standard options:\n"
7857 "-M machine select emulated machine (-M ? for list)\n"
7858 "-cpu cpu select CPU (-cpu ? for list)\n"
7859 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7860 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7861 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7862 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7863 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7864 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7865 " [,cache=on|off][,format=f]\n"
7866 " use 'file' as a drive image\n"
7867 "-mtdblock file use 'file' as on-board Flash memory image\n"
7868 "-sd file use 'file' as SecureDigital card image\n"
7869 "-pflash file use 'file' as a parallel flash image\n"
7870 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7871 "-snapshot write to temporary files instead of disk image files\n"
7873 "-no-frame open SDL window without a frame and window decorations\n"
7874 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7875 "-no-quit disable SDL window close capability\n"
7878 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7880 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7881 "-smp n set the number of CPUs to 'n' [default=1]\n"
7882 "-nographic disable graphical output and redirect serial I/Os to console\n"
7883 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7885 "-k language use keyboard layout (for example \"fr\" for French)\n"
7888 "-audio-help print list of audio drivers and their options\n"
7889 "-soundhw c1,... enable audio support\n"
7890 " and only specified sound cards (comma separated list)\n"
7891 " use -soundhw ? to get the list of supported cards\n"
7892 " use -soundhw all to enable all of them\n"
7894 "-vga [std|cirrus|vmware]\n"
7895 " select video card type\n"
7896 "-localtime set the real time clock to local time [default=utc]\n"
7897 "-full-screen start in full screen\n"
7899 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7901 "-usb enable the USB driver (will be the default soon)\n"
7902 "-usbdevice name add the host or guest USB device 'name'\n"
7903 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7904 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7906 "-name string set the name of the guest\n"
7907 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
7909 "Network options:\n"
7910 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7911 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7913 "-net user[,vlan=n][,hostname=host]\n"
7914 " connect the user mode network stack to VLAN 'n' and send\n"
7915 " hostname 'host' to DHCP clients\n"
7918 "-net tap[,vlan=n],ifname=name\n"
7919 " connect the host TAP network interface to VLAN 'n'\n"
7921 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7922 " connect the host TAP network interface to VLAN 'n' and use the\n"
7923 " network scripts 'file' (default=%s)\n"
7924 " and 'dfile' (default=%s);\n"
7925 " use '[down]script=no' to disable script execution;\n"
7926 " use 'fd=h' to connect to an already opened TAP interface\n"
7928 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7929 " connect the vlan 'n' to another VLAN using a socket connection\n"
7930 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7931 " connect the vlan 'n' to multicast maddr and port\n"
7933 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7934 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7935 " on host and listening for incoming connections on 'socketpath'.\n"
7936 " Use group 'groupname' and mode 'octalmode' to change default\n"
7937 " ownership and permissions for communication port.\n"
7939 "-net none use it alone to have zero network devices; if no -net option\n"
7940 " is provided, the default is '-net nic -net user'\n"
7943 "-tftp dir allow tftp access to files in dir [-net user]\n"
7944 "-bootp file advertise file in BOOTP replies\n"
7946 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7948 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7949 " redirect TCP or UDP connections from host to guest [-net user]\n"
7952 "Linux boot specific:\n"
7953 "-kernel bzImage use 'bzImage' as kernel image\n"
7954 "-append cmdline use 'cmdline' as kernel command line\n"
7955 "-initrd file use 'file' as initial ram disk\n"
7957 "Debug/Expert options:\n"
7958 "-monitor dev redirect the monitor to char device 'dev'\n"
7959 "-serial dev redirect the serial port to char device 'dev'\n"
7960 "-parallel dev redirect the parallel port to char device 'dev'\n"
7961 "-pidfile file Write PID to 'file'\n"
7962 "-S freeze CPU at startup (use 'c' to start execution)\n"
7963 "-s wait gdb connection to port\n"
7964 "-p port set gdb connection port [default=%s]\n"
7965 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7966 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7967 " translation (t=none or lba) (usually qemu can guess them)\n"
7968 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7970 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7971 "-no-kqemu disable KQEMU kernel module usage\n"
7974 "-no-acpi disable ACPI\n"
7976 #ifdef CONFIG_CURSES
7977 "-curses use a curses/ncurses interface instead of SDL\n"
7979 "-no-reboot exit instead of rebooting\n"
7980 "-no-shutdown stop before shutdown\n"
7981 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7982 "-vnc display start a VNC server on display\n"
7984 "-daemonize daemonize QEMU after initializing\n"
7986 "-option-rom rom load a file, rom, into the option ROM space\n"
7988 "-prom-env variable=value set OpenBIOS nvram variables\n"
7990 "-clock force the use of the given methods for timer alarm.\n"
7991 " To see what timers are available use -clock ?\n"
7992 "-startdate select initial date of the clock\n"
7993 "-icount [N|auto]\n"
7994 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7996 "During emulation, the following keys are useful:\n"
7997 "ctrl-alt-f toggle full screen\n"
7998 "ctrl-alt-n switch to virtual console 'n'\n"
7999 "ctrl-alt toggle mouse and keyboard grab\n"
8001 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8006 DEFAULT_NETWORK_SCRIPT
,
8007 DEFAULT_NETWORK_DOWN_SCRIPT
,
8009 DEFAULT_GDBSTUB_PORT
,
8014 #define HAS_ARG 0x0001
8029 QEMU_OPTION_mtdblock
,
8033 QEMU_OPTION_snapshot
,
8035 QEMU_OPTION_no_fd_bootchk
,
8038 QEMU_OPTION_nographic
,
8039 QEMU_OPTION_portrait
,
8041 QEMU_OPTION_audio_help
,
8042 QEMU_OPTION_soundhw
,
8063 QEMU_OPTION_localtime
,
8067 QEMU_OPTION_monitor
,
8069 QEMU_OPTION_parallel
,
8071 QEMU_OPTION_full_screen
,
8072 QEMU_OPTION_no_frame
,
8073 QEMU_OPTION_alt_grab
,
8074 QEMU_OPTION_no_quit
,
8075 QEMU_OPTION_pidfile
,
8076 QEMU_OPTION_no_kqemu
,
8077 QEMU_OPTION_kernel_kqemu
,
8078 QEMU_OPTION_win2k_hack
,
8080 QEMU_OPTION_usbdevice
,
8083 QEMU_OPTION_no_acpi
,
8085 QEMU_OPTION_no_reboot
,
8086 QEMU_OPTION_no_shutdown
,
8087 QEMU_OPTION_show_cursor
,
8088 QEMU_OPTION_daemonize
,
8089 QEMU_OPTION_option_rom
,
8090 QEMU_OPTION_semihosting
,
8092 QEMU_OPTION_prom_env
,
8093 QEMU_OPTION_old_param
,
8095 QEMU_OPTION_startdate
,
8096 QEMU_OPTION_tb_size
,
8101 typedef struct QEMUOption
{
8107 static const QEMUOption qemu_options
[] = {
8108 { "h", 0, QEMU_OPTION_h
},
8109 { "help", 0, QEMU_OPTION_h
},
8111 { "M", HAS_ARG
, QEMU_OPTION_M
},
8112 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8113 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8114 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8115 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8116 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8117 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8118 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8119 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8120 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8121 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8122 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8123 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8124 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8125 { "snapshot", 0, QEMU_OPTION_snapshot
},
8127 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8129 { "m", HAS_ARG
, QEMU_OPTION_m
},
8130 { "nographic", 0, QEMU_OPTION_nographic
},
8131 { "portrait", 0, QEMU_OPTION_portrait
},
8132 { "k", HAS_ARG
, QEMU_OPTION_k
},
8134 { "audio-help", 0, QEMU_OPTION_audio_help
},
8135 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8138 { "net", HAS_ARG
, QEMU_OPTION_net
},
8140 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8141 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8143 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8145 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8148 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8149 { "append", HAS_ARG
, QEMU_OPTION_append
},
8150 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8152 { "S", 0, QEMU_OPTION_S
},
8153 { "s", 0, QEMU_OPTION_s
},
8154 { "p", HAS_ARG
, QEMU_OPTION_p
},
8155 { "d", HAS_ARG
, QEMU_OPTION_d
},
8156 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8157 { "L", HAS_ARG
, QEMU_OPTION_L
},
8158 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8160 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8161 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8163 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8164 { "g", 1, QEMU_OPTION_g
},
8166 { "localtime", 0, QEMU_OPTION_localtime
},
8167 { "vga", HAS_ARG
, QEMU_OPTION_vga
},
8168 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8169 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8170 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8171 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8172 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8173 { "full-screen", 0, QEMU_OPTION_full_screen
},
8175 { "no-frame", 0, QEMU_OPTION_no_frame
},
8176 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8177 { "no-quit", 0, QEMU_OPTION_no_quit
},
8179 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8180 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8181 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8182 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8183 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8184 #ifdef CONFIG_CURSES
8185 { "curses", 0, QEMU_OPTION_curses
},
8187 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
8189 /* temporary options */
8190 { "usb", 0, QEMU_OPTION_usb
},
8191 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8192 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8193 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8194 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8195 { "daemonize", 0, QEMU_OPTION_daemonize
},
8196 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8197 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8198 { "semihosting", 0, QEMU_OPTION_semihosting
},
8200 { "name", HAS_ARG
, QEMU_OPTION_name
},
8201 #if defined(TARGET_SPARC)
8202 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8204 #if defined(TARGET_ARM)
8205 { "old-param", 0, QEMU_OPTION_old_param
},
8207 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8208 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8209 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8210 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8214 /* password input */
8216 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8221 if (!bdrv_is_encrypted(bs
))
8224 term_printf("%s is encrypted.\n", name
);
8225 for(i
= 0; i
< 3; i
++) {
8226 monitor_readline("Password: ", 1, password
, sizeof(password
));
8227 if (bdrv_set_key(bs
, password
) == 0)
8229 term_printf("invalid password\n");
8234 static BlockDriverState
*get_bdrv(int index
)
8236 if (index
> nb_drives
)
8238 return drives_table
[index
].bdrv
;
8241 static void read_passwords(void)
8243 BlockDriverState
*bs
;
8246 for(i
= 0; i
< 6; i
++) {
8249 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8254 struct soundhw soundhw
[] = {
8255 #ifdef HAS_AUDIO_CHOICE
8256 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8262 { .init_isa
= pcspk_audio_init
}
8267 "Creative Sound Blaster 16",
8270 { .init_isa
= SB16_init
}
8273 #ifdef CONFIG_CS4231A
8279 { .init_isa
= cs4231a_init
}
8287 "Yamaha YMF262 (OPL3)",
8289 "Yamaha YM3812 (OPL2)",
8293 { .init_isa
= Adlib_init
}
8300 "Gravis Ultrasound GF1",
8303 { .init_isa
= GUS_init
}
8310 "Intel 82801AA AC97 Audio",
8313 { .init_pci
= ac97_init
}
8319 "ENSONIQ AudioPCI ES1370",
8322 { .init_pci
= es1370_init
}
8326 { NULL
, NULL
, 0, 0, { NULL
} }
8329 static void select_soundhw (const char *optarg
)
8333 if (*optarg
== '?') {
8336 printf ("Valid sound card names (comma separated):\n");
8337 for (c
= soundhw
; c
->name
; ++c
) {
8338 printf ("%-11s %s\n", c
->name
, c
->descr
);
8340 printf ("\n-soundhw all will enable all of the above\n");
8341 exit (*optarg
!= '?');
8349 if (!strcmp (optarg
, "all")) {
8350 for (c
= soundhw
; c
->name
; ++c
) {
8358 e
= strchr (p
, ',');
8359 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8361 for (c
= soundhw
; c
->name
; ++c
) {
8362 if (!strncmp (c
->name
, p
, l
)) {
8371 "Unknown sound card name (too big to show)\n");
8374 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8379 p
+= l
+ (e
!= NULL
);
8383 goto show_valid_cards
;
8388 static void select_vgahw (const char *p
)
8392 if (strstart(p
, "std", &opts
)) {
8393 cirrus_vga_enabled
= 0;
8395 } else if (strstart(p
, "cirrus", &opts
)) {
8396 cirrus_vga_enabled
= 1;
8398 } else if (strstart(p
, "vmware", &opts
)) {
8399 cirrus_vga_enabled
= 0;
8403 fprintf(stderr
, "Unknown vga type: %s\n", p
);
8407 const char *nextopt
;
8409 if (strstart(opts
, ",retrace=", &nextopt
)) {
8411 if (strstart(opts
, "dumb", &nextopt
))
8412 vga_retrace_method
= VGA_RETRACE_DUMB
;
8413 else if (strstart(opts
, "precise", &nextopt
))
8414 vga_retrace_method
= VGA_RETRACE_PRECISE
;
8415 else goto invalid_vga
;
8416 } else goto invalid_vga
;
8422 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8424 exit(STATUS_CONTROL_C_EXIT
);
8429 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8433 if(strlen(str
) != 36)
8436 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8437 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8438 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8446 #define MAX_NET_CLIENTS 32
8450 static void termsig_handler(int signal
)
8452 qemu_system_shutdown_request();
8455 static void termsig_setup(void)
8457 struct sigaction act
;
8459 memset(&act
, 0, sizeof(act
));
8460 act
.sa_handler
= termsig_handler
;
8461 sigaction(SIGINT
, &act
, NULL
);
8462 sigaction(SIGHUP
, &act
, NULL
);
8463 sigaction(SIGTERM
, &act
, NULL
);
8468 int main(int argc
, char **argv
)
8470 #ifdef CONFIG_GDBSTUB
8472 const char *gdbstub_port
;
8474 uint32_t boot_devices_bitmap
= 0;
8476 int snapshot
, linux_boot
, net_boot
;
8477 const char *initrd_filename
;
8478 const char *kernel_filename
, *kernel_cmdline
;
8479 const char *boot_devices
= "";
8480 DisplayState
*ds
= &display_state
;
8481 int cyls
, heads
, secs
, translation
;
8482 const char *net_clients
[MAX_NET_CLIENTS
];
8486 const char *r
, *optarg
;
8487 CharDriverState
*monitor_hd
;
8488 const char *monitor_device
;
8489 const char *serial_devices
[MAX_SERIAL_PORTS
];
8490 int serial_device_index
;
8491 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8492 int parallel_device_index
;
8493 const char *loadvm
= NULL
;
8494 QEMUMachine
*machine
;
8495 const char *cpu_model
;
8496 const char *usb_devices
[MAX_USB_CMDLINE
];
8497 int usb_devices_index
;
8500 const char *pid_file
= NULL
;
8503 LIST_INIT (&vm_change_state_head
);
8506 struct sigaction act
;
8507 sigfillset(&act
.sa_mask
);
8509 act
.sa_handler
= SIG_IGN
;
8510 sigaction(SIGPIPE
, &act
, NULL
);
8513 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8514 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8515 QEMU to run on a single CPU */
8520 h
= GetCurrentProcess();
8521 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8522 for(i
= 0; i
< 32; i
++) {
8523 if (mask
& (1 << i
))
8528 SetProcessAffinityMask(h
, mask
);
8534 register_machines();
8535 machine
= first_machine
;
8537 initrd_filename
= NULL
;
8539 vga_ram_size
= VGA_RAM_SIZE
;
8540 #ifdef CONFIG_GDBSTUB
8542 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8547 kernel_filename
= NULL
;
8548 kernel_cmdline
= "";
8549 cyls
= heads
= secs
= 0;
8550 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8551 monitor_device
= "vc";
8553 serial_devices
[0] = "vc:80Cx24C";
8554 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8555 serial_devices
[i
] = NULL
;
8556 serial_device_index
= 0;
8558 parallel_devices
[0] = "vc:640x480";
8559 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8560 parallel_devices
[i
] = NULL
;
8561 parallel_device_index
= 0;
8563 usb_devices_index
= 0;
8580 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8582 const QEMUOption
*popt
;
8585 /* Treat --foo the same as -foo. */
8588 popt
= qemu_options
;
8591 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8595 if (!strcmp(popt
->name
, r
+ 1))
8599 if (popt
->flags
& HAS_ARG
) {
8600 if (optind
>= argc
) {
8601 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8605 optarg
= argv
[optind
++];
8610 switch(popt
->index
) {
8612 machine
= find_machine(optarg
);
8615 printf("Supported machines are:\n");
8616 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8617 printf("%-10s %s%s\n",
8619 m
== first_machine
? " (default)" : "");
8621 exit(*optarg
!= '?');
8624 case QEMU_OPTION_cpu
:
8625 /* hw initialization will check this */
8626 if (*optarg
== '?') {
8627 /* XXX: implement xxx_cpu_list for targets that still miss it */
8628 #if defined(cpu_list)
8629 cpu_list(stdout
, &fprintf
);
8636 case QEMU_OPTION_initrd
:
8637 initrd_filename
= optarg
;
8639 case QEMU_OPTION_hda
:
8641 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8643 hda_index
= drive_add(optarg
, HD_ALIAS
8644 ",cyls=%d,heads=%d,secs=%d%s",
8645 0, cyls
, heads
, secs
,
8646 translation
== BIOS_ATA_TRANSLATION_LBA
?
8648 translation
== BIOS_ATA_TRANSLATION_NONE
?
8649 ",trans=none" : "");
8651 case QEMU_OPTION_hdb
:
8652 case QEMU_OPTION_hdc
:
8653 case QEMU_OPTION_hdd
:
8654 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8656 case QEMU_OPTION_drive
:
8657 drive_add(NULL
, "%s", optarg
);
8659 case QEMU_OPTION_mtdblock
:
8660 drive_add(optarg
, MTD_ALIAS
);
8662 case QEMU_OPTION_sd
:
8663 drive_add(optarg
, SD_ALIAS
);
8665 case QEMU_OPTION_pflash
:
8666 drive_add(optarg
, PFLASH_ALIAS
);
8668 case QEMU_OPTION_snapshot
:
8671 case QEMU_OPTION_hdachs
:
8675 cyls
= strtol(p
, (char **)&p
, 0);
8676 if (cyls
< 1 || cyls
> 16383)
8681 heads
= strtol(p
, (char **)&p
, 0);
8682 if (heads
< 1 || heads
> 16)
8687 secs
= strtol(p
, (char **)&p
, 0);
8688 if (secs
< 1 || secs
> 63)
8692 if (!strcmp(p
, "none"))
8693 translation
= BIOS_ATA_TRANSLATION_NONE
;
8694 else if (!strcmp(p
, "lba"))
8695 translation
= BIOS_ATA_TRANSLATION_LBA
;
8696 else if (!strcmp(p
, "auto"))
8697 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8700 } else if (*p
!= '\0') {
8702 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8705 if (hda_index
!= -1)
8706 snprintf(drives_opt
[hda_index
].opt
,
8707 sizeof(drives_opt
[hda_index
].opt
),
8708 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8709 0, cyls
, heads
, secs
,
8710 translation
== BIOS_ATA_TRANSLATION_LBA
?
8712 translation
== BIOS_ATA_TRANSLATION_NONE
?
8713 ",trans=none" : "");
8716 case QEMU_OPTION_nographic
:
8719 #ifdef CONFIG_CURSES
8720 case QEMU_OPTION_curses
:
8724 case QEMU_OPTION_portrait
:
8727 case QEMU_OPTION_kernel
:
8728 kernel_filename
= optarg
;
8730 case QEMU_OPTION_append
:
8731 kernel_cmdline
= optarg
;
8733 case QEMU_OPTION_cdrom
:
8734 drive_add(optarg
, CDROM_ALIAS
);
8736 case QEMU_OPTION_boot
:
8737 boot_devices
= optarg
;
8738 /* We just do some generic consistency checks */
8740 /* Could easily be extended to 64 devices if needed */
8743 boot_devices_bitmap
= 0;
8744 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8745 /* Allowed boot devices are:
8746 * a b : floppy disk drives
8747 * c ... f : IDE disk drives
8748 * g ... m : machine implementation dependant drives
8749 * n ... p : network devices
8750 * It's up to each machine implementation to check
8751 * if the given boot devices match the actual hardware
8752 * implementation and firmware features.
8754 if (*p
< 'a' || *p
> 'q') {
8755 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8758 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8760 "Boot device '%c' was given twice\n",*p
);
8763 boot_devices_bitmap
|= 1 << (*p
- 'a');
8767 case QEMU_OPTION_fda
:
8768 case QEMU_OPTION_fdb
:
8769 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8772 case QEMU_OPTION_no_fd_bootchk
:
8776 case QEMU_OPTION_net
:
8777 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8778 fprintf(stderr
, "qemu: too many network clients\n");
8781 net_clients
[nb_net_clients
] = optarg
;
8785 case QEMU_OPTION_tftp
:
8786 tftp_prefix
= optarg
;
8788 case QEMU_OPTION_bootp
:
8789 bootp_filename
= optarg
;
8792 case QEMU_OPTION_smb
:
8793 net_slirp_smb(optarg
);
8796 case QEMU_OPTION_redir
:
8797 net_slirp_redir(optarg
);
8801 case QEMU_OPTION_audio_help
:
8805 case QEMU_OPTION_soundhw
:
8806 select_soundhw (optarg
);
8812 case QEMU_OPTION_m
: {
8816 value
= strtoul(optarg
, &ptr
, 10);
8818 case 0: case 'M': case 'm':
8825 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8829 /* On 32-bit hosts, QEMU is limited by virtual address space */
8830 if (value
> (2047 << 20)
8832 && HOST_LONG_BITS
== 32
8835 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8838 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8839 fprintf(stderr
, "qemu: ram size too large\n");
8848 const CPULogItem
*item
;
8850 mask
= cpu_str_to_log_mask(optarg
);
8852 printf("Log items (comma separated):\n");
8853 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8854 printf("%-10s %s\n", item
->name
, item
->help
);
8861 #ifdef CONFIG_GDBSTUB
8866 gdbstub_port
= optarg
;
8872 case QEMU_OPTION_bios
:
8879 keyboard_layout
= optarg
;
8881 case QEMU_OPTION_localtime
:
8884 case QEMU_OPTION_vga
:
8885 select_vgahw (optarg
);
8892 w
= strtol(p
, (char **)&p
, 10);
8895 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8901 h
= strtol(p
, (char **)&p
, 10);
8906 depth
= strtol(p
, (char **)&p
, 10);
8907 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8908 depth
!= 24 && depth
!= 32)
8910 } else if (*p
== '\0') {
8911 depth
= graphic_depth
;
8918 graphic_depth
= depth
;
8921 case QEMU_OPTION_echr
:
8924 term_escape_char
= strtol(optarg
, &r
, 0);
8926 printf("Bad argument to echr\n");
8929 case QEMU_OPTION_monitor
:
8930 monitor_device
= optarg
;
8932 case QEMU_OPTION_serial
:
8933 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8934 fprintf(stderr
, "qemu: too many serial ports\n");
8937 serial_devices
[serial_device_index
] = optarg
;
8938 serial_device_index
++;
8940 case QEMU_OPTION_parallel
:
8941 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8942 fprintf(stderr
, "qemu: too many parallel ports\n");
8945 parallel_devices
[parallel_device_index
] = optarg
;
8946 parallel_device_index
++;
8948 case QEMU_OPTION_loadvm
:
8951 case QEMU_OPTION_full_screen
:
8955 case QEMU_OPTION_no_frame
:
8958 case QEMU_OPTION_alt_grab
:
8961 case QEMU_OPTION_no_quit
:
8965 case QEMU_OPTION_pidfile
:
8969 case QEMU_OPTION_win2k_hack
:
8970 win2k_install_hack
= 1;
8974 case QEMU_OPTION_no_kqemu
:
8977 case QEMU_OPTION_kernel_kqemu
:
8981 case QEMU_OPTION_usb
:
8984 case QEMU_OPTION_usbdevice
:
8986 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8987 fprintf(stderr
, "Too many USB devices\n");
8990 usb_devices
[usb_devices_index
] = optarg
;
8991 usb_devices_index
++;
8993 case QEMU_OPTION_smp
:
8994 smp_cpus
= atoi(optarg
);
8995 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8996 fprintf(stderr
, "Invalid number of CPUs\n");
9000 case QEMU_OPTION_vnc
:
9001 vnc_display
= optarg
;
9003 case QEMU_OPTION_no_acpi
:
9006 case QEMU_OPTION_no_reboot
:
9009 case QEMU_OPTION_no_shutdown
:
9012 case QEMU_OPTION_show_cursor
:
9015 case QEMU_OPTION_uuid
:
9016 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
9017 fprintf(stderr
, "Fail to parse UUID string."
9018 " Wrong format.\n");
9022 case QEMU_OPTION_daemonize
:
9025 case QEMU_OPTION_option_rom
:
9026 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9027 fprintf(stderr
, "Too many option ROMs\n");
9030 option_rom
[nb_option_roms
] = optarg
;
9033 case QEMU_OPTION_semihosting
:
9034 semihosting_enabled
= 1;
9036 case QEMU_OPTION_name
:
9040 case QEMU_OPTION_prom_env
:
9041 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9042 fprintf(stderr
, "Too many prom variables\n");
9045 prom_envs
[nb_prom_envs
] = optarg
;
9050 case QEMU_OPTION_old_param
:
9054 case QEMU_OPTION_clock
:
9055 configure_alarms(optarg
);
9057 case QEMU_OPTION_startdate
:
9060 time_t rtc_start_date
;
9061 if (!strcmp(optarg
, "now")) {
9062 rtc_date_offset
= -1;
9064 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9072 } else if (sscanf(optarg
, "%d-%d-%d",
9075 &tm
.tm_mday
) == 3) {
9084 rtc_start_date
= mktimegm(&tm
);
9085 if (rtc_start_date
== -1) {
9087 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9088 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9091 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9095 case QEMU_OPTION_tb_size
:
9096 tb_size
= strtol(optarg
, NULL
, 0);
9100 case QEMU_OPTION_icount
:
9102 if (strcmp(optarg
, "auto") == 0) {
9103 icount_time_shift
= -1;
9105 icount_time_shift
= strtol(optarg
, NULL
, 0);
9113 if (serial_device_index
== 0)
9114 serial_devices
[0] = "stdio";
9115 if (parallel_device_index
== 0)
9116 parallel_devices
[0] = "null";
9117 if (strncmp(monitor_device
, "vc", 2) == 0)
9118 monitor_device
= "stdio";
9125 if (pipe(fds
) == -1)
9136 len
= read(fds
[0], &status
, 1);
9137 if (len
== -1 && (errno
== EINTR
))
9142 else if (status
== 1) {
9143 fprintf(stderr
, "Could not acquire pidfile\n");
9160 signal(SIGTSTP
, SIG_IGN
);
9161 signal(SIGTTOU
, SIG_IGN
);
9162 signal(SIGTTIN
, SIG_IGN
);
9166 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9169 write(fds
[1], &status
, 1);
9171 fprintf(stderr
, "Could not acquire pid file\n");
9179 linux_boot
= (kernel_filename
!= NULL
);
9180 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9182 if (!linux_boot
&& net_boot
== 0 &&
9183 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9186 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9187 fprintf(stderr
, "-append only allowed with -kernel option\n");
9191 if (!linux_boot
&& initrd_filename
!= NULL
) {
9192 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9196 /* boot to floppy or the default cd if no hard disk defined yet */
9197 if (!boot_devices
[0]) {
9198 boot_devices
= "cad";
9200 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9204 if (use_icount
&& icount_time_shift
< 0) {
9206 /* 125MIPS seems a reasonable initial guess at the guest speed.
9207 It will be corrected fairly quickly anyway. */
9208 icount_time_shift
= 3;
9209 init_icount_adjust();
9216 /* init network clients */
9217 if (nb_net_clients
== 0) {
9218 /* if no clients, we use a default config */
9219 net_clients
[nb_net_clients
++] = "nic";
9221 net_clients
[nb_net_clients
++] = "user";
9225 for(i
= 0;i
< nb_net_clients
; i
++) {
9226 if (net_client_parse(net_clients
[i
]) < 0)
9229 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9230 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9232 if (vlan
->nb_guest_devs
== 0)
9233 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9234 if (vlan
->nb_host_devs
== 0)
9236 "Warning: vlan %d is not connected to host network\n",
9241 /* XXX: this should be moved in the PC machine instantiation code */
9242 if (net_boot
!= 0) {
9244 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9245 const char *model
= nd_table
[i
].model
;
9247 if (net_boot
& (1 << i
)) {
9250 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9251 if (get_image_size(buf
) > 0) {
9252 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9253 fprintf(stderr
, "Too many option ROMs\n");
9256 option_rom
[nb_option_roms
] = strdup(buf
);
9263 fprintf(stderr
, "No valid PXE rom found for network device\n");
9269 /* init the memory */
9270 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9272 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9274 if (ram_size
< phys_ram_size
) {
9275 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9276 machine
->name
, (unsigned long long) phys_ram_size
);
9280 phys_ram_size
= ram_size
;
9282 ram_size
= phys_ram_size
;
9285 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9287 phys_ram_size
+= ram_size
;
9290 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9291 if (!phys_ram_base
) {
9292 fprintf(stderr
, "Could not allocate physical memory\n");
9296 /* init the dynamic translator */
9297 cpu_exec_init_all(tb_size
* 1024 * 1024);
9301 /* we always create the cdrom drive, even if no disk is there */
9303 if (nb_drives_opt
< MAX_DRIVES
)
9304 drive_add(NULL
, CDROM_ALIAS
);
9306 /* we always create at least one floppy */
9308 if (nb_drives_opt
< MAX_DRIVES
)
9309 drive_add(NULL
, FD_ALIAS
, 0);
9311 /* we always create one sd slot, even if no card is in it */
9313 if (nb_drives_opt
< MAX_DRIVES
)
9314 drive_add(NULL
, SD_ALIAS
);
9316 /* open the virtual block devices */
9318 for(i
= 0; i
< nb_drives_opt
; i
++)
9319 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9322 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9323 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9326 memset(&display_state
, 0, sizeof(display_state
));
9329 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9332 /* nearly nothing to do */
9333 dumb_display_init(ds
);
9334 } else if (vnc_display
!= NULL
) {
9335 vnc_display_init(ds
);
9336 if (vnc_display_open(ds
, vnc_display
) < 0)
9339 #if defined(CONFIG_CURSES)
9341 curses_display_init(ds
, full_screen
);
9345 #if defined(CONFIG_SDL)
9346 sdl_display_init(ds
, full_screen
, no_frame
);
9347 #elif defined(CONFIG_COCOA)
9348 cocoa_display_init(ds
, full_screen
);
9350 dumb_display_init(ds
);
9355 /* must be after terminal init, SDL library changes signal handlers */
9359 /* Maintain compatibility with multiple stdio monitors */
9360 if (!strcmp(monitor_device
,"stdio")) {
9361 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9362 const char *devname
= serial_devices
[i
];
9363 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9364 monitor_device
= NULL
;
9366 } else if (devname
&& !strcmp(devname
,"stdio")) {
9367 monitor_device
= NULL
;
9368 serial_devices
[i
] = "mon:stdio";
9373 if (monitor_device
) {
9374 monitor_hd
= qemu_chr_open(monitor_device
);
9376 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9379 monitor_init(monitor_hd
, !nographic
);
9382 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9383 const char *devname
= serial_devices
[i
];
9384 if (devname
&& strcmp(devname
, "none")) {
9385 serial_hds
[i
] = qemu_chr_open(devname
);
9386 if (!serial_hds
[i
]) {
9387 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9391 if (strstart(devname
, "vc", 0))
9392 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9396 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9397 const char *devname
= parallel_devices
[i
];
9398 if (devname
&& strcmp(devname
, "none")) {
9399 parallel_hds
[i
] = qemu_chr_open(devname
);
9400 if (!parallel_hds
[i
]) {
9401 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9405 if (strstart(devname
, "vc", 0))
9406 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9410 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9411 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9413 /* init USB devices */
9415 for(i
= 0; i
< usb_devices_index
; i
++) {
9416 if (usb_device_add(usb_devices
[i
]) < 0) {
9417 fprintf(stderr
, "Warning: could not add USB device %s\n",
9423 if (display_state
.dpy_refresh
) {
9424 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9425 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9428 #ifdef CONFIG_GDBSTUB
9430 /* XXX: use standard host:port notation and modify options
9432 if (gdbserver_start(gdbstub_port
) < 0) {
9433 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9444 /* XXX: simplify init */
9457 len
= write(fds
[1], &status
, 1);
9458 if (len
== -1 && (errno
== EINTR
))
9465 TFR(fd
= open("/dev/null", O_RDWR
));
9479 #if !defined(_WIN32)
9480 /* close network clients */
9481 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9482 VLANClientState
*vc
;
9484 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9485 if (vc
->fd_read
== tap_receive
) {
9487 TAPState
*s
= vc
->opaque
;
9489 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9491 launch_script(s
->down_script
, ifname
, s
->fd
);
9493 #if defined(CONFIG_VDE)
9494 if (vc
->fd_read
== vde_from_qemu
) {
9495 VDEState
*s
= vc
->opaque
;