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 void *ioport_opaque
[MAX_IOPORTS
];
170 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
171 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 BlockDriverState
*bs_snapshots
;
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
;
186 int pit_min_timer_count
= 0;
188 NICInfo nd_table
[MAX_NICS
];
190 static int rtc_utc
= 1;
191 static int rtc_date_offset
= -1; /* -1 means no change */
192 int cirrus_vga_enabled
= 1;
193 int vmsvga_enabled
= 0;
195 int graphic_width
= 1024;
196 int graphic_height
= 768;
197 int graphic_depth
= 8;
199 int graphic_width
= 800;
200 int graphic_height
= 600;
201 int graphic_depth
= 15;
206 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
207 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
209 int win2k_install_hack
= 0;
212 static VLANState
*first_vlan
;
214 const char *vnc_display
;
215 #if defined(TARGET_SPARC)
217 #elif defined(TARGET_I386)
222 int acpi_enabled
= 1;
227 int graphic_rotate
= 0;
229 const char *option_rom
[MAX_OPTION_ROMS
];
231 int semihosting_enabled
= 0;
236 const char *qemu_name
;
239 unsigned int nb_prom_envs
= 0;
240 const char *prom_envs
[MAX_PROM_ENVS
];
246 } drives_opt
[MAX_DRIVES
];
248 static CPUState
*cur_cpu
;
249 static CPUState
*next_cpu
;
250 static int event_pending
= 1;
251 /* Conversion factor from emulated instructions to virtual clock ticks. */
252 static int icount_time_shift
;
253 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
254 #define MAX_ICOUNT_SHIFT 10
255 /* Compensate for varying guest execution speed. */
256 static int64_t qemu_icount_bias
;
257 QEMUTimer
*icount_rt_timer
;
258 QEMUTimer
*icount_vm_timer
;
260 uint8_t qemu_uuid
[16];
262 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
264 /***********************************************************/
265 /* x86 ISA bus support */
267 target_phys_addr_t isa_mem_base
= 0;
270 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
271 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
273 static uint32_t ioport_read(int index
, uint32_t address
)
275 static IOPortReadFunc
*default_func
[3] = {
276 default_ioport_readb
,
277 default_ioport_readw
,
280 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
282 func
= default_func
[index
];
283 return func(ioport_opaque
[address
], address
);
286 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
288 static IOPortWriteFunc
*default_func
[3] = {
289 default_ioport_writeb
,
290 default_ioport_writew
,
291 default_ioport_writel
293 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
295 func
= default_func
[index
];
296 func(ioport_opaque
[address
], address
, data
);
299 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
301 #ifdef DEBUG_UNUSED_IOPORT
302 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
307 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
309 #ifdef DEBUG_UNUSED_IOPORT
310 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
314 /* default is to make two byte accesses */
315 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
318 data
= ioport_read(0, address
);
319 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
320 data
|= ioport_read(0, address
) << 8;
324 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
326 ioport_write(0, address
, data
& 0xff);
327 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
328 ioport_write(0, address
, (data
>> 8) & 0xff);
331 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
333 #ifdef DEBUG_UNUSED_IOPORT
334 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
339 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
341 #ifdef DEBUG_UNUSED_IOPORT
342 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
346 /* size is the word size in byte */
347 int register_ioport_read(int start
, int length
, int size
,
348 IOPortReadFunc
*func
, void *opaque
)
354 } else if (size
== 2) {
356 } else if (size
== 4) {
359 hw_error("register_ioport_read: invalid size");
362 for(i
= start
; i
< start
+ length
; i
+= size
) {
363 ioport_read_table
[bsize
][i
] = func
;
364 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
365 hw_error("register_ioport_read: invalid opaque");
366 ioport_opaque
[i
] = opaque
;
371 /* size is the word size in byte */
372 int register_ioport_write(int start
, int length
, int size
,
373 IOPortWriteFunc
*func
, void *opaque
)
379 } else if (size
== 2) {
381 } else if (size
== 4) {
384 hw_error("register_ioport_write: invalid size");
387 for(i
= start
; i
< start
+ length
; i
+= size
) {
388 ioport_write_table
[bsize
][i
] = func
;
389 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
390 hw_error("register_ioport_write: invalid opaque");
391 ioport_opaque
[i
] = opaque
;
396 void isa_unassign_ioport(int start
, int length
)
400 for(i
= start
; i
< start
+ length
; i
++) {
401 ioport_read_table
[0][i
] = default_ioport_readb
;
402 ioport_read_table
[1][i
] = default_ioport_readw
;
403 ioport_read_table
[2][i
] = default_ioport_readl
;
405 ioport_write_table
[0][i
] = default_ioport_writeb
;
406 ioport_write_table
[1][i
] = default_ioport_writew
;
407 ioport_write_table
[2][i
] = default_ioport_writel
;
411 /***********************************************************/
413 void cpu_outb(CPUState
*env
, int addr
, int val
)
416 if (loglevel
& CPU_LOG_IOPORT
)
417 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
419 ioport_write(0, addr
, val
);
422 env
->last_io_time
= cpu_get_time_fast();
426 void cpu_outw(CPUState
*env
, int addr
, int val
)
429 if (loglevel
& CPU_LOG_IOPORT
)
430 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
432 ioport_write(1, addr
, val
);
435 env
->last_io_time
= cpu_get_time_fast();
439 void cpu_outl(CPUState
*env
, int addr
, int val
)
442 if (loglevel
& CPU_LOG_IOPORT
)
443 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
445 ioport_write(2, addr
, val
);
448 env
->last_io_time
= cpu_get_time_fast();
452 int cpu_inb(CPUState
*env
, int addr
)
455 val
= ioport_read(0, addr
);
457 if (loglevel
& CPU_LOG_IOPORT
)
458 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
462 env
->last_io_time
= cpu_get_time_fast();
467 int cpu_inw(CPUState
*env
, int addr
)
470 val
= ioport_read(1, addr
);
472 if (loglevel
& CPU_LOG_IOPORT
)
473 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
477 env
->last_io_time
= cpu_get_time_fast();
482 int cpu_inl(CPUState
*env
, int addr
)
485 val
= ioport_read(2, addr
);
487 if (loglevel
& CPU_LOG_IOPORT
)
488 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
492 env
->last_io_time
= cpu_get_time_fast();
497 /***********************************************************/
498 void hw_error(const char *fmt
, ...)
504 fprintf(stderr
, "qemu: hardware error: ");
505 vfprintf(stderr
, fmt
, ap
);
506 fprintf(stderr
, "\n");
507 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
508 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
510 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
512 cpu_dump_state(env
, stderr
, fprintf
, 0);
519 /***********************************************************/
522 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
523 static void *qemu_put_kbd_event_opaque
;
524 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
525 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
527 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
529 qemu_put_kbd_event_opaque
= opaque
;
530 qemu_put_kbd_event
= func
;
533 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
534 void *opaque
, int absolute
,
537 QEMUPutMouseEntry
*s
, *cursor
;
539 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
543 s
->qemu_put_mouse_event
= func
;
544 s
->qemu_put_mouse_event_opaque
= opaque
;
545 s
->qemu_put_mouse_event_absolute
= absolute
;
546 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
549 if (!qemu_put_mouse_event_head
) {
550 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
554 cursor
= qemu_put_mouse_event_head
;
555 while (cursor
->next
!= NULL
)
556 cursor
= cursor
->next
;
559 qemu_put_mouse_event_current
= s
;
564 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
566 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
568 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
571 cursor
= qemu_put_mouse_event_head
;
572 while (cursor
!= NULL
&& cursor
!= entry
) {
574 cursor
= cursor
->next
;
577 if (cursor
== NULL
) // does not exist or list empty
579 else if (prev
== NULL
) { // entry is head
580 qemu_put_mouse_event_head
= cursor
->next
;
581 if (qemu_put_mouse_event_current
== entry
)
582 qemu_put_mouse_event_current
= cursor
->next
;
583 qemu_free(entry
->qemu_put_mouse_event_name
);
588 prev
->next
= entry
->next
;
590 if (qemu_put_mouse_event_current
== entry
)
591 qemu_put_mouse_event_current
= prev
;
593 qemu_free(entry
->qemu_put_mouse_event_name
);
597 void kbd_put_keycode(int keycode
)
599 if (qemu_put_kbd_event
) {
600 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
604 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
606 QEMUPutMouseEvent
*mouse_event
;
607 void *mouse_event_opaque
;
610 if (!qemu_put_mouse_event_current
) {
615 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
617 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
620 if (graphic_rotate
) {
621 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
624 width
= graphic_width
- 1;
625 mouse_event(mouse_event_opaque
,
626 width
- dy
, dx
, dz
, buttons_state
);
628 mouse_event(mouse_event_opaque
,
629 dx
, dy
, dz
, buttons_state
);
633 int kbd_mouse_is_absolute(void)
635 if (!qemu_put_mouse_event_current
)
638 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
641 void do_info_mice(void)
643 QEMUPutMouseEntry
*cursor
;
646 if (!qemu_put_mouse_event_head
) {
647 term_printf("No mouse devices connected\n");
651 term_printf("Mouse devices available:\n");
652 cursor
= qemu_put_mouse_event_head
;
653 while (cursor
!= NULL
) {
654 term_printf("%c Mouse #%d: %s\n",
655 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
656 index
, cursor
->qemu_put_mouse_event_name
);
658 cursor
= cursor
->next
;
662 void do_mouse_set(int index
)
664 QEMUPutMouseEntry
*cursor
;
667 if (!qemu_put_mouse_event_head
) {
668 term_printf("No mouse devices connected\n");
672 cursor
= qemu_put_mouse_event_head
;
673 while (cursor
!= NULL
&& index
!= i
) {
675 cursor
= cursor
->next
;
679 qemu_put_mouse_event_current
= cursor
;
681 term_printf("Mouse at given index not found\n");
684 /* compute with 96 bit intermediate result: (a*b)/c */
685 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
690 #ifdef WORDS_BIGENDIAN
700 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
701 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
704 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
708 /***********************************************************/
709 /* real time host monotonic timer */
711 #define QEMU_TIMER_BASE 1000000000LL
715 static int64_t clock_freq
;
717 static void init_get_clock(void)
721 ret
= QueryPerformanceFrequency(&freq
);
723 fprintf(stderr
, "Could not calibrate ticks\n");
726 clock_freq
= freq
.QuadPart
;
729 static int64_t get_clock(void)
732 QueryPerformanceCounter(&ti
);
733 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
738 static int use_rt_clock
;
740 static void init_get_clock(void)
743 #if defined(__linux__)
746 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
753 static int64_t get_clock(void)
755 #if defined(__linux__)
758 clock_gettime(CLOCK_MONOTONIC
, &ts
);
759 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
763 /* XXX: using gettimeofday leads to problems if the date
764 changes, so it should be avoided. */
766 gettimeofday(&tv
, NULL
);
767 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
772 /* Return the virtual CPU time, based on the instruction counter. */
773 static int64_t cpu_get_icount(void)
776 CPUState
*env
= cpu_single_env
;;
777 icount
= qemu_icount
;
780 fprintf(stderr
, "Bad clock read\n");
781 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
783 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
786 /***********************************************************/
787 /* guest cycle counter */
789 static int64_t cpu_ticks_prev
;
790 static int64_t cpu_ticks_offset
;
791 static int64_t cpu_clock_offset
;
792 static int cpu_ticks_enabled
;
794 /* return the host CPU cycle counter and handle stop/restart */
795 int64_t cpu_get_ticks(void)
798 return cpu_get_icount();
800 if (!cpu_ticks_enabled
) {
801 return cpu_ticks_offset
;
804 ticks
= cpu_get_real_ticks();
805 if (cpu_ticks_prev
> ticks
) {
806 /* Note: non increasing ticks may happen if the host uses
808 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
810 cpu_ticks_prev
= ticks
;
811 return ticks
+ cpu_ticks_offset
;
815 /* return the host CPU monotonic timer and handle stop/restart */
816 static int64_t cpu_get_clock(void)
819 if (!cpu_ticks_enabled
) {
820 return cpu_clock_offset
;
823 return ti
+ cpu_clock_offset
;
827 /* enable cpu_get_ticks() */
828 void cpu_enable_ticks(void)
830 if (!cpu_ticks_enabled
) {
831 cpu_ticks_offset
-= cpu_get_real_ticks();
832 cpu_clock_offset
-= get_clock();
833 cpu_ticks_enabled
= 1;
837 /* disable cpu_get_ticks() : the clock is stopped. You must not call
838 cpu_get_ticks() after that. */
839 void cpu_disable_ticks(void)
841 if (cpu_ticks_enabled
) {
842 cpu_ticks_offset
= cpu_get_ticks();
843 cpu_clock_offset
= cpu_get_clock();
844 cpu_ticks_enabled
= 0;
848 /***********************************************************/
851 #define QEMU_TIMER_REALTIME 0
852 #define QEMU_TIMER_VIRTUAL 1
856 /* XXX: add frequency */
864 struct QEMUTimer
*next
;
867 struct qemu_alarm_timer
{
871 int (*start
)(struct qemu_alarm_timer
*t
);
872 void (*stop
)(struct qemu_alarm_timer
*t
);
873 void (*rearm
)(struct qemu_alarm_timer
*t
);
877 #define ALARM_FLAG_DYNTICKS 0x1
878 #define ALARM_FLAG_EXPIRED 0x2
880 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
882 return t
->flags
& ALARM_FLAG_DYNTICKS
;
885 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
887 if (!alarm_has_dynticks(t
))
893 /* TODO: MIN_TIMER_REARM_US should be optimized */
894 #define MIN_TIMER_REARM_US 250
896 static struct qemu_alarm_timer
*alarm_timer
;
900 struct qemu_alarm_win32
{
904 } alarm_win32_data
= {0, NULL
, -1};
906 static int win32_start_timer(struct qemu_alarm_timer
*t
);
907 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
908 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
912 static int unix_start_timer(struct qemu_alarm_timer
*t
);
913 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
917 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
918 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
919 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
921 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
922 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
924 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
925 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
927 #endif /* __linux__ */
931 /* Correlation between real and virtual time is always going to be
932 fairly approximate, so ignore small variation.
933 When the guest is idle real and virtual time will be aligned in
935 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
937 static void icount_adjust(void)
942 static int64_t last_delta
;
943 /* If the VM is not running, then do nothing. */
947 cur_time
= cpu_get_clock();
948 cur_icount
= qemu_get_clock(vm_clock
);
949 delta
= cur_icount
- cur_time
;
950 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
952 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
953 && icount_time_shift
> 0) {
954 /* The guest is getting too far ahead. Slow time down. */
958 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
959 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
960 /* The guest is getting too far behind. Speed time up. */
964 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
967 static void icount_adjust_rt(void * opaque
)
969 qemu_mod_timer(icount_rt_timer
,
970 qemu_get_clock(rt_clock
) + 1000);
974 static void icount_adjust_vm(void * opaque
)
976 qemu_mod_timer(icount_vm_timer
,
977 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
981 static void init_icount_adjust(void)
983 /* Have both realtime and virtual time triggers for speed adjustment.
984 The realtime trigger catches emulated time passing too slowly,
985 the virtual time trigger catches emulated time passing too fast.
986 Realtime triggers occur even when idle, so use them less frequently
988 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
989 qemu_mod_timer(icount_rt_timer
,
990 qemu_get_clock(rt_clock
) + 1000);
991 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
992 qemu_mod_timer(icount_vm_timer
,
993 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
996 static struct qemu_alarm_timer alarm_timers
[] = {
999 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1000 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1001 /* HPET - if available - is preferred */
1002 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1003 /* ...otherwise try RTC */
1004 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1006 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1008 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1009 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1010 {"win32", 0, win32_start_timer
,
1011 win32_stop_timer
, NULL
, &alarm_win32_data
},
1016 static void show_available_alarms(void)
1020 printf("Available alarm timers, in order of precedence:\n");
1021 for (i
= 0; alarm_timers
[i
].name
; i
++)
1022 printf("%s\n", alarm_timers
[i
].name
);
1025 static void configure_alarms(char const *opt
)
1029 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1032 struct qemu_alarm_timer tmp
;
1034 if (!strcmp(opt
, "?")) {
1035 show_available_alarms();
1041 /* Reorder the array */
1042 name
= strtok(arg
, ",");
1044 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1045 if (!strcmp(alarm_timers
[i
].name
, name
))
1050 fprintf(stderr
, "Unknown clock %s\n", name
);
1059 tmp
= alarm_timers
[i
];
1060 alarm_timers
[i
] = alarm_timers
[cur
];
1061 alarm_timers
[cur
] = tmp
;
1065 name
= strtok(NULL
, ",");
1071 /* Disable remaining timers */
1072 for (i
= cur
; i
< count
; i
++)
1073 alarm_timers
[i
].name
= NULL
;
1075 show_available_alarms();
1080 QEMUClock
*rt_clock
;
1081 QEMUClock
*vm_clock
;
1083 static QEMUTimer
*active_timers
[2];
1085 static QEMUClock
*qemu_new_clock(int type
)
1088 clock
= qemu_mallocz(sizeof(QEMUClock
));
1095 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1099 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1102 ts
->opaque
= opaque
;
1106 void qemu_free_timer(QEMUTimer
*ts
)
1111 /* stop a timer, but do not dealloc it */
1112 void qemu_del_timer(QEMUTimer
*ts
)
1116 /* NOTE: this code must be signal safe because
1117 qemu_timer_expired() can be called from a signal. */
1118 pt
= &active_timers
[ts
->clock
->type
];
1131 /* modify the current timer so that it will be fired when current_time
1132 >= expire_time. The corresponding callback will be called. */
1133 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1139 /* add the timer in the sorted list */
1140 /* NOTE: this code must be signal safe because
1141 qemu_timer_expired() can be called from a signal. */
1142 pt
= &active_timers
[ts
->clock
->type
];
1147 if (t
->expire_time
> expire_time
)
1151 ts
->expire_time
= expire_time
;
1155 /* Rearm if necessary */
1156 if (pt
== &active_timers
[ts
->clock
->type
]) {
1157 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1158 qemu_rearm_alarm_timer(alarm_timer
);
1160 /* Interrupt execution to force deadline recalculation. */
1161 if (use_icount
&& cpu_single_env
) {
1162 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1167 int qemu_timer_pending(QEMUTimer
*ts
)
1170 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1177 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1181 return (timer_head
->expire_time
<= current_time
);
1184 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1190 if (!ts
|| ts
->expire_time
> current_time
)
1192 /* remove timer from the list before calling the callback */
1193 *ptimer_head
= ts
->next
;
1196 /* run the callback (the timer list can be modified) */
1201 int64_t qemu_get_clock(QEMUClock
*clock
)
1203 switch(clock
->type
) {
1204 case QEMU_TIMER_REALTIME
:
1205 return get_clock() / 1000000;
1207 case QEMU_TIMER_VIRTUAL
:
1209 return cpu_get_icount();
1211 return cpu_get_clock();
1216 static void init_timers(void)
1219 ticks_per_sec
= QEMU_TIMER_BASE
;
1220 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1221 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1225 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1227 uint64_t expire_time
;
1229 if (qemu_timer_pending(ts
)) {
1230 expire_time
= ts
->expire_time
;
1234 qemu_put_be64(f
, expire_time
);
1237 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1239 uint64_t expire_time
;
1241 expire_time
= qemu_get_be64(f
);
1242 if (expire_time
!= -1) {
1243 qemu_mod_timer(ts
, expire_time
);
1249 static void timer_save(QEMUFile
*f
, void *opaque
)
1251 if (cpu_ticks_enabled
) {
1252 hw_error("cannot save state if virtual timers are running");
1254 qemu_put_be64(f
, cpu_ticks_offset
);
1255 qemu_put_be64(f
, ticks_per_sec
);
1256 qemu_put_be64(f
, cpu_clock_offset
);
1259 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1261 if (version_id
!= 1 && version_id
!= 2)
1263 if (cpu_ticks_enabled
) {
1266 cpu_ticks_offset
=qemu_get_be64(f
);
1267 ticks_per_sec
=qemu_get_be64(f
);
1268 if (version_id
== 2) {
1269 cpu_clock_offset
=qemu_get_be64(f
);
1275 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1276 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1278 static void host_alarm_handler(int host_signum
)
1282 #define DISP_FREQ 1000
1284 static int64_t delta_min
= INT64_MAX
;
1285 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1287 ti
= qemu_get_clock(vm_clock
);
1288 if (last_clock
!= 0) {
1289 delta
= ti
- last_clock
;
1290 if (delta
< delta_min
)
1292 if (delta
> delta_max
)
1295 if (++count
== DISP_FREQ
) {
1296 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1297 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1298 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1299 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1300 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1302 delta_min
= INT64_MAX
;
1310 if (alarm_has_dynticks(alarm_timer
) ||
1312 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1313 qemu_get_clock(vm_clock
))) ||
1314 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1315 qemu_get_clock(rt_clock
))) {
1317 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1318 SetEvent(data
->host_alarm
);
1320 CPUState
*env
= next_cpu
;
1322 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1325 /* stop the currently executing cpu because a timer occured */
1326 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1328 if (env
->kqemu_enabled
) {
1329 kqemu_cpu_interrupt(env
);
1337 static int64_t qemu_next_deadline(void)
1341 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1342 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1343 qemu_get_clock(vm_clock
);
1345 /* To avoid problems with overflow limit this to 2^32. */
1355 #if defined(__linux__) || defined(_WIN32)
1356 static uint64_t qemu_next_deadline_dyntick(void)
1364 delta
= (qemu_next_deadline() + 999) / 1000;
1366 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1367 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1368 qemu_get_clock(rt_clock
))*1000;
1369 if (rtdelta
< delta
)
1373 if (delta
< MIN_TIMER_REARM_US
)
1374 delta
= MIN_TIMER_REARM_US
;
1382 #if defined(__linux__)
1384 #define RTC_FREQ 1024
1386 static void enable_sigio_timer(int fd
)
1388 struct sigaction act
;
1391 sigfillset(&act
.sa_mask
);
1393 act
.sa_handler
= host_alarm_handler
;
1395 sigaction(SIGIO
, &act
, NULL
);
1396 fcntl(fd
, F_SETFL
, O_ASYNC
);
1397 fcntl(fd
, F_SETOWN
, getpid());
1400 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1402 struct hpet_info info
;
1405 fd
= open("/dev/hpet", O_RDONLY
);
1410 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1412 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1413 "error, but for better emulation accuracy type:\n"
1414 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1418 /* Check capabilities */
1419 r
= ioctl(fd
, HPET_INFO
, &info
);
1423 /* Enable periodic mode */
1424 r
= ioctl(fd
, HPET_EPI
, 0);
1425 if (info
.hi_flags
&& (r
< 0))
1428 /* Enable interrupt */
1429 r
= ioctl(fd
, HPET_IE_ON
, 0);
1433 enable_sigio_timer(fd
);
1434 t
->priv
= (void *)(long)fd
;
1442 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1444 int fd
= (long)t
->priv
;
1449 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1452 unsigned long current_rtc_freq
= 0;
1454 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1457 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1458 if (current_rtc_freq
!= RTC_FREQ
&&
1459 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1460 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1461 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1462 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1465 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1471 enable_sigio_timer(rtc_fd
);
1473 t
->priv
= (void *)(long)rtc_fd
;
1478 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1480 int rtc_fd
= (long)t
->priv
;
1485 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1489 struct sigaction act
;
1491 sigfillset(&act
.sa_mask
);
1493 act
.sa_handler
= host_alarm_handler
;
1495 sigaction(SIGALRM
, &act
, NULL
);
1497 ev
.sigev_value
.sival_int
= 0;
1498 ev
.sigev_notify
= SIGEV_SIGNAL
;
1499 ev
.sigev_signo
= SIGALRM
;
1501 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1502 perror("timer_create");
1504 /* disable dynticks */
1505 fprintf(stderr
, "Dynamic Ticks disabled\n");
1510 t
->priv
= (void *)host_timer
;
1515 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1517 timer_t host_timer
= (timer_t
)t
->priv
;
1519 timer_delete(host_timer
);
1522 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1524 timer_t host_timer
= (timer_t
)t
->priv
;
1525 struct itimerspec timeout
;
1526 int64_t nearest_delta_us
= INT64_MAX
;
1529 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1530 !active_timers
[QEMU_TIMER_VIRTUAL
])
1533 nearest_delta_us
= qemu_next_deadline_dyntick();
1535 /* check whether a timer is already running */
1536 if (timer_gettime(host_timer
, &timeout
)) {
1538 fprintf(stderr
, "Internal timer error: aborting\n");
1541 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1542 if (current_us
&& current_us
<= nearest_delta_us
)
1545 timeout
.it_interval
.tv_sec
= 0;
1546 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1547 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1548 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1549 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1551 fprintf(stderr
, "Internal timer error: aborting\n");
1556 #endif /* defined(__linux__) */
1558 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1560 struct sigaction act
;
1561 struct itimerval itv
;
1565 sigfillset(&act
.sa_mask
);
1567 act
.sa_handler
= host_alarm_handler
;
1569 sigaction(SIGALRM
, &act
, NULL
);
1571 itv
.it_interval
.tv_sec
= 0;
1572 /* for i386 kernel 2.6 to get 1 ms */
1573 itv
.it_interval
.tv_usec
= 999;
1574 itv
.it_value
.tv_sec
= 0;
1575 itv
.it_value
.tv_usec
= 10 * 1000;
1577 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1584 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1586 struct itimerval itv
;
1588 memset(&itv
, 0, sizeof(itv
));
1589 setitimer(ITIMER_REAL
, &itv
, NULL
);
1592 #endif /* !defined(_WIN32) */
1596 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1599 struct qemu_alarm_win32
*data
= t
->priv
;
1602 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1603 if (!data
->host_alarm
) {
1604 perror("Failed CreateEvent");
1608 memset(&tc
, 0, sizeof(tc
));
1609 timeGetDevCaps(&tc
, sizeof(tc
));
1611 if (data
->period
< tc
.wPeriodMin
)
1612 data
->period
= tc
.wPeriodMin
;
1614 timeBeginPeriod(data
->period
);
1616 flags
= TIME_CALLBACK_FUNCTION
;
1617 if (alarm_has_dynticks(t
))
1618 flags
|= TIME_ONESHOT
;
1620 flags
|= TIME_PERIODIC
;
1622 data
->timerId
= timeSetEvent(1, // interval (ms)
1623 data
->period
, // resolution
1624 host_alarm_handler
, // function
1625 (DWORD
)t
, // parameter
1628 if (!data
->timerId
) {
1629 perror("Failed to initialize win32 alarm timer");
1631 timeEndPeriod(data
->period
);
1632 CloseHandle(data
->host_alarm
);
1636 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1641 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1643 struct qemu_alarm_win32
*data
= t
->priv
;
1645 timeKillEvent(data
->timerId
);
1646 timeEndPeriod(data
->period
);
1648 CloseHandle(data
->host_alarm
);
1651 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1653 struct qemu_alarm_win32
*data
= t
->priv
;
1654 uint64_t nearest_delta_us
;
1656 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1657 !active_timers
[QEMU_TIMER_VIRTUAL
])
1660 nearest_delta_us
= qemu_next_deadline_dyntick();
1661 nearest_delta_us
/= 1000;
1663 timeKillEvent(data
->timerId
);
1665 data
->timerId
= timeSetEvent(1,
1669 TIME_ONESHOT
| TIME_PERIODIC
);
1671 if (!data
->timerId
) {
1672 perror("Failed to re-arm win32 alarm timer");
1674 timeEndPeriod(data
->period
);
1675 CloseHandle(data
->host_alarm
);
1682 static void init_timer_alarm(void)
1684 struct qemu_alarm_timer
*t
= NULL
;
1687 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1688 t
= &alarm_timers
[i
];
1696 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1697 fprintf(stderr
, "Terminating\n");
1704 static void quit_timers(void)
1706 alarm_timer
->stop(alarm_timer
);
1710 /***********************************************************/
1711 /* host time/date access */
1712 void qemu_get_timedate(struct tm
*tm
, int offset
)
1719 if (rtc_date_offset
== -1) {
1723 ret
= localtime(&ti
);
1725 ti
-= rtc_date_offset
;
1729 memcpy(tm
, ret
, sizeof(struct tm
));
1732 int qemu_timedate_diff(struct tm
*tm
)
1736 if (rtc_date_offset
== -1)
1738 seconds
= mktimegm(tm
);
1740 seconds
= mktime(tm
);
1742 seconds
= mktimegm(tm
) + rtc_date_offset
;
1744 return seconds
- time(NULL
);
1747 /***********************************************************/
1748 /* character device */
1750 static void qemu_chr_event(CharDriverState
*s
, int event
)
1754 s
->chr_event(s
->handler_opaque
, event
);
1757 static void qemu_chr_reset_bh(void *opaque
)
1759 CharDriverState
*s
= opaque
;
1760 qemu_chr_event(s
, CHR_EVENT_RESET
);
1761 qemu_bh_delete(s
->bh
);
1765 void qemu_chr_reset(CharDriverState
*s
)
1767 if (s
->bh
== NULL
) {
1768 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1769 qemu_bh_schedule(s
->bh
);
1773 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1775 return s
->chr_write(s
, buf
, len
);
1778 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1782 return s
->chr_ioctl(s
, cmd
, arg
);
1785 int qemu_chr_can_read(CharDriverState
*s
)
1787 if (!s
->chr_can_read
)
1789 return s
->chr_can_read(s
->handler_opaque
);
1792 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1794 s
->chr_read(s
->handler_opaque
, buf
, len
);
1797 void qemu_chr_accept_input(CharDriverState
*s
)
1799 if (s
->chr_accept_input
)
1800 s
->chr_accept_input(s
);
1803 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1808 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1809 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1813 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1815 if (s
->chr_send_event
)
1816 s
->chr_send_event(s
, event
);
1819 void qemu_chr_add_handlers(CharDriverState
*s
,
1820 IOCanRWHandler
*fd_can_read
,
1821 IOReadHandler
*fd_read
,
1822 IOEventHandler
*fd_event
,
1825 s
->chr_can_read
= fd_can_read
;
1826 s
->chr_read
= fd_read
;
1827 s
->chr_event
= fd_event
;
1828 s
->handler_opaque
= opaque
;
1829 if (s
->chr_update_read_handler
)
1830 s
->chr_update_read_handler(s
);
1833 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1838 static CharDriverState
*qemu_chr_open_null(void)
1840 CharDriverState
*chr
;
1842 chr
= qemu_mallocz(sizeof(CharDriverState
));
1845 chr
->chr_write
= null_chr_write
;
1849 /* MUX driver for serial I/O splitting */
1850 static int term_timestamps
;
1851 static int64_t term_timestamps_start
;
1853 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1854 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1856 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1857 IOReadHandler
*chr_read
[MAX_MUX
];
1858 IOEventHandler
*chr_event
[MAX_MUX
];
1859 void *ext_opaque
[MAX_MUX
];
1860 CharDriverState
*drv
;
1861 unsigned char buffer
[MUX_BUFFER_SIZE
];
1865 int term_got_escape
;
1870 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1872 MuxDriver
*d
= chr
->opaque
;
1874 if (!term_timestamps
) {
1875 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1880 for(i
= 0; i
< len
; i
++) {
1881 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1882 if (buf
[i
] == '\n') {
1888 if (term_timestamps_start
== -1)
1889 term_timestamps_start
= ti
;
1890 ti
-= term_timestamps_start
;
1891 secs
= ti
/ 1000000000;
1892 snprintf(buf1
, sizeof(buf1
),
1893 "[%02d:%02d:%02d.%03d] ",
1897 (int)((ti
/ 1000000) % 1000));
1898 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1905 static const char * const mux_help
[] = {
1906 "% h print this help\n\r",
1907 "% x exit emulator\n\r",
1908 "% s save disk data back to file (if -snapshot)\n\r",
1909 "% t toggle console timestamps\n\r"
1910 "% b send break (magic sysrq)\n\r",
1911 "% c switch between console and monitor\n\r",
1916 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1917 static void mux_print_help(CharDriverState
*chr
)
1920 char ebuf
[15] = "Escape-Char";
1921 char cbuf
[50] = "\n\r";
1923 if (term_escape_char
> 0 && term_escape_char
< 26) {
1924 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1925 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1927 snprintf(cbuf
, sizeof(cbuf
),
1928 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1931 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1932 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1933 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1934 if (mux_help
[i
][j
] == '%')
1935 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1937 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1942 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1944 if (d
->term_got_escape
) {
1945 d
->term_got_escape
= 0;
1946 if (ch
== term_escape_char
)
1951 mux_print_help(chr
);
1955 const char *term
= "QEMU: Terminated\n\r";
1956 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1963 for (i
= 0; i
< nb_drives
; i
++) {
1964 bdrv_commit(drives_table
[i
].bdrv
);
1969 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1972 /* Switch to the next registered device */
1974 if (chr
->focus
>= d
->mux_cnt
)
1978 term_timestamps
= !term_timestamps
;
1979 term_timestamps_start
= -1;
1982 } else if (ch
== term_escape_char
) {
1983 d
->term_got_escape
= 1;
1991 static void mux_chr_accept_input(CharDriverState
*chr
)
1994 MuxDriver
*d
= chr
->opaque
;
1996 while (d
->prod
!= d
->cons
&&
1997 d
->chr_can_read
[m
] &&
1998 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1999 d
->chr_read
[m
](d
->ext_opaque
[m
],
2000 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2004 static int mux_chr_can_read(void *opaque
)
2006 CharDriverState
*chr
= opaque
;
2007 MuxDriver
*d
= chr
->opaque
;
2009 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2011 if (d
->chr_can_read
[chr
->focus
])
2012 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2016 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2018 CharDriverState
*chr
= opaque
;
2019 MuxDriver
*d
= chr
->opaque
;
2023 mux_chr_accept_input (opaque
);
2025 for(i
= 0; i
< size
; i
++)
2026 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2027 if (d
->prod
== d
->cons
&&
2028 d
->chr_can_read
[m
] &&
2029 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2030 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2032 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2036 static void mux_chr_event(void *opaque
, int event
)
2038 CharDriverState
*chr
= opaque
;
2039 MuxDriver
*d
= chr
->opaque
;
2042 /* Send the event to all registered listeners */
2043 for (i
= 0; i
< d
->mux_cnt
; i
++)
2044 if (d
->chr_event
[i
])
2045 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2048 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2050 MuxDriver
*d
= chr
->opaque
;
2052 if (d
->mux_cnt
>= MAX_MUX
) {
2053 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2056 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2057 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2058 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2059 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2060 /* Fix up the real driver with mux routines */
2061 if (d
->mux_cnt
== 0) {
2062 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2063 mux_chr_event
, chr
);
2065 chr
->focus
= d
->mux_cnt
;
2069 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2071 CharDriverState
*chr
;
2074 chr
= qemu_mallocz(sizeof(CharDriverState
));
2077 d
= qemu_mallocz(sizeof(MuxDriver
));
2086 chr
->chr_write
= mux_chr_write
;
2087 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2088 chr
->chr_accept_input
= mux_chr_accept_input
;
2095 static void socket_cleanup(void)
2100 static int socket_init(void)
2105 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2107 err
= WSAGetLastError();
2108 fprintf(stderr
, "WSAStartup: %d\n", err
);
2111 atexit(socket_cleanup
);
2115 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2121 ret
= send(fd
, buf
, len
, 0);
2124 errno
= WSAGetLastError();
2125 if (errno
!= WSAEWOULDBLOCK
) {
2128 } else if (ret
== 0) {
2140 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2146 ret
= write(fd
, buf
, len
);
2148 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2150 } else if (ret
== 0) {
2160 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2162 return unix_write(fd
, buf
, len1
);
2164 #endif /* !_WIN32 */
2173 #define STDIO_MAX_CLIENTS 1
2174 static int stdio_nb_clients
= 0;
2176 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2178 FDCharDriver
*s
= chr
->opaque
;
2179 return unix_write(s
->fd_out
, buf
, len
);
2182 static int fd_chr_read_poll(void *opaque
)
2184 CharDriverState
*chr
= opaque
;
2185 FDCharDriver
*s
= chr
->opaque
;
2187 s
->max_size
= qemu_chr_can_read(chr
);
2191 static void fd_chr_read(void *opaque
)
2193 CharDriverState
*chr
= opaque
;
2194 FDCharDriver
*s
= chr
->opaque
;
2199 if (len
> s
->max_size
)
2203 size
= read(s
->fd_in
, buf
, len
);
2205 /* FD has been closed. Remove it from the active list. */
2206 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2210 qemu_chr_read(chr
, buf
, size
);
2214 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2216 FDCharDriver
*s
= chr
->opaque
;
2218 if (s
->fd_in
>= 0) {
2219 if (nographic
&& s
->fd_in
== 0) {
2221 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2222 fd_chr_read
, NULL
, chr
);
2227 static void fd_chr_close(struct CharDriverState
*chr
)
2229 FDCharDriver
*s
= chr
->opaque
;
2231 if (s
->fd_in
>= 0) {
2232 if (nographic
&& s
->fd_in
== 0) {
2234 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2241 /* open a character device to a unix fd */
2242 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2244 CharDriverState
*chr
;
2247 chr
= qemu_mallocz(sizeof(CharDriverState
));
2250 s
= qemu_mallocz(sizeof(FDCharDriver
));
2258 chr
->chr_write
= fd_chr_write
;
2259 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2260 chr
->chr_close
= fd_chr_close
;
2262 qemu_chr_reset(chr
);
2267 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2271 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2274 return qemu_chr_open_fd(-1, fd_out
);
2277 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2280 char filename_in
[256], filename_out
[256];
2282 snprintf(filename_in
, 256, "%s.in", filename
);
2283 snprintf(filename_out
, 256, "%s.out", filename
);
2284 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2285 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2286 if (fd_in
< 0 || fd_out
< 0) {
2291 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2295 return qemu_chr_open_fd(fd_in
, fd_out
);
2299 /* for STDIO, we handle the case where several clients use it
2302 #define TERM_FIFO_MAX_SIZE 1
2304 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2305 static int term_fifo_size
;
2307 static int stdio_read_poll(void *opaque
)
2309 CharDriverState
*chr
= opaque
;
2311 /* try to flush the queue if needed */
2312 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2313 qemu_chr_read(chr
, term_fifo
, 1);
2316 /* see if we can absorb more chars */
2317 if (term_fifo_size
== 0)
2323 static void stdio_read(void *opaque
)
2327 CharDriverState
*chr
= opaque
;
2329 size
= read(0, buf
, 1);
2331 /* stdin has been closed. Remove it from the active list. */
2332 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2336 if (qemu_chr_can_read(chr
) > 0) {
2337 qemu_chr_read(chr
, buf
, 1);
2338 } else if (term_fifo_size
== 0) {
2339 term_fifo
[term_fifo_size
++] = buf
[0];
2344 /* init terminal so that we can grab keys */
2345 static struct termios oldtty
;
2346 static int old_fd0_flags
;
2347 static int term_atexit_done
;
2349 static void term_exit(void)
2351 tcsetattr (0, TCSANOW
, &oldtty
);
2352 fcntl(0, F_SETFL
, old_fd0_flags
);
2355 static void term_init(void)
2359 tcgetattr (0, &tty
);
2361 old_fd0_flags
= fcntl(0, F_GETFL
);
2363 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2364 |INLCR
|IGNCR
|ICRNL
|IXON
);
2365 tty
.c_oflag
|= OPOST
;
2366 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2367 /* if graphical mode, we allow Ctrl-C handling */
2369 tty
.c_lflag
&= ~ISIG
;
2370 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2373 tty
.c_cc
[VTIME
] = 0;
2375 tcsetattr (0, TCSANOW
, &tty
);
2377 if (!term_atexit_done
++)
2380 fcntl(0, F_SETFL
, O_NONBLOCK
);
2383 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2387 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2391 static CharDriverState
*qemu_chr_open_stdio(void)
2393 CharDriverState
*chr
;
2395 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2397 chr
= qemu_chr_open_fd(0, 1);
2398 chr
->chr_close
= qemu_chr_close_stdio
;
2399 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2407 /* Once Solaris has openpty(), this is going to be removed. */
2408 int openpty(int *amaster
, int *aslave
, char *name
,
2409 struct termios
*termp
, struct winsize
*winp
)
2412 int mfd
= -1, sfd
= -1;
2414 *amaster
= *aslave
= -1;
2416 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2420 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2423 if ((slave
= ptsname(mfd
)) == NULL
)
2426 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2429 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2430 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2438 ioctl(sfd
, TIOCSWINSZ
, winp
);
2449 void cfmakeraw (struct termios
*termios_p
)
2451 termios_p
->c_iflag
&=
2452 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2453 termios_p
->c_oflag
&= ~OPOST
;
2454 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2455 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2456 termios_p
->c_cflag
|= CS8
;
2458 termios_p
->c_cc
[VMIN
] = 0;
2459 termios_p
->c_cc
[VTIME
] = 0;
2463 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2464 || defined(__NetBSD__) || defined(__OpenBSD__)
2474 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2475 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2477 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2479 PtyCharDriver
*s
= chr
->opaque
;
2481 if (!s
->connected
) {
2482 /* guest sends data, check for (re-)connect */
2483 pty_chr_update_read_handler(chr
);
2486 return unix_write(s
->fd
, buf
, len
);
2489 static int pty_chr_read_poll(void *opaque
)
2491 CharDriverState
*chr
= opaque
;
2492 PtyCharDriver
*s
= chr
->opaque
;
2494 s
->read_bytes
= qemu_chr_can_read(chr
);
2495 return s
->read_bytes
;
2498 static void pty_chr_read(void *opaque
)
2500 CharDriverState
*chr
= opaque
;
2501 PtyCharDriver
*s
= chr
->opaque
;
2506 if (len
> s
->read_bytes
)
2507 len
= s
->read_bytes
;
2510 size
= read(s
->fd
, buf
, len
);
2511 if ((size
== -1 && errno
== EIO
) ||
2513 pty_chr_state(chr
, 0);
2517 pty_chr_state(chr
, 1);
2518 qemu_chr_read(chr
, buf
, size
);
2522 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2524 PtyCharDriver
*s
= chr
->opaque
;
2526 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2527 pty_chr_read
, NULL
, chr
);
2530 * Short timeout here: just need wait long enougth that qemu makes
2531 * it through the poll loop once. When reconnected we want a
2532 * short timeout so we notice it almost instantly. Otherwise
2533 * read() gives us -EIO instantly, making pty_chr_state() reset the
2534 * timeout to the normal (much longer) poll interval before the
2537 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2540 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2542 PtyCharDriver
*s
= chr
->opaque
;
2545 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2548 /* (re-)connect poll interval for idle guests: once per second.
2549 * We check more frequently in case the guests sends data to
2550 * the virtual device linked to our pty. */
2551 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2554 qemu_chr_reset(chr
);
2559 static void pty_chr_timer(void *opaque
)
2561 struct CharDriverState
*chr
= opaque
;
2562 PtyCharDriver
*s
= chr
->opaque
;
2567 /* If we arrive here without polling being cleared due
2568 * read returning -EIO, then we are (re-)connected */
2569 pty_chr_state(chr
, 1);
2574 pty_chr_update_read_handler(chr
);
2577 static void pty_chr_close(struct CharDriverState
*chr
)
2579 PtyCharDriver
*s
= chr
->opaque
;
2581 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2586 static CharDriverState
*qemu_chr_open_pty(void)
2588 CharDriverState
*chr
;
2592 #if defined(__OpenBSD__)
2593 char pty_name
[PATH_MAX
];
2594 #define q_ptsname(x) pty_name
2596 char *pty_name
= NULL
;
2597 #define q_ptsname(x) ptsname(x)
2600 chr
= qemu_mallocz(sizeof(CharDriverState
));
2603 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2609 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2613 /* Set raw attributes on the pty. */
2615 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2618 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2621 chr
->chr_write
= pty_chr_write
;
2622 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2623 chr
->chr_close
= pty_chr_close
;
2625 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2630 static void tty_serial_init(int fd
, int speed
,
2631 int parity
, int data_bits
, int stop_bits
)
2637 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2638 speed
, parity
, data_bits
, stop_bits
);
2640 tcgetattr (fd
, &tty
);
2643 if (speed
<= 50 * MARGIN
)
2645 else if (speed
<= 75 * MARGIN
)
2647 else if (speed
<= 300 * MARGIN
)
2649 else if (speed
<= 600 * MARGIN
)
2651 else if (speed
<= 1200 * MARGIN
)
2653 else if (speed
<= 2400 * MARGIN
)
2655 else if (speed
<= 4800 * MARGIN
)
2657 else if (speed
<= 9600 * MARGIN
)
2659 else if (speed
<= 19200 * MARGIN
)
2661 else if (speed
<= 38400 * MARGIN
)
2663 else if (speed
<= 57600 * MARGIN
)
2665 else if (speed
<= 115200 * MARGIN
)
2670 cfsetispeed(&tty
, spd
);
2671 cfsetospeed(&tty
, spd
);
2673 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2674 |INLCR
|IGNCR
|ICRNL
|IXON
);
2675 tty
.c_oflag
|= OPOST
;
2676 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2677 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2698 tty
.c_cflag
|= PARENB
;
2701 tty
.c_cflag
|= PARENB
| PARODD
;
2705 tty
.c_cflag
|= CSTOPB
;
2707 tcsetattr (fd
, TCSANOW
, &tty
);
2710 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2712 FDCharDriver
*s
= chr
->opaque
;
2715 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2717 QEMUSerialSetParams
*ssp
= arg
;
2718 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2719 ssp
->data_bits
, ssp
->stop_bits
);
2722 case CHR_IOCTL_SERIAL_SET_BREAK
:
2724 int enable
= *(int *)arg
;
2726 tcsendbreak(s
->fd_in
, 1);
2729 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2732 int *targ
= (int *)arg
;
2733 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2735 if (sarg
| TIOCM_CTS
)
2736 *targ
|= CHR_TIOCM_CTS
;
2737 if (sarg
| TIOCM_CAR
)
2738 *targ
|= CHR_TIOCM_CAR
;
2739 if (sarg
| TIOCM_DSR
)
2740 *targ
|= CHR_TIOCM_DSR
;
2741 if (sarg
| TIOCM_RI
)
2742 *targ
|= CHR_TIOCM_RI
;
2743 if (sarg
| TIOCM_DTR
)
2744 *targ
|= CHR_TIOCM_DTR
;
2745 if (sarg
| TIOCM_RTS
)
2746 *targ
|= CHR_TIOCM_RTS
;
2749 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2751 int sarg
= *(int *)arg
;
2753 if (sarg
| CHR_TIOCM_DTR
)
2755 if (sarg
| CHR_TIOCM_RTS
)
2757 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2766 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2768 CharDriverState
*chr
;
2771 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2772 tty_serial_init(fd
, 115200, 'N', 8, 1);
2773 chr
= qemu_chr_open_fd(fd
, fd
);
2778 chr
->chr_ioctl
= tty_serial_ioctl
;
2779 qemu_chr_reset(chr
);
2782 #else /* ! __linux__ && ! __sun__ */
2783 static CharDriverState
*qemu_chr_open_pty(void)
2787 #endif /* __linux__ || __sun__ */
2789 #if defined(__linux__)
2793 } ParallelCharDriver
;
2795 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2797 if (s
->mode
!= mode
) {
2799 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2806 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2808 ParallelCharDriver
*drv
= chr
->opaque
;
2813 case CHR_IOCTL_PP_READ_DATA
:
2814 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2816 *(uint8_t *)arg
= b
;
2818 case CHR_IOCTL_PP_WRITE_DATA
:
2819 b
= *(uint8_t *)arg
;
2820 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2823 case CHR_IOCTL_PP_READ_CONTROL
:
2824 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2826 /* Linux gives only the lowest bits, and no way to know data
2827 direction! For better compatibility set the fixed upper
2829 *(uint8_t *)arg
= b
| 0xc0;
2831 case CHR_IOCTL_PP_WRITE_CONTROL
:
2832 b
= *(uint8_t *)arg
;
2833 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2836 case CHR_IOCTL_PP_READ_STATUS
:
2837 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2839 *(uint8_t *)arg
= b
;
2841 case CHR_IOCTL_PP_DATA_DIR
:
2842 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2845 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2846 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2847 struct ParallelIOArg
*parg
= arg
;
2848 int n
= read(fd
, parg
->buffer
, parg
->count
);
2849 if (n
!= parg
->count
) {
2854 case CHR_IOCTL_PP_EPP_READ
:
2855 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2856 struct ParallelIOArg
*parg
= arg
;
2857 int n
= read(fd
, parg
->buffer
, parg
->count
);
2858 if (n
!= parg
->count
) {
2863 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2864 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2865 struct ParallelIOArg
*parg
= arg
;
2866 int n
= write(fd
, parg
->buffer
, parg
->count
);
2867 if (n
!= parg
->count
) {
2872 case CHR_IOCTL_PP_EPP_WRITE
:
2873 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2874 struct ParallelIOArg
*parg
= arg
;
2875 int n
= write(fd
, parg
->buffer
, parg
->count
);
2876 if (n
!= parg
->count
) {
2887 static void pp_close(CharDriverState
*chr
)
2889 ParallelCharDriver
*drv
= chr
->opaque
;
2892 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2893 ioctl(fd
, PPRELEASE
);
2898 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2900 CharDriverState
*chr
;
2901 ParallelCharDriver
*drv
;
2904 TFR(fd
= open(filename
, O_RDWR
));
2908 if (ioctl(fd
, PPCLAIM
) < 0) {
2913 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2919 drv
->mode
= IEEE1284_MODE_COMPAT
;
2921 chr
= qemu_mallocz(sizeof(CharDriverState
));
2927 chr
->chr_write
= null_chr_write
;
2928 chr
->chr_ioctl
= pp_ioctl
;
2929 chr
->chr_close
= pp_close
;
2932 qemu_chr_reset(chr
);
2936 #endif /* __linux__ */
2942 HANDLE hcom
, hrecv
, hsend
;
2943 OVERLAPPED orecv
, osend
;
2948 #define NSENDBUF 2048
2949 #define NRECVBUF 2048
2950 #define MAXCONNECT 1
2951 #define NTIMEOUT 5000
2953 static int win_chr_poll(void *opaque
);
2954 static int win_chr_pipe_poll(void *opaque
);
2956 static void win_chr_close(CharDriverState
*chr
)
2958 WinCharState
*s
= chr
->opaque
;
2961 CloseHandle(s
->hsend
);
2965 CloseHandle(s
->hrecv
);
2969 CloseHandle(s
->hcom
);
2973 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2975 qemu_del_polling_cb(win_chr_poll
, chr
);
2978 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2980 WinCharState
*s
= chr
->opaque
;
2982 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2987 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2989 fprintf(stderr
, "Failed CreateEvent\n");
2992 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2994 fprintf(stderr
, "Failed CreateEvent\n");
2998 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2999 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3000 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3001 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3006 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3007 fprintf(stderr
, "Failed SetupComm\n");
3011 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3012 size
= sizeof(COMMCONFIG
);
3013 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3014 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3015 CommConfigDialog(filename
, NULL
, &comcfg
);
3017 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3018 fprintf(stderr
, "Failed SetCommState\n");
3022 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3023 fprintf(stderr
, "Failed SetCommMask\n");
3027 cto
.ReadIntervalTimeout
= MAXDWORD
;
3028 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3029 fprintf(stderr
, "Failed SetCommTimeouts\n");
3033 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3034 fprintf(stderr
, "Failed ClearCommError\n");
3037 qemu_add_polling_cb(win_chr_poll
, chr
);
3045 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3047 WinCharState
*s
= chr
->opaque
;
3048 DWORD len
, ret
, size
, err
;
3051 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3052 s
->osend
.hEvent
= s
->hsend
;
3055 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3057 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3059 err
= GetLastError();
3060 if (err
== ERROR_IO_PENDING
) {
3061 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3079 static int win_chr_read_poll(CharDriverState
*chr
)
3081 WinCharState
*s
= chr
->opaque
;
3083 s
->max_size
= qemu_chr_can_read(chr
);
3087 static void win_chr_readfile(CharDriverState
*chr
)
3089 WinCharState
*s
= chr
->opaque
;
3094 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3095 s
->orecv
.hEvent
= s
->hrecv
;
3096 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3098 err
= GetLastError();
3099 if (err
== ERROR_IO_PENDING
) {
3100 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3105 qemu_chr_read(chr
, buf
, size
);
3109 static void win_chr_read(CharDriverState
*chr
)
3111 WinCharState
*s
= chr
->opaque
;
3113 if (s
->len
> s
->max_size
)
3114 s
->len
= s
->max_size
;
3118 win_chr_readfile(chr
);
3121 static int win_chr_poll(void *opaque
)
3123 CharDriverState
*chr
= opaque
;
3124 WinCharState
*s
= chr
->opaque
;
3128 ClearCommError(s
->hcom
, &comerr
, &status
);
3129 if (status
.cbInQue
> 0) {
3130 s
->len
= status
.cbInQue
;
3131 win_chr_read_poll(chr
);
3138 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3140 CharDriverState
*chr
;
3143 chr
= qemu_mallocz(sizeof(CharDriverState
));
3146 s
= qemu_mallocz(sizeof(WinCharState
));
3152 chr
->chr_write
= win_chr_write
;
3153 chr
->chr_close
= win_chr_close
;
3155 if (win_chr_init(chr
, filename
) < 0) {
3160 qemu_chr_reset(chr
);
3164 static int win_chr_pipe_poll(void *opaque
)
3166 CharDriverState
*chr
= opaque
;
3167 WinCharState
*s
= chr
->opaque
;
3170 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3173 win_chr_read_poll(chr
);
3180 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3182 WinCharState
*s
= chr
->opaque
;
3190 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3192 fprintf(stderr
, "Failed CreateEvent\n");
3195 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3197 fprintf(stderr
, "Failed CreateEvent\n");
3201 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3202 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3203 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3205 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3206 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3207 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3212 ZeroMemory(&ov
, sizeof(ov
));
3213 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3214 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3216 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3220 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3222 fprintf(stderr
, "Failed GetOverlappedResult\n");
3224 CloseHandle(ov
.hEvent
);
3231 CloseHandle(ov
.hEvent
);
3234 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3243 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3245 CharDriverState
*chr
;
3248 chr
= qemu_mallocz(sizeof(CharDriverState
));
3251 s
= qemu_mallocz(sizeof(WinCharState
));
3257 chr
->chr_write
= win_chr_write
;
3258 chr
->chr_close
= win_chr_close
;
3260 if (win_chr_pipe_init(chr
, filename
) < 0) {
3265 qemu_chr_reset(chr
);
3269 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3271 CharDriverState
*chr
;
3274 chr
= qemu_mallocz(sizeof(CharDriverState
));
3277 s
= qemu_mallocz(sizeof(WinCharState
));
3284 chr
->chr_write
= win_chr_write
;
3285 qemu_chr_reset(chr
);
3289 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3291 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3294 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3298 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3299 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3300 if (fd_out
== INVALID_HANDLE_VALUE
)
3303 return qemu_chr_open_win_file(fd_out
);
3305 #endif /* !_WIN32 */
3307 /***********************************************************/
3308 /* UDP Net console */
3312 struct sockaddr_in daddr
;
3319 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3321 NetCharDriver
*s
= chr
->opaque
;
3323 return sendto(s
->fd
, buf
, len
, 0,
3324 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3327 static int udp_chr_read_poll(void *opaque
)
3329 CharDriverState
*chr
= opaque
;
3330 NetCharDriver
*s
= chr
->opaque
;
3332 s
->max_size
= qemu_chr_can_read(chr
);
3334 /* If there were any stray characters in the queue process them
3337 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3338 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3340 s
->max_size
= qemu_chr_can_read(chr
);
3345 static void udp_chr_read(void *opaque
)
3347 CharDriverState
*chr
= opaque
;
3348 NetCharDriver
*s
= chr
->opaque
;
3350 if (s
->max_size
== 0)
3352 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3353 s
->bufptr
= s
->bufcnt
;
3358 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3359 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3361 s
->max_size
= qemu_chr_can_read(chr
);
3365 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3367 NetCharDriver
*s
= chr
->opaque
;
3370 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3371 udp_chr_read
, NULL
, chr
);
3375 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3377 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3379 int parse_host_src_port(struct sockaddr_in
*haddr
,
3380 struct sockaddr_in
*saddr
,
3383 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3385 CharDriverState
*chr
= NULL
;
3386 NetCharDriver
*s
= NULL
;
3388 struct sockaddr_in saddr
;
3390 chr
= qemu_mallocz(sizeof(CharDriverState
));
3393 s
= qemu_mallocz(sizeof(NetCharDriver
));
3397 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3399 perror("socket(PF_INET, SOCK_DGRAM)");
3403 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3404 printf("Could not parse: %s\n", def
);
3408 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3418 chr
->chr_write
= udp_chr_write
;
3419 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3432 /***********************************************************/
3433 /* TCP Net console */
3444 static void tcp_chr_accept(void *opaque
);
3446 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3448 TCPCharDriver
*s
= chr
->opaque
;
3450 return send_all(s
->fd
, buf
, len
);
3452 /* XXX: indicate an error ? */
3457 static int tcp_chr_read_poll(void *opaque
)
3459 CharDriverState
*chr
= opaque
;
3460 TCPCharDriver
*s
= chr
->opaque
;
3463 s
->max_size
= qemu_chr_can_read(chr
);
3468 #define IAC_BREAK 243
3469 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3471 uint8_t *buf
, int *size
)
3473 /* Handle any telnet client's basic IAC options to satisfy char by
3474 * char mode with no echo. All IAC options will be removed from
3475 * the buf and the do_telnetopt variable will be used to track the
3476 * state of the width of the IAC information.
3478 * IAC commands come in sets of 3 bytes with the exception of the
3479 * "IAC BREAK" command and the double IAC.
3485 for (i
= 0; i
< *size
; i
++) {
3486 if (s
->do_telnetopt
> 1) {
3487 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3488 /* Double IAC means send an IAC */
3492 s
->do_telnetopt
= 1;
3494 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3495 /* Handle IAC break commands by sending a serial break */
3496 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3501 if (s
->do_telnetopt
>= 4) {
3502 s
->do_telnetopt
= 1;
3505 if ((unsigned char)buf
[i
] == IAC
) {
3506 s
->do_telnetopt
= 2;
3517 static void tcp_chr_read(void *opaque
)
3519 CharDriverState
*chr
= opaque
;
3520 TCPCharDriver
*s
= chr
->opaque
;
3524 if (!s
->connected
|| s
->max_size
<= 0)
3527 if (len
> s
->max_size
)
3529 size
= recv(s
->fd
, buf
, len
, 0);
3531 /* connection closed */
3533 if (s
->listen_fd
>= 0) {
3534 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3536 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3539 } else if (size
> 0) {
3540 if (s
->do_telnetopt
)
3541 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3543 qemu_chr_read(chr
, buf
, size
);
3547 static void tcp_chr_connect(void *opaque
)
3549 CharDriverState
*chr
= opaque
;
3550 TCPCharDriver
*s
= chr
->opaque
;
3553 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3554 tcp_chr_read
, NULL
, chr
);
3555 qemu_chr_reset(chr
);
3558 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3559 static void tcp_chr_telnet_init(int fd
)
3562 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3563 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3564 send(fd
, (char *)buf
, 3, 0);
3565 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3566 send(fd
, (char *)buf
, 3, 0);
3567 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3568 send(fd
, (char *)buf
, 3, 0);
3569 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3570 send(fd
, (char *)buf
, 3, 0);
3573 static void socket_set_nodelay(int fd
)
3576 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3579 static void tcp_chr_accept(void *opaque
)
3581 CharDriverState
*chr
= opaque
;
3582 TCPCharDriver
*s
= chr
->opaque
;
3583 struct sockaddr_in saddr
;
3585 struct sockaddr_un uaddr
;
3587 struct sockaddr
*addr
;
3594 len
= sizeof(uaddr
);
3595 addr
= (struct sockaddr
*)&uaddr
;
3599 len
= sizeof(saddr
);
3600 addr
= (struct sockaddr
*)&saddr
;
3602 fd
= accept(s
->listen_fd
, addr
, &len
);
3603 if (fd
< 0 && errno
!= EINTR
) {
3605 } else if (fd
>= 0) {
3606 if (s
->do_telnetopt
)
3607 tcp_chr_telnet_init(fd
);
3611 socket_set_nonblock(fd
);
3613 socket_set_nodelay(fd
);
3615 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3616 tcp_chr_connect(chr
);
3619 static void tcp_chr_close(CharDriverState
*chr
)
3621 TCPCharDriver
*s
= chr
->opaque
;
3624 if (s
->listen_fd
>= 0)
3625 closesocket(s
->listen_fd
);
3629 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3633 CharDriverState
*chr
= NULL
;
3634 TCPCharDriver
*s
= NULL
;
3635 int fd
= -1, ret
, err
, val
;
3637 int is_waitconnect
= 1;
3640 struct sockaddr_in saddr
;
3642 struct sockaddr_un uaddr
;
3644 struct sockaddr
*addr
;
3649 addr
= (struct sockaddr
*)&uaddr
;
3650 addrlen
= sizeof(uaddr
);
3651 if (parse_unix_path(&uaddr
, host_str
) < 0)
3656 addr
= (struct sockaddr
*)&saddr
;
3657 addrlen
= sizeof(saddr
);
3658 if (parse_host_port(&saddr
, host_str
) < 0)
3663 while((ptr
= strchr(ptr
,','))) {
3665 if (!strncmp(ptr
,"server",6)) {
3667 } else if (!strncmp(ptr
,"nowait",6)) {
3669 } else if (!strncmp(ptr
,"nodelay",6)) {
3672 printf("Unknown option: %s\n", ptr
);
3679 chr
= qemu_mallocz(sizeof(CharDriverState
));
3682 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3688 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3691 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3696 if (!is_waitconnect
)
3697 socket_set_nonblock(fd
);
3702 s
->is_unix
= is_unix
;
3703 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3706 chr
->chr_write
= tcp_chr_write
;
3707 chr
->chr_close
= tcp_chr_close
;
3710 /* allow fast reuse */
3714 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3720 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3723 ret
= bind(fd
, addr
, addrlen
);
3727 ret
= listen(fd
, 0);
3732 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3734 s
->do_telnetopt
= 1;
3737 ret
= connect(fd
, addr
, addrlen
);
3739 err
= socket_error();
3740 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3741 } else if (err
== EINPROGRESS
) {
3744 } else if (err
== WSAEALREADY
) {
3756 socket_set_nodelay(fd
);
3758 tcp_chr_connect(chr
);
3760 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3763 if (is_listen
&& is_waitconnect
) {
3764 printf("QEMU waiting for connection on: %s\n", host_str
);
3765 tcp_chr_accept(chr
);
3766 socket_set_nonblock(s
->listen_fd
);
3778 CharDriverState
*qemu_chr_open(const char *filename
)
3782 if (!strcmp(filename
, "vc")) {
3783 return text_console_init(&display_state
, 0);
3784 } else if (strstart(filename
, "vc:", &p
)) {
3785 return text_console_init(&display_state
, p
);
3786 } else if (!strcmp(filename
, "null")) {
3787 return qemu_chr_open_null();
3789 if (strstart(filename
, "tcp:", &p
)) {
3790 return qemu_chr_open_tcp(p
, 0, 0);
3792 if (strstart(filename
, "telnet:", &p
)) {
3793 return qemu_chr_open_tcp(p
, 1, 0);
3795 if (strstart(filename
, "udp:", &p
)) {
3796 return qemu_chr_open_udp(p
);
3798 if (strstart(filename
, "mon:", &p
)) {
3799 CharDriverState
*drv
= qemu_chr_open(p
);
3801 drv
= qemu_chr_open_mux(drv
);
3802 monitor_init(drv
, !nographic
);
3805 printf("Unable to open driver: %s\n", p
);
3809 if (strstart(filename
, "unix:", &p
)) {
3810 return qemu_chr_open_tcp(p
, 0, 1);
3811 } else if (strstart(filename
, "file:", &p
)) {
3812 return qemu_chr_open_file_out(p
);
3813 } else if (strstart(filename
, "pipe:", &p
)) {
3814 return qemu_chr_open_pipe(p
);
3815 } else if (!strcmp(filename
, "pty")) {
3816 return qemu_chr_open_pty();
3817 } else if (!strcmp(filename
, "stdio")) {
3818 return qemu_chr_open_stdio();
3820 #if defined(__linux__)
3821 if (strstart(filename
, "/dev/parport", NULL
)) {
3822 return qemu_chr_open_pp(filename
);
3825 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3826 || defined(__NetBSD__) || defined(__OpenBSD__)
3827 if (strstart(filename
, "/dev/", NULL
)) {
3828 return qemu_chr_open_tty(filename
);
3832 if (strstart(filename
, "COM", NULL
)) {
3833 return qemu_chr_open_win(filename
);
3835 if (strstart(filename
, "pipe:", &p
)) {
3836 return qemu_chr_open_win_pipe(p
);
3838 if (strstart(filename
, "con:", NULL
)) {
3839 return qemu_chr_open_win_con(filename
);
3841 if (strstart(filename
, "file:", &p
)) {
3842 return qemu_chr_open_win_file_out(p
);
3845 #ifdef CONFIG_BRLAPI
3846 if (!strcmp(filename
, "braille")) {
3847 return chr_baum_init();
3855 void qemu_chr_close(CharDriverState
*chr
)
3858 chr
->chr_close(chr
);
3862 /***********************************************************/
3863 /* network device redirectors */
3865 __attribute__ (( unused
))
3866 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3870 for(i
=0;i
<size
;i
+=16) {
3874 fprintf(f
, "%08x ", i
);
3877 fprintf(f
, " %02x", buf
[i
+j
]);
3882 for(j
=0;j
<len
;j
++) {
3884 if (c
< ' ' || c
> '~')
3886 fprintf(f
, "%c", c
);
3892 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3899 offset
= strtol(p
, &last_char
, 0);
3900 if (0 == errno
&& '\0' == *last_char
&&
3901 offset
>= 0 && offset
<= 0xFFFFFF) {
3902 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3903 macaddr
[4] = (offset
& 0xFF00) >> 8;
3904 macaddr
[5] = offset
& 0xFF;
3907 for(i
= 0; i
< 6; i
++) {
3908 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3913 if (*p
!= ':' && *p
!= '-')
3924 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3929 p1
= strchr(p
, sep
);
3935 if (len
> buf_size
- 1)
3937 memcpy(buf
, p
, len
);
3944 int parse_host_src_port(struct sockaddr_in
*haddr
,
3945 struct sockaddr_in
*saddr
,
3946 const char *input_str
)
3948 char *str
= strdup(input_str
);
3949 char *host_str
= str
;
3951 const char *src_str2
;
3955 * Chop off any extra arguments at the end of the string which
3956 * would start with a comma, then fill in the src port information
3957 * if it was provided else use the "any address" and "any port".
3959 if ((ptr
= strchr(str
,',')))
3962 if ((src_str
= strchr(input_str
,'@'))) {
3967 if (parse_host_port(haddr
, host_str
) < 0)
3971 if (!src_str
|| *src_str
== '\0')
3974 if (parse_host_port(saddr
, src_str2
) < 0)
3985 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3993 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3995 saddr
->sin_family
= AF_INET
;
3996 if (buf
[0] == '\0') {
3997 saddr
->sin_addr
.s_addr
= 0;
3999 if (isdigit(buf
[0])) {
4000 if (!inet_aton(buf
, &saddr
->sin_addr
))
4003 if ((he
= gethostbyname(buf
)) == NULL
)
4005 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4008 port
= strtol(p
, (char **)&r
, 0);
4011 saddr
->sin_port
= htons(port
);
4016 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4021 len
= MIN(108, strlen(str
));
4022 p
= strchr(str
, ',');
4024 len
= MIN(len
, p
- str
);
4026 memset(uaddr
, 0, sizeof(*uaddr
));
4028 uaddr
->sun_family
= AF_UNIX
;
4029 memcpy(uaddr
->sun_path
, str
, len
);
4035 /* find or alloc a new VLAN */
4036 VLANState
*qemu_find_vlan(int id
)
4038 VLANState
**pvlan
, *vlan
;
4039 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4043 vlan
= qemu_mallocz(sizeof(VLANState
));
4048 pvlan
= &first_vlan
;
4049 while (*pvlan
!= NULL
)
4050 pvlan
= &(*pvlan
)->next
;
4055 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4056 IOReadHandler
*fd_read
,
4057 IOCanRWHandler
*fd_can_read
,
4060 VLANClientState
*vc
, **pvc
;
4061 vc
= qemu_mallocz(sizeof(VLANClientState
));
4064 vc
->fd_read
= fd_read
;
4065 vc
->fd_can_read
= fd_can_read
;
4066 vc
->opaque
= opaque
;
4070 pvc
= &vlan
->first_client
;
4071 while (*pvc
!= NULL
)
4072 pvc
= &(*pvc
)->next
;
4077 void qemu_del_vlan_client(VLANClientState
*vc
)
4079 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4081 while (*pvc
!= NULL
)
4087 pvc
= &(*pvc
)->next
;
4090 int qemu_can_send_packet(VLANClientState
*vc1
)
4092 VLANState
*vlan
= vc1
->vlan
;
4093 VLANClientState
*vc
;
4095 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4097 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4104 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4106 VLANState
*vlan
= vc1
->vlan
;
4107 VLANClientState
*vc
;
4110 printf("vlan %d send:\n", vlan
->id
);
4111 hex_dump(stdout
, buf
, size
);
4113 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4115 vc
->fd_read(vc
->opaque
, buf
, size
);
4120 #if defined(CONFIG_SLIRP)
4122 /* slirp network adapter */
4124 static int slirp_inited
;
4125 static VLANClientState
*slirp_vc
;
4127 int slirp_can_output(void)
4129 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4132 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4135 printf("slirp output:\n");
4136 hex_dump(stdout
, pkt
, pkt_len
);
4140 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4143 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4146 printf("slirp input:\n");
4147 hex_dump(stdout
, buf
, size
);
4149 slirp_input(buf
, size
);
4152 static int net_slirp_init(VLANState
*vlan
)
4154 if (!slirp_inited
) {
4158 slirp_vc
= qemu_new_vlan_client(vlan
,
4159 slirp_receive
, NULL
, NULL
);
4160 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4164 static void net_slirp_redir(const char *redir_str
)
4169 struct in_addr guest_addr
;
4170 int host_port
, guest_port
;
4172 if (!slirp_inited
) {
4178 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4180 if (!strcmp(buf
, "tcp")) {
4182 } else if (!strcmp(buf
, "udp")) {
4188 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4190 host_port
= strtol(buf
, &r
, 0);
4194 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4196 if (buf
[0] == '\0') {
4197 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4199 if (!inet_aton(buf
, &guest_addr
))
4202 guest_port
= strtol(p
, &r
, 0);
4206 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4207 fprintf(stderr
, "qemu: could not set up redirection\n");
4212 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4220 static void erase_dir(char *dir_name
)
4224 char filename
[1024];
4226 /* erase all the files in the directory */
4227 if ((d
= opendir(dir_name
)) != 0) {
4232 if (strcmp(de
->d_name
, ".") != 0 &&
4233 strcmp(de
->d_name
, "..") != 0) {
4234 snprintf(filename
, sizeof(filename
), "%s/%s",
4235 smb_dir
, de
->d_name
);
4236 if (unlink(filename
) != 0) /* is it a directory? */
4237 erase_dir(filename
);
4245 /* automatic user mode samba server configuration */
4246 static void smb_exit(void)
4251 /* automatic user mode samba server configuration */
4252 static void net_slirp_smb(const char *exported_dir
)
4254 char smb_conf
[1024];
4255 char smb_cmdline
[1024];
4258 if (!slirp_inited
) {
4263 /* XXX: better tmp dir construction */
4264 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4265 if (mkdir(smb_dir
, 0700) < 0) {
4266 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4269 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4271 f
= fopen(smb_conf
, "w");
4273 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4280 "socket address=127.0.0.1\n"
4281 "pid directory=%s\n"
4282 "lock directory=%s\n"
4283 "log file=%s/log.smbd\n"
4284 "smb passwd file=%s/smbpasswd\n"
4285 "security = share\n"
4300 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4301 SMBD_COMMAND
, smb_conf
);
4303 slirp_add_exec(0, smb_cmdline
, 4, 139);
4306 #endif /* !defined(_WIN32) */
4307 void do_info_slirp(void)
4312 #endif /* CONFIG_SLIRP */
4314 #if !defined(_WIN32)
4316 typedef struct TAPState
{
4317 VLANClientState
*vc
;
4319 char down_script
[1024];
4322 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4324 TAPState
*s
= opaque
;
4327 ret
= write(s
->fd
, buf
, size
);
4328 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4335 static void tap_send(void *opaque
)
4337 TAPState
*s
= opaque
;
4344 sbuf
.maxlen
= sizeof(buf
);
4346 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4348 size
= read(s
->fd
, buf
, sizeof(buf
));
4351 qemu_send_packet(s
->vc
, buf
, size
);
4357 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4361 s
= qemu_mallocz(sizeof(TAPState
));
4365 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4366 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4367 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4371 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4372 static int tap_open(char *ifname
, int ifname_size
)
4378 TFR(fd
= open("/dev/tap", O_RDWR
));
4380 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4385 dev
= devname(s
.st_rdev
, S_IFCHR
);
4386 pstrcpy(ifname
, ifname_size
, dev
);
4388 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4391 #elif defined(__sun__)
4392 #define TUNNEWPPA (('T'<<16) | 0x0001)
4394 * Allocate TAP device, returns opened fd.
4395 * Stores dev name in the first arg(must be large enough).
4397 int tap_alloc(char *dev
, size_t dev_size
)
4399 int tap_fd
, if_fd
, ppa
= -1;
4400 static int ip_fd
= 0;
4403 static int arp_fd
= 0;
4404 int ip_muxid
, arp_muxid
;
4405 struct strioctl strioc_if
, strioc_ppa
;
4406 int link_type
= I_PLINK
;;
4408 char actual_name
[32] = "";
4410 memset(&ifr
, 0x0, sizeof(ifr
));
4414 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4418 /* Check if IP device was opened */
4422 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4424 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4428 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4430 syslog(LOG_ERR
, "Can't open /dev/tap");
4434 /* Assign a new PPA and get its unit number. */
4435 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4436 strioc_ppa
.ic_timout
= 0;
4437 strioc_ppa
.ic_len
= sizeof(ppa
);
4438 strioc_ppa
.ic_dp
= (char *)&ppa
;
4439 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4440 syslog (LOG_ERR
, "Can't assign new interface");
4442 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4444 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4447 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4448 syslog(LOG_ERR
, "Can't push IP module");
4452 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4453 syslog(LOG_ERR
, "Can't get flags\n");
4455 snprintf (actual_name
, 32, "tap%d", ppa
);
4456 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4459 /* Assign ppa according to the unit number returned by tun device */
4461 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4462 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4463 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4464 syslog (LOG_ERR
, "Can't get flags\n");
4465 /* Push arp module to if_fd */
4466 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4467 syslog (LOG_ERR
, "Can't push ARP module (2)");
4469 /* Push arp module to ip_fd */
4470 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4471 syslog (LOG_ERR
, "I_POP failed\n");
4472 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4473 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4475 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4477 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4479 /* Set ifname to arp */
4480 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4481 strioc_if
.ic_timout
= 0;
4482 strioc_if
.ic_len
= sizeof(ifr
);
4483 strioc_if
.ic_dp
= (char *)&ifr
;
4484 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4485 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4488 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4489 syslog(LOG_ERR
, "Can't link TAP device to IP");
4493 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4494 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4498 memset(&ifr
, 0x0, sizeof(ifr
));
4499 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4500 ifr
.lifr_ip_muxid
= ip_muxid
;
4501 ifr
.lifr_arp_muxid
= arp_muxid
;
4503 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4505 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4506 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4507 syslog (LOG_ERR
, "Can't set multiplexor id");
4510 snprintf(dev
, dev_size
, "tap%d", ppa
);
4514 static int tap_open(char *ifname
, int ifname_size
)
4518 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4519 fprintf(stderr
, "Cannot allocate TAP device\n");
4522 pstrcpy(ifname
, ifname_size
, dev
);
4523 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4527 static int tap_open(char *ifname
, int ifname_size
)
4532 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4534 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4537 memset(&ifr
, 0, sizeof(ifr
));
4538 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4539 if (ifname
[0] != '\0')
4540 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4542 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4543 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4545 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4549 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4550 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4555 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4561 /* try to launch network script */
4565 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4566 for (i
= 0; i
< open_max
; i
++)
4567 if (i
!= STDIN_FILENO
&&
4568 i
!= STDOUT_FILENO
&&
4569 i
!= STDERR_FILENO
&&
4574 *parg
++ = (char *)setup_script
;
4575 *parg
++ = (char *)ifname
;
4577 execv(setup_script
, args
);
4580 while (waitpid(pid
, &status
, 0) != pid
);
4581 if (!WIFEXITED(status
) ||
4582 WEXITSTATUS(status
) != 0) {
4583 fprintf(stderr
, "%s: could not launch network script\n",
4591 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4592 const char *setup_script
, const char *down_script
)
4598 if (ifname1
!= NULL
)
4599 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4602 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4606 if (!setup_script
|| !strcmp(setup_script
, "no"))
4608 if (setup_script
[0] != '\0') {
4609 if (launch_script(setup_script
, ifname
, fd
))
4612 s
= net_tap_fd_init(vlan
, fd
);
4615 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4616 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4617 if (down_script
&& strcmp(down_script
, "no"))
4618 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4622 #endif /* !_WIN32 */
4624 #if defined(CONFIG_VDE)
4625 typedef struct VDEState
{
4626 VLANClientState
*vc
;
4630 static void vde_to_qemu(void *opaque
)
4632 VDEState
*s
= opaque
;
4636 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4638 qemu_send_packet(s
->vc
, buf
, size
);
4642 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4644 VDEState
*s
= opaque
;
4647 ret
= vde_send(s
->vde
, buf
, size
, 0);
4648 if (ret
< 0 && errno
== EINTR
) {
4655 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4656 const char *group
, int mode
)
4659 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4660 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4662 struct vde_open_args args
= {
4664 .group
= init_group
,
4668 s
= qemu_mallocz(sizeof(VDEState
));
4671 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4676 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4677 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4678 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4679 sock
, vde_datafd(s
->vde
));
4684 /* network connection */
4685 typedef struct NetSocketState
{
4686 VLANClientState
*vc
;
4688 int state
; /* 0 = getting length, 1 = getting data */
4692 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4695 typedef struct NetSocketListenState
{
4698 } NetSocketListenState
;
4700 /* XXX: we consider we can send the whole packet without blocking */
4701 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4703 NetSocketState
*s
= opaque
;
4707 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4708 send_all(s
->fd
, buf
, size
);
4711 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4713 NetSocketState
*s
= opaque
;
4714 sendto(s
->fd
, buf
, size
, 0,
4715 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4718 static void net_socket_send(void *opaque
)
4720 NetSocketState
*s
= opaque
;
4725 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4727 err
= socket_error();
4728 if (err
!= EWOULDBLOCK
)
4730 } else if (size
== 0) {
4731 /* end of connection */
4733 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4739 /* reassemble a packet from the network */
4745 memcpy(s
->buf
+ s
->index
, buf
, l
);
4749 if (s
->index
== 4) {
4751 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4757 l
= s
->packet_len
- s
->index
;
4760 memcpy(s
->buf
+ s
->index
, buf
, l
);
4764 if (s
->index
>= s
->packet_len
) {
4765 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4774 static void net_socket_send_dgram(void *opaque
)
4776 NetSocketState
*s
= opaque
;
4779 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4783 /* end of connection */
4784 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4787 qemu_send_packet(s
->vc
, s
->buf
, size
);
4790 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4795 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4796 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4797 inet_ntoa(mcastaddr
->sin_addr
),
4798 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4802 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4804 perror("socket(PF_INET, SOCK_DGRAM)");
4809 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4810 (const char *)&val
, sizeof(val
));
4812 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4816 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4822 /* Add host to multicast group */
4823 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4824 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4826 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4827 (const char *)&imr
, sizeof(struct ip_mreq
));
4829 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4833 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4835 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4836 (const char *)&val
, sizeof(val
));
4838 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4842 socket_set_nonblock(fd
);
4850 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4853 struct sockaddr_in saddr
;
4855 socklen_t saddr_len
;
4858 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4859 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4860 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4864 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4866 if (saddr
.sin_addr
.s_addr
==0) {
4867 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4871 /* clone dgram socket */
4872 newfd
= net_socket_mcast_create(&saddr
);
4874 /* error already reported by net_socket_mcast_create() */
4878 /* clone newfd to fd, close newfd */
4883 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4884 fd
, strerror(errno
));
4889 s
= qemu_mallocz(sizeof(NetSocketState
));
4894 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4895 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4897 /* mcast: save bound address as dst */
4898 if (is_connected
) s
->dgram_dst
=saddr
;
4900 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4901 "socket: fd=%d (%s mcast=%s:%d)",
4902 fd
, is_connected
? "cloned" : "",
4903 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4907 static void net_socket_connect(void *opaque
)
4909 NetSocketState
*s
= opaque
;
4910 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4913 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4917 s
= qemu_mallocz(sizeof(NetSocketState
));
4921 s
->vc
= qemu_new_vlan_client(vlan
,
4922 net_socket_receive
, NULL
, s
);
4923 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4924 "socket: fd=%d", fd
);
4926 net_socket_connect(s
);
4928 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4933 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4936 int so_type
=-1, optlen
=sizeof(so_type
);
4938 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4939 (socklen_t
*)&optlen
)< 0) {
4940 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4945 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4947 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4949 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4950 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4951 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4956 static void net_socket_accept(void *opaque
)
4958 NetSocketListenState
*s
= opaque
;
4960 struct sockaddr_in saddr
;
4965 len
= sizeof(saddr
);
4966 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4967 if (fd
< 0 && errno
!= EINTR
) {
4969 } else if (fd
>= 0) {
4973 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4977 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4978 "socket: connection from %s:%d",
4979 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4983 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4985 NetSocketListenState
*s
;
4987 struct sockaddr_in saddr
;
4989 if (parse_host_port(&saddr
, host_str
) < 0)
4992 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4996 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5001 socket_set_nonblock(fd
);
5003 /* allow fast reuse */
5005 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5007 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5012 ret
= listen(fd
, 0);
5019 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5023 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5026 int fd
, connected
, ret
, err
;
5027 struct sockaddr_in saddr
;
5029 if (parse_host_port(&saddr
, host_str
) < 0)
5032 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5037 socket_set_nonblock(fd
);
5041 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5043 err
= socket_error();
5044 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5045 } else if (err
== EINPROGRESS
) {
5048 } else if (err
== WSAEALREADY
) {
5061 s
= net_socket_fd_init(vlan
, fd
, connected
);
5064 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5065 "socket: connect to %s:%d",
5066 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5070 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5074 struct sockaddr_in saddr
;
5076 if (parse_host_port(&saddr
, host_str
) < 0)
5080 fd
= net_socket_mcast_create(&saddr
);
5084 s
= net_socket_fd_init(vlan
, fd
, 0);
5088 s
->dgram_dst
= saddr
;
5090 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5091 "socket: mcast=%s:%d",
5092 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5097 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5102 while (*p
!= '\0' && *p
!= '=') {
5103 if (q
&& (q
- buf
) < buf_size
- 1)
5113 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5118 while (*p
!= '\0') {
5120 if (*(p
+ 1) != ',')
5124 if (q
&& (q
- buf
) < buf_size
- 1)
5134 static int get_param_value(char *buf
, int buf_size
,
5135 const char *tag
, const char *str
)
5142 p
= get_opt_name(option
, sizeof(option
), p
);
5146 if (!strcmp(tag
, option
)) {
5147 (void)get_opt_value(buf
, buf_size
, p
);
5150 p
= get_opt_value(NULL
, 0, p
);
5159 static int check_params(char *buf
, int buf_size
,
5160 const char * const *params
, const char *str
)
5167 p
= get_opt_name(buf
, buf_size
, p
);
5171 for(i
= 0; params
[i
] != NULL
; i
++)
5172 if (!strcmp(params
[i
], buf
))
5174 if (params
[i
] == NULL
)
5176 p
= get_opt_value(NULL
, 0, p
);
5184 static int net_client_init(const char *device
, const char *p
)
5191 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5192 vlan_id
= strtol(buf
, NULL
, 0);
5194 vlan
= qemu_find_vlan(vlan_id
);
5196 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5199 if (!strcmp(device
, "nic")) {
5203 if (nb_nics
>= MAX_NICS
) {
5204 fprintf(stderr
, "Too Many NICs\n");
5207 nd
= &nd_table
[nb_nics
];
5208 macaddr
= nd
->macaddr
;
5214 macaddr
[5] = 0x56 + nb_nics
;
5216 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5217 if (parse_macaddr(macaddr
, buf
) < 0) {
5218 fprintf(stderr
, "invalid syntax for ethernet address\n");
5222 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5223 nd
->model
= strdup(buf
);
5227 vlan
->nb_guest_devs
++;
5230 if (!strcmp(device
, "none")) {
5231 /* does nothing. It is needed to signal that no network cards
5236 if (!strcmp(device
, "user")) {
5237 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5238 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5240 vlan
->nb_host_devs
++;
5241 ret
= net_slirp_init(vlan
);
5245 if (!strcmp(device
, "tap")) {
5247 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5248 fprintf(stderr
, "tap: no interface name\n");
5251 vlan
->nb_host_devs
++;
5252 ret
= tap_win32_init(vlan
, ifname
);
5255 if (!strcmp(device
, "tap")) {
5257 char setup_script
[1024], down_script
[1024];
5259 vlan
->nb_host_devs
++;
5260 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5261 fd
= strtol(buf
, NULL
, 0);
5262 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5264 if (net_tap_fd_init(vlan
, fd
))
5267 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5270 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5271 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5273 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5274 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5276 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5280 if (!strcmp(device
, "socket")) {
5281 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5283 fd
= strtol(buf
, NULL
, 0);
5285 if (net_socket_fd_init(vlan
, fd
, 1))
5287 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5288 ret
= net_socket_listen_init(vlan
, buf
);
5289 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5290 ret
= net_socket_connect_init(vlan
, buf
);
5291 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5292 ret
= net_socket_mcast_init(vlan
, buf
);
5294 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5297 vlan
->nb_host_devs
++;
5300 if (!strcmp(device
, "vde")) {
5301 char vde_sock
[1024], vde_group
[512];
5302 int vde_port
, vde_mode
;
5303 vlan
->nb_host_devs
++;
5304 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5307 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5308 vde_port
= strtol(buf
, NULL
, 10);
5312 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5313 vde_group
[0] = '\0';
5315 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5316 vde_mode
= strtol(buf
, NULL
, 8);
5320 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5324 fprintf(stderr
, "Unknown network device: %s\n", device
);
5328 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5334 static int net_client_parse(const char *str
)
5342 while (*p
!= '\0' && *p
!= ',') {
5343 if ((q
- device
) < sizeof(device
) - 1)
5351 return net_client_init(device
, p
);
5354 void do_info_network(void)
5357 VLANClientState
*vc
;
5359 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5360 term_printf("VLAN %d devices:\n", vlan
->id
);
5361 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5362 term_printf(" %s\n", vc
->info_str
);
5366 /***********************************************************/
5367 /* Bluetooth support */
5370 static struct HCIInfo
*hci_table
[MAX_NICS
];
5371 static struct bt_vlan_s
{
5372 struct bt_scatternet_s net
;
5374 struct bt_vlan_s
*next
;
5377 /* find or alloc a new bluetooth "VLAN" */
5378 static struct bt_scatternet_s
*qemu_find_bt_vlan(int id
)
5380 struct bt_vlan_s
**pvlan
, *vlan
;
5381 for (vlan
= first_bt_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5385 vlan
= qemu_mallocz(sizeof(struct bt_vlan_s
));
5387 pvlan
= &first_bt_vlan
;
5388 while (*pvlan
!= NULL
)
5389 pvlan
= &(*pvlan
)->next
;
5394 static void null_hci_send(struct HCIInfo
*hci
, const uint8_t *data
, int len
)
5398 static int null_hci_addr_set(struct HCIInfo
*hci
, const uint8_t *bd_addr
)
5403 static struct HCIInfo null_hci
= {
5404 .cmd_send
= null_hci_send
,
5405 .sco_send
= null_hci_send
,
5406 .acl_send
= null_hci_send
,
5407 .bdaddr_set
= null_hci_addr_set
,
5410 struct HCIInfo
*qemu_next_hci(void)
5412 if (cur_hci
== nb_hcis
)
5415 return hci_table
[cur_hci
++];
5418 /***********************************************************/
5419 /* QEMU Block devices */
5421 #define HD_ALIAS "index=%d,media=disk"
5423 #define CDROM_ALIAS "index=1,media=cdrom"
5425 #define CDROM_ALIAS "index=2,media=cdrom"
5427 #define FD_ALIAS "index=%d,if=floppy"
5428 #define PFLASH_ALIAS "if=pflash"
5429 #define MTD_ALIAS "if=mtd"
5430 #define SD_ALIAS "index=0,if=sd"
5432 static int drive_add(const char *file
, const char *fmt
, ...)
5436 if (nb_drives_opt
>= MAX_DRIVES
) {
5437 fprintf(stderr
, "qemu: too many drives\n");
5441 drives_opt
[nb_drives_opt
].file
= file
;
5443 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5444 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5447 return nb_drives_opt
++;
5450 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5454 /* seek interface, bus and unit */
5456 for (index
= 0; index
< nb_drives
; index
++)
5457 if (drives_table
[index
].type
== type
&&
5458 drives_table
[index
].bus
== bus
&&
5459 drives_table
[index
].unit
== unit
)
5465 int drive_get_max_bus(BlockInterfaceType type
)
5471 for (index
= 0; index
< nb_drives
; index
++) {
5472 if(drives_table
[index
].type
== type
&&
5473 drives_table
[index
].bus
> max_bus
)
5474 max_bus
= drives_table
[index
].bus
;
5479 static void bdrv_format_print(void *opaque
, const char *name
)
5481 fprintf(stderr
, " %s", name
);
5484 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5485 QEMUMachine
*machine
)
5490 const char *mediastr
= "";
5491 BlockInterfaceType type
;
5492 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5493 int bus_id
, unit_id
;
5494 int cyls
, heads
, secs
, translation
;
5495 BlockDriverState
*bdrv
;
5496 BlockDriver
*drv
= NULL
;
5501 char *str
= arg
->opt
;
5502 static const char * const params
[] = { "bus", "unit", "if", "index",
5503 "cyls", "heads", "secs", "trans",
5504 "media", "snapshot", "file",
5505 "cache", "format", NULL
};
5507 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5508 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5514 cyls
= heads
= secs
= 0;
5517 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5521 if (machine
->use_scsi
) {
5523 max_devs
= MAX_SCSI_DEVS
;
5524 pstrcpy(devname
, sizeof(devname
), "scsi");
5527 max_devs
= MAX_IDE_DEVS
;
5528 pstrcpy(devname
, sizeof(devname
), "ide");
5532 /* extract parameters */
5534 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5535 bus_id
= strtol(buf
, NULL
, 0);
5537 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5542 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5543 unit_id
= strtol(buf
, NULL
, 0);
5545 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5550 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5551 pstrcpy(devname
, sizeof(devname
), buf
);
5552 if (!strcmp(buf
, "ide")) {
5554 max_devs
= MAX_IDE_DEVS
;
5555 } else if (!strcmp(buf
, "scsi")) {
5557 max_devs
= MAX_SCSI_DEVS
;
5558 } else if (!strcmp(buf
, "floppy")) {
5561 } else if (!strcmp(buf
, "pflash")) {
5564 } else if (!strcmp(buf
, "mtd")) {
5567 } else if (!strcmp(buf
, "sd")) {
5571 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5576 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5577 index
= strtol(buf
, NULL
, 0);
5579 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5584 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5585 cyls
= strtol(buf
, NULL
, 0);
5588 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5589 heads
= strtol(buf
, NULL
, 0);
5592 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5593 secs
= strtol(buf
, NULL
, 0);
5596 if (cyls
|| heads
|| secs
) {
5597 if (cyls
< 1 || cyls
> 16383) {
5598 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5601 if (heads
< 1 || heads
> 16) {
5602 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5605 if (secs
< 1 || secs
> 63) {
5606 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5611 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5614 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5618 if (!strcmp(buf
, "none"))
5619 translation
= BIOS_ATA_TRANSLATION_NONE
;
5620 else if (!strcmp(buf
, "lba"))
5621 translation
= BIOS_ATA_TRANSLATION_LBA
;
5622 else if (!strcmp(buf
, "auto"))
5623 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5625 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5630 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5631 if (!strcmp(buf
, "disk")) {
5633 } else if (!strcmp(buf
, "cdrom")) {
5634 if (cyls
|| secs
|| heads
) {
5636 "qemu: '%s' invalid physical CHS format\n", str
);
5639 media
= MEDIA_CDROM
;
5641 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5646 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5647 if (!strcmp(buf
, "on"))
5649 else if (!strcmp(buf
, "off"))
5652 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5657 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5658 if (!strcmp(buf
, "off"))
5660 else if (!strcmp(buf
, "on"))
5663 fprintf(stderr
, "qemu: invalid cache option\n");
5668 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5669 if (strcmp(buf
, "?") == 0) {
5670 fprintf(stderr
, "qemu: Supported formats:");
5671 bdrv_iterate_format(bdrv_format_print
, NULL
);
5672 fprintf(stderr
, "\n");
5675 drv
= bdrv_find_format(buf
);
5677 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5682 if (arg
->file
== NULL
)
5683 get_param_value(file
, sizeof(file
), "file", str
);
5685 pstrcpy(file
, sizeof(file
), arg
->file
);
5687 /* compute bus and unit according index */
5690 if (bus_id
!= 0 || unit_id
!= -1) {
5692 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5700 unit_id
= index
% max_devs
;
5701 bus_id
= index
/ max_devs
;
5705 /* if user doesn't specify a unit_id,
5706 * try to find the first free
5709 if (unit_id
== -1) {
5711 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5713 if (max_devs
&& unit_id
>= max_devs
) {
5714 unit_id
-= max_devs
;
5722 if (max_devs
&& unit_id
>= max_devs
) {
5723 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5724 str
, unit_id
, max_devs
- 1);
5729 * ignore multiple definitions
5732 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5737 if (type
== IF_IDE
|| type
== IF_SCSI
)
5738 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5740 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5741 devname
, bus_id
, mediastr
, unit_id
);
5743 snprintf(buf
, sizeof(buf
), "%s%s%i",
5744 devname
, mediastr
, unit_id
);
5745 bdrv
= bdrv_new(buf
);
5746 drives_table
[nb_drives
].bdrv
= bdrv
;
5747 drives_table
[nb_drives
].type
= type
;
5748 drives_table
[nb_drives
].bus
= bus_id
;
5749 drives_table
[nb_drives
].unit
= unit_id
;
5758 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5759 bdrv_set_translation_hint(bdrv
, translation
);
5763 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5768 /* FIXME: This isn't really a floppy, but it's a reasonable
5771 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5781 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5783 bdrv_flags
|= BDRV_O_DIRECT
;
5784 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5785 fprintf(stderr
, "qemu: could not open disk image %s\n",
5792 /***********************************************************/
5795 static USBPort
*used_usb_ports
;
5796 static USBPort
*free_usb_ports
;
5798 /* ??? Maybe change this to register a hub to keep track of the topology. */
5799 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5800 usb_attachfn attach
)
5802 port
->opaque
= opaque
;
5803 port
->index
= index
;
5804 port
->attach
= attach
;
5805 port
->next
= free_usb_ports
;
5806 free_usb_ports
= port
;
5809 int usb_device_add_dev(USBDevice
*dev
)
5813 /* Find a USB port to add the device to. */
5814 port
= free_usb_ports
;
5818 /* Create a new hub and chain it on. */
5819 free_usb_ports
= NULL
;
5820 port
->next
= used_usb_ports
;
5821 used_usb_ports
= port
;
5823 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5824 usb_attach(port
, hub
);
5825 port
= free_usb_ports
;
5828 free_usb_ports
= port
->next
;
5829 port
->next
= used_usb_ports
;
5830 used_usb_ports
= port
;
5831 usb_attach(port
, dev
);
5835 static int usb_device_add(const char *devname
)
5840 if (!free_usb_ports
)
5843 if (strstart(devname
, "host:", &p
)) {
5844 dev
= usb_host_device_open(p
);
5845 } else if (!strcmp(devname
, "mouse")) {
5846 dev
= usb_mouse_init();
5847 } else if (!strcmp(devname
, "tablet")) {
5848 dev
= usb_tablet_init();
5849 } else if (!strcmp(devname
, "keyboard")) {
5850 dev
= usb_keyboard_init();
5851 } else if (strstart(devname
, "disk:", &p
)) {
5852 dev
= usb_msd_init(p
);
5853 } else if (!strcmp(devname
, "wacom-tablet")) {
5854 dev
= usb_wacom_init();
5855 } else if (strstart(devname
, "serial:", &p
)) {
5856 dev
= usb_serial_init(p
);
5857 #ifdef CONFIG_BRLAPI
5858 } else if (!strcmp(devname
, "braille")) {
5859 dev
= usb_baum_init();
5861 } else if (strstart(devname
, "net:", &p
)) {
5864 if (net_client_init("nic", p
) < 0)
5866 nd_table
[nic
].model
= "usb";
5867 dev
= usb_net_init(&nd_table
[nic
]);
5874 return usb_device_add_dev(dev
);
5877 int usb_device_del_addr(int bus_num
, int addr
)
5883 if (!used_usb_ports
)
5889 lastp
= &used_usb_ports
;
5890 port
= used_usb_ports
;
5891 while (port
&& port
->dev
->addr
!= addr
) {
5892 lastp
= &port
->next
;
5900 *lastp
= port
->next
;
5901 usb_attach(port
, NULL
);
5902 dev
->handle_destroy(dev
);
5903 port
->next
= free_usb_ports
;
5904 free_usb_ports
= port
;
5908 static int usb_device_del(const char *devname
)
5913 if (strstart(devname
, "host:", &p
))
5914 return usb_host_device_close(p
);
5916 if (!used_usb_ports
)
5919 p
= strchr(devname
, '.');
5922 bus_num
= strtoul(devname
, NULL
, 0);
5923 addr
= strtoul(p
+ 1, NULL
, 0);
5925 return usb_device_del_addr(bus_num
, addr
);
5928 void do_usb_add(const char *devname
)
5930 usb_device_add(devname
);
5933 void do_usb_del(const char *devname
)
5935 usb_device_del(devname
);
5942 const char *speed_str
;
5945 term_printf("USB support not enabled\n");
5949 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5953 switch(dev
->speed
) {
5957 case USB_SPEED_FULL
:
5960 case USB_SPEED_HIGH
:
5967 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5968 0, dev
->addr
, speed_str
, dev
->devname
);
5972 /***********************************************************/
5973 /* PCMCIA/Cardbus */
5975 static struct pcmcia_socket_entry_s
{
5976 struct pcmcia_socket_s
*socket
;
5977 struct pcmcia_socket_entry_s
*next
;
5978 } *pcmcia_sockets
= 0;
5980 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5982 struct pcmcia_socket_entry_s
*entry
;
5984 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5985 entry
->socket
= socket
;
5986 entry
->next
= pcmcia_sockets
;
5987 pcmcia_sockets
= entry
;
5990 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5992 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5994 ptr
= &pcmcia_sockets
;
5995 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5996 if (entry
->socket
== socket
) {
6002 void pcmcia_info(void)
6004 struct pcmcia_socket_entry_s
*iter
;
6005 if (!pcmcia_sockets
)
6006 term_printf("No PCMCIA sockets\n");
6008 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6009 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6010 iter
->socket
->attached
? iter
->socket
->card_string
:
6014 /***********************************************************/
6017 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6021 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6025 static void dumb_refresh(DisplayState
*ds
)
6027 #if defined(CONFIG_SDL)
6032 static void dumb_display_init(DisplayState
*ds
)
6037 ds
->dpy_update
= dumb_update
;
6038 ds
->dpy_resize
= dumb_resize
;
6039 ds
->dpy_refresh
= dumb_refresh
;
6040 ds
->gui_timer_interval
= 500;
6044 /***********************************************************/
6047 #define MAX_IO_HANDLERS 64
6049 typedef struct IOHandlerRecord
{
6051 IOCanRWHandler
*fd_read_poll
;
6053 IOHandler
*fd_write
;
6056 /* temporary data */
6058 struct IOHandlerRecord
*next
;
6061 static IOHandlerRecord
*first_io_handler
;
6063 /* XXX: fd_read_poll should be suppressed, but an API change is
6064 necessary in the character devices to suppress fd_can_read(). */
6065 int qemu_set_fd_handler2(int fd
,
6066 IOCanRWHandler
*fd_read_poll
,
6068 IOHandler
*fd_write
,
6071 IOHandlerRecord
**pioh
, *ioh
;
6073 if (!fd_read
&& !fd_write
) {
6074 pioh
= &first_io_handler
;
6079 if (ioh
->fd
== fd
) {
6086 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6090 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6093 ioh
->next
= first_io_handler
;
6094 first_io_handler
= ioh
;
6097 ioh
->fd_read_poll
= fd_read_poll
;
6098 ioh
->fd_read
= fd_read
;
6099 ioh
->fd_write
= fd_write
;
6100 ioh
->opaque
= opaque
;
6106 int qemu_set_fd_handler(int fd
,
6108 IOHandler
*fd_write
,
6111 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6114 /***********************************************************/
6115 /* Polling handling */
6117 typedef struct PollingEntry
{
6120 struct PollingEntry
*next
;
6123 static PollingEntry
*first_polling_entry
;
6125 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6127 PollingEntry
**ppe
, *pe
;
6128 pe
= qemu_mallocz(sizeof(PollingEntry
));
6132 pe
->opaque
= opaque
;
6133 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6138 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6140 PollingEntry
**ppe
, *pe
;
6141 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6143 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6152 /***********************************************************/
6153 /* Wait objects support */
6154 typedef struct WaitObjects
{
6156 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6157 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6158 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6161 static WaitObjects wait_objects
= {0};
6163 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6165 WaitObjects
*w
= &wait_objects
;
6167 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6169 w
->events
[w
->num
] = handle
;
6170 w
->func
[w
->num
] = func
;
6171 w
->opaque
[w
->num
] = opaque
;
6176 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6179 WaitObjects
*w
= &wait_objects
;
6182 for (i
= 0; i
< w
->num
; i
++) {
6183 if (w
->events
[i
] == handle
)
6186 w
->events
[i
] = w
->events
[i
+ 1];
6187 w
->func
[i
] = w
->func
[i
+ 1];
6188 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6196 /***********************************************************/
6197 /* savevm/loadvm support */
6199 #define IO_BUF_SIZE 32768
6202 QEMUFilePutBufferFunc
*put_buffer
;
6203 QEMUFileGetBufferFunc
*get_buffer
;
6204 QEMUFileCloseFunc
*close
;
6205 QEMUFileRateLimit
*rate_limit
;
6208 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6211 int buf_size
; /* 0 when writing */
6212 uint8_t buf
[IO_BUF_SIZE
];
6215 typedef struct QEMUFileFD
6221 static void fd_put_notify(void *opaque
)
6223 QEMUFileFD
*s
= opaque
;
6225 /* Remove writable callback and do a put notify */
6226 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
6227 qemu_file_put_notify(s
->file
);
6230 static int fd_put_buffer(void *opaque
, const uint8_t *buf
,
6231 int64_t pos
, int size
)
6233 QEMUFileFD
*s
= opaque
;
6237 len
= write(s
->fd
, buf
, size
);
6238 } while (len
== -1 && errno
== EINTR
);
6243 /* When the fd becomes writable again, register a callback to do
6246 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, fd_put_notify
, s
);
6251 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6253 QEMUFileFD
*s
= opaque
;
6257 len
= read(s
->fd
, buf
, size
);
6258 } while (len
== -1 && errno
== EINTR
);
6266 static int fd_close(void *opaque
)
6268 QEMUFileFD
*s
= opaque
;
6273 QEMUFile
*qemu_fopen_fd(int fd
)
6275 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6281 s
->file
= qemu_fopen_ops(s
, fd_put_buffer
, fd_get_buffer
, fd_close
, NULL
);
6285 typedef struct QEMUFileStdio
6290 static void file_put_buffer(void *opaque
, const uint8_t *buf
,
6291 int64_t pos
, int size
)
6293 QEMUFileStdio
*s
= opaque
;
6294 fseek(s
->outfile
, pos
, SEEK_SET
);
6295 fwrite(buf
, 1, size
, s
->outfile
);
6298 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6300 QEMUFileStdio
*s
= opaque
;
6301 fseek(s
->outfile
, pos
, SEEK_SET
);
6302 return fread(buf
, 1, size
, s
->outfile
);
6305 static int file_close(void *opaque
)
6307 QEMUFileStdio
*s
= opaque
;
6313 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6317 s
= qemu_mallocz(sizeof(QEMUFileStdio
));
6321 s
->outfile
= fopen(filename
, mode
);
6325 if (!strcmp(mode
, "wb"))
6326 return qemu_fopen_ops(s
, file_put_buffer
, NULL
, file_close
, NULL
);
6327 else if (!strcmp(mode
, "rb"))
6328 return qemu_fopen_ops(s
, NULL
, file_get_buffer
, file_close
, NULL
);
6337 typedef struct QEMUFileBdrv
6339 BlockDriverState
*bs
;
6340 int64_t base_offset
;
6343 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
,
6344 int64_t pos
, int size
)
6346 QEMUFileBdrv
*s
= opaque
;
6347 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6350 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6352 QEMUFileBdrv
*s
= opaque
;
6353 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6356 static int bdrv_fclose(void *opaque
)
6358 QEMUFileBdrv
*s
= opaque
;
6363 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6367 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6372 s
->base_offset
= offset
;
6375 return qemu_fopen_ops(s
, bdrv_put_buffer
, NULL
, bdrv_fclose
, NULL
);
6377 return qemu_fopen_ops(s
, NULL
, bdrv_get_buffer
, bdrv_fclose
, NULL
);
6380 QEMUFile
*qemu_fopen_ops(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6381 QEMUFileGetBufferFunc
*get_buffer
,
6382 QEMUFileCloseFunc
*close
,
6383 QEMUFileRateLimit
*rate_limit
)
6387 f
= qemu_mallocz(sizeof(QEMUFile
));
6392 f
->put_buffer
= put_buffer
;
6393 f
->get_buffer
= get_buffer
;
6395 f
->rate_limit
= rate_limit
;
6400 void qemu_fflush(QEMUFile
*f
)
6405 if (f
->buf_index
> 0) {
6406 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6407 f
->buf_offset
+= f
->buf_index
;
6412 static void qemu_fill_buffer(QEMUFile
*f
)
6419 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6425 f
->buf_offset
+= len
;
6428 int qemu_fclose(QEMUFile
*f
)
6433 ret
= f
->close(f
->opaque
);
6438 void qemu_file_put_notify(QEMUFile
*f
)
6440 f
->put_buffer(f
->opaque
, NULL
, 0, 0);
6443 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6447 l
= IO_BUF_SIZE
- f
->buf_index
;
6450 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6454 if (f
->buf_index
>= IO_BUF_SIZE
)
6459 void qemu_put_byte(QEMUFile
*f
, int v
)
6461 f
->buf
[f
->buf_index
++] = v
;
6462 if (f
->buf_index
>= IO_BUF_SIZE
)
6466 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6472 l
= f
->buf_size
- f
->buf_index
;
6474 qemu_fill_buffer(f
);
6475 l
= f
->buf_size
- f
->buf_index
;
6481 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6486 return size1
- size
;
6489 int qemu_get_byte(QEMUFile
*f
)
6491 if (f
->buf_index
>= f
->buf_size
) {
6492 qemu_fill_buffer(f
);
6493 if (f
->buf_index
>= f
->buf_size
)
6496 return f
->buf
[f
->buf_index
++];
6499 int64_t qemu_ftell(QEMUFile
*f
)
6501 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6504 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6506 if (whence
== SEEK_SET
) {
6508 } else if (whence
== SEEK_CUR
) {
6509 pos
+= qemu_ftell(f
);
6511 /* SEEK_END not supported */
6514 if (f
->put_buffer
) {
6516 f
->buf_offset
= pos
;
6518 f
->buf_offset
= pos
;
6525 int qemu_file_rate_limit(QEMUFile
*f
)
6528 return f
->rate_limit(f
->opaque
);
6533 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6535 qemu_put_byte(f
, v
>> 8);
6536 qemu_put_byte(f
, v
);
6539 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6541 qemu_put_byte(f
, v
>> 24);
6542 qemu_put_byte(f
, v
>> 16);
6543 qemu_put_byte(f
, v
>> 8);
6544 qemu_put_byte(f
, v
);
6547 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6549 qemu_put_be32(f
, v
>> 32);
6550 qemu_put_be32(f
, v
);
6553 unsigned int qemu_get_be16(QEMUFile
*f
)
6556 v
= qemu_get_byte(f
) << 8;
6557 v
|= qemu_get_byte(f
);
6561 unsigned int qemu_get_be32(QEMUFile
*f
)
6564 v
= qemu_get_byte(f
) << 24;
6565 v
|= qemu_get_byte(f
) << 16;
6566 v
|= qemu_get_byte(f
) << 8;
6567 v
|= qemu_get_byte(f
);
6571 uint64_t qemu_get_be64(QEMUFile
*f
)
6574 v
= (uint64_t)qemu_get_be32(f
) << 32;
6575 v
|= qemu_get_be32(f
);
6579 typedef struct SaveStateEntry
{
6583 SaveStateHandler
*save_state
;
6584 LoadStateHandler
*load_state
;
6586 struct SaveStateEntry
*next
;
6589 static SaveStateEntry
*first_se
;
6591 /* TODO: Individual devices generally have very little idea about the rest
6592 of the system, so instance_id should be removed/replaced.
6593 Meanwhile pass -1 as instance_id if you do not already have a clearly
6594 distinguishing id for all instances of your device class. */
6595 int register_savevm(const char *idstr
,
6598 SaveStateHandler
*save_state
,
6599 LoadStateHandler
*load_state
,
6602 SaveStateEntry
*se
, **pse
;
6604 se
= qemu_malloc(sizeof(SaveStateEntry
));
6607 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6608 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6609 se
->version_id
= version_id
;
6610 se
->save_state
= save_state
;
6611 se
->load_state
= load_state
;
6612 se
->opaque
= opaque
;
6615 /* add at the end of list */
6617 while (*pse
!= NULL
) {
6618 if (instance_id
== -1
6619 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6620 && se
->instance_id
<= (*pse
)->instance_id
)
6621 se
->instance_id
= (*pse
)->instance_id
+ 1;
6622 pse
= &(*pse
)->next
;
6628 #define QEMU_VM_FILE_MAGIC 0x5145564d
6629 #define QEMU_VM_FILE_VERSION 0x00000002
6631 static int qemu_savevm_state(QEMUFile
*f
)
6635 int64_t cur_pos
, len_pos
, total_len_pos
;
6637 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6638 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6639 total_len_pos
= qemu_ftell(f
);
6640 qemu_put_be64(f
, 0); /* total size */
6642 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6643 if (se
->save_state
== NULL
)
6644 /* this one has a loader only, for backwards compatibility */
6648 len
= strlen(se
->idstr
);
6649 qemu_put_byte(f
, len
);
6650 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6652 qemu_put_be32(f
, se
->instance_id
);
6653 qemu_put_be32(f
, se
->version_id
);
6655 /* record size: filled later */
6656 len_pos
= qemu_ftell(f
);
6657 qemu_put_be32(f
, 0);
6658 se
->save_state(f
, se
->opaque
);
6660 /* fill record size */
6661 cur_pos
= qemu_ftell(f
);
6662 len
= cur_pos
- len_pos
- 4;
6663 qemu_fseek(f
, len_pos
, SEEK_SET
);
6664 qemu_put_be32(f
, len
);
6665 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6667 cur_pos
= qemu_ftell(f
);
6668 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6669 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6670 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6676 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6680 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6681 if (!strcmp(se
->idstr
, idstr
) &&
6682 instance_id
== se
->instance_id
)
6688 static int qemu_loadvm_state(QEMUFile
*f
)
6691 int len
, ret
, instance_id
, record_len
, version_id
;
6692 int64_t total_len
, end_pos
, cur_pos
;
6696 v
= qemu_get_be32(f
);
6697 if (v
!= QEMU_VM_FILE_MAGIC
)
6699 v
= qemu_get_be32(f
);
6700 if (v
!= QEMU_VM_FILE_VERSION
) {
6705 total_len
= qemu_get_be64(f
);
6706 end_pos
= total_len
+ qemu_ftell(f
);
6708 if (qemu_ftell(f
) >= end_pos
)
6710 len
= qemu_get_byte(f
);
6711 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6713 instance_id
= qemu_get_be32(f
);
6714 version_id
= qemu_get_be32(f
);
6715 record_len
= qemu_get_be32(f
);
6717 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6718 idstr
, instance_id
, version_id
, record_len
);
6720 cur_pos
= qemu_ftell(f
);
6721 se
= find_se(idstr
, instance_id
);
6723 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6724 instance_id
, idstr
);
6726 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6728 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6729 instance_id
, idstr
);
6732 /* always seek to exact end of record */
6733 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6740 /* device can contain snapshots */
6741 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6744 !bdrv_is_removable(bs
) &&
6745 !bdrv_is_read_only(bs
));
6748 /* device must be snapshots in order to have a reliable snapshot */
6749 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6752 !bdrv_is_removable(bs
) &&
6753 !bdrv_is_read_only(bs
));
6756 static BlockDriverState
*get_bs_snapshots(void)
6758 BlockDriverState
*bs
;
6762 return bs_snapshots
;
6763 for(i
= 0; i
<= nb_drives
; i
++) {
6764 bs
= drives_table
[i
].bdrv
;
6765 if (bdrv_can_snapshot(bs
))
6774 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6777 QEMUSnapshotInfo
*sn_tab
, *sn
;
6781 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6784 for(i
= 0; i
< nb_sns
; i
++) {
6786 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6796 void do_savevm(const char *name
)
6798 BlockDriverState
*bs
, *bs1
;
6799 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6800 int must_delete
, ret
, i
;
6801 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6803 int saved_vm_running
;
6810 bs
= get_bs_snapshots();
6812 term_printf("No block device can accept snapshots\n");
6816 /* ??? Should this occur after vm_stop? */
6819 saved_vm_running
= vm_running
;
6824 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6829 memset(sn
, 0, sizeof(*sn
));
6831 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6832 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6835 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6838 /* fill auxiliary fields */
6841 sn
->date_sec
= tb
.time
;
6842 sn
->date_nsec
= tb
.millitm
* 1000000;
6844 gettimeofday(&tv
, NULL
);
6845 sn
->date_sec
= tv
.tv_sec
;
6846 sn
->date_nsec
= tv
.tv_usec
* 1000;
6848 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6850 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6851 term_printf("Device %s does not support VM state snapshots\n",
6852 bdrv_get_device_name(bs
));
6856 /* save the VM state */
6857 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6859 term_printf("Could not open VM state file\n");
6862 ret
= qemu_savevm_state(f
);
6863 sn
->vm_state_size
= qemu_ftell(f
);
6866 term_printf("Error %d while writing VM\n", ret
);
6870 /* create the snapshots */
6872 for(i
= 0; i
< nb_drives
; i
++) {
6873 bs1
= drives_table
[i
].bdrv
;
6874 if (bdrv_has_snapshot(bs1
)) {
6876 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6878 term_printf("Error while deleting snapshot on '%s'\n",
6879 bdrv_get_device_name(bs1
));
6882 ret
= bdrv_snapshot_create(bs1
, sn
);
6884 term_printf("Error while creating snapshot on '%s'\n",
6885 bdrv_get_device_name(bs1
));
6891 if (saved_vm_running
)
6895 void do_loadvm(const char *name
)
6897 BlockDriverState
*bs
, *bs1
;
6898 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6901 int saved_vm_running
;
6903 bs
= get_bs_snapshots();
6905 term_printf("No block device supports snapshots\n");
6909 /* Flush all IO requests so they don't interfere with the new state. */
6912 saved_vm_running
= vm_running
;
6915 for(i
= 0; i
<= nb_drives
; i
++) {
6916 bs1
= drives_table
[i
].bdrv
;
6917 if (bdrv_has_snapshot(bs1
)) {
6918 ret
= bdrv_snapshot_goto(bs1
, name
);
6921 term_printf("Warning: ");
6924 term_printf("Snapshots not supported on device '%s'\n",
6925 bdrv_get_device_name(bs1
));
6928 term_printf("Could not find snapshot '%s' on device '%s'\n",
6929 name
, bdrv_get_device_name(bs1
));
6932 term_printf("Error %d while activating snapshot on '%s'\n",
6933 ret
, bdrv_get_device_name(bs1
));
6936 /* fatal on snapshot block device */
6943 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6944 term_printf("Device %s does not support VM state snapshots\n",
6945 bdrv_get_device_name(bs
));
6949 /* restore the VM state */
6950 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6952 term_printf("Could not open VM state file\n");
6955 ret
= qemu_loadvm_state(f
);
6958 term_printf("Error %d while loading VM state\n", ret
);
6961 if (saved_vm_running
)
6965 void do_delvm(const char *name
)
6967 BlockDriverState
*bs
, *bs1
;
6970 bs
= get_bs_snapshots();
6972 term_printf("No block device supports snapshots\n");
6976 for(i
= 0; i
<= nb_drives
; i
++) {
6977 bs1
= drives_table
[i
].bdrv
;
6978 if (bdrv_has_snapshot(bs1
)) {
6979 ret
= bdrv_snapshot_delete(bs1
, name
);
6981 if (ret
== -ENOTSUP
)
6982 term_printf("Snapshots not supported on device '%s'\n",
6983 bdrv_get_device_name(bs1
));
6985 term_printf("Error %d while deleting snapshot on '%s'\n",
6986 ret
, bdrv_get_device_name(bs1
));
6992 void do_info_snapshots(void)
6994 BlockDriverState
*bs
, *bs1
;
6995 QEMUSnapshotInfo
*sn_tab
, *sn
;
6999 bs
= get_bs_snapshots();
7001 term_printf("No available block device supports snapshots\n");
7004 term_printf("Snapshot devices:");
7005 for(i
= 0; i
<= nb_drives
; i
++) {
7006 bs1
= drives_table
[i
].bdrv
;
7007 if (bdrv_has_snapshot(bs1
)) {
7009 term_printf(" %s", bdrv_get_device_name(bs1
));
7014 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7016 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7019 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7020 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7021 for(i
= 0; i
< nb_sns
; i
++) {
7023 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7028 /***********************************************************/
7029 /* ram save/restore */
7031 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7035 v
= qemu_get_byte(f
);
7038 if (qemu_get_buffer(f
, buf
, len
) != len
)
7042 v
= qemu_get_byte(f
);
7043 memset(buf
, v
, len
);
7051 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7056 if (qemu_get_be32(f
) != phys_ram_size
)
7058 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7059 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7066 #define BDRV_HASH_BLOCK_SIZE 1024
7067 #define IOBUF_SIZE 4096
7068 #define RAM_CBLOCK_MAGIC 0xfabe
7070 typedef struct RamCompressState
{
7073 uint8_t buf
[IOBUF_SIZE
];
7076 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7079 memset(s
, 0, sizeof(*s
));
7081 ret
= deflateInit2(&s
->zstream
, 1,
7083 9, Z_DEFAULT_STRATEGY
);
7086 s
->zstream
.avail_out
= IOBUF_SIZE
;
7087 s
->zstream
.next_out
= s
->buf
;
7091 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7093 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7094 qemu_put_be16(s
->f
, len
);
7095 qemu_put_buffer(s
->f
, buf
, len
);
7098 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7102 s
->zstream
.avail_in
= len
;
7103 s
->zstream
.next_in
= (uint8_t *)buf
;
7104 while (s
->zstream
.avail_in
> 0) {
7105 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7108 if (s
->zstream
.avail_out
== 0) {
7109 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7110 s
->zstream
.avail_out
= IOBUF_SIZE
;
7111 s
->zstream
.next_out
= s
->buf
;
7117 static void ram_compress_close(RamCompressState
*s
)
7121 /* compress last bytes */
7123 ret
= deflate(&s
->zstream
, Z_FINISH
);
7124 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7125 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7127 ram_put_cblock(s
, s
->buf
, len
);
7129 s
->zstream
.avail_out
= IOBUF_SIZE
;
7130 s
->zstream
.next_out
= s
->buf
;
7131 if (ret
== Z_STREAM_END
)
7138 deflateEnd(&s
->zstream
);
7141 typedef struct RamDecompressState
{
7144 uint8_t buf
[IOBUF_SIZE
];
7145 } RamDecompressState
;
7147 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7150 memset(s
, 0, sizeof(*s
));
7152 ret
= inflateInit(&s
->zstream
);
7158 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7162 s
->zstream
.avail_out
= len
;
7163 s
->zstream
.next_out
= buf
;
7164 while (s
->zstream
.avail_out
> 0) {
7165 if (s
->zstream
.avail_in
== 0) {
7166 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7168 clen
= qemu_get_be16(s
->f
);
7169 if (clen
> IOBUF_SIZE
)
7171 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7172 s
->zstream
.avail_in
= clen
;
7173 s
->zstream
.next_in
= s
->buf
;
7175 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7176 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7183 static void ram_decompress_close(RamDecompressState
*s
)
7185 inflateEnd(&s
->zstream
);
7188 static void ram_save(QEMUFile
*f
, void *opaque
)
7191 RamCompressState s1
, *s
= &s1
;
7194 qemu_put_be32(f
, phys_ram_size
);
7195 if (ram_compress_open(s
, f
) < 0)
7197 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7199 if (tight_savevm_enabled
) {
7203 /* find if the memory block is available on a virtual
7206 for(j
= 0; j
< nb_drives
; j
++) {
7207 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7209 BDRV_HASH_BLOCK_SIZE
);
7210 if (sector_num
>= 0)
7214 goto normal_compress
;
7217 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7218 ram_compress_buf(s
, buf
, 10);
7224 ram_compress_buf(s
, buf
, 1);
7225 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7228 ram_compress_close(s
);
7231 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7233 RamDecompressState s1
, *s
= &s1
;
7237 if (version_id
== 1)
7238 return ram_load_v1(f
, opaque
);
7239 if (version_id
!= 2)
7241 if (qemu_get_be32(f
) != phys_ram_size
)
7243 if (ram_decompress_open(s
, f
) < 0)
7245 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7246 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7247 fprintf(stderr
, "Error while reading ram block header\n");
7251 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7252 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7261 ram_decompress_buf(s
, buf
+ 1, 9);
7263 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7264 if (bs_index
>= nb_drives
) {
7265 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7268 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7270 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7271 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7272 bs_index
, sector_num
);
7279 printf("Error block header\n");
7283 ram_decompress_close(s
);
7287 /***********************************************************/
7288 /* bottom halves (can be seen as timers which expire ASAP) */
7297 static QEMUBH
*first_bh
= NULL
;
7299 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7302 bh
= qemu_mallocz(sizeof(QEMUBH
));
7306 bh
->opaque
= opaque
;
7310 int qemu_bh_poll(void)
7329 void qemu_bh_schedule(QEMUBH
*bh
)
7331 CPUState
*env
= cpu_single_env
;
7335 bh
->next
= first_bh
;
7338 /* stop the currently executing CPU to execute the BH ASAP */
7340 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7344 void qemu_bh_cancel(QEMUBH
*bh
)
7347 if (bh
->scheduled
) {
7350 pbh
= &(*pbh
)->next
;
7356 void qemu_bh_delete(QEMUBH
*bh
)
7362 /***********************************************************/
7363 /* machine registration */
7365 QEMUMachine
*first_machine
= NULL
;
7367 int qemu_register_machine(QEMUMachine
*m
)
7370 pm
= &first_machine
;
7378 static QEMUMachine
*find_machine(const char *name
)
7382 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7383 if (!strcmp(m
->name
, name
))
7389 /***********************************************************/
7390 /* main execution loop */
7392 static void gui_update(void *opaque
)
7394 DisplayState
*ds
= opaque
;
7395 ds
->dpy_refresh(ds
);
7396 qemu_mod_timer(ds
->gui_timer
,
7397 (ds
->gui_timer_interval
?
7398 ds
->gui_timer_interval
:
7399 GUI_REFRESH_INTERVAL
)
7400 + qemu_get_clock(rt_clock
));
7403 struct vm_change_state_entry
{
7404 VMChangeStateHandler
*cb
;
7406 LIST_ENTRY (vm_change_state_entry
) entries
;
7409 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7411 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7414 VMChangeStateEntry
*e
;
7416 e
= qemu_mallocz(sizeof (*e
));
7422 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7426 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7428 LIST_REMOVE (e
, entries
);
7432 static void vm_state_notify(int running
)
7434 VMChangeStateEntry
*e
;
7436 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7437 e
->cb(e
->opaque
, running
);
7441 /* XXX: support several handlers */
7442 static VMStopHandler
*vm_stop_cb
;
7443 static void *vm_stop_opaque
;
7445 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7448 vm_stop_opaque
= opaque
;
7452 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7463 qemu_rearm_alarm_timer(alarm_timer
);
7467 void vm_stop(int reason
)
7470 cpu_disable_ticks();
7474 vm_stop_cb(vm_stop_opaque
, reason
);
7481 /* reset/shutdown handler */
7483 typedef struct QEMUResetEntry
{
7484 QEMUResetHandler
*func
;
7486 struct QEMUResetEntry
*next
;
7489 static QEMUResetEntry
*first_reset_entry
;
7490 static int reset_requested
;
7491 static int shutdown_requested
;
7492 static int powerdown_requested
;
7494 int qemu_shutdown_requested(void)
7496 int r
= shutdown_requested
;
7497 shutdown_requested
= 0;
7501 int qemu_reset_requested(void)
7503 int r
= reset_requested
;
7504 reset_requested
= 0;
7508 int qemu_powerdown_requested(void)
7510 int r
= powerdown_requested
;
7511 powerdown_requested
= 0;
7515 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7517 QEMUResetEntry
**pre
, *re
;
7519 pre
= &first_reset_entry
;
7520 while (*pre
!= NULL
)
7521 pre
= &(*pre
)->next
;
7522 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7524 re
->opaque
= opaque
;
7529 void qemu_system_reset(void)
7533 /* reset all devices */
7534 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7535 re
->func(re
->opaque
);
7539 void qemu_system_reset_request(void)
7542 shutdown_requested
= 1;
7544 reset_requested
= 1;
7547 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7550 void qemu_system_shutdown_request(void)
7552 shutdown_requested
= 1;
7554 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7557 void qemu_system_powerdown_request(void)
7559 powerdown_requested
= 1;
7561 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7564 void main_loop_wait(int timeout
)
7566 IOHandlerRecord
*ioh
;
7567 fd_set rfds
, wfds
, xfds
;
7576 /* XXX: need to suppress polling by better using win32 events */
7578 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7579 ret
|= pe
->func(pe
->opaque
);
7584 WaitObjects
*w
= &wait_objects
;
7586 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7587 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7588 if (w
->func
[ret
- WAIT_OBJECT_0
])
7589 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7591 /* Check for additional signaled events */
7592 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7594 /* Check if event is signaled */
7595 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7596 if(ret2
== WAIT_OBJECT_0
) {
7598 w
->func
[i
](w
->opaque
[i
]);
7599 } else if (ret2
== WAIT_TIMEOUT
) {
7601 err
= GetLastError();
7602 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7605 } else if (ret
== WAIT_TIMEOUT
) {
7607 err
= GetLastError();
7608 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7612 /* poll any events */
7613 /* XXX: separate device handlers from system ones */
7618 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7622 (!ioh
->fd_read_poll
||
7623 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7624 FD_SET(ioh
->fd
, &rfds
);
7628 if (ioh
->fd_write
) {
7629 FD_SET(ioh
->fd
, &wfds
);
7639 tv
.tv_usec
= timeout
* 1000;
7641 #if defined(CONFIG_SLIRP)
7643 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7646 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7648 IOHandlerRecord
**pioh
;
7650 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7651 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7652 ioh
->fd_read(ioh
->opaque
);
7654 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7655 ioh
->fd_write(ioh
->opaque
);
7659 /* remove deleted IO handlers */
7660 pioh
= &first_io_handler
;
7670 #if defined(CONFIG_SLIRP)
7677 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7682 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7683 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7684 qemu_get_clock(vm_clock
));
7685 /* run dma transfers, if any */
7689 /* real time timers */
7690 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7691 qemu_get_clock(rt_clock
));
7693 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7694 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7695 qemu_rearm_alarm_timer(alarm_timer
);
7698 /* Check bottom-halves last in case any of the earlier events triggered
7704 static int main_loop(void)
7707 #ifdef CONFIG_PROFILER
7712 cur_cpu
= first_cpu
;
7713 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7720 #ifdef CONFIG_PROFILER
7721 ti
= profile_getclock();
7726 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7727 env
->icount_decr
.u16
.low
= 0;
7728 env
->icount_extra
= 0;
7729 count
= qemu_next_deadline();
7730 count
= (count
+ (1 << icount_time_shift
) - 1)
7731 >> icount_time_shift
;
7732 qemu_icount
+= count
;
7733 decr
= (count
> 0xffff) ? 0xffff : count
;
7735 env
->icount_decr
.u16
.low
= decr
;
7736 env
->icount_extra
= count
;
7738 ret
= cpu_exec(env
);
7739 #ifdef CONFIG_PROFILER
7740 qemu_time
+= profile_getclock() - ti
;
7743 /* Fold pending instructions back into the
7744 instruction counter, and clear the interrupt flag. */
7745 qemu_icount
-= (env
->icount_decr
.u16
.low
7746 + env
->icount_extra
);
7747 env
->icount_decr
.u32
= 0;
7748 env
->icount_extra
= 0;
7750 next_cpu
= env
->next_cpu
?: first_cpu
;
7751 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7752 ret
= EXCP_INTERRUPT
;
7756 if (ret
== EXCP_HLT
) {
7757 /* Give the next CPU a chance to run. */
7761 if (ret
!= EXCP_HALTED
)
7763 /* all CPUs are halted ? */
7769 if (shutdown_requested
) {
7770 ret
= EXCP_INTERRUPT
;
7778 if (reset_requested
) {
7779 reset_requested
= 0;
7780 qemu_system_reset();
7781 ret
= EXCP_INTERRUPT
;
7783 if (powerdown_requested
) {
7784 powerdown_requested
= 0;
7785 qemu_system_powerdown();
7786 ret
= EXCP_INTERRUPT
;
7788 if (unlikely(ret
== EXCP_DEBUG
)) {
7789 vm_stop(EXCP_DEBUG
);
7791 /* If all cpus are halted then wait until the next IRQ */
7792 /* XXX: use timeout computed from timers */
7793 if (ret
== EXCP_HALTED
) {
7797 /* Advance virtual time to the next event. */
7798 if (use_icount
== 1) {
7799 /* When not using an adaptive execution frequency
7800 we tend to get badly out of sync with real time,
7801 so just delay for a reasonable amount of time. */
7804 delta
= cpu_get_icount() - cpu_get_clock();
7807 /* If virtual time is ahead of real time then just
7809 timeout
= (delta
/ 1000000) + 1;
7811 /* Wait for either IO to occur or the next
7813 add
= qemu_next_deadline();
7814 /* We advance the timer before checking for IO.
7815 Limit the amount we advance so that early IO
7816 activity won't get the guest too far ahead. */
7820 add
= (add
+ (1 << icount_time_shift
) - 1)
7821 >> icount_time_shift
;
7823 timeout
= delta
/ 1000000;
7834 if (shutdown_requested
) {
7835 ret
= EXCP_INTERRUPT
;
7840 #ifdef CONFIG_PROFILER
7841 ti
= profile_getclock();
7843 main_loop_wait(timeout
);
7844 #ifdef CONFIG_PROFILER
7845 dev_time
+= profile_getclock() - ti
;
7848 cpu_disable_ticks();
7852 static void help(int exitcode
)
7854 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7855 "usage: %s [options] [disk_image]\n"
7857 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7859 "Standard options:\n"
7860 "-M machine select emulated machine (-M ? for list)\n"
7861 "-cpu cpu select CPU (-cpu ? for list)\n"
7862 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7863 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7864 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7865 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7866 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7867 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7868 " [,cache=on|off][,format=f]\n"
7869 " use 'file' as a drive image\n"
7870 "-mtdblock file use 'file' as on-board Flash memory image\n"
7871 "-sd file use 'file' as SecureDigital card image\n"
7872 "-pflash file use 'file' as a parallel flash image\n"
7873 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7874 "-snapshot write to temporary files instead of disk image files\n"
7876 "-no-frame open SDL window without a frame and window decorations\n"
7877 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7878 "-no-quit disable SDL window close capability\n"
7881 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7883 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7884 "-smp n set the number of CPUs to 'n' [default=1]\n"
7885 "-nographic disable graphical output and redirect serial I/Os to console\n"
7886 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7888 "-k language use keyboard layout (for example \"fr\" for French)\n"
7891 "-audio-help print list of audio drivers and their options\n"
7892 "-soundhw c1,... enable audio support\n"
7893 " and only specified sound cards (comma separated list)\n"
7894 " use -soundhw ? to get the list of supported cards\n"
7895 " use -soundhw all to enable all of them\n"
7897 "-vga [std|cirrus|vmware]\n"
7898 " select video card type\n"
7899 "-localtime set the real time clock to local time [default=utc]\n"
7900 "-full-screen start in full screen\n"
7902 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7904 "-usb enable the USB driver (will be the default soon)\n"
7905 "-usbdevice name add the host or guest USB device 'name'\n"
7906 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7907 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7909 "-name string set the name of the guest\n"
7910 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
7912 "Network options:\n"
7913 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7914 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7916 "-net user[,vlan=n][,hostname=host]\n"
7917 " connect the user mode network stack to VLAN 'n' and send\n"
7918 " hostname 'host' to DHCP clients\n"
7921 "-net tap[,vlan=n],ifname=name\n"
7922 " connect the host TAP network interface to VLAN 'n'\n"
7924 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7925 " connect the host TAP network interface to VLAN 'n' and use the\n"
7926 " network scripts 'file' (default=%s)\n"
7927 " and 'dfile' (default=%s);\n"
7928 " use '[down]script=no' to disable script execution;\n"
7929 " use 'fd=h' to connect to an already opened TAP interface\n"
7931 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7932 " connect the vlan 'n' to another VLAN using a socket connection\n"
7933 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7934 " connect the vlan 'n' to multicast maddr and port\n"
7936 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7937 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7938 " on host and listening for incoming connections on 'socketpath'.\n"
7939 " Use group 'groupname' and mode 'octalmode' to change default\n"
7940 " ownership and permissions for communication port.\n"
7942 "-net none use it alone to have zero network devices; if no -net option\n"
7943 " is provided, the default is '-net nic -net user'\n"
7946 "-tftp dir allow tftp access to files in dir [-net user]\n"
7947 "-bootp file advertise file in BOOTP replies\n"
7949 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7951 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7952 " redirect TCP or UDP connections from host to guest [-net user]\n"
7955 "Linux boot specific:\n"
7956 "-kernel bzImage use 'bzImage' as kernel image\n"
7957 "-append cmdline use 'cmdline' as kernel command line\n"
7958 "-initrd file use 'file' as initial ram disk\n"
7960 "Debug/Expert options:\n"
7961 "-monitor dev redirect the monitor to char device 'dev'\n"
7962 "-serial dev redirect the serial port to char device 'dev'\n"
7963 "-parallel dev redirect the parallel port to char device 'dev'\n"
7964 "-pidfile file Write PID to 'file'\n"
7965 "-S freeze CPU at startup (use 'c' to start execution)\n"
7966 "-s wait gdb connection to port\n"
7967 "-p port set gdb connection port [default=%s]\n"
7968 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7969 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7970 " translation (t=none or lba) (usually qemu can guess them)\n"
7971 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7973 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7974 "-no-kqemu disable KQEMU kernel module usage\n"
7977 "-no-acpi disable ACPI\n"
7979 #ifdef CONFIG_CURSES
7980 "-curses use a curses/ncurses interface instead of SDL\n"
7982 "-no-reboot exit instead of rebooting\n"
7983 "-no-shutdown stop before shutdown\n"
7984 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7985 "-vnc display start a VNC server on display\n"
7987 "-daemonize daemonize QEMU after initializing\n"
7989 "-option-rom rom load a file, rom, into the option ROM space\n"
7991 "-prom-env variable=value set OpenBIOS nvram variables\n"
7993 "-clock force the use of the given methods for timer alarm.\n"
7994 " To see what timers are available use -clock ?\n"
7995 "-startdate select initial date of the clock\n"
7996 "-icount [N|auto]\n"
7997 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7999 "During emulation, the following keys are useful:\n"
8000 "ctrl-alt-f toggle full screen\n"
8001 "ctrl-alt-n switch to virtual console 'n'\n"
8002 "ctrl-alt toggle mouse and keyboard grab\n"
8004 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8009 DEFAULT_NETWORK_SCRIPT
,
8010 DEFAULT_NETWORK_DOWN_SCRIPT
,
8012 DEFAULT_GDBSTUB_PORT
,
8017 #define HAS_ARG 0x0001
8032 QEMU_OPTION_mtdblock
,
8036 QEMU_OPTION_snapshot
,
8038 QEMU_OPTION_no_fd_bootchk
,
8041 QEMU_OPTION_nographic
,
8042 QEMU_OPTION_portrait
,
8044 QEMU_OPTION_audio_help
,
8045 QEMU_OPTION_soundhw
,
8066 QEMU_OPTION_localtime
,
8070 QEMU_OPTION_monitor
,
8072 QEMU_OPTION_parallel
,
8074 QEMU_OPTION_full_screen
,
8075 QEMU_OPTION_no_frame
,
8076 QEMU_OPTION_alt_grab
,
8077 QEMU_OPTION_no_quit
,
8078 QEMU_OPTION_pidfile
,
8079 QEMU_OPTION_no_kqemu
,
8080 QEMU_OPTION_kernel_kqemu
,
8081 QEMU_OPTION_win2k_hack
,
8083 QEMU_OPTION_usbdevice
,
8086 QEMU_OPTION_no_acpi
,
8088 QEMU_OPTION_no_reboot
,
8089 QEMU_OPTION_no_shutdown
,
8090 QEMU_OPTION_show_cursor
,
8091 QEMU_OPTION_daemonize
,
8092 QEMU_OPTION_option_rom
,
8093 QEMU_OPTION_semihosting
,
8095 QEMU_OPTION_prom_env
,
8096 QEMU_OPTION_old_param
,
8098 QEMU_OPTION_startdate
,
8099 QEMU_OPTION_tb_size
,
8104 typedef struct QEMUOption
{
8110 const QEMUOption qemu_options
[] = {
8111 { "h", 0, QEMU_OPTION_h
},
8112 { "help", 0, QEMU_OPTION_h
},
8114 { "M", HAS_ARG
, QEMU_OPTION_M
},
8115 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8116 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8117 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8118 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8119 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8120 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8121 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8122 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8123 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8124 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8125 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8126 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8127 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8128 { "snapshot", 0, QEMU_OPTION_snapshot
},
8130 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8132 { "m", HAS_ARG
, QEMU_OPTION_m
},
8133 { "nographic", 0, QEMU_OPTION_nographic
},
8134 { "portrait", 0, QEMU_OPTION_portrait
},
8135 { "k", HAS_ARG
, QEMU_OPTION_k
},
8137 { "audio-help", 0, QEMU_OPTION_audio_help
},
8138 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8141 { "net", HAS_ARG
, QEMU_OPTION_net
},
8143 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8144 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8146 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8148 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8151 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8152 { "append", HAS_ARG
, QEMU_OPTION_append
},
8153 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8155 { "S", 0, QEMU_OPTION_S
},
8156 { "s", 0, QEMU_OPTION_s
},
8157 { "p", HAS_ARG
, QEMU_OPTION_p
},
8158 { "d", HAS_ARG
, QEMU_OPTION_d
},
8159 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8160 { "L", HAS_ARG
, QEMU_OPTION_L
},
8161 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8163 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8164 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8166 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8167 { "g", 1, QEMU_OPTION_g
},
8169 { "localtime", 0, QEMU_OPTION_localtime
},
8170 { "vga", HAS_ARG
, QEMU_OPTION_vga
},
8171 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8172 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8173 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8174 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8175 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8176 { "full-screen", 0, QEMU_OPTION_full_screen
},
8178 { "no-frame", 0, QEMU_OPTION_no_frame
},
8179 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8180 { "no-quit", 0, QEMU_OPTION_no_quit
},
8182 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8183 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8184 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8185 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8186 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8187 #ifdef CONFIG_CURSES
8188 { "curses", 0, QEMU_OPTION_curses
},
8190 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
8192 /* temporary options */
8193 { "usb", 0, QEMU_OPTION_usb
},
8194 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8195 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8196 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8197 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8198 { "daemonize", 0, QEMU_OPTION_daemonize
},
8199 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8200 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8201 { "semihosting", 0, QEMU_OPTION_semihosting
},
8203 { "name", HAS_ARG
, QEMU_OPTION_name
},
8204 #if defined(TARGET_SPARC)
8205 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8207 #if defined(TARGET_ARM)
8208 { "old-param", 0, QEMU_OPTION_old_param
},
8210 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8211 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8212 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8213 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8217 /* password input */
8219 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8224 if (!bdrv_is_encrypted(bs
))
8227 term_printf("%s is encrypted.\n", name
);
8228 for(i
= 0; i
< 3; i
++) {
8229 monitor_readline("Password: ", 1, password
, sizeof(password
));
8230 if (bdrv_set_key(bs
, password
) == 0)
8232 term_printf("invalid password\n");
8237 static BlockDriverState
*get_bdrv(int index
)
8239 if (index
> nb_drives
)
8241 return drives_table
[index
].bdrv
;
8244 static void read_passwords(void)
8246 BlockDriverState
*bs
;
8249 for(i
= 0; i
< 6; i
++) {
8252 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8257 struct soundhw soundhw
[] = {
8258 #ifdef HAS_AUDIO_CHOICE
8259 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8265 { .init_isa
= pcspk_audio_init
}
8270 "Creative Sound Blaster 16",
8273 { .init_isa
= SB16_init
}
8276 #ifdef CONFIG_CS4231A
8282 { .init_isa
= cs4231a_init
}
8290 "Yamaha YMF262 (OPL3)",
8292 "Yamaha YM3812 (OPL2)",
8296 { .init_isa
= Adlib_init
}
8303 "Gravis Ultrasound GF1",
8306 { .init_isa
= GUS_init
}
8313 "Intel 82801AA AC97 Audio",
8316 { .init_pci
= ac97_init
}
8322 "ENSONIQ AudioPCI ES1370",
8325 { .init_pci
= es1370_init
}
8329 { NULL
, NULL
, 0, 0, { NULL
} }
8332 static void select_soundhw (const char *optarg
)
8336 if (*optarg
== '?') {
8339 printf ("Valid sound card names (comma separated):\n");
8340 for (c
= soundhw
; c
->name
; ++c
) {
8341 printf ("%-11s %s\n", c
->name
, c
->descr
);
8343 printf ("\n-soundhw all will enable all of the above\n");
8344 exit (*optarg
!= '?');
8352 if (!strcmp (optarg
, "all")) {
8353 for (c
= soundhw
; c
->name
; ++c
) {
8361 e
= strchr (p
, ',');
8362 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8364 for (c
= soundhw
; c
->name
; ++c
) {
8365 if (!strncmp (c
->name
, p
, l
)) {
8374 "Unknown sound card name (too big to show)\n");
8377 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8382 p
+= l
+ (e
!= NULL
);
8386 goto show_valid_cards
;
8391 static void select_vgahw (const char *p
)
8395 if (strstart(p
, "std", &opts
)) {
8396 cirrus_vga_enabled
= 0;
8398 } else if (strstart(p
, "cirrus", &opts
)) {
8399 cirrus_vga_enabled
= 1;
8401 } else if (strstart(p
, "vmware", &opts
)) {
8402 cirrus_vga_enabled
= 0;
8406 fprintf(stderr
, "Unknown vga type: %s\n", p
);
8410 const char *nextopt
;
8412 if (strstart(opts
, ",retrace=", &nextopt
)) {
8414 if (strstart(opts
, "dumb", &nextopt
))
8415 vga_retrace_method
= VGA_RETRACE_DUMB
;
8416 else if (strstart(opts
, "precise", &nextopt
))
8417 vga_retrace_method
= VGA_RETRACE_PRECISE
;
8418 else goto invalid_vga
;
8419 } else goto invalid_vga
;
8425 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8427 exit(STATUS_CONTROL_C_EXIT
);
8432 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8436 if(strlen(str
) != 36)
8439 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8440 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8441 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8449 #define MAX_NET_CLIENTS 32
8453 static void termsig_handler(int signal
)
8455 qemu_system_shutdown_request();
8458 static void termsig_setup(void)
8460 struct sigaction act
;
8462 memset(&act
, 0, sizeof(act
));
8463 act
.sa_handler
= termsig_handler
;
8464 sigaction(SIGINT
, &act
, NULL
);
8465 sigaction(SIGHUP
, &act
, NULL
);
8466 sigaction(SIGTERM
, &act
, NULL
);
8471 int main(int argc
, char **argv
)
8473 #ifdef CONFIG_GDBSTUB
8475 const char *gdbstub_port
;
8477 uint32_t boot_devices_bitmap
= 0;
8479 int snapshot
, linux_boot
, net_boot
;
8480 const char *initrd_filename
;
8481 const char *kernel_filename
, *kernel_cmdline
;
8482 const char *boot_devices
= "";
8483 DisplayState
*ds
= &display_state
;
8484 int cyls
, heads
, secs
, translation
;
8485 const char *net_clients
[MAX_NET_CLIENTS
];
8489 const char *r
, *optarg
;
8490 CharDriverState
*monitor_hd
;
8491 const char *monitor_device
;
8492 const char *serial_devices
[MAX_SERIAL_PORTS
];
8493 int serial_device_index
;
8494 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8495 int parallel_device_index
;
8496 const char *loadvm
= NULL
;
8497 QEMUMachine
*machine
;
8498 const char *cpu_model
;
8499 const char *usb_devices
[MAX_USB_CMDLINE
];
8500 int usb_devices_index
;
8503 const char *pid_file
= NULL
;
8506 LIST_INIT (&vm_change_state_head
);
8509 struct sigaction act
;
8510 sigfillset(&act
.sa_mask
);
8512 act
.sa_handler
= SIG_IGN
;
8513 sigaction(SIGPIPE
, &act
, NULL
);
8516 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8517 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8518 QEMU to run on a single CPU */
8523 h
= GetCurrentProcess();
8524 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8525 for(i
= 0; i
< 32; i
++) {
8526 if (mask
& (1 << i
))
8531 SetProcessAffinityMask(h
, mask
);
8537 register_machines();
8538 machine
= first_machine
;
8540 initrd_filename
= NULL
;
8542 vga_ram_size
= VGA_RAM_SIZE
;
8543 #ifdef CONFIG_GDBSTUB
8545 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8550 kernel_filename
= NULL
;
8551 kernel_cmdline
= "";
8552 cyls
= heads
= secs
= 0;
8553 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8554 monitor_device
= "vc";
8556 serial_devices
[0] = "vc:80Cx24C";
8557 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8558 serial_devices
[i
] = NULL
;
8559 serial_device_index
= 0;
8561 parallel_devices
[0] = "vc:640x480";
8562 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8563 parallel_devices
[i
] = NULL
;
8564 parallel_device_index
= 0;
8566 usb_devices_index
= 0;
8583 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8585 const QEMUOption
*popt
;
8588 /* Treat --foo the same as -foo. */
8591 popt
= qemu_options
;
8594 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8598 if (!strcmp(popt
->name
, r
+ 1))
8602 if (popt
->flags
& HAS_ARG
) {
8603 if (optind
>= argc
) {
8604 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8608 optarg
= argv
[optind
++];
8613 switch(popt
->index
) {
8615 machine
= find_machine(optarg
);
8618 printf("Supported machines are:\n");
8619 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8620 printf("%-10s %s%s\n",
8622 m
== first_machine
? " (default)" : "");
8624 exit(*optarg
!= '?');
8627 case QEMU_OPTION_cpu
:
8628 /* hw initialization will check this */
8629 if (*optarg
== '?') {
8630 /* XXX: implement xxx_cpu_list for targets that still miss it */
8631 #if defined(cpu_list)
8632 cpu_list(stdout
, &fprintf
);
8639 case QEMU_OPTION_initrd
:
8640 initrd_filename
= optarg
;
8642 case QEMU_OPTION_hda
:
8644 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8646 hda_index
= drive_add(optarg
, HD_ALIAS
8647 ",cyls=%d,heads=%d,secs=%d%s",
8648 0, cyls
, heads
, secs
,
8649 translation
== BIOS_ATA_TRANSLATION_LBA
?
8651 translation
== BIOS_ATA_TRANSLATION_NONE
?
8652 ",trans=none" : "");
8654 case QEMU_OPTION_hdb
:
8655 case QEMU_OPTION_hdc
:
8656 case QEMU_OPTION_hdd
:
8657 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8659 case QEMU_OPTION_drive
:
8660 drive_add(NULL
, "%s", optarg
);
8662 case QEMU_OPTION_mtdblock
:
8663 drive_add(optarg
, MTD_ALIAS
);
8665 case QEMU_OPTION_sd
:
8666 drive_add(optarg
, SD_ALIAS
);
8668 case QEMU_OPTION_pflash
:
8669 drive_add(optarg
, PFLASH_ALIAS
);
8671 case QEMU_OPTION_snapshot
:
8674 case QEMU_OPTION_hdachs
:
8678 cyls
= strtol(p
, (char **)&p
, 0);
8679 if (cyls
< 1 || cyls
> 16383)
8684 heads
= strtol(p
, (char **)&p
, 0);
8685 if (heads
< 1 || heads
> 16)
8690 secs
= strtol(p
, (char **)&p
, 0);
8691 if (secs
< 1 || secs
> 63)
8695 if (!strcmp(p
, "none"))
8696 translation
= BIOS_ATA_TRANSLATION_NONE
;
8697 else if (!strcmp(p
, "lba"))
8698 translation
= BIOS_ATA_TRANSLATION_LBA
;
8699 else if (!strcmp(p
, "auto"))
8700 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8703 } else if (*p
!= '\0') {
8705 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8708 if (hda_index
!= -1)
8709 snprintf(drives_opt
[hda_index
].opt
,
8710 sizeof(drives_opt
[hda_index
].opt
),
8711 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8712 0, cyls
, heads
, secs
,
8713 translation
== BIOS_ATA_TRANSLATION_LBA
?
8715 translation
== BIOS_ATA_TRANSLATION_NONE
?
8716 ",trans=none" : "");
8719 case QEMU_OPTION_nographic
:
8722 #ifdef CONFIG_CURSES
8723 case QEMU_OPTION_curses
:
8727 case QEMU_OPTION_portrait
:
8730 case QEMU_OPTION_kernel
:
8731 kernel_filename
= optarg
;
8733 case QEMU_OPTION_append
:
8734 kernel_cmdline
= optarg
;
8736 case QEMU_OPTION_cdrom
:
8737 drive_add(optarg
, CDROM_ALIAS
);
8739 case QEMU_OPTION_boot
:
8740 boot_devices
= optarg
;
8741 /* We just do some generic consistency checks */
8743 /* Could easily be extended to 64 devices if needed */
8746 boot_devices_bitmap
= 0;
8747 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8748 /* Allowed boot devices are:
8749 * a b : floppy disk drives
8750 * c ... f : IDE disk drives
8751 * g ... m : machine implementation dependant drives
8752 * n ... p : network devices
8753 * It's up to each machine implementation to check
8754 * if the given boot devices match the actual hardware
8755 * implementation and firmware features.
8757 if (*p
< 'a' || *p
> 'q') {
8758 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8761 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8763 "Boot device '%c' was given twice\n",*p
);
8766 boot_devices_bitmap
|= 1 << (*p
- 'a');
8770 case QEMU_OPTION_fda
:
8771 case QEMU_OPTION_fdb
:
8772 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8775 case QEMU_OPTION_no_fd_bootchk
:
8779 case QEMU_OPTION_net
:
8780 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8781 fprintf(stderr
, "qemu: too many network clients\n");
8784 net_clients
[nb_net_clients
] = optarg
;
8788 case QEMU_OPTION_tftp
:
8789 tftp_prefix
= optarg
;
8791 case QEMU_OPTION_bootp
:
8792 bootp_filename
= optarg
;
8795 case QEMU_OPTION_smb
:
8796 net_slirp_smb(optarg
);
8799 case QEMU_OPTION_redir
:
8800 net_slirp_redir(optarg
);
8804 case QEMU_OPTION_audio_help
:
8808 case QEMU_OPTION_soundhw
:
8809 select_soundhw (optarg
);
8815 case QEMU_OPTION_m
: {
8819 value
= strtoul(optarg
, &ptr
, 10);
8821 case 0: case 'M': case 'm':
8828 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8832 /* On 32-bit hosts, QEMU is limited by virtual address space */
8833 if (value
> (2047 << 20)
8835 && HOST_LONG_BITS
== 32
8838 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8841 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8842 fprintf(stderr
, "qemu: ram size too large\n");
8853 mask
= cpu_str_to_log_mask(optarg
);
8855 printf("Log items (comma separated):\n");
8856 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8857 printf("%-10s %s\n", item
->name
, item
->help
);
8864 #ifdef CONFIG_GDBSTUB
8869 gdbstub_port
= optarg
;
8875 case QEMU_OPTION_bios
:
8882 keyboard_layout
= optarg
;
8884 case QEMU_OPTION_localtime
:
8887 case QEMU_OPTION_vga
:
8888 select_vgahw (optarg
);
8895 w
= strtol(p
, (char **)&p
, 10);
8898 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8904 h
= strtol(p
, (char **)&p
, 10);
8909 depth
= strtol(p
, (char **)&p
, 10);
8910 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8911 depth
!= 24 && depth
!= 32)
8913 } else if (*p
== '\0') {
8914 depth
= graphic_depth
;
8921 graphic_depth
= depth
;
8924 case QEMU_OPTION_echr
:
8927 term_escape_char
= strtol(optarg
, &r
, 0);
8929 printf("Bad argument to echr\n");
8932 case QEMU_OPTION_monitor
:
8933 monitor_device
= optarg
;
8935 case QEMU_OPTION_serial
:
8936 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8937 fprintf(stderr
, "qemu: too many serial ports\n");
8940 serial_devices
[serial_device_index
] = optarg
;
8941 serial_device_index
++;
8943 case QEMU_OPTION_parallel
:
8944 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8945 fprintf(stderr
, "qemu: too many parallel ports\n");
8948 parallel_devices
[parallel_device_index
] = optarg
;
8949 parallel_device_index
++;
8951 case QEMU_OPTION_loadvm
:
8954 case QEMU_OPTION_full_screen
:
8958 case QEMU_OPTION_no_frame
:
8961 case QEMU_OPTION_alt_grab
:
8964 case QEMU_OPTION_no_quit
:
8968 case QEMU_OPTION_pidfile
:
8972 case QEMU_OPTION_win2k_hack
:
8973 win2k_install_hack
= 1;
8977 case QEMU_OPTION_no_kqemu
:
8980 case QEMU_OPTION_kernel_kqemu
:
8984 case QEMU_OPTION_usb
:
8987 case QEMU_OPTION_usbdevice
:
8989 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8990 fprintf(stderr
, "Too many USB devices\n");
8993 usb_devices
[usb_devices_index
] = optarg
;
8994 usb_devices_index
++;
8996 case QEMU_OPTION_smp
:
8997 smp_cpus
= atoi(optarg
);
8998 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8999 fprintf(stderr
, "Invalid number of CPUs\n");
9003 case QEMU_OPTION_vnc
:
9004 vnc_display
= optarg
;
9006 case QEMU_OPTION_no_acpi
:
9009 case QEMU_OPTION_no_reboot
:
9012 case QEMU_OPTION_no_shutdown
:
9015 case QEMU_OPTION_show_cursor
:
9018 case QEMU_OPTION_uuid
:
9019 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
9020 fprintf(stderr
, "Fail to parse UUID string."
9021 " Wrong format.\n");
9025 case QEMU_OPTION_daemonize
:
9028 case QEMU_OPTION_option_rom
:
9029 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9030 fprintf(stderr
, "Too many option ROMs\n");
9033 option_rom
[nb_option_roms
] = optarg
;
9036 case QEMU_OPTION_semihosting
:
9037 semihosting_enabled
= 1;
9039 case QEMU_OPTION_name
:
9043 case QEMU_OPTION_prom_env
:
9044 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9045 fprintf(stderr
, "Too many prom variables\n");
9048 prom_envs
[nb_prom_envs
] = optarg
;
9053 case QEMU_OPTION_old_param
:
9057 case QEMU_OPTION_clock
:
9058 configure_alarms(optarg
);
9060 case QEMU_OPTION_startdate
:
9063 time_t rtc_start_date
;
9064 if (!strcmp(optarg
, "now")) {
9065 rtc_date_offset
= -1;
9067 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9075 } else if (sscanf(optarg
, "%d-%d-%d",
9078 &tm
.tm_mday
) == 3) {
9087 rtc_start_date
= mktimegm(&tm
);
9088 if (rtc_start_date
== -1) {
9090 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9091 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9094 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9098 case QEMU_OPTION_tb_size
:
9099 tb_size
= strtol(optarg
, NULL
, 0);
9103 case QEMU_OPTION_icount
:
9105 if (strcmp(optarg
, "auto") == 0) {
9106 icount_time_shift
= -1;
9108 icount_time_shift
= strtol(optarg
, NULL
, 0);
9116 if (serial_device_index
== 0)
9117 serial_devices
[0] = "stdio";
9118 if (parallel_device_index
== 0)
9119 parallel_devices
[0] = "null";
9120 if (strncmp(monitor_device
, "vc", 2) == 0)
9121 monitor_device
= "stdio";
9128 if (pipe(fds
) == -1)
9139 len
= read(fds
[0], &status
, 1);
9140 if (len
== -1 && (errno
== EINTR
))
9145 else if (status
== 1) {
9146 fprintf(stderr
, "Could not acquire pidfile\n");
9163 signal(SIGTSTP
, SIG_IGN
);
9164 signal(SIGTTOU
, SIG_IGN
);
9165 signal(SIGTTIN
, SIG_IGN
);
9169 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9172 write(fds
[1], &status
, 1);
9174 fprintf(stderr
, "Could not acquire pid file\n");
9182 linux_boot
= (kernel_filename
!= NULL
);
9183 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9185 if (!linux_boot
&& net_boot
== 0 &&
9186 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9189 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9190 fprintf(stderr
, "-append only allowed with -kernel option\n");
9194 if (!linux_boot
&& initrd_filename
!= NULL
) {
9195 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9199 /* boot to floppy or the default cd if no hard disk defined yet */
9200 if (!boot_devices
[0]) {
9201 boot_devices
= "cad";
9203 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9207 if (use_icount
&& icount_time_shift
< 0) {
9209 /* 125MIPS seems a reasonable initial guess at the guest speed.
9210 It will be corrected fairly quickly anyway. */
9211 icount_time_shift
= 3;
9212 init_icount_adjust();
9219 /* init network clients */
9220 if (nb_net_clients
== 0) {
9221 /* if no clients, we use a default config */
9222 net_clients
[nb_net_clients
++] = "nic";
9224 net_clients
[nb_net_clients
++] = "user";
9228 for(i
= 0;i
< nb_net_clients
; i
++) {
9229 if (net_client_parse(net_clients
[i
]) < 0)
9232 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9233 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9235 if (vlan
->nb_guest_devs
== 0)
9236 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9237 if (vlan
->nb_host_devs
== 0)
9239 "Warning: vlan %d is not connected to host network\n",
9244 /* XXX: this should be moved in the PC machine instantiation code */
9245 if (net_boot
!= 0) {
9247 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9248 const char *model
= nd_table
[i
].model
;
9250 if (net_boot
& (1 << i
)) {
9253 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9254 if (get_image_size(buf
) > 0) {
9255 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9256 fprintf(stderr
, "Too many option ROMs\n");
9259 option_rom
[nb_option_roms
] = strdup(buf
);
9266 fprintf(stderr
, "No valid PXE rom found for network device\n");
9272 /* init the memory */
9273 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9275 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9277 if (ram_size
< phys_ram_size
) {
9278 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9279 machine
->name
, (unsigned long long) phys_ram_size
);
9283 phys_ram_size
= ram_size
;
9285 ram_size
= phys_ram_size
;
9288 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9290 phys_ram_size
+= ram_size
;
9293 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9294 if (!phys_ram_base
) {
9295 fprintf(stderr
, "Could not allocate physical memory\n");
9299 /* init the dynamic translator */
9300 cpu_exec_init_all(tb_size
* 1024 * 1024);
9304 /* we always create the cdrom drive, even if no disk is there */
9306 if (nb_drives_opt
< MAX_DRIVES
)
9307 drive_add(NULL
, CDROM_ALIAS
);
9309 /* we always create at least one floppy */
9311 if (nb_drives_opt
< MAX_DRIVES
)
9312 drive_add(NULL
, FD_ALIAS
, 0);
9314 /* we always create one sd slot, even if no card is in it */
9316 if (nb_drives_opt
< MAX_DRIVES
)
9317 drive_add(NULL
, SD_ALIAS
);
9319 /* open the virtual block devices */
9321 for(i
= 0; i
< nb_drives_opt
; i
++)
9322 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9325 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9326 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9329 memset(&display_state
, 0, sizeof(display_state
));
9332 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9335 /* nearly nothing to do */
9336 dumb_display_init(ds
);
9337 } else if (vnc_display
!= NULL
) {
9338 vnc_display_init(ds
);
9339 if (vnc_display_open(ds
, vnc_display
) < 0)
9342 #if defined(CONFIG_CURSES)
9344 curses_display_init(ds
, full_screen
);
9348 #if defined(CONFIG_SDL)
9349 sdl_display_init(ds
, full_screen
, no_frame
);
9350 #elif defined(CONFIG_COCOA)
9351 cocoa_display_init(ds
, full_screen
);
9353 dumb_display_init(ds
);
9358 /* must be after terminal init, SDL library changes signal handlers */
9362 /* Maintain compatibility with multiple stdio monitors */
9363 if (!strcmp(monitor_device
,"stdio")) {
9364 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9365 const char *devname
= serial_devices
[i
];
9366 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9367 monitor_device
= NULL
;
9369 } else if (devname
&& !strcmp(devname
,"stdio")) {
9370 monitor_device
= NULL
;
9371 serial_devices
[i
] = "mon:stdio";
9376 if (monitor_device
) {
9377 monitor_hd
= qemu_chr_open(monitor_device
);
9379 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9382 monitor_init(monitor_hd
, !nographic
);
9385 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9386 const char *devname
= serial_devices
[i
];
9387 if (devname
&& strcmp(devname
, "none")) {
9388 serial_hds
[i
] = qemu_chr_open(devname
);
9389 if (!serial_hds
[i
]) {
9390 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9394 if (strstart(devname
, "vc", 0))
9395 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9399 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9400 const char *devname
= parallel_devices
[i
];
9401 if (devname
&& strcmp(devname
, "none")) {
9402 parallel_hds
[i
] = qemu_chr_open(devname
);
9403 if (!parallel_hds
[i
]) {
9404 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9408 if (strstart(devname
, "vc", 0))
9409 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9413 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9414 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9416 /* init USB devices */
9418 for(i
= 0; i
< usb_devices_index
; i
++) {
9419 if (usb_device_add(usb_devices
[i
]) < 0) {
9420 fprintf(stderr
, "Warning: could not add USB device %s\n",
9426 if (display_state
.dpy_refresh
) {
9427 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9428 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9431 #ifdef CONFIG_GDBSTUB
9433 /* XXX: use standard host:port notation and modify options
9435 if (gdbserver_start(gdbstub_port
) < 0) {
9436 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9447 /* XXX: simplify init */
9460 len
= write(fds
[1], &status
, 1);
9461 if (len
== -1 && (errno
== EINTR
))
9468 TFR(fd
= open("/dev/null", O_RDWR
));
9482 #if !defined(_WIN32)
9483 /* close network clients */
9484 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9485 VLANClientState
*vc
;
9487 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9488 if (vc
->fd_read
== tap_receive
) {
9490 TAPState
*s
= vc
->opaque
;
9492 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9494 launch_script(s
->down_script
, ifname
, s
->fd
);
9496 #if defined(CONFIG_VDE)
9497 if (vc
->fd_read
== vde_from_qemu
) {
9498 VDEState
*s
= vc
->opaque
;