4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
72 #include <linux/if_tun.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
101 #include <winsock2.h>
102 int inet_aton(const char *cp
, struct in_addr
*ia
);
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
109 #if defined(CONFIG_VDE)
110 #include <libvdeplug.h>
115 #include <sys/timeb.h>
116 #include <mmsystem.h>
117 #define getopt_long_only getopt_long
118 #define memalign(align, size) malloc(size)
121 #include "qemu_socket.h"
127 #endif /* CONFIG_SDL */
131 #define main qemu_main
132 #endif /* CONFIG_COCOA */
136 #include "exec-all.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
143 #define SMBD_COMMAND "/usr/sbin/smbd"
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
150 #define DEFAULT_RAM_SIZE 144
152 #define DEFAULT_RAM_SIZE 128
155 #define GUI_REFRESH_INTERVAL 30
157 /* Max number of USB devices that can be specified on the commandline. */
158 #define MAX_USB_CMDLINE 8
160 /* XXX: use a two level table to limit memory usage */
161 #define MAX_IOPORTS 65536
163 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
164 const char *bios_name
= NULL
;
165 void *ioport_opaque
[MAX_IOPORTS
];
166 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
167 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
168 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
169 to store the VM snapshots */
170 DriveInfo drives_table
[MAX_DRIVES
+1];
172 /* point to the block driver where the snapshots are managed */
173 BlockDriverState
*bs_snapshots
;
175 static DisplayState display_state
;
178 const char* keyboard_layout
= NULL
;
179 int64_t ticks_per_sec
;
181 int pit_min_timer_count
= 0;
183 NICInfo nd_table
[MAX_NICS
];
185 static int rtc_utc
= 1;
186 static int rtc_date_offset
= -1; /* -1 means no change */
187 int cirrus_vga_enabled
= 1;
188 int vmsvga_enabled
= 0;
190 int graphic_width
= 1024;
191 int graphic_height
= 768;
192 int graphic_depth
= 8;
194 int graphic_width
= 800;
195 int graphic_height
= 600;
196 int graphic_depth
= 15;
201 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
202 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
204 int win2k_install_hack
= 0;
207 static VLANState
*first_vlan
;
209 const char *vnc_display
;
210 #if defined(TARGET_SPARC)
212 #elif defined(TARGET_I386)
217 int acpi_enabled
= 1;
222 int graphic_rotate
= 0;
224 const char *option_rom
[MAX_OPTION_ROMS
];
226 int semihosting_enabled
= 0;
231 const char *qemu_name
;
234 unsigned int nb_prom_envs
= 0;
235 const char *prom_envs
[MAX_PROM_ENVS
];
241 } drives_opt
[MAX_DRIVES
];
243 static CPUState
*cur_cpu
;
244 static CPUState
*next_cpu
;
245 static int event_pending
= 1;
246 /* Conversion factor from emulated instructions to virtual clock ticks. */
247 static int icount_time_shift
;
248 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
249 #define MAX_ICOUNT_SHIFT 10
250 /* Compensate for varying guest execution speed. */
251 static int64_t qemu_icount_bias
;
252 QEMUTimer
*icount_rt_timer
;
253 QEMUTimer
*icount_vm_timer
;
255 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
257 /***********************************************************/
258 /* x86 ISA bus support */
260 target_phys_addr_t isa_mem_base
= 0;
263 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
265 #ifdef DEBUG_UNUSED_IOPORT
266 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
271 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
273 #ifdef DEBUG_UNUSED_IOPORT
274 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
278 /* default is to make two byte accesses */
279 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
282 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
283 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
284 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
288 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
290 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
291 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
292 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
295 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
297 #ifdef DEBUG_UNUSED_IOPORT
298 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
303 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
305 #ifdef DEBUG_UNUSED_IOPORT
306 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
310 static void init_ioports(void)
314 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
315 ioport_read_table
[0][i
] = default_ioport_readb
;
316 ioport_write_table
[0][i
] = default_ioport_writeb
;
317 ioport_read_table
[1][i
] = default_ioport_readw
;
318 ioport_write_table
[1][i
] = default_ioport_writew
;
319 ioport_read_table
[2][i
] = default_ioport_readl
;
320 ioport_write_table
[2][i
] = default_ioport_writel
;
324 /* size is the word size in byte */
325 int register_ioport_read(int start
, int length
, int size
,
326 IOPortReadFunc
*func
, void *opaque
)
332 } else if (size
== 2) {
334 } else if (size
== 4) {
337 hw_error("register_ioport_read: invalid size");
340 for(i
= start
; i
< start
+ length
; i
+= size
) {
341 ioport_read_table
[bsize
][i
] = func
;
342 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
343 hw_error("register_ioport_read: invalid opaque");
344 ioport_opaque
[i
] = opaque
;
349 /* size is the word size in byte */
350 int register_ioport_write(int start
, int length
, int size
,
351 IOPortWriteFunc
*func
, void *opaque
)
357 } else if (size
== 2) {
359 } else if (size
== 4) {
362 hw_error("register_ioport_write: invalid size");
365 for(i
= start
; i
< start
+ length
; i
+= size
) {
366 ioport_write_table
[bsize
][i
] = func
;
367 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
368 hw_error("register_ioport_write: invalid opaque");
369 ioport_opaque
[i
] = opaque
;
374 void isa_unassign_ioport(int start
, int length
)
378 for(i
= start
; i
< start
+ length
; i
++) {
379 ioport_read_table
[0][i
] = default_ioport_readb
;
380 ioport_read_table
[1][i
] = default_ioport_readw
;
381 ioport_read_table
[2][i
] = default_ioport_readl
;
383 ioport_write_table
[0][i
] = default_ioport_writeb
;
384 ioport_write_table
[1][i
] = default_ioport_writew
;
385 ioport_write_table
[2][i
] = default_ioport_writel
;
389 /***********************************************************/
391 void cpu_outb(CPUState
*env
, int addr
, int val
)
394 if (loglevel
& CPU_LOG_IOPORT
)
395 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
397 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
400 env
->last_io_time
= cpu_get_time_fast();
404 void cpu_outw(CPUState
*env
, int addr
, int val
)
407 if (loglevel
& CPU_LOG_IOPORT
)
408 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
410 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
413 env
->last_io_time
= cpu_get_time_fast();
417 void cpu_outl(CPUState
*env
, int addr
, int val
)
420 if (loglevel
& CPU_LOG_IOPORT
)
421 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
423 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
426 env
->last_io_time
= cpu_get_time_fast();
430 int cpu_inb(CPUState
*env
, int addr
)
433 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
435 if (loglevel
& CPU_LOG_IOPORT
)
436 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
440 env
->last_io_time
= cpu_get_time_fast();
445 int cpu_inw(CPUState
*env
, int addr
)
448 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
450 if (loglevel
& CPU_LOG_IOPORT
)
451 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
455 env
->last_io_time
= cpu_get_time_fast();
460 int cpu_inl(CPUState
*env
, int addr
)
463 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
465 if (loglevel
& CPU_LOG_IOPORT
)
466 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
470 env
->last_io_time
= cpu_get_time_fast();
475 /***********************************************************/
476 void hw_error(const char *fmt
, ...)
482 fprintf(stderr
, "qemu: hardware error: ");
483 vfprintf(stderr
, fmt
, ap
);
484 fprintf(stderr
, "\n");
485 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
486 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
488 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
490 cpu_dump_state(env
, stderr
, fprintf
, 0);
497 /***********************************************************/
500 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
501 static void *qemu_put_kbd_event_opaque
;
502 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
503 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
505 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
507 qemu_put_kbd_event_opaque
= opaque
;
508 qemu_put_kbd_event
= func
;
511 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
512 void *opaque
, int absolute
,
515 QEMUPutMouseEntry
*s
, *cursor
;
517 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
521 s
->qemu_put_mouse_event
= func
;
522 s
->qemu_put_mouse_event_opaque
= opaque
;
523 s
->qemu_put_mouse_event_absolute
= absolute
;
524 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
527 if (!qemu_put_mouse_event_head
) {
528 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
532 cursor
= qemu_put_mouse_event_head
;
533 while (cursor
->next
!= NULL
)
534 cursor
= cursor
->next
;
537 qemu_put_mouse_event_current
= s
;
542 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
544 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
546 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
549 cursor
= qemu_put_mouse_event_head
;
550 while (cursor
!= NULL
&& cursor
!= entry
) {
552 cursor
= cursor
->next
;
555 if (cursor
== NULL
) // does not exist or list empty
557 else if (prev
== NULL
) { // entry is head
558 qemu_put_mouse_event_head
= cursor
->next
;
559 if (qemu_put_mouse_event_current
== entry
)
560 qemu_put_mouse_event_current
= cursor
->next
;
561 qemu_free(entry
->qemu_put_mouse_event_name
);
566 prev
->next
= entry
->next
;
568 if (qemu_put_mouse_event_current
== entry
)
569 qemu_put_mouse_event_current
= prev
;
571 qemu_free(entry
->qemu_put_mouse_event_name
);
575 void kbd_put_keycode(int keycode
)
577 if (qemu_put_kbd_event
) {
578 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
582 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
584 QEMUPutMouseEvent
*mouse_event
;
585 void *mouse_event_opaque
;
588 if (!qemu_put_mouse_event_current
) {
593 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
595 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
598 if (graphic_rotate
) {
599 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
602 width
= graphic_width
- 1;
603 mouse_event(mouse_event_opaque
,
604 width
- dy
, dx
, dz
, buttons_state
);
606 mouse_event(mouse_event_opaque
,
607 dx
, dy
, dz
, buttons_state
);
611 int kbd_mouse_is_absolute(void)
613 if (!qemu_put_mouse_event_current
)
616 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
619 void do_info_mice(void)
621 QEMUPutMouseEntry
*cursor
;
624 if (!qemu_put_mouse_event_head
) {
625 term_printf("No mouse devices connected\n");
629 term_printf("Mouse devices available:\n");
630 cursor
= qemu_put_mouse_event_head
;
631 while (cursor
!= NULL
) {
632 term_printf("%c Mouse #%d: %s\n",
633 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
634 index
, cursor
->qemu_put_mouse_event_name
);
636 cursor
= cursor
->next
;
640 void do_mouse_set(int index
)
642 QEMUPutMouseEntry
*cursor
;
645 if (!qemu_put_mouse_event_head
) {
646 term_printf("No mouse devices connected\n");
650 cursor
= qemu_put_mouse_event_head
;
651 while (cursor
!= NULL
&& index
!= i
) {
653 cursor
= cursor
->next
;
657 qemu_put_mouse_event_current
= cursor
;
659 term_printf("Mouse at given index not found\n");
662 /* compute with 96 bit intermediate result: (a*b)/c */
663 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
668 #ifdef WORDS_BIGENDIAN
678 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
679 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
682 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
686 /***********************************************************/
687 /* real time host monotonic timer */
689 #define QEMU_TIMER_BASE 1000000000LL
693 static int64_t clock_freq
;
695 static void init_get_clock(void)
699 ret
= QueryPerformanceFrequency(&freq
);
701 fprintf(stderr
, "Could not calibrate ticks\n");
704 clock_freq
= freq
.QuadPart
;
707 static int64_t get_clock(void)
710 QueryPerformanceCounter(&ti
);
711 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
716 static int use_rt_clock
;
718 static void init_get_clock(void)
721 #if defined(__linux__)
724 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
731 static int64_t get_clock(void)
733 #if defined(__linux__)
736 clock_gettime(CLOCK_MONOTONIC
, &ts
);
737 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
741 /* XXX: using gettimeofday leads to problems if the date
742 changes, so it should be avoided. */
744 gettimeofday(&tv
, NULL
);
745 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
750 /* Return the virtual CPU time, based on the instruction counter. */
751 static int64_t cpu_get_icount(void)
754 CPUState
*env
= cpu_single_env
;;
755 icount
= qemu_icount
;
758 fprintf(stderr
, "Bad clock read\n");
759 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
761 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
764 /***********************************************************/
765 /* guest cycle counter */
767 static int64_t cpu_ticks_prev
;
768 static int64_t cpu_ticks_offset
;
769 static int64_t cpu_clock_offset
;
770 static int cpu_ticks_enabled
;
772 /* return the host CPU cycle counter and handle stop/restart */
773 int64_t cpu_get_ticks(void)
776 return cpu_get_icount();
778 if (!cpu_ticks_enabled
) {
779 return cpu_ticks_offset
;
782 ticks
= cpu_get_real_ticks();
783 if (cpu_ticks_prev
> ticks
) {
784 /* Note: non increasing ticks may happen if the host uses
786 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
788 cpu_ticks_prev
= ticks
;
789 return ticks
+ cpu_ticks_offset
;
793 /* return the host CPU monotonic timer and handle stop/restart */
794 static int64_t cpu_get_clock(void)
797 if (!cpu_ticks_enabled
) {
798 return cpu_clock_offset
;
801 return ti
+ cpu_clock_offset
;
805 /* enable cpu_get_ticks() */
806 void cpu_enable_ticks(void)
808 if (!cpu_ticks_enabled
) {
809 cpu_ticks_offset
-= cpu_get_real_ticks();
810 cpu_clock_offset
-= get_clock();
811 cpu_ticks_enabled
= 1;
815 /* disable cpu_get_ticks() : the clock is stopped. You must not call
816 cpu_get_ticks() after that. */
817 void cpu_disable_ticks(void)
819 if (cpu_ticks_enabled
) {
820 cpu_ticks_offset
= cpu_get_ticks();
821 cpu_clock_offset
= cpu_get_clock();
822 cpu_ticks_enabled
= 0;
826 /***********************************************************/
829 #define QEMU_TIMER_REALTIME 0
830 #define QEMU_TIMER_VIRTUAL 1
834 /* XXX: add frequency */
842 struct QEMUTimer
*next
;
845 struct qemu_alarm_timer
{
849 int (*start
)(struct qemu_alarm_timer
*t
);
850 void (*stop
)(struct qemu_alarm_timer
*t
);
851 void (*rearm
)(struct qemu_alarm_timer
*t
);
855 #define ALARM_FLAG_DYNTICKS 0x1
856 #define ALARM_FLAG_EXPIRED 0x2
858 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
860 return t
->flags
& ALARM_FLAG_DYNTICKS
;
863 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
865 if (!alarm_has_dynticks(t
))
871 /* TODO: MIN_TIMER_REARM_US should be optimized */
872 #define MIN_TIMER_REARM_US 250
874 static struct qemu_alarm_timer
*alarm_timer
;
878 struct qemu_alarm_win32
{
882 } alarm_win32_data
= {0, NULL
, -1};
884 static int win32_start_timer(struct qemu_alarm_timer
*t
);
885 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
886 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
890 static int unix_start_timer(struct qemu_alarm_timer
*t
);
891 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
895 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
896 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
897 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
899 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
900 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
902 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
903 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
905 #endif /* __linux__ */
909 /* Correlation between real and virtual time is always going to be
910 fairly approximate, so ignore small variation.
911 When the guest is idle real and virtual time will be aligned in
913 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
915 static void icount_adjust(void)
920 static int64_t last_delta
;
921 /* If the VM is not running, then do nothing. */
925 cur_time
= cpu_get_clock();
926 cur_icount
= qemu_get_clock(vm_clock
);
927 delta
= cur_icount
- cur_time
;
928 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
930 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
931 && icount_time_shift
> 0) {
932 /* The guest is getting too far ahead. Slow time down. */
936 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
937 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
938 /* The guest is getting too far behind. Speed time up. */
942 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
945 static void icount_adjust_rt(void * opaque
)
947 qemu_mod_timer(icount_rt_timer
,
948 qemu_get_clock(rt_clock
) + 1000);
952 static void icount_adjust_vm(void * opaque
)
954 qemu_mod_timer(icount_vm_timer
,
955 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
959 static void init_icount_adjust(void)
961 /* Have both realtime and virtual time triggers for speed adjustment.
962 The realtime trigger catches emulated time passing too slowly,
963 the virtual time trigger catches emulated time passing too fast.
964 Realtime triggers occur even when idle, so use them less frequently
966 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
967 qemu_mod_timer(icount_rt_timer
,
968 qemu_get_clock(rt_clock
) + 1000);
969 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
970 qemu_mod_timer(icount_vm_timer
,
971 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
974 static struct qemu_alarm_timer alarm_timers
[] = {
977 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
978 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
979 /* HPET - if available - is preferred */
980 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
981 /* ...otherwise try RTC */
982 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
984 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
986 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
987 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
988 {"win32", 0, win32_start_timer
,
989 win32_stop_timer
, NULL
, &alarm_win32_data
},
994 static void show_available_alarms(void)
998 printf("Available alarm timers, in order of precedence:\n");
999 for (i
= 0; alarm_timers
[i
].name
; i
++)
1000 printf("%s\n", alarm_timers
[i
].name
);
1003 static void configure_alarms(char const *opt
)
1007 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1010 struct qemu_alarm_timer tmp
;
1012 if (!strcmp(opt
, "?")) {
1013 show_available_alarms();
1019 /* Reorder the array */
1020 name
= strtok(arg
, ",");
1022 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1023 if (!strcmp(alarm_timers
[i
].name
, name
))
1028 fprintf(stderr
, "Unknown clock %s\n", name
);
1037 tmp
= alarm_timers
[i
];
1038 alarm_timers
[i
] = alarm_timers
[cur
];
1039 alarm_timers
[cur
] = tmp
;
1043 name
= strtok(NULL
, ",");
1049 /* Disable remaining timers */
1050 for (i
= cur
; i
< count
; i
++)
1051 alarm_timers
[i
].name
= NULL
;
1053 show_available_alarms();
1058 QEMUClock
*rt_clock
;
1059 QEMUClock
*vm_clock
;
1061 static QEMUTimer
*active_timers
[2];
1063 static QEMUClock
*qemu_new_clock(int type
)
1066 clock
= qemu_mallocz(sizeof(QEMUClock
));
1073 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1077 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1080 ts
->opaque
= opaque
;
1084 void qemu_free_timer(QEMUTimer
*ts
)
1089 /* stop a timer, but do not dealloc it */
1090 void qemu_del_timer(QEMUTimer
*ts
)
1094 /* NOTE: this code must be signal safe because
1095 qemu_timer_expired() can be called from a signal. */
1096 pt
= &active_timers
[ts
->clock
->type
];
1109 /* modify the current timer so that it will be fired when current_time
1110 >= expire_time. The corresponding callback will be called. */
1111 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1117 /* add the timer in the sorted list */
1118 /* NOTE: this code must be signal safe because
1119 qemu_timer_expired() can be called from a signal. */
1120 pt
= &active_timers
[ts
->clock
->type
];
1125 if (t
->expire_time
> expire_time
)
1129 ts
->expire_time
= expire_time
;
1133 /* Rearm if necessary */
1134 if (pt
== &active_timers
[ts
->clock
->type
]) {
1135 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1136 qemu_rearm_alarm_timer(alarm_timer
);
1138 /* Interrupt execution to force deadline recalculation. */
1139 if (use_icount
&& cpu_single_env
) {
1140 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1145 int qemu_timer_pending(QEMUTimer
*ts
)
1148 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1155 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1159 return (timer_head
->expire_time
<= current_time
);
1162 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1168 if (!ts
|| ts
->expire_time
> current_time
)
1170 /* remove timer from the list before calling the callback */
1171 *ptimer_head
= ts
->next
;
1174 /* run the callback (the timer list can be modified) */
1179 int64_t qemu_get_clock(QEMUClock
*clock
)
1181 switch(clock
->type
) {
1182 case QEMU_TIMER_REALTIME
:
1183 return get_clock() / 1000000;
1185 case QEMU_TIMER_VIRTUAL
:
1187 return cpu_get_icount();
1189 return cpu_get_clock();
1194 static void init_timers(void)
1197 ticks_per_sec
= QEMU_TIMER_BASE
;
1198 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1199 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1203 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1205 uint64_t expire_time
;
1207 if (qemu_timer_pending(ts
)) {
1208 expire_time
= ts
->expire_time
;
1212 qemu_put_be64(f
, expire_time
);
1215 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1217 uint64_t expire_time
;
1219 expire_time
= qemu_get_be64(f
);
1220 if (expire_time
!= -1) {
1221 qemu_mod_timer(ts
, expire_time
);
1227 static void timer_save(QEMUFile
*f
, void *opaque
)
1229 if (cpu_ticks_enabled
) {
1230 hw_error("cannot save state if virtual timers are running");
1232 qemu_put_be64(f
, cpu_ticks_offset
);
1233 qemu_put_be64(f
, ticks_per_sec
);
1234 qemu_put_be64(f
, cpu_clock_offset
);
1237 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1239 if (version_id
!= 1 && version_id
!= 2)
1241 if (cpu_ticks_enabled
) {
1244 cpu_ticks_offset
=qemu_get_be64(f
);
1245 ticks_per_sec
=qemu_get_be64(f
);
1246 if (version_id
== 2) {
1247 cpu_clock_offset
=qemu_get_be64(f
);
1253 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1254 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1256 static void host_alarm_handler(int host_signum
)
1260 #define DISP_FREQ 1000
1262 static int64_t delta_min
= INT64_MAX
;
1263 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1265 ti
= qemu_get_clock(vm_clock
);
1266 if (last_clock
!= 0) {
1267 delta
= ti
- last_clock
;
1268 if (delta
< delta_min
)
1270 if (delta
> delta_max
)
1273 if (++count
== DISP_FREQ
) {
1274 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1275 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1276 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1277 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1278 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1280 delta_min
= INT64_MAX
;
1288 if (alarm_has_dynticks(alarm_timer
) ||
1290 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1291 qemu_get_clock(vm_clock
))) ||
1292 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1293 qemu_get_clock(rt_clock
))) {
1295 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1296 SetEvent(data
->host_alarm
);
1298 CPUState
*env
= next_cpu
;
1300 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1303 /* stop the currently executing cpu because a timer occured */
1304 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1306 if (env
->kqemu_enabled
) {
1307 kqemu_cpu_interrupt(env
);
1315 static int64_t qemu_next_deadline(void)
1319 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1320 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1321 qemu_get_clock(vm_clock
);
1323 /* To avoid problems with overflow limit this to 2^32. */
1333 static uint64_t qemu_next_deadline_dyntick(void)
1341 delta
= (qemu_next_deadline() + 999) / 1000;
1343 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1344 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1345 qemu_get_clock(rt_clock
))*1000;
1346 if (rtdelta
< delta
)
1350 if (delta
< MIN_TIMER_REARM_US
)
1351 delta
= MIN_TIMER_REARM_US
;
1358 #if defined(__linux__)
1360 #define RTC_FREQ 1024
1362 static void enable_sigio_timer(int fd
)
1364 struct sigaction act
;
1367 sigfillset(&act
.sa_mask
);
1369 act
.sa_handler
= host_alarm_handler
;
1371 sigaction(SIGIO
, &act
, NULL
);
1372 fcntl(fd
, F_SETFL
, O_ASYNC
);
1373 fcntl(fd
, F_SETOWN
, getpid());
1376 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1378 struct hpet_info info
;
1381 fd
= open("/dev/hpet", O_RDONLY
);
1386 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1388 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1389 "error, but for better emulation accuracy type:\n"
1390 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1394 /* Check capabilities */
1395 r
= ioctl(fd
, HPET_INFO
, &info
);
1399 /* Enable periodic mode */
1400 r
= ioctl(fd
, HPET_EPI
, 0);
1401 if (info
.hi_flags
&& (r
< 0))
1404 /* Enable interrupt */
1405 r
= ioctl(fd
, HPET_IE_ON
, 0);
1409 enable_sigio_timer(fd
);
1410 t
->priv
= (void *)(long)fd
;
1418 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1420 int fd
= (long)t
->priv
;
1425 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1428 unsigned long current_rtc_freq
= 0;
1430 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1433 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1434 if (current_rtc_freq
!= RTC_FREQ
&&
1435 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1436 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1437 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1438 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1441 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1447 enable_sigio_timer(rtc_fd
);
1449 t
->priv
= (void *)(long)rtc_fd
;
1454 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1456 int rtc_fd
= (long)t
->priv
;
1461 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1465 struct sigaction act
;
1467 sigfillset(&act
.sa_mask
);
1469 act
.sa_handler
= host_alarm_handler
;
1471 sigaction(SIGALRM
, &act
, NULL
);
1473 ev
.sigev_value
.sival_int
= 0;
1474 ev
.sigev_notify
= SIGEV_SIGNAL
;
1475 ev
.sigev_signo
= SIGALRM
;
1477 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1478 perror("timer_create");
1480 /* disable dynticks */
1481 fprintf(stderr
, "Dynamic Ticks disabled\n");
1486 t
->priv
= (void *)host_timer
;
1491 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1493 timer_t host_timer
= (timer_t
)t
->priv
;
1495 timer_delete(host_timer
);
1498 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1500 timer_t host_timer
= (timer_t
)t
->priv
;
1501 struct itimerspec timeout
;
1502 int64_t nearest_delta_us
= INT64_MAX
;
1505 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1506 !active_timers
[QEMU_TIMER_VIRTUAL
])
1509 nearest_delta_us
= qemu_next_deadline_dyntick();
1511 /* check whether a timer is already running */
1512 if (timer_gettime(host_timer
, &timeout
)) {
1514 fprintf(stderr
, "Internal timer error: aborting\n");
1517 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1518 if (current_us
&& current_us
<= nearest_delta_us
)
1521 timeout
.it_interval
.tv_sec
= 0;
1522 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1523 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1524 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1525 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1527 fprintf(stderr
, "Internal timer error: aborting\n");
1532 #endif /* defined(__linux__) */
1534 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1536 struct sigaction act
;
1537 struct itimerval itv
;
1541 sigfillset(&act
.sa_mask
);
1543 act
.sa_handler
= host_alarm_handler
;
1545 sigaction(SIGALRM
, &act
, NULL
);
1547 itv
.it_interval
.tv_sec
= 0;
1548 /* for i386 kernel 2.6 to get 1 ms */
1549 itv
.it_interval
.tv_usec
= 999;
1550 itv
.it_value
.tv_sec
= 0;
1551 itv
.it_value
.tv_usec
= 10 * 1000;
1553 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1560 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1562 struct itimerval itv
;
1564 memset(&itv
, 0, sizeof(itv
));
1565 setitimer(ITIMER_REAL
, &itv
, NULL
);
1568 #endif /* !defined(_WIN32) */
1572 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1575 struct qemu_alarm_win32
*data
= t
->priv
;
1578 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1579 if (!data
->host_alarm
) {
1580 perror("Failed CreateEvent");
1584 memset(&tc
, 0, sizeof(tc
));
1585 timeGetDevCaps(&tc
, sizeof(tc
));
1587 if (data
->period
< tc
.wPeriodMin
)
1588 data
->period
= tc
.wPeriodMin
;
1590 timeBeginPeriod(data
->period
);
1592 flags
= TIME_CALLBACK_FUNCTION
;
1593 if (alarm_has_dynticks(t
))
1594 flags
|= TIME_ONESHOT
;
1596 flags
|= TIME_PERIODIC
;
1598 data
->timerId
= timeSetEvent(1, // interval (ms)
1599 data
->period
, // resolution
1600 host_alarm_handler
, // function
1601 (DWORD
)t
, // parameter
1604 if (!data
->timerId
) {
1605 perror("Failed to initialize win32 alarm timer");
1607 timeEndPeriod(data
->period
);
1608 CloseHandle(data
->host_alarm
);
1612 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1617 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1619 struct qemu_alarm_win32
*data
= t
->priv
;
1621 timeKillEvent(data
->timerId
);
1622 timeEndPeriod(data
->period
);
1624 CloseHandle(data
->host_alarm
);
1627 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1629 struct qemu_alarm_win32
*data
= t
->priv
;
1630 uint64_t nearest_delta_us
;
1632 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1633 !active_timers
[QEMU_TIMER_VIRTUAL
])
1636 nearest_delta_us
= qemu_next_deadline_dyntick();
1637 nearest_delta_us
/= 1000;
1639 timeKillEvent(data
->timerId
);
1641 data
->timerId
= timeSetEvent(1,
1645 TIME_ONESHOT
| TIME_PERIODIC
);
1647 if (!data
->timerId
) {
1648 perror("Failed to re-arm win32 alarm timer");
1650 timeEndPeriod(data
->period
);
1651 CloseHandle(data
->host_alarm
);
1658 static void init_timer_alarm(void)
1660 struct qemu_alarm_timer
*t
;
1663 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1664 t
= &alarm_timers
[i
];
1672 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1673 fprintf(stderr
, "Terminating\n");
1680 static void quit_timers(void)
1682 alarm_timer
->stop(alarm_timer
);
1686 /***********************************************************/
1687 /* host time/date access */
1688 void qemu_get_timedate(struct tm
*tm
, int offset
)
1695 if (rtc_date_offset
== -1) {
1699 ret
= localtime(&ti
);
1701 ti
-= rtc_date_offset
;
1705 memcpy(tm
, ret
, sizeof(struct tm
));
1708 int qemu_timedate_diff(struct tm
*tm
)
1712 if (rtc_date_offset
== -1)
1714 seconds
= mktimegm(tm
);
1716 seconds
= mktime(tm
);
1718 seconds
= mktimegm(tm
) + rtc_date_offset
;
1720 return seconds
- time(NULL
);
1723 /***********************************************************/
1724 /* character device */
1726 static void qemu_chr_event(CharDriverState
*s
, int event
)
1730 s
->chr_event(s
->handler_opaque
, event
);
1733 static void qemu_chr_reset_bh(void *opaque
)
1735 CharDriverState
*s
= opaque
;
1736 qemu_chr_event(s
, CHR_EVENT_RESET
);
1737 qemu_bh_delete(s
->bh
);
1741 void qemu_chr_reset(CharDriverState
*s
)
1743 if (s
->bh
== NULL
) {
1744 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1745 qemu_bh_schedule(s
->bh
);
1749 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1751 return s
->chr_write(s
, buf
, len
);
1754 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1758 return s
->chr_ioctl(s
, cmd
, arg
);
1761 int qemu_chr_can_read(CharDriverState
*s
)
1763 if (!s
->chr_can_read
)
1765 return s
->chr_can_read(s
->handler_opaque
);
1768 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1770 s
->chr_read(s
->handler_opaque
, buf
, len
);
1773 void qemu_chr_accept_input(CharDriverState
*s
)
1775 if (s
->chr_accept_input
)
1776 s
->chr_accept_input(s
);
1779 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1784 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1785 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1789 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1791 if (s
->chr_send_event
)
1792 s
->chr_send_event(s
, event
);
1795 void qemu_chr_add_handlers(CharDriverState
*s
,
1796 IOCanRWHandler
*fd_can_read
,
1797 IOReadHandler
*fd_read
,
1798 IOEventHandler
*fd_event
,
1801 s
->chr_can_read
= fd_can_read
;
1802 s
->chr_read
= fd_read
;
1803 s
->chr_event
= fd_event
;
1804 s
->handler_opaque
= opaque
;
1805 if (s
->chr_update_read_handler
)
1806 s
->chr_update_read_handler(s
);
1809 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1814 static CharDriverState
*qemu_chr_open_null(void)
1816 CharDriverState
*chr
;
1818 chr
= qemu_mallocz(sizeof(CharDriverState
));
1821 chr
->chr_write
= null_chr_write
;
1825 /* MUX driver for serial I/O splitting */
1826 static int term_timestamps
;
1827 static int64_t term_timestamps_start
;
1829 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1830 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1832 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1833 IOReadHandler
*chr_read
[MAX_MUX
];
1834 IOEventHandler
*chr_event
[MAX_MUX
];
1835 void *ext_opaque
[MAX_MUX
];
1836 CharDriverState
*drv
;
1837 unsigned char buffer
[MUX_BUFFER_SIZE
];
1841 int term_got_escape
;
1846 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1848 MuxDriver
*d
= chr
->opaque
;
1850 if (!term_timestamps
) {
1851 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1856 for(i
= 0; i
< len
; i
++) {
1857 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1858 if (buf
[i
] == '\n') {
1864 if (term_timestamps_start
== -1)
1865 term_timestamps_start
= ti
;
1866 ti
-= term_timestamps_start
;
1867 secs
= ti
/ 1000000000;
1868 snprintf(buf1
, sizeof(buf1
),
1869 "[%02d:%02d:%02d.%03d] ",
1873 (int)((ti
/ 1000000) % 1000));
1874 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1881 static char *mux_help
[] = {
1882 "% h print this help\n\r",
1883 "% x exit emulator\n\r",
1884 "% s save disk data back to file (if -snapshot)\n\r",
1885 "% t toggle console timestamps\n\r"
1886 "% b send break (magic sysrq)\n\r",
1887 "% c switch between console and monitor\n\r",
1892 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1893 static void mux_print_help(CharDriverState
*chr
)
1896 char ebuf
[15] = "Escape-Char";
1897 char cbuf
[50] = "\n\r";
1899 if (term_escape_char
> 0 && term_escape_char
< 26) {
1900 sprintf(cbuf
,"\n\r");
1901 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1903 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1906 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1907 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1908 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1909 if (mux_help
[i
][j
] == '%')
1910 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1912 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1917 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1919 if (d
->term_got_escape
) {
1920 d
->term_got_escape
= 0;
1921 if (ch
== term_escape_char
)
1926 mux_print_help(chr
);
1930 char *term
= "QEMU: Terminated\n\r";
1931 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1938 for (i
= 0; i
< nb_drives
; i
++) {
1939 bdrv_commit(drives_table
[i
].bdrv
);
1944 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1947 /* Switch to the next registered device */
1949 if (chr
->focus
>= d
->mux_cnt
)
1953 term_timestamps
= !term_timestamps
;
1954 term_timestamps_start
= -1;
1957 } else if (ch
== term_escape_char
) {
1958 d
->term_got_escape
= 1;
1966 static void mux_chr_accept_input(CharDriverState
*chr
)
1969 MuxDriver
*d
= chr
->opaque
;
1971 while (d
->prod
!= d
->cons
&&
1972 d
->chr_can_read
[m
] &&
1973 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1974 d
->chr_read
[m
](d
->ext_opaque
[m
],
1975 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1979 static int mux_chr_can_read(void *opaque
)
1981 CharDriverState
*chr
= opaque
;
1982 MuxDriver
*d
= chr
->opaque
;
1984 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
1986 if (d
->chr_can_read
[chr
->focus
])
1987 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1991 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1993 CharDriverState
*chr
= opaque
;
1994 MuxDriver
*d
= chr
->opaque
;
1998 mux_chr_accept_input (opaque
);
2000 for(i
= 0; i
< size
; i
++)
2001 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2002 if (d
->prod
== d
->cons
&&
2003 d
->chr_can_read
[m
] &&
2004 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2005 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2007 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2011 static void mux_chr_event(void *opaque
, int event
)
2013 CharDriverState
*chr
= opaque
;
2014 MuxDriver
*d
= chr
->opaque
;
2017 /* Send the event to all registered listeners */
2018 for (i
= 0; i
< d
->mux_cnt
; i
++)
2019 if (d
->chr_event
[i
])
2020 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2023 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2025 MuxDriver
*d
= chr
->opaque
;
2027 if (d
->mux_cnt
>= MAX_MUX
) {
2028 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2031 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2032 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2033 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2034 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2035 /* Fix up the real driver with mux routines */
2036 if (d
->mux_cnt
== 0) {
2037 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2038 mux_chr_event
, chr
);
2040 chr
->focus
= d
->mux_cnt
;
2044 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2046 CharDriverState
*chr
;
2049 chr
= qemu_mallocz(sizeof(CharDriverState
));
2052 d
= qemu_mallocz(sizeof(MuxDriver
));
2061 chr
->chr_write
= mux_chr_write
;
2062 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2063 chr
->chr_accept_input
= mux_chr_accept_input
;
2070 static void socket_cleanup(void)
2075 static int socket_init(void)
2080 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2082 err
= WSAGetLastError();
2083 fprintf(stderr
, "WSAStartup: %d\n", err
);
2086 atexit(socket_cleanup
);
2090 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2096 ret
= send(fd
, buf
, len
, 0);
2099 errno
= WSAGetLastError();
2100 if (errno
!= WSAEWOULDBLOCK
) {
2103 } else if (ret
== 0) {
2113 void socket_set_nonblock(int fd
)
2115 unsigned long opt
= 1;
2116 ioctlsocket(fd
, FIONBIO
, &opt
);
2121 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2127 ret
= write(fd
, buf
, len
);
2129 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2131 } else if (ret
== 0) {
2141 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2143 return unix_write(fd
, buf
, len1
);
2146 void socket_set_nonblock(int fd
)
2149 f
= fcntl(fd
, F_GETFL
);
2150 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2152 #endif /* !_WIN32 */
2161 #define STDIO_MAX_CLIENTS 1
2162 static int stdio_nb_clients
= 0;
2164 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2166 FDCharDriver
*s
= chr
->opaque
;
2167 return unix_write(s
->fd_out
, buf
, len
);
2170 static int fd_chr_read_poll(void *opaque
)
2172 CharDriverState
*chr
= opaque
;
2173 FDCharDriver
*s
= chr
->opaque
;
2175 s
->max_size
= qemu_chr_can_read(chr
);
2179 static void fd_chr_read(void *opaque
)
2181 CharDriverState
*chr
= opaque
;
2182 FDCharDriver
*s
= chr
->opaque
;
2187 if (len
> s
->max_size
)
2191 size
= read(s
->fd_in
, buf
, len
);
2193 /* FD has been closed. Remove it from the active list. */
2194 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2198 qemu_chr_read(chr
, buf
, size
);
2202 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2204 FDCharDriver
*s
= chr
->opaque
;
2206 if (s
->fd_in
>= 0) {
2207 if (nographic
&& s
->fd_in
== 0) {
2209 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2210 fd_chr_read
, NULL
, chr
);
2215 static void fd_chr_close(struct CharDriverState
*chr
)
2217 FDCharDriver
*s
= chr
->opaque
;
2219 if (s
->fd_in
>= 0) {
2220 if (nographic
&& s
->fd_in
== 0) {
2222 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2229 /* open a character device to a unix fd */
2230 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2232 CharDriverState
*chr
;
2235 chr
= qemu_mallocz(sizeof(CharDriverState
));
2238 s
= qemu_mallocz(sizeof(FDCharDriver
));
2246 chr
->chr_write
= fd_chr_write
;
2247 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2248 chr
->chr_close
= fd_chr_close
;
2250 qemu_chr_reset(chr
);
2255 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2259 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2262 return qemu_chr_open_fd(-1, fd_out
);
2265 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2268 char filename_in
[256], filename_out
[256];
2270 snprintf(filename_in
, 256, "%s.in", filename
);
2271 snprintf(filename_out
, 256, "%s.out", filename
);
2272 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2273 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2274 if (fd_in
< 0 || fd_out
< 0) {
2279 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2283 return qemu_chr_open_fd(fd_in
, fd_out
);
2287 /* for STDIO, we handle the case where several clients use it
2290 #define TERM_FIFO_MAX_SIZE 1
2292 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2293 static int term_fifo_size
;
2295 static int stdio_read_poll(void *opaque
)
2297 CharDriverState
*chr
= opaque
;
2299 /* try to flush the queue if needed */
2300 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2301 qemu_chr_read(chr
, term_fifo
, 1);
2304 /* see if we can absorb more chars */
2305 if (term_fifo_size
== 0)
2311 static void stdio_read(void *opaque
)
2315 CharDriverState
*chr
= opaque
;
2317 size
= read(0, buf
, 1);
2319 /* stdin has been closed. Remove it from the active list. */
2320 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2324 if (qemu_chr_can_read(chr
) > 0) {
2325 qemu_chr_read(chr
, buf
, 1);
2326 } else if (term_fifo_size
== 0) {
2327 term_fifo
[term_fifo_size
++] = buf
[0];
2332 /* init terminal so that we can grab keys */
2333 static struct termios oldtty
;
2334 static int old_fd0_flags
;
2335 static int term_atexit_done
;
2337 static void term_exit(void)
2339 tcsetattr (0, TCSANOW
, &oldtty
);
2340 fcntl(0, F_SETFL
, old_fd0_flags
);
2343 static void term_init(void)
2347 tcgetattr (0, &tty
);
2349 old_fd0_flags
= fcntl(0, F_GETFL
);
2351 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2352 |INLCR
|IGNCR
|ICRNL
|IXON
);
2353 tty
.c_oflag
|= OPOST
;
2354 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2355 /* if graphical mode, we allow Ctrl-C handling */
2357 tty
.c_lflag
&= ~ISIG
;
2358 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2361 tty
.c_cc
[VTIME
] = 0;
2363 tcsetattr (0, TCSANOW
, &tty
);
2365 if (!term_atexit_done
++)
2368 fcntl(0, F_SETFL
, O_NONBLOCK
);
2371 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2375 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2379 static CharDriverState
*qemu_chr_open_stdio(void)
2381 CharDriverState
*chr
;
2383 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2385 chr
= qemu_chr_open_fd(0, 1);
2386 chr
->chr_close
= qemu_chr_close_stdio
;
2387 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2395 /* Once Solaris has openpty(), this is going to be removed. */
2396 int openpty(int *amaster
, int *aslave
, char *name
,
2397 struct termios
*termp
, struct winsize
*winp
)
2400 int mfd
= -1, sfd
= -1;
2402 *amaster
= *aslave
= -1;
2404 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2408 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2411 if ((slave
= ptsname(mfd
)) == NULL
)
2414 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2417 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2418 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2426 ioctl(sfd
, TIOCSWINSZ
, winp
);
2437 void cfmakeraw (struct termios
*termios_p
)
2439 termios_p
->c_iflag
&=
2440 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2441 termios_p
->c_oflag
&= ~OPOST
;
2442 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2443 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2444 termios_p
->c_cflag
|= CS8
;
2446 termios_p
->c_cc
[VMIN
] = 0;
2447 termios_p
->c_cc
[VTIME
] = 0;
2451 #if defined(__linux__) || defined(__sun__)
2452 static CharDriverState
*qemu_chr_open_pty(void)
2455 int master_fd
, slave_fd
;
2457 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2461 /* Set raw attributes on the pty. */
2463 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2465 fprintf(stderr
, "char device redirected to %s\n", ptsname(master_fd
));
2466 return qemu_chr_open_fd(master_fd
, master_fd
);
2469 static void tty_serial_init(int fd
, int speed
,
2470 int parity
, int data_bits
, int stop_bits
)
2476 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2477 speed
, parity
, data_bits
, stop_bits
);
2479 tcgetattr (fd
, &tty
);
2482 if (speed
<= 50 * MARGIN
)
2484 else if (speed
<= 75 * MARGIN
)
2486 else if (speed
<= 300 * MARGIN
)
2488 else if (speed
<= 600 * MARGIN
)
2490 else if (speed
<= 1200 * MARGIN
)
2492 else if (speed
<= 2400 * MARGIN
)
2494 else if (speed
<= 4800 * MARGIN
)
2496 else if (speed
<= 9600 * MARGIN
)
2498 else if (speed
<= 19200 * MARGIN
)
2500 else if (speed
<= 38400 * MARGIN
)
2502 else if (speed
<= 57600 * MARGIN
)
2504 else if (speed
<= 115200 * MARGIN
)
2509 cfsetispeed(&tty
, spd
);
2510 cfsetospeed(&tty
, spd
);
2512 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2513 |INLCR
|IGNCR
|ICRNL
|IXON
);
2514 tty
.c_oflag
|= OPOST
;
2515 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2516 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2537 tty
.c_cflag
|= PARENB
;
2540 tty
.c_cflag
|= PARENB
| PARODD
;
2544 tty
.c_cflag
|= CSTOPB
;
2546 tcsetattr (fd
, TCSANOW
, &tty
);
2549 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2551 FDCharDriver
*s
= chr
->opaque
;
2554 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2556 QEMUSerialSetParams
*ssp
= arg
;
2557 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2558 ssp
->data_bits
, ssp
->stop_bits
);
2561 case CHR_IOCTL_SERIAL_SET_BREAK
:
2563 int enable
= *(int *)arg
;
2565 tcsendbreak(s
->fd_in
, 1);
2574 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2576 CharDriverState
*chr
;
2579 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2580 tty_serial_init(fd
, 115200, 'N', 8, 1);
2581 chr
= qemu_chr_open_fd(fd
, fd
);
2586 chr
->chr_ioctl
= tty_serial_ioctl
;
2587 qemu_chr_reset(chr
);
2590 #else /* ! __linux__ && ! __sun__ */
2591 static CharDriverState
*qemu_chr_open_pty(void)
2595 #endif /* __linux__ || __sun__ */
2597 #if defined(__linux__)
2601 } ParallelCharDriver
;
2603 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2605 if (s
->mode
!= mode
) {
2607 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2614 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2616 ParallelCharDriver
*drv
= chr
->opaque
;
2621 case CHR_IOCTL_PP_READ_DATA
:
2622 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2624 *(uint8_t *)arg
= b
;
2626 case CHR_IOCTL_PP_WRITE_DATA
:
2627 b
= *(uint8_t *)arg
;
2628 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2631 case CHR_IOCTL_PP_READ_CONTROL
:
2632 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2634 /* Linux gives only the lowest bits, and no way to know data
2635 direction! For better compatibility set the fixed upper
2637 *(uint8_t *)arg
= b
| 0xc0;
2639 case CHR_IOCTL_PP_WRITE_CONTROL
:
2640 b
= *(uint8_t *)arg
;
2641 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2644 case CHR_IOCTL_PP_READ_STATUS
:
2645 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2647 *(uint8_t *)arg
= b
;
2649 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2650 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2651 struct ParallelIOArg
*parg
= arg
;
2652 int n
= read(fd
, parg
->buffer
, parg
->count
);
2653 if (n
!= parg
->count
) {
2658 case CHR_IOCTL_PP_EPP_READ
:
2659 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2660 struct ParallelIOArg
*parg
= arg
;
2661 int n
= read(fd
, parg
->buffer
, parg
->count
);
2662 if (n
!= parg
->count
) {
2667 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2668 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2669 struct ParallelIOArg
*parg
= arg
;
2670 int n
= write(fd
, parg
->buffer
, parg
->count
);
2671 if (n
!= parg
->count
) {
2676 case CHR_IOCTL_PP_EPP_WRITE
:
2677 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2678 struct ParallelIOArg
*parg
= arg
;
2679 int n
= write(fd
, parg
->buffer
, parg
->count
);
2680 if (n
!= parg
->count
) {
2691 static void pp_close(CharDriverState
*chr
)
2693 ParallelCharDriver
*drv
= chr
->opaque
;
2696 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2697 ioctl(fd
, PPRELEASE
);
2702 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2704 CharDriverState
*chr
;
2705 ParallelCharDriver
*drv
;
2708 TFR(fd
= open(filename
, O_RDWR
));
2712 if (ioctl(fd
, PPCLAIM
) < 0) {
2717 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2723 drv
->mode
= IEEE1284_MODE_COMPAT
;
2725 chr
= qemu_mallocz(sizeof(CharDriverState
));
2731 chr
->chr_write
= null_chr_write
;
2732 chr
->chr_ioctl
= pp_ioctl
;
2733 chr
->chr_close
= pp_close
;
2736 qemu_chr_reset(chr
);
2740 #endif /* __linux__ */
2746 HANDLE hcom
, hrecv
, hsend
;
2747 OVERLAPPED orecv
, osend
;
2752 #define NSENDBUF 2048
2753 #define NRECVBUF 2048
2754 #define MAXCONNECT 1
2755 #define NTIMEOUT 5000
2757 static int win_chr_poll(void *opaque
);
2758 static int win_chr_pipe_poll(void *opaque
);
2760 static void win_chr_close(CharDriverState
*chr
)
2762 WinCharState
*s
= chr
->opaque
;
2765 CloseHandle(s
->hsend
);
2769 CloseHandle(s
->hrecv
);
2773 CloseHandle(s
->hcom
);
2777 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2779 qemu_del_polling_cb(win_chr_poll
, chr
);
2782 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2784 WinCharState
*s
= chr
->opaque
;
2786 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2791 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2793 fprintf(stderr
, "Failed CreateEvent\n");
2796 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2798 fprintf(stderr
, "Failed CreateEvent\n");
2802 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2803 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2804 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2805 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2810 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2811 fprintf(stderr
, "Failed SetupComm\n");
2815 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2816 size
= sizeof(COMMCONFIG
);
2817 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2818 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2819 CommConfigDialog(filename
, NULL
, &comcfg
);
2821 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2822 fprintf(stderr
, "Failed SetCommState\n");
2826 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2827 fprintf(stderr
, "Failed SetCommMask\n");
2831 cto
.ReadIntervalTimeout
= MAXDWORD
;
2832 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2833 fprintf(stderr
, "Failed SetCommTimeouts\n");
2837 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2838 fprintf(stderr
, "Failed ClearCommError\n");
2841 qemu_add_polling_cb(win_chr_poll
, chr
);
2849 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2851 WinCharState
*s
= chr
->opaque
;
2852 DWORD len
, ret
, size
, err
;
2855 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2856 s
->osend
.hEvent
= s
->hsend
;
2859 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2861 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2863 err
= GetLastError();
2864 if (err
== ERROR_IO_PENDING
) {
2865 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2883 static int win_chr_read_poll(CharDriverState
*chr
)
2885 WinCharState
*s
= chr
->opaque
;
2887 s
->max_size
= qemu_chr_can_read(chr
);
2891 static void win_chr_readfile(CharDriverState
*chr
)
2893 WinCharState
*s
= chr
->opaque
;
2898 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2899 s
->orecv
.hEvent
= s
->hrecv
;
2900 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2902 err
= GetLastError();
2903 if (err
== ERROR_IO_PENDING
) {
2904 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2909 qemu_chr_read(chr
, buf
, size
);
2913 static void win_chr_read(CharDriverState
*chr
)
2915 WinCharState
*s
= chr
->opaque
;
2917 if (s
->len
> s
->max_size
)
2918 s
->len
= s
->max_size
;
2922 win_chr_readfile(chr
);
2925 static int win_chr_poll(void *opaque
)
2927 CharDriverState
*chr
= opaque
;
2928 WinCharState
*s
= chr
->opaque
;
2932 ClearCommError(s
->hcom
, &comerr
, &status
);
2933 if (status
.cbInQue
> 0) {
2934 s
->len
= status
.cbInQue
;
2935 win_chr_read_poll(chr
);
2942 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2944 CharDriverState
*chr
;
2947 chr
= qemu_mallocz(sizeof(CharDriverState
));
2950 s
= qemu_mallocz(sizeof(WinCharState
));
2956 chr
->chr_write
= win_chr_write
;
2957 chr
->chr_close
= win_chr_close
;
2959 if (win_chr_init(chr
, filename
) < 0) {
2964 qemu_chr_reset(chr
);
2968 static int win_chr_pipe_poll(void *opaque
)
2970 CharDriverState
*chr
= opaque
;
2971 WinCharState
*s
= chr
->opaque
;
2974 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2977 win_chr_read_poll(chr
);
2984 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2986 WinCharState
*s
= chr
->opaque
;
2994 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2996 fprintf(stderr
, "Failed CreateEvent\n");
2999 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3001 fprintf(stderr
, "Failed CreateEvent\n");
3005 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3006 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3007 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3009 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3010 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3011 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3016 ZeroMemory(&ov
, sizeof(ov
));
3017 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3018 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3020 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3024 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3026 fprintf(stderr
, "Failed GetOverlappedResult\n");
3028 CloseHandle(ov
.hEvent
);
3035 CloseHandle(ov
.hEvent
);
3038 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3047 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3049 CharDriverState
*chr
;
3052 chr
= qemu_mallocz(sizeof(CharDriverState
));
3055 s
= qemu_mallocz(sizeof(WinCharState
));
3061 chr
->chr_write
= win_chr_write
;
3062 chr
->chr_close
= win_chr_close
;
3064 if (win_chr_pipe_init(chr
, filename
) < 0) {
3069 qemu_chr_reset(chr
);
3073 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3075 CharDriverState
*chr
;
3078 chr
= qemu_mallocz(sizeof(CharDriverState
));
3081 s
= qemu_mallocz(sizeof(WinCharState
));
3088 chr
->chr_write
= win_chr_write
;
3089 qemu_chr_reset(chr
);
3093 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3095 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3098 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3102 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3103 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3104 if (fd_out
== INVALID_HANDLE_VALUE
)
3107 return qemu_chr_open_win_file(fd_out
);
3109 #endif /* !_WIN32 */
3111 /***********************************************************/
3112 /* UDP Net console */
3116 struct sockaddr_in daddr
;
3123 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3125 NetCharDriver
*s
= chr
->opaque
;
3127 return sendto(s
->fd
, buf
, len
, 0,
3128 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3131 static int udp_chr_read_poll(void *opaque
)
3133 CharDriverState
*chr
= opaque
;
3134 NetCharDriver
*s
= chr
->opaque
;
3136 s
->max_size
= qemu_chr_can_read(chr
);
3138 /* If there were any stray characters in the queue process them
3141 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3142 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3144 s
->max_size
= qemu_chr_can_read(chr
);
3149 static void udp_chr_read(void *opaque
)
3151 CharDriverState
*chr
= opaque
;
3152 NetCharDriver
*s
= chr
->opaque
;
3154 if (s
->max_size
== 0)
3156 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3157 s
->bufptr
= s
->bufcnt
;
3162 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3163 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3165 s
->max_size
= qemu_chr_can_read(chr
);
3169 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3171 NetCharDriver
*s
= chr
->opaque
;
3174 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3175 udp_chr_read
, NULL
, chr
);
3179 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3181 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3183 int parse_host_src_port(struct sockaddr_in
*haddr
,
3184 struct sockaddr_in
*saddr
,
3187 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3189 CharDriverState
*chr
= NULL
;
3190 NetCharDriver
*s
= NULL
;
3192 struct sockaddr_in saddr
;
3194 chr
= qemu_mallocz(sizeof(CharDriverState
));
3197 s
= qemu_mallocz(sizeof(NetCharDriver
));
3201 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3203 perror("socket(PF_INET, SOCK_DGRAM)");
3207 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3208 printf("Could not parse: %s\n", def
);
3212 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3222 chr
->chr_write
= udp_chr_write
;
3223 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3236 /***********************************************************/
3237 /* TCP Net console */
3248 static void tcp_chr_accept(void *opaque
);
3250 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3252 TCPCharDriver
*s
= chr
->opaque
;
3254 return send_all(s
->fd
, buf
, len
);
3256 /* XXX: indicate an error ? */
3261 static int tcp_chr_read_poll(void *opaque
)
3263 CharDriverState
*chr
= opaque
;
3264 TCPCharDriver
*s
= chr
->opaque
;
3267 s
->max_size
= qemu_chr_can_read(chr
);
3272 #define IAC_BREAK 243
3273 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3275 uint8_t *buf
, int *size
)
3277 /* Handle any telnet client's basic IAC options to satisfy char by
3278 * char mode with no echo. All IAC options will be removed from
3279 * the buf and the do_telnetopt variable will be used to track the
3280 * state of the width of the IAC information.
3282 * IAC commands come in sets of 3 bytes with the exception of the
3283 * "IAC BREAK" command and the double IAC.
3289 for (i
= 0; i
< *size
; i
++) {
3290 if (s
->do_telnetopt
> 1) {
3291 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3292 /* Double IAC means send an IAC */
3296 s
->do_telnetopt
= 1;
3298 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3299 /* Handle IAC break commands by sending a serial break */
3300 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3305 if (s
->do_telnetopt
>= 4) {
3306 s
->do_telnetopt
= 1;
3309 if ((unsigned char)buf
[i
] == IAC
) {
3310 s
->do_telnetopt
= 2;
3321 static void tcp_chr_read(void *opaque
)
3323 CharDriverState
*chr
= opaque
;
3324 TCPCharDriver
*s
= chr
->opaque
;
3328 if (!s
->connected
|| s
->max_size
<= 0)
3331 if (len
> s
->max_size
)
3333 size
= recv(s
->fd
, buf
, len
, 0);
3335 /* connection closed */
3337 if (s
->listen_fd
>= 0) {
3338 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3340 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3343 } else if (size
> 0) {
3344 if (s
->do_telnetopt
)
3345 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3347 qemu_chr_read(chr
, buf
, size
);
3351 static void tcp_chr_connect(void *opaque
)
3353 CharDriverState
*chr
= opaque
;
3354 TCPCharDriver
*s
= chr
->opaque
;
3357 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3358 tcp_chr_read
, NULL
, chr
);
3359 qemu_chr_reset(chr
);
3362 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3363 static void tcp_chr_telnet_init(int fd
)
3366 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3367 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3368 send(fd
, (char *)buf
, 3, 0);
3369 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3370 send(fd
, (char *)buf
, 3, 0);
3371 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3372 send(fd
, (char *)buf
, 3, 0);
3373 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3374 send(fd
, (char *)buf
, 3, 0);
3377 static void socket_set_nodelay(int fd
)
3380 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3383 static void tcp_chr_accept(void *opaque
)
3385 CharDriverState
*chr
= opaque
;
3386 TCPCharDriver
*s
= chr
->opaque
;
3387 struct sockaddr_in saddr
;
3389 struct sockaddr_un uaddr
;
3391 struct sockaddr
*addr
;
3398 len
= sizeof(uaddr
);
3399 addr
= (struct sockaddr
*)&uaddr
;
3403 len
= sizeof(saddr
);
3404 addr
= (struct sockaddr
*)&saddr
;
3406 fd
= accept(s
->listen_fd
, addr
, &len
);
3407 if (fd
< 0 && errno
!= EINTR
) {
3409 } else if (fd
>= 0) {
3410 if (s
->do_telnetopt
)
3411 tcp_chr_telnet_init(fd
);
3415 socket_set_nonblock(fd
);
3417 socket_set_nodelay(fd
);
3419 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3420 tcp_chr_connect(chr
);
3423 static void tcp_chr_close(CharDriverState
*chr
)
3425 TCPCharDriver
*s
= chr
->opaque
;
3428 if (s
->listen_fd
>= 0)
3429 closesocket(s
->listen_fd
);
3433 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3437 CharDriverState
*chr
= NULL
;
3438 TCPCharDriver
*s
= NULL
;
3439 int fd
= -1, ret
, err
, val
;
3441 int is_waitconnect
= 1;
3444 struct sockaddr_in saddr
;
3446 struct sockaddr_un uaddr
;
3448 struct sockaddr
*addr
;
3453 addr
= (struct sockaddr
*)&uaddr
;
3454 addrlen
= sizeof(uaddr
);
3455 if (parse_unix_path(&uaddr
, host_str
) < 0)
3460 addr
= (struct sockaddr
*)&saddr
;
3461 addrlen
= sizeof(saddr
);
3462 if (parse_host_port(&saddr
, host_str
) < 0)
3467 while((ptr
= strchr(ptr
,','))) {
3469 if (!strncmp(ptr
,"server",6)) {
3471 } else if (!strncmp(ptr
,"nowait",6)) {
3473 } else if (!strncmp(ptr
,"nodelay",6)) {
3476 printf("Unknown option: %s\n", ptr
);
3483 chr
= qemu_mallocz(sizeof(CharDriverState
));
3486 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3492 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3495 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3500 if (!is_waitconnect
)
3501 socket_set_nonblock(fd
);
3506 s
->is_unix
= is_unix
;
3507 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3510 chr
->chr_write
= tcp_chr_write
;
3511 chr
->chr_close
= tcp_chr_close
;
3514 /* allow fast reuse */
3518 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3524 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3527 ret
= bind(fd
, addr
, addrlen
);
3531 ret
= listen(fd
, 0);
3536 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3538 s
->do_telnetopt
= 1;
3541 ret
= connect(fd
, addr
, addrlen
);
3543 err
= socket_error();
3544 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3545 } else if (err
== EINPROGRESS
) {
3548 } else if (err
== WSAEALREADY
) {
3560 socket_set_nodelay(fd
);
3562 tcp_chr_connect(chr
);
3564 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3567 if (is_listen
&& is_waitconnect
) {
3568 printf("QEMU waiting for connection on: %s\n", host_str
);
3569 tcp_chr_accept(chr
);
3570 socket_set_nonblock(s
->listen_fd
);
3582 CharDriverState
*qemu_chr_open(const char *filename
)
3586 if (!strcmp(filename
, "vc")) {
3587 return text_console_init(&display_state
, 0);
3588 } else if (strstart(filename
, "vc:", &p
)) {
3589 return text_console_init(&display_state
, p
);
3590 } else if (!strcmp(filename
, "null")) {
3591 return qemu_chr_open_null();
3593 if (strstart(filename
, "tcp:", &p
)) {
3594 return qemu_chr_open_tcp(p
, 0, 0);
3596 if (strstart(filename
, "telnet:", &p
)) {
3597 return qemu_chr_open_tcp(p
, 1, 0);
3599 if (strstart(filename
, "udp:", &p
)) {
3600 return qemu_chr_open_udp(p
);
3602 if (strstart(filename
, "mon:", &p
)) {
3603 CharDriverState
*drv
= qemu_chr_open(p
);
3605 drv
= qemu_chr_open_mux(drv
);
3606 monitor_init(drv
, !nographic
);
3609 printf("Unable to open driver: %s\n", p
);
3613 if (strstart(filename
, "unix:", &p
)) {
3614 return qemu_chr_open_tcp(p
, 0, 1);
3615 } else if (strstart(filename
, "file:", &p
)) {
3616 return qemu_chr_open_file_out(p
);
3617 } else if (strstart(filename
, "pipe:", &p
)) {
3618 return qemu_chr_open_pipe(p
);
3619 } else if (!strcmp(filename
, "pty")) {
3620 return qemu_chr_open_pty();
3621 } else if (!strcmp(filename
, "stdio")) {
3622 return qemu_chr_open_stdio();
3624 #if defined(__linux__)
3625 if (strstart(filename
, "/dev/parport", NULL
)) {
3626 return qemu_chr_open_pp(filename
);
3629 #if defined(__linux__) || defined(__sun__)
3630 if (strstart(filename
, "/dev/", NULL
)) {
3631 return qemu_chr_open_tty(filename
);
3635 if (strstart(filename
, "COM", NULL
)) {
3636 return qemu_chr_open_win(filename
);
3638 if (strstart(filename
, "pipe:", &p
)) {
3639 return qemu_chr_open_win_pipe(p
);
3641 if (strstart(filename
, "con:", NULL
)) {
3642 return qemu_chr_open_win_con(filename
);
3644 if (strstart(filename
, "file:", &p
)) {
3645 return qemu_chr_open_win_file_out(p
);
3648 #ifdef CONFIG_BRLAPI
3649 if (!strcmp(filename
, "braille")) {
3650 return chr_baum_init();
3658 void qemu_chr_close(CharDriverState
*chr
)
3661 chr
->chr_close(chr
);
3665 /***********************************************************/
3666 /* network device redirectors */
3668 __attribute__ (( unused
))
3669 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3673 for(i
=0;i
<size
;i
+=16) {
3677 fprintf(f
, "%08x ", i
);
3680 fprintf(f
, " %02x", buf
[i
+j
]);
3685 for(j
=0;j
<len
;j
++) {
3687 if (c
< ' ' || c
> '~')
3689 fprintf(f
, "%c", c
);
3695 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3702 offset
= strtol(p
, &last_char
, 0);
3703 if (0 == errno
&& '\0' == *last_char
&&
3704 offset
>= 0 && offset
<= 0xFFFFFF) {
3705 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3706 macaddr
[4] = (offset
& 0xFF00) >> 8;
3707 macaddr
[5] = offset
& 0xFF;
3710 for(i
= 0; i
< 6; i
++) {
3711 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3716 if (*p
!= ':' && *p
!= '-')
3727 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3732 p1
= strchr(p
, sep
);
3738 if (len
> buf_size
- 1)
3740 memcpy(buf
, p
, len
);
3747 int parse_host_src_port(struct sockaddr_in
*haddr
,
3748 struct sockaddr_in
*saddr
,
3749 const char *input_str
)
3751 char *str
= strdup(input_str
);
3752 char *host_str
= str
;
3757 * Chop off any extra arguments at the end of the string which
3758 * would start with a comma, then fill in the src port information
3759 * if it was provided else use the "any address" and "any port".
3761 if ((ptr
= strchr(str
,',')))
3764 if ((src_str
= strchr(input_str
,'@'))) {
3769 if (parse_host_port(haddr
, host_str
) < 0)
3772 if (!src_str
|| *src_str
== '\0')
3775 if (parse_host_port(saddr
, src_str
) < 0)
3786 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3794 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3796 saddr
->sin_family
= AF_INET
;
3797 if (buf
[0] == '\0') {
3798 saddr
->sin_addr
.s_addr
= 0;
3800 if (isdigit(buf
[0])) {
3801 if (!inet_aton(buf
, &saddr
->sin_addr
))
3804 if ((he
= gethostbyname(buf
)) == NULL
)
3806 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3809 port
= strtol(p
, (char **)&r
, 0);
3812 saddr
->sin_port
= htons(port
);
3817 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3822 len
= MIN(108, strlen(str
));
3823 p
= strchr(str
, ',');
3825 len
= MIN(len
, p
- str
);
3827 memset(uaddr
, 0, sizeof(*uaddr
));
3829 uaddr
->sun_family
= AF_UNIX
;
3830 memcpy(uaddr
->sun_path
, str
, len
);
3836 /* find or alloc a new VLAN */
3837 VLANState
*qemu_find_vlan(int id
)
3839 VLANState
**pvlan
, *vlan
;
3840 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3844 vlan
= qemu_mallocz(sizeof(VLANState
));
3849 pvlan
= &first_vlan
;
3850 while (*pvlan
!= NULL
)
3851 pvlan
= &(*pvlan
)->next
;
3856 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3857 IOReadHandler
*fd_read
,
3858 IOCanRWHandler
*fd_can_read
,
3861 VLANClientState
*vc
, **pvc
;
3862 vc
= qemu_mallocz(sizeof(VLANClientState
));
3865 vc
->fd_read
= fd_read
;
3866 vc
->fd_can_read
= fd_can_read
;
3867 vc
->opaque
= opaque
;
3871 pvc
= &vlan
->first_client
;
3872 while (*pvc
!= NULL
)
3873 pvc
= &(*pvc
)->next
;
3878 void qemu_del_vlan_client(VLANClientState
*vc
)
3880 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
3882 while (*pvc
!= NULL
)
3888 pvc
= &(*pvc
)->next
;
3891 int qemu_can_send_packet(VLANClientState
*vc1
)
3893 VLANState
*vlan
= vc1
->vlan
;
3894 VLANClientState
*vc
;
3896 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3898 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
3905 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3907 VLANState
*vlan
= vc1
->vlan
;
3908 VLANClientState
*vc
;
3911 printf("vlan %d send:\n", vlan
->id
);
3912 hex_dump(stdout
, buf
, size
);
3914 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3916 vc
->fd_read(vc
->opaque
, buf
, size
);
3921 #if defined(CONFIG_SLIRP)
3923 /* slirp network adapter */
3925 static int slirp_inited
;
3926 static VLANClientState
*slirp_vc
;
3928 int slirp_can_output(void)
3930 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3933 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3936 printf("slirp output:\n");
3937 hex_dump(stdout
, pkt
, pkt_len
);
3941 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3944 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3947 printf("slirp input:\n");
3948 hex_dump(stdout
, buf
, size
);
3950 slirp_input(buf
, size
);
3953 static int net_slirp_init(VLANState
*vlan
)
3955 if (!slirp_inited
) {
3959 slirp_vc
= qemu_new_vlan_client(vlan
,
3960 slirp_receive
, NULL
, NULL
);
3961 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3965 static void net_slirp_redir(const char *redir_str
)
3970 struct in_addr guest_addr
;
3971 int host_port
, guest_port
;
3973 if (!slirp_inited
) {
3979 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3981 if (!strcmp(buf
, "tcp")) {
3983 } else if (!strcmp(buf
, "udp")) {
3989 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3991 host_port
= strtol(buf
, &r
, 0);
3995 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3997 if (buf
[0] == '\0') {
3998 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4000 if (!inet_aton(buf
, &guest_addr
))
4003 guest_port
= strtol(p
, &r
, 0);
4007 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4008 fprintf(stderr
, "qemu: could not set up redirection\n");
4013 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4021 static void erase_dir(char *dir_name
)
4025 char filename
[1024];
4027 /* erase all the files in the directory */
4028 if ((d
= opendir(dir_name
)) != 0) {
4033 if (strcmp(de
->d_name
, ".") != 0 &&
4034 strcmp(de
->d_name
, "..") != 0) {
4035 snprintf(filename
, sizeof(filename
), "%s/%s",
4036 smb_dir
, de
->d_name
);
4037 if (unlink(filename
) != 0) /* is it a directory? */
4038 erase_dir(filename
);
4046 /* automatic user mode samba server configuration */
4047 static void smb_exit(void)
4052 /* automatic user mode samba server configuration */
4053 static void net_slirp_smb(const char *exported_dir
)
4055 char smb_conf
[1024];
4056 char smb_cmdline
[1024];
4059 if (!slirp_inited
) {
4064 /* XXX: better tmp dir construction */
4065 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4066 if (mkdir(smb_dir
, 0700) < 0) {
4067 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4070 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4072 f
= fopen(smb_conf
, "w");
4074 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4081 "socket address=127.0.0.1\n"
4082 "pid directory=%s\n"
4083 "lock directory=%s\n"
4084 "log file=%s/log.smbd\n"
4085 "smb passwd file=%s/smbpasswd\n"
4086 "security = share\n"
4101 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4102 SMBD_COMMAND
, smb_conf
);
4104 slirp_add_exec(0, smb_cmdline
, 4, 139);
4107 #endif /* !defined(_WIN32) */
4108 void do_info_slirp(void)
4113 #endif /* CONFIG_SLIRP */
4115 #if !defined(_WIN32)
4117 typedef struct TAPState
{
4118 VLANClientState
*vc
;
4120 char down_script
[1024];
4123 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4125 TAPState
*s
= opaque
;
4128 ret
= write(s
->fd
, buf
, size
);
4129 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4136 static void tap_send(void *opaque
)
4138 TAPState
*s
= opaque
;
4145 sbuf
.maxlen
= sizeof(buf
);
4147 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4149 size
= read(s
->fd
, buf
, sizeof(buf
));
4152 qemu_send_packet(s
->vc
, buf
, size
);
4158 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4162 s
= qemu_mallocz(sizeof(TAPState
));
4166 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4167 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4168 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4172 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4173 static int tap_open(char *ifname
, int ifname_size
)
4179 TFR(fd
= open("/dev/tap", O_RDWR
));
4181 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4186 dev
= devname(s
.st_rdev
, S_IFCHR
);
4187 pstrcpy(ifname
, ifname_size
, dev
);
4189 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4192 #elif defined(__sun__)
4193 #define TUNNEWPPA (('T'<<16) | 0x0001)
4195 * Allocate TAP device, returns opened fd.
4196 * Stores dev name in the first arg(must be large enough).
4198 int tap_alloc(char *dev
)
4200 int tap_fd
, if_fd
, ppa
= -1;
4201 static int ip_fd
= 0;
4204 static int arp_fd
= 0;
4205 int ip_muxid
, arp_muxid
;
4206 struct strioctl strioc_if
, strioc_ppa
;
4207 int link_type
= I_PLINK
;;
4209 char actual_name
[32] = "";
4211 memset(&ifr
, 0x0, sizeof(ifr
));
4215 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4219 /* Check if IP device was opened */
4223 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4225 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4229 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4231 syslog(LOG_ERR
, "Can't open /dev/tap");
4235 /* Assign a new PPA and get its unit number. */
4236 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4237 strioc_ppa
.ic_timout
= 0;
4238 strioc_ppa
.ic_len
= sizeof(ppa
);
4239 strioc_ppa
.ic_dp
= (char *)&ppa
;
4240 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4241 syslog (LOG_ERR
, "Can't assign new interface");
4243 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4245 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4248 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4249 syslog(LOG_ERR
, "Can't push IP module");
4253 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4254 syslog(LOG_ERR
, "Can't get flags\n");
4256 snprintf (actual_name
, 32, "tap%d", ppa
);
4257 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4260 /* Assign ppa according to the unit number returned by tun device */
4262 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4263 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4264 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4265 syslog (LOG_ERR
, "Can't get flags\n");
4266 /* Push arp module to if_fd */
4267 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4268 syslog (LOG_ERR
, "Can't push ARP module (2)");
4270 /* Push arp module to ip_fd */
4271 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4272 syslog (LOG_ERR
, "I_POP failed\n");
4273 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4274 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4276 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4278 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4280 /* Set ifname to arp */
4281 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4282 strioc_if
.ic_timout
= 0;
4283 strioc_if
.ic_len
= sizeof(ifr
);
4284 strioc_if
.ic_dp
= (char *)&ifr
;
4285 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4286 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4289 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4290 syslog(LOG_ERR
, "Can't link TAP device to IP");
4294 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4295 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4299 memset(&ifr
, 0x0, sizeof(ifr
));
4300 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4301 ifr
.lifr_ip_muxid
= ip_muxid
;
4302 ifr
.lifr_arp_muxid
= arp_muxid
;
4304 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4306 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4307 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4308 syslog (LOG_ERR
, "Can't set multiplexor id");
4311 sprintf(dev
, "tap%d", ppa
);
4315 static int tap_open(char *ifname
, int ifname_size
)
4319 if( (fd
= tap_alloc(dev
)) < 0 ){
4320 fprintf(stderr
, "Cannot allocate TAP device\n");
4323 pstrcpy(ifname
, ifname_size
, dev
);
4324 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4328 static int tap_open(char *ifname
, int ifname_size
)
4333 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4335 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4338 memset(&ifr
, 0, sizeof(ifr
));
4339 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4340 if (ifname
[0] != '\0')
4341 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4343 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4344 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4346 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4350 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4351 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4356 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4362 /* try to launch network script */
4366 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4367 for (i
= 0; i
< open_max
; i
++)
4368 if (i
!= STDIN_FILENO
&&
4369 i
!= STDOUT_FILENO
&&
4370 i
!= STDERR_FILENO
&&
4375 *parg
++ = (char *)setup_script
;
4376 *parg
++ = (char *)ifname
;
4378 execv(setup_script
, args
);
4381 while (waitpid(pid
, &status
, 0) != pid
);
4382 if (!WIFEXITED(status
) ||
4383 WEXITSTATUS(status
) != 0) {
4384 fprintf(stderr
, "%s: could not launch network script\n",
4392 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4393 const char *setup_script
, const char *down_script
)
4399 if (ifname1
!= NULL
)
4400 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4403 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4407 if (!setup_script
|| !strcmp(setup_script
, "no"))
4409 if (setup_script
[0] != '\0') {
4410 if (launch_script(setup_script
, ifname
, fd
))
4413 s
= net_tap_fd_init(vlan
, fd
);
4416 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4417 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4418 if (down_script
&& strcmp(down_script
, "no"))
4419 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4423 #endif /* !_WIN32 */
4425 #if defined(CONFIG_VDE)
4426 typedef struct VDEState
{
4427 VLANClientState
*vc
;
4431 static void vde_to_qemu(void *opaque
)
4433 VDEState
*s
= opaque
;
4437 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4439 qemu_send_packet(s
->vc
, buf
, size
);
4443 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4445 VDEState
*s
= opaque
;
4448 ret
= vde_send(s
->vde
, buf
, size
, 0);
4449 if (ret
< 0 && errno
== EINTR
) {
4456 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4457 const char *group
, int mode
)
4460 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4461 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4463 struct vde_open_args args
= {
4465 .group
= init_group
,
4469 s
= qemu_mallocz(sizeof(VDEState
));
4472 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4477 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4478 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4479 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4480 sock
, vde_datafd(s
->vde
));
4485 /* network connection */
4486 typedef struct NetSocketState
{
4487 VLANClientState
*vc
;
4489 int state
; /* 0 = getting length, 1 = getting data */
4493 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4496 typedef struct NetSocketListenState
{
4499 } NetSocketListenState
;
4501 /* XXX: we consider we can send the whole packet without blocking */
4502 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4504 NetSocketState
*s
= opaque
;
4508 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4509 send_all(s
->fd
, buf
, size
);
4512 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4514 NetSocketState
*s
= opaque
;
4515 sendto(s
->fd
, buf
, size
, 0,
4516 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4519 static void net_socket_send(void *opaque
)
4521 NetSocketState
*s
= opaque
;
4526 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4528 err
= socket_error();
4529 if (err
!= EWOULDBLOCK
)
4531 } else if (size
== 0) {
4532 /* end of connection */
4534 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4540 /* reassemble a packet from the network */
4546 memcpy(s
->buf
+ s
->index
, buf
, l
);
4550 if (s
->index
== 4) {
4552 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4558 l
= s
->packet_len
- s
->index
;
4561 memcpy(s
->buf
+ s
->index
, buf
, l
);
4565 if (s
->index
>= s
->packet_len
) {
4566 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4575 static void net_socket_send_dgram(void *opaque
)
4577 NetSocketState
*s
= opaque
;
4580 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4584 /* end of connection */
4585 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4588 qemu_send_packet(s
->vc
, s
->buf
, size
);
4591 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4596 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4597 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4598 inet_ntoa(mcastaddr
->sin_addr
),
4599 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4603 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4605 perror("socket(PF_INET, SOCK_DGRAM)");
4610 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4611 (const char *)&val
, sizeof(val
));
4613 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4617 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4623 /* Add host to multicast group */
4624 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4625 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4627 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4628 (const char *)&imr
, sizeof(struct ip_mreq
));
4630 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4634 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4636 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4637 (const char *)&val
, sizeof(val
));
4639 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4643 socket_set_nonblock(fd
);
4651 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4654 struct sockaddr_in saddr
;
4656 socklen_t saddr_len
;
4659 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4660 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4661 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4665 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4667 if (saddr
.sin_addr
.s_addr
==0) {
4668 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4672 /* clone dgram socket */
4673 newfd
= net_socket_mcast_create(&saddr
);
4675 /* error already reported by net_socket_mcast_create() */
4679 /* clone newfd to fd, close newfd */
4684 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4685 fd
, strerror(errno
));
4690 s
= qemu_mallocz(sizeof(NetSocketState
));
4695 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4696 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4698 /* mcast: save bound address as dst */
4699 if (is_connected
) s
->dgram_dst
=saddr
;
4701 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4702 "socket: fd=%d (%s mcast=%s:%d)",
4703 fd
, is_connected
? "cloned" : "",
4704 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4708 static void net_socket_connect(void *opaque
)
4710 NetSocketState
*s
= opaque
;
4711 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4714 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4718 s
= qemu_mallocz(sizeof(NetSocketState
));
4722 s
->vc
= qemu_new_vlan_client(vlan
,
4723 net_socket_receive
, NULL
, s
);
4724 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4725 "socket: fd=%d", fd
);
4727 net_socket_connect(s
);
4729 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4734 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4737 int so_type
=-1, optlen
=sizeof(so_type
);
4739 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4740 (socklen_t
*)&optlen
)< 0) {
4741 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4746 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4748 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4750 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4751 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4752 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4757 static void net_socket_accept(void *opaque
)
4759 NetSocketListenState
*s
= opaque
;
4761 struct sockaddr_in saddr
;
4766 len
= sizeof(saddr
);
4767 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4768 if (fd
< 0 && errno
!= EINTR
) {
4770 } else if (fd
>= 0) {
4774 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4778 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4779 "socket: connection from %s:%d",
4780 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4784 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4786 NetSocketListenState
*s
;
4788 struct sockaddr_in saddr
;
4790 if (parse_host_port(&saddr
, host_str
) < 0)
4793 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4797 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4802 socket_set_nonblock(fd
);
4804 /* allow fast reuse */
4806 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4808 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4813 ret
= listen(fd
, 0);
4820 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4824 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4827 int fd
, connected
, ret
, err
;
4828 struct sockaddr_in saddr
;
4830 if (parse_host_port(&saddr
, host_str
) < 0)
4833 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4838 socket_set_nonblock(fd
);
4842 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4844 err
= socket_error();
4845 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4846 } else if (err
== EINPROGRESS
) {
4849 } else if (err
== WSAEALREADY
) {
4862 s
= net_socket_fd_init(vlan
, fd
, connected
);
4865 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4866 "socket: connect to %s:%d",
4867 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4871 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4875 struct sockaddr_in saddr
;
4877 if (parse_host_port(&saddr
, host_str
) < 0)
4881 fd
= net_socket_mcast_create(&saddr
);
4885 s
= net_socket_fd_init(vlan
, fd
, 0);
4889 s
->dgram_dst
= saddr
;
4891 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4892 "socket: mcast=%s:%d",
4893 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4898 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
4903 while (*p
!= '\0' && *p
!= '=') {
4904 if (q
&& (q
- buf
) < buf_size
- 1)
4914 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
4919 while (*p
!= '\0') {
4921 if (*(p
+ 1) != ',')
4925 if (q
&& (q
- buf
) < buf_size
- 1)
4935 static int get_param_value(char *buf
, int buf_size
,
4936 const char *tag
, const char *str
)
4943 p
= get_opt_name(option
, sizeof(option
), p
);
4947 if (!strcmp(tag
, option
)) {
4948 (void)get_opt_value(buf
, buf_size
, p
);
4951 p
= get_opt_value(NULL
, 0, p
);
4960 static int check_params(char *buf
, int buf_size
,
4961 char **params
, const char *str
)
4968 p
= get_opt_name(buf
, buf_size
, p
);
4972 for(i
= 0; params
[i
] != NULL
; i
++)
4973 if (!strcmp(params
[i
], buf
))
4975 if (params
[i
] == NULL
)
4977 p
= get_opt_value(NULL
, 0, p
);
4986 static int net_client_init(const char *str
)
4997 while (*p
!= '\0' && *p
!= ',') {
4998 if ((q
- device
) < sizeof(device
) - 1)
5006 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5007 vlan_id
= strtol(buf
, NULL
, 0);
5009 vlan
= qemu_find_vlan(vlan_id
);
5011 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5014 if (!strcmp(device
, "nic")) {
5018 if (nb_nics
>= MAX_NICS
) {
5019 fprintf(stderr
, "Too Many NICs\n");
5022 nd
= &nd_table
[nb_nics
];
5023 macaddr
= nd
->macaddr
;
5029 macaddr
[5] = 0x56 + nb_nics
;
5031 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5032 if (parse_macaddr(macaddr
, buf
) < 0) {
5033 fprintf(stderr
, "invalid syntax for ethernet address\n");
5037 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5038 nd
->model
= strdup(buf
);
5042 vlan
->nb_guest_devs
++;
5045 if (!strcmp(device
, "none")) {
5046 /* does nothing. It is needed to signal that no network cards
5051 if (!strcmp(device
, "user")) {
5052 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5053 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5055 vlan
->nb_host_devs
++;
5056 ret
= net_slirp_init(vlan
);
5060 if (!strcmp(device
, "tap")) {
5062 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5063 fprintf(stderr
, "tap: no interface name\n");
5066 vlan
->nb_host_devs
++;
5067 ret
= tap_win32_init(vlan
, ifname
);
5070 if (!strcmp(device
, "tap")) {
5072 char setup_script
[1024], down_script
[1024];
5074 vlan
->nb_host_devs
++;
5075 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5076 fd
= strtol(buf
, NULL
, 0);
5077 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5079 if (net_tap_fd_init(vlan
, fd
))
5082 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5085 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5086 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5088 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5089 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5091 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5095 if (!strcmp(device
, "socket")) {
5096 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5098 fd
= strtol(buf
, NULL
, 0);
5100 if (net_socket_fd_init(vlan
, fd
, 1))
5102 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5103 ret
= net_socket_listen_init(vlan
, buf
);
5104 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5105 ret
= net_socket_connect_init(vlan
, buf
);
5106 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5107 ret
= net_socket_mcast_init(vlan
, buf
);
5109 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5112 vlan
->nb_host_devs
++;
5115 if (!strcmp(device
, "vde")) {
5116 char vde_sock
[1024], vde_group
[512];
5117 int vde_port
, vde_mode
;
5118 vlan
->nb_host_devs
++;
5119 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5122 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5123 vde_port
= strtol(buf
, NULL
, 10);
5127 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5128 vde_group
[0] = '\0';
5130 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5131 vde_mode
= strtol(buf
, NULL
, 8);
5135 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5139 fprintf(stderr
, "Unknown network device: %s\n", device
);
5143 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5149 void do_info_network(void)
5152 VLANClientState
*vc
;
5154 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5155 term_printf("VLAN %d devices:\n", vlan
->id
);
5156 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5157 term_printf(" %s\n", vc
->info_str
);
5161 #define HD_ALIAS "index=%d,media=disk"
5163 #define CDROM_ALIAS "index=1,media=cdrom"
5165 #define CDROM_ALIAS "index=2,media=cdrom"
5167 #define FD_ALIAS "index=%d,if=floppy"
5168 #define PFLASH_ALIAS "if=pflash"
5169 #define MTD_ALIAS "if=mtd"
5170 #define SD_ALIAS "index=0,if=sd"
5172 static int drive_add(const char *file
, const char *fmt
, ...)
5176 if (nb_drives_opt
>= MAX_DRIVES
) {
5177 fprintf(stderr
, "qemu: too many drives\n");
5181 drives_opt
[nb_drives_opt
].file
= file
;
5183 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5184 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5187 return nb_drives_opt
++;
5190 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5194 /* seek interface, bus and unit */
5196 for (index
= 0; index
< nb_drives
; index
++)
5197 if (drives_table
[index
].type
== type
&&
5198 drives_table
[index
].bus
== bus
&&
5199 drives_table
[index
].unit
== unit
)
5205 int drive_get_max_bus(BlockInterfaceType type
)
5211 for (index
= 0; index
< nb_drives
; index
++) {
5212 if(drives_table
[index
].type
== type
&&
5213 drives_table
[index
].bus
> max_bus
)
5214 max_bus
= drives_table
[index
].bus
;
5219 static void bdrv_format_print(void *opaque
, const char *name
)
5221 fprintf(stderr
, " %s", name
);
5224 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5225 QEMUMachine
*machine
)
5230 const char *mediastr
= "";
5231 BlockInterfaceType type
;
5232 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5233 int bus_id
, unit_id
;
5234 int cyls
, heads
, secs
, translation
;
5235 BlockDriverState
*bdrv
;
5236 BlockDriver
*drv
= NULL
;
5241 char *str
= arg
->opt
;
5242 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5243 "secs", "trans", "media", "snapshot", "file",
5244 "cache", "format", NULL
};
5246 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5247 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5253 cyls
= heads
= secs
= 0;
5256 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5260 if (!strcmp(machine
->name
, "realview") ||
5261 !strcmp(machine
->name
, "SS-5") ||
5262 !strcmp(machine
->name
, "SS-10") ||
5263 !strcmp(machine
->name
, "SS-600MP") ||
5264 !strcmp(machine
->name
, "versatilepb") ||
5265 !strcmp(machine
->name
, "versatileab")) {
5267 max_devs
= MAX_SCSI_DEVS
;
5268 strcpy(devname
, "scsi");
5271 max_devs
= MAX_IDE_DEVS
;
5272 strcpy(devname
, "ide");
5276 /* extract parameters */
5278 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5279 bus_id
= strtol(buf
, NULL
, 0);
5281 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5286 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5287 unit_id
= strtol(buf
, NULL
, 0);
5289 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5294 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5295 pstrcpy(devname
, sizeof(devname
), buf
);
5296 if (!strcmp(buf
, "ide")) {
5298 max_devs
= MAX_IDE_DEVS
;
5299 } else if (!strcmp(buf
, "scsi")) {
5301 max_devs
= MAX_SCSI_DEVS
;
5302 } else if (!strcmp(buf
, "floppy")) {
5305 } else if (!strcmp(buf
, "pflash")) {
5308 } else if (!strcmp(buf
, "mtd")) {
5311 } else if (!strcmp(buf
, "sd")) {
5315 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5320 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5321 index
= strtol(buf
, NULL
, 0);
5323 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5328 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5329 cyls
= strtol(buf
, NULL
, 0);
5332 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5333 heads
= strtol(buf
, NULL
, 0);
5336 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5337 secs
= strtol(buf
, NULL
, 0);
5340 if (cyls
|| heads
|| secs
) {
5341 if (cyls
< 1 || cyls
> 16383) {
5342 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5345 if (heads
< 1 || heads
> 16) {
5346 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5349 if (secs
< 1 || secs
> 63) {
5350 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5355 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5358 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5362 if (!strcmp(buf
, "none"))
5363 translation
= BIOS_ATA_TRANSLATION_NONE
;
5364 else if (!strcmp(buf
, "lba"))
5365 translation
= BIOS_ATA_TRANSLATION_LBA
;
5366 else if (!strcmp(buf
, "auto"))
5367 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5369 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5374 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5375 if (!strcmp(buf
, "disk")) {
5377 } else if (!strcmp(buf
, "cdrom")) {
5378 if (cyls
|| secs
|| heads
) {
5380 "qemu: '%s' invalid physical CHS format\n", str
);
5383 media
= MEDIA_CDROM
;
5385 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5390 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5391 if (!strcmp(buf
, "on"))
5393 else if (!strcmp(buf
, "off"))
5396 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5401 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5402 if (!strcmp(buf
, "off"))
5404 else if (!strcmp(buf
, "on"))
5407 fprintf(stderr
, "qemu: invalid cache option\n");
5412 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5413 if (strcmp(buf
, "?") == 0) {
5414 fprintf(stderr
, "qemu: Supported formats:");
5415 bdrv_iterate_format(bdrv_format_print
, NULL
);
5416 fprintf(stderr
, "\n");
5419 drv
= bdrv_find_format(buf
);
5421 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5426 if (arg
->file
== NULL
)
5427 get_param_value(file
, sizeof(file
), "file", str
);
5429 pstrcpy(file
, sizeof(file
), arg
->file
);
5431 /* compute bus and unit according index */
5434 if (bus_id
!= 0 || unit_id
!= -1) {
5436 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5444 unit_id
= index
% max_devs
;
5445 bus_id
= index
/ max_devs
;
5449 /* if user doesn't specify a unit_id,
5450 * try to find the first free
5453 if (unit_id
== -1) {
5455 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5457 if (max_devs
&& unit_id
>= max_devs
) {
5458 unit_id
-= max_devs
;
5466 if (max_devs
&& unit_id
>= max_devs
) {
5467 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5468 str
, unit_id
, max_devs
- 1);
5473 * ignore multiple definitions
5476 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5481 if (type
== IF_IDE
|| type
== IF_SCSI
)
5482 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5484 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5485 devname
, bus_id
, mediastr
, unit_id
);
5487 snprintf(buf
, sizeof(buf
), "%s%s%i",
5488 devname
, mediastr
, unit_id
);
5489 bdrv
= bdrv_new(buf
);
5490 drives_table
[nb_drives
].bdrv
= bdrv
;
5491 drives_table
[nb_drives
].type
= type
;
5492 drives_table
[nb_drives
].bus
= bus_id
;
5493 drives_table
[nb_drives
].unit
= unit_id
;
5502 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5503 bdrv_set_translation_hint(bdrv
, translation
);
5507 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5512 /* FIXME: This isn't really a floppy, but it's a reasonable
5515 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5525 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5527 bdrv_flags
|= BDRV_O_DIRECT
;
5528 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5529 fprintf(stderr
, "qemu: could not open disk image %s\n",
5536 /***********************************************************/
5539 static USBPort
*used_usb_ports
;
5540 static USBPort
*free_usb_ports
;
5542 /* ??? Maybe change this to register a hub to keep track of the topology. */
5543 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5544 usb_attachfn attach
)
5546 port
->opaque
= opaque
;
5547 port
->index
= index
;
5548 port
->attach
= attach
;
5549 port
->next
= free_usb_ports
;
5550 free_usb_ports
= port
;
5553 static int usb_device_add(const char *devname
)
5559 if (!free_usb_ports
)
5562 if (strstart(devname
, "host:", &p
)) {
5563 dev
= usb_host_device_open(p
);
5564 } else if (!strcmp(devname
, "mouse")) {
5565 dev
= usb_mouse_init();
5566 } else if (!strcmp(devname
, "tablet")) {
5567 dev
= usb_tablet_init();
5568 } else if (!strcmp(devname
, "keyboard")) {
5569 dev
= usb_keyboard_init();
5570 } else if (strstart(devname
, "disk:", &p
)) {
5571 dev
= usb_msd_init(p
);
5572 } else if (!strcmp(devname
, "wacom-tablet")) {
5573 dev
= usb_wacom_init();
5574 } else if (strstart(devname
, "serial:", &p
)) {
5575 dev
= usb_serial_init(p
);
5576 #ifdef CONFIG_BRLAPI
5577 } else if (!strcmp(devname
, "braille")) {
5578 dev
= usb_baum_init();
5580 } else if (strstart(devname
, "net:", &p
)) {
5581 int nicidx
= strtoul(p
, NULL
, 0);
5583 if (nicidx
>= nb_nics
|| strcmp(nd_table
[nicidx
].model
, "usb"))
5585 dev
= usb_net_init(&nd_table
[nicidx
]);
5592 /* Find a USB port to add the device to. */
5593 port
= free_usb_ports
;
5597 /* Create a new hub and chain it on. */
5598 free_usb_ports
= NULL
;
5599 port
->next
= used_usb_ports
;
5600 used_usb_ports
= port
;
5602 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5603 usb_attach(port
, hub
);
5604 port
= free_usb_ports
;
5607 free_usb_ports
= port
->next
;
5608 port
->next
= used_usb_ports
;
5609 used_usb_ports
= port
;
5610 usb_attach(port
, dev
);
5614 static int usb_device_del(const char *devname
)
5622 if (!used_usb_ports
)
5625 p
= strchr(devname
, '.');
5628 bus_num
= strtoul(devname
, NULL
, 0);
5629 addr
= strtoul(p
+ 1, NULL
, 0);
5633 lastp
= &used_usb_ports
;
5634 port
= used_usb_ports
;
5635 while (port
&& port
->dev
->addr
!= addr
) {
5636 lastp
= &port
->next
;
5644 *lastp
= port
->next
;
5645 usb_attach(port
, NULL
);
5646 dev
->handle_destroy(dev
);
5647 port
->next
= free_usb_ports
;
5648 free_usb_ports
= port
;
5652 void do_usb_add(const char *devname
)
5655 ret
= usb_device_add(devname
);
5657 term_printf("Could not add USB device '%s'\n", devname
);
5660 void do_usb_del(const char *devname
)
5663 ret
= usb_device_del(devname
);
5665 term_printf("Could not remove USB device '%s'\n", devname
);
5672 const char *speed_str
;
5675 term_printf("USB support not enabled\n");
5679 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5683 switch(dev
->speed
) {
5687 case USB_SPEED_FULL
:
5690 case USB_SPEED_HIGH
:
5697 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5698 0, dev
->addr
, speed_str
, dev
->devname
);
5702 /***********************************************************/
5703 /* PCMCIA/Cardbus */
5705 static struct pcmcia_socket_entry_s
{
5706 struct pcmcia_socket_s
*socket
;
5707 struct pcmcia_socket_entry_s
*next
;
5708 } *pcmcia_sockets
= 0;
5710 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5712 struct pcmcia_socket_entry_s
*entry
;
5714 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5715 entry
->socket
= socket
;
5716 entry
->next
= pcmcia_sockets
;
5717 pcmcia_sockets
= entry
;
5720 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5722 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5724 ptr
= &pcmcia_sockets
;
5725 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5726 if (entry
->socket
== socket
) {
5732 void pcmcia_info(void)
5734 struct pcmcia_socket_entry_s
*iter
;
5735 if (!pcmcia_sockets
)
5736 term_printf("No PCMCIA sockets\n");
5738 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5739 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5740 iter
->socket
->attached
? iter
->socket
->card_string
:
5744 /***********************************************************/
5747 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5751 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5755 static void dumb_refresh(DisplayState
*ds
)
5757 #if defined(CONFIG_SDL)
5762 static void dumb_display_init(DisplayState
*ds
)
5767 ds
->dpy_update
= dumb_update
;
5768 ds
->dpy_resize
= dumb_resize
;
5769 ds
->dpy_refresh
= dumb_refresh
;
5772 /***********************************************************/
5775 #define MAX_IO_HANDLERS 64
5777 typedef struct IOHandlerRecord
{
5779 IOCanRWHandler
*fd_read_poll
;
5781 IOHandler
*fd_write
;
5784 /* temporary data */
5786 struct IOHandlerRecord
*next
;
5789 static IOHandlerRecord
*first_io_handler
;
5791 /* XXX: fd_read_poll should be suppressed, but an API change is
5792 necessary in the character devices to suppress fd_can_read(). */
5793 int qemu_set_fd_handler2(int fd
,
5794 IOCanRWHandler
*fd_read_poll
,
5796 IOHandler
*fd_write
,
5799 IOHandlerRecord
**pioh
, *ioh
;
5801 if (!fd_read
&& !fd_write
) {
5802 pioh
= &first_io_handler
;
5807 if (ioh
->fd
== fd
) {
5814 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5818 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5821 ioh
->next
= first_io_handler
;
5822 first_io_handler
= ioh
;
5825 ioh
->fd_read_poll
= fd_read_poll
;
5826 ioh
->fd_read
= fd_read
;
5827 ioh
->fd_write
= fd_write
;
5828 ioh
->opaque
= opaque
;
5834 int qemu_set_fd_handler(int fd
,
5836 IOHandler
*fd_write
,
5839 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5842 /***********************************************************/
5843 /* Polling handling */
5845 typedef struct PollingEntry
{
5848 struct PollingEntry
*next
;
5851 static PollingEntry
*first_polling_entry
;
5853 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5855 PollingEntry
**ppe
, *pe
;
5856 pe
= qemu_mallocz(sizeof(PollingEntry
));
5860 pe
->opaque
= opaque
;
5861 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5866 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5868 PollingEntry
**ppe
, *pe
;
5869 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5871 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5880 /***********************************************************/
5881 /* Wait objects support */
5882 typedef struct WaitObjects
{
5884 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
5885 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
5886 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
5889 static WaitObjects wait_objects
= {0};
5891 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5893 WaitObjects
*w
= &wait_objects
;
5895 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
5897 w
->events
[w
->num
] = handle
;
5898 w
->func
[w
->num
] = func
;
5899 w
->opaque
[w
->num
] = opaque
;
5904 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5907 WaitObjects
*w
= &wait_objects
;
5910 for (i
= 0; i
< w
->num
; i
++) {
5911 if (w
->events
[i
] == handle
)
5914 w
->events
[i
] = w
->events
[i
+ 1];
5915 w
->func
[i
] = w
->func
[i
+ 1];
5916 w
->opaque
[i
] = w
->opaque
[i
+ 1];
5924 /***********************************************************/
5925 /* savevm/loadvm support */
5927 #define IO_BUF_SIZE 32768
5931 BlockDriverState
*bs
;
5934 int64_t base_offset
;
5935 int64_t buf_offset
; /* start of buffer when writing, end of buffer
5938 int buf_size
; /* 0 when writing */
5939 uint8_t buf
[IO_BUF_SIZE
];
5942 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
5946 f
= qemu_mallocz(sizeof(QEMUFile
));
5949 if (!strcmp(mode
, "wb")) {
5951 } else if (!strcmp(mode
, "rb")) {
5956 f
->outfile
= fopen(filename
, mode
);
5968 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
5972 f
= qemu_mallocz(sizeof(QEMUFile
));
5977 f
->is_writable
= is_writable
;
5978 f
->base_offset
= offset
;
5982 void qemu_fflush(QEMUFile
*f
)
5984 if (!f
->is_writable
)
5986 if (f
->buf_index
> 0) {
5988 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
5989 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
5991 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
5992 f
->buf
, f
->buf_index
);
5994 f
->buf_offset
+= f
->buf_index
;
5999 static void qemu_fill_buffer(QEMUFile
*f
)
6006 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6007 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6011 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6012 f
->buf
, IO_BUF_SIZE
);
6018 f
->buf_offset
+= len
;
6021 void qemu_fclose(QEMUFile
*f
)
6031 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6035 l
= IO_BUF_SIZE
- f
->buf_index
;
6038 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6042 if (f
->buf_index
>= IO_BUF_SIZE
)
6047 void qemu_put_byte(QEMUFile
*f
, int v
)
6049 f
->buf
[f
->buf_index
++] = v
;
6050 if (f
->buf_index
>= IO_BUF_SIZE
)
6054 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6060 l
= f
->buf_size
- f
->buf_index
;
6062 qemu_fill_buffer(f
);
6063 l
= f
->buf_size
- f
->buf_index
;
6069 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6074 return size1
- size
;
6077 int qemu_get_byte(QEMUFile
*f
)
6079 if (f
->buf_index
>= f
->buf_size
) {
6080 qemu_fill_buffer(f
);
6081 if (f
->buf_index
>= f
->buf_size
)
6084 return f
->buf
[f
->buf_index
++];
6087 int64_t qemu_ftell(QEMUFile
*f
)
6089 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6092 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6094 if (whence
== SEEK_SET
) {
6096 } else if (whence
== SEEK_CUR
) {
6097 pos
+= qemu_ftell(f
);
6099 /* SEEK_END not supported */
6102 if (f
->is_writable
) {
6104 f
->buf_offset
= pos
;
6106 f
->buf_offset
= pos
;
6113 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6115 qemu_put_byte(f
, v
>> 8);
6116 qemu_put_byte(f
, v
);
6119 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6121 qemu_put_byte(f
, v
>> 24);
6122 qemu_put_byte(f
, v
>> 16);
6123 qemu_put_byte(f
, v
>> 8);
6124 qemu_put_byte(f
, v
);
6127 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6129 qemu_put_be32(f
, v
>> 32);
6130 qemu_put_be32(f
, v
);
6133 unsigned int qemu_get_be16(QEMUFile
*f
)
6136 v
= qemu_get_byte(f
) << 8;
6137 v
|= qemu_get_byte(f
);
6141 unsigned int qemu_get_be32(QEMUFile
*f
)
6144 v
= qemu_get_byte(f
) << 24;
6145 v
|= qemu_get_byte(f
) << 16;
6146 v
|= qemu_get_byte(f
) << 8;
6147 v
|= qemu_get_byte(f
);
6151 uint64_t qemu_get_be64(QEMUFile
*f
)
6154 v
= (uint64_t)qemu_get_be32(f
) << 32;
6155 v
|= qemu_get_be32(f
);
6159 typedef struct SaveStateEntry
{
6163 SaveStateHandler
*save_state
;
6164 LoadStateHandler
*load_state
;
6166 struct SaveStateEntry
*next
;
6169 static SaveStateEntry
*first_se
;
6171 /* TODO: Individual devices generally have very little idea about the rest
6172 of the system, so instance_id should be removed/replaced.
6173 Meanwhile pass -1 as instance_id if you do not already have a clearly
6174 distinguishing id for all instances of your device class. */
6175 int register_savevm(const char *idstr
,
6178 SaveStateHandler
*save_state
,
6179 LoadStateHandler
*load_state
,
6182 SaveStateEntry
*se
, **pse
;
6184 se
= qemu_malloc(sizeof(SaveStateEntry
));
6187 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6188 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6189 se
->version_id
= version_id
;
6190 se
->save_state
= save_state
;
6191 se
->load_state
= load_state
;
6192 se
->opaque
= opaque
;
6195 /* add at the end of list */
6197 while (*pse
!= NULL
) {
6198 if (instance_id
== -1
6199 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6200 && se
->instance_id
<= (*pse
)->instance_id
)
6201 se
->instance_id
= (*pse
)->instance_id
+ 1;
6202 pse
= &(*pse
)->next
;
6208 #define QEMU_VM_FILE_MAGIC 0x5145564d
6209 #define QEMU_VM_FILE_VERSION 0x00000002
6211 static int qemu_savevm_state(QEMUFile
*f
)
6215 int64_t cur_pos
, len_pos
, total_len_pos
;
6217 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6218 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6219 total_len_pos
= qemu_ftell(f
);
6220 qemu_put_be64(f
, 0); /* total size */
6222 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6223 if (se
->save_state
== NULL
)
6224 /* this one has a loader only, for backwards compatibility */
6228 len
= strlen(se
->idstr
);
6229 qemu_put_byte(f
, len
);
6230 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6232 qemu_put_be32(f
, se
->instance_id
);
6233 qemu_put_be32(f
, se
->version_id
);
6235 /* record size: filled later */
6236 len_pos
= qemu_ftell(f
);
6237 qemu_put_be32(f
, 0);
6238 se
->save_state(f
, se
->opaque
);
6240 /* fill record size */
6241 cur_pos
= qemu_ftell(f
);
6242 len
= cur_pos
- len_pos
- 4;
6243 qemu_fseek(f
, len_pos
, SEEK_SET
);
6244 qemu_put_be32(f
, len
);
6245 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6247 cur_pos
= qemu_ftell(f
);
6248 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6249 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6250 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6256 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6260 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6261 if (!strcmp(se
->idstr
, idstr
) &&
6262 instance_id
== se
->instance_id
)
6268 static int qemu_loadvm_state(QEMUFile
*f
)
6271 int len
, ret
, instance_id
, record_len
, version_id
;
6272 int64_t total_len
, end_pos
, cur_pos
;
6276 v
= qemu_get_be32(f
);
6277 if (v
!= QEMU_VM_FILE_MAGIC
)
6279 v
= qemu_get_be32(f
);
6280 if (v
!= QEMU_VM_FILE_VERSION
) {
6285 total_len
= qemu_get_be64(f
);
6286 end_pos
= total_len
+ qemu_ftell(f
);
6288 if (qemu_ftell(f
) >= end_pos
)
6290 len
= qemu_get_byte(f
);
6291 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6293 instance_id
= qemu_get_be32(f
);
6294 version_id
= qemu_get_be32(f
);
6295 record_len
= qemu_get_be32(f
);
6297 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6298 idstr
, instance_id
, version_id
, record_len
);
6300 cur_pos
= qemu_ftell(f
);
6301 se
= find_se(idstr
, instance_id
);
6303 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6304 instance_id
, idstr
);
6306 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6308 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6309 instance_id
, idstr
);
6312 /* always seek to exact end of record */
6313 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6320 /* device can contain snapshots */
6321 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6324 !bdrv_is_removable(bs
) &&
6325 !bdrv_is_read_only(bs
));
6328 /* device must be snapshots in order to have a reliable snapshot */
6329 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6332 !bdrv_is_removable(bs
) &&
6333 !bdrv_is_read_only(bs
));
6336 static BlockDriverState
*get_bs_snapshots(void)
6338 BlockDriverState
*bs
;
6342 return bs_snapshots
;
6343 for(i
= 0; i
<= nb_drives
; i
++) {
6344 bs
= drives_table
[i
].bdrv
;
6345 if (bdrv_can_snapshot(bs
))
6354 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6357 QEMUSnapshotInfo
*sn_tab
, *sn
;
6361 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6364 for(i
= 0; i
< nb_sns
; i
++) {
6366 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6376 void do_savevm(const char *name
)
6378 BlockDriverState
*bs
, *bs1
;
6379 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6380 int must_delete
, ret
, i
;
6381 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6383 int saved_vm_running
;
6390 bs
= get_bs_snapshots();
6392 term_printf("No block device can accept snapshots\n");
6396 /* ??? Should this occur after vm_stop? */
6399 saved_vm_running
= vm_running
;
6404 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6409 memset(sn
, 0, sizeof(*sn
));
6411 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6412 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6415 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6418 /* fill auxiliary fields */
6421 sn
->date_sec
= tb
.time
;
6422 sn
->date_nsec
= tb
.millitm
* 1000000;
6424 gettimeofday(&tv
, NULL
);
6425 sn
->date_sec
= tv
.tv_sec
;
6426 sn
->date_nsec
= tv
.tv_usec
* 1000;
6428 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6430 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6431 term_printf("Device %s does not support VM state snapshots\n",
6432 bdrv_get_device_name(bs
));
6436 /* save the VM state */
6437 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6439 term_printf("Could not open VM state file\n");
6442 ret
= qemu_savevm_state(f
);
6443 sn
->vm_state_size
= qemu_ftell(f
);
6446 term_printf("Error %d while writing VM\n", ret
);
6450 /* create the snapshots */
6452 for(i
= 0; i
< nb_drives
; i
++) {
6453 bs1
= drives_table
[i
].bdrv
;
6454 if (bdrv_has_snapshot(bs1
)) {
6456 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6458 term_printf("Error while deleting snapshot on '%s'\n",
6459 bdrv_get_device_name(bs1
));
6462 ret
= bdrv_snapshot_create(bs1
, sn
);
6464 term_printf("Error while creating snapshot on '%s'\n",
6465 bdrv_get_device_name(bs1
));
6471 if (saved_vm_running
)
6475 void do_loadvm(const char *name
)
6477 BlockDriverState
*bs
, *bs1
;
6478 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6481 int saved_vm_running
;
6483 bs
= get_bs_snapshots();
6485 term_printf("No block device supports snapshots\n");
6489 /* Flush all IO requests so they don't interfere with the new state. */
6492 saved_vm_running
= vm_running
;
6495 for(i
= 0; i
<= nb_drives
; i
++) {
6496 bs1
= drives_table
[i
].bdrv
;
6497 if (bdrv_has_snapshot(bs1
)) {
6498 ret
= bdrv_snapshot_goto(bs1
, name
);
6501 term_printf("Warning: ");
6504 term_printf("Snapshots not supported on device '%s'\n",
6505 bdrv_get_device_name(bs1
));
6508 term_printf("Could not find snapshot '%s' on device '%s'\n",
6509 name
, bdrv_get_device_name(bs1
));
6512 term_printf("Error %d while activating snapshot on '%s'\n",
6513 ret
, bdrv_get_device_name(bs1
));
6516 /* fatal on snapshot block device */
6523 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6524 term_printf("Device %s does not support VM state snapshots\n",
6525 bdrv_get_device_name(bs
));
6529 /* restore the VM state */
6530 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6532 term_printf("Could not open VM state file\n");
6535 ret
= qemu_loadvm_state(f
);
6538 term_printf("Error %d while loading VM state\n", ret
);
6541 if (saved_vm_running
)
6545 void do_delvm(const char *name
)
6547 BlockDriverState
*bs
, *bs1
;
6550 bs
= get_bs_snapshots();
6552 term_printf("No block device supports snapshots\n");
6556 for(i
= 0; i
<= nb_drives
; i
++) {
6557 bs1
= drives_table
[i
].bdrv
;
6558 if (bdrv_has_snapshot(bs1
)) {
6559 ret
= bdrv_snapshot_delete(bs1
, name
);
6561 if (ret
== -ENOTSUP
)
6562 term_printf("Snapshots not supported on device '%s'\n",
6563 bdrv_get_device_name(bs1
));
6565 term_printf("Error %d while deleting snapshot on '%s'\n",
6566 ret
, bdrv_get_device_name(bs1
));
6572 void do_info_snapshots(void)
6574 BlockDriverState
*bs
, *bs1
;
6575 QEMUSnapshotInfo
*sn_tab
, *sn
;
6579 bs
= get_bs_snapshots();
6581 term_printf("No available block device supports snapshots\n");
6584 term_printf("Snapshot devices:");
6585 for(i
= 0; i
<= nb_drives
; i
++) {
6586 bs1
= drives_table
[i
].bdrv
;
6587 if (bdrv_has_snapshot(bs1
)) {
6589 term_printf(" %s", bdrv_get_device_name(bs1
));
6594 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6596 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6599 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6600 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6601 for(i
= 0; i
< nb_sns
; i
++) {
6603 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6608 /***********************************************************/
6609 /* ram save/restore */
6611 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6615 v
= qemu_get_byte(f
);
6618 if (qemu_get_buffer(f
, buf
, len
) != len
)
6622 v
= qemu_get_byte(f
);
6623 memset(buf
, v
, len
);
6631 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6636 if (qemu_get_be32(f
) != phys_ram_size
)
6638 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6639 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6646 #define BDRV_HASH_BLOCK_SIZE 1024
6647 #define IOBUF_SIZE 4096
6648 #define RAM_CBLOCK_MAGIC 0xfabe
6650 typedef struct RamCompressState
{
6653 uint8_t buf
[IOBUF_SIZE
];
6656 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6659 memset(s
, 0, sizeof(*s
));
6661 ret
= deflateInit2(&s
->zstream
, 1,
6663 9, Z_DEFAULT_STRATEGY
);
6666 s
->zstream
.avail_out
= IOBUF_SIZE
;
6667 s
->zstream
.next_out
= s
->buf
;
6671 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6673 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6674 qemu_put_be16(s
->f
, len
);
6675 qemu_put_buffer(s
->f
, buf
, len
);
6678 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6682 s
->zstream
.avail_in
= len
;
6683 s
->zstream
.next_in
= (uint8_t *)buf
;
6684 while (s
->zstream
.avail_in
> 0) {
6685 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6688 if (s
->zstream
.avail_out
== 0) {
6689 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6690 s
->zstream
.avail_out
= IOBUF_SIZE
;
6691 s
->zstream
.next_out
= s
->buf
;
6697 static void ram_compress_close(RamCompressState
*s
)
6701 /* compress last bytes */
6703 ret
= deflate(&s
->zstream
, Z_FINISH
);
6704 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6705 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6707 ram_put_cblock(s
, s
->buf
, len
);
6709 s
->zstream
.avail_out
= IOBUF_SIZE
;
6710 s
->zstream
.next_out
= s
->buf
;
6711 if (ret
== Z_STREAM_END
)
6718 deflateEnd(&s
->zstream
);
6721 typedef struct RamDecompressState
{
6724 uint8_t buf
[IOBUF_SIZE
];
6725 } RamDecompressState
;
6727 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6730 memset(s
, 0, sizeof(*s
));
6732 ret
= inflateInit(&s
->zstream
);
6738 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6742 s
->zstream
.avail_out
= len
;
6743 s
->zstream
.next_out
= buf
;
6744 while (s
->zstream
.avail_out
> 0) {
6745 if (s
->zstream
.avail_in
== 0) {
6746 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6748 clen
= qemu_get_be16(s
->f
);
6749 if (clen
> IOBUF_SIZE
)
6751 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6752 s
->zstream
.avail_in
= clen
;
6753 s
->zstream
.next_in
= s
->buf
;
6755 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6756 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6763 static void ram_decompress_close(RamDecompressState
*s
)
6765 inflateEnd(&s
->zstream
);
6768 static void ram_save(QEMUFile
*f
, void *opaque
)
6771 RamCompressState s1
, *s
= &s1
;
6774 qemu_put_be32(f
, phys_ram_size
);
6775 if (ram_compress_open(s
, f
) < 0)
6777 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6779 if (tight_savevm_enabled
) {
6783 /* find if the memory block is available on a virtual
6786 for(j
= 0; j
< nb_drives
; j
++) {
6787 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
6789 BDRV_HASH_BLOCK_SIZE
);
6790 if (sector_num
>= 0)
6794 goto normal_compress
;
6797 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
6798 ram_compress_buf(s
, buf
, 10);
6804 ram_compress_buf(s
, buf
, 1);
6805 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
6808 ram_compress_close(s
);
6811 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
6813 RamDecompressState s1
, *s
= &s1
;
6817 if (version_id
== 1)
6818 return ram_load_v1(f
, opaque
);
6819 if (version_id
!= 2)
6821 if (qemu_get_be32(f
) != phys_ram_size
)
6823 if (ram_decompress_open(s
, f
) < 0)
6825 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6826 if (ram_decompress_buf(s
, buf
, 1) < 0) {
6827 fprintf(stderr
, "Error while reading ram block header\n");
6831 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
6832 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
6841 ram_decompress_buf(s
, buf
+ 1, 9);
6843 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
6844 if (bs_index
>= nb_drives
) {
6845 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
6848 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
6850 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
6851 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
6852 bs_index
, sector_num
);
6859 printf("Error block header\n");
6863 ram_decompress_close(s
);
6867 /***********************************************************/
6868 /* bottom halves (can be seen as timers which expire ASAP) */
6877 static QEMUBH
*first_bh
= NULL
;
6879 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
6882 bh
= qemu_mallocz(sizeof(QEMUBH
));
6886 bh
->opaque
= opaque
;
6890 int qemu_bh_poll(void)
6909 void qemu_bh_schedule(QEMUBH
*bh
)
6911 CPUState
*env
= cpu_single_env
;
6915 bh
->next
= first_bh
;
6918 /* stop the currently executing CPU to execute the BH ASAP */
6920 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
6924 void qemu_bh_cancel(QEMUBH
*bh
)
6927 if (bh
->scheduled
) {
6930 pbh
= &(*pbh
)->next
;
6936 void qemu_bh_delete(QEMUBH
*bh
)
6942 /***********************************************************/
6943 /* machine registration */
6945 QEMUMachine
*first_machine
= NULL
;
6947 int qemu_register_machine(QEMUMachine
*m
)
6950 pm
= &first_machine
;
6958 static QEMUMachine
*find_machine(const char *name
)
6962 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6963 if (!strcmp(m
->name
, name
))
6969 /***********************************************************/
6970 /* main execution loop */
6972 static void gui_update(void *opaque
)
6974 DisplayState
*ds
= opaque
;
6975 ds
->dpy_refresh(ds
);
6976 qemu_mod_timer(ds
->gui_timer
,
6977 (ds
->gui_timer_interval
?
6978 ds
->gui_timer_interval
:
6979 GUI_REFRESH_INTERVAL
)
6980 + qemu_get_clock(rt_clock
));
6983 struct vm_change_state_entry
{
6984 VMChangeStateHandler
*cb
;
6986 LIST_ENTRY (vm_change_state_entry
) entries
;
6989 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6991 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6994 VMChangeStateEntry
*e
;
6996 e
= qemu_mallocz(sizeof (*e
));
7002 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7006 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7008 LIST_REMOVE (e
, entries
);
7012 static void vm_state_notify(int running
)
7014 VMChangeStateEntry
*e
;
7016 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7017 e
->cb(e
->opaque
, running
);
7021 /* XXX: support several handlers */
7022 static VMStopHandler
*vm_stop_cb
;
7023 static void *vm_stop_opaque
;
7025 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7028 vm_stop_opaque
= opaque
;
7032 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7043 qemu_rearm_alarm_timer(alarm_timer
);
7047 void vm_stop(int reason
)
7050 cpu_disable_ticks();
7054 vm_stop_cb(vm_stop_opaque
, reason
);
7061 /* reset/shutdown handler */
7063 typedef struct QEMUResetEntry
{
7064 QEMUResetHandler
*func
;
7066 struct QEMUResetEntry
*next
;
7069 static QEMUResetEntry
*first_reset_entry
;
7070 static int reset_requested
;
7071 static int shutdown_requested
;
7072 static int powerdown_requested
;
7074 int qemu_shutdown_requested(void)
7076 int r
= shutdown_requested
;
7077 shutdown_requested
= 0;
7081 int qemu_reset_requested(void)
7083 int r
= reset_requested
;
7084 reset_requested
= 0;
7088 int qemu_powerdown_requested(void)
7090 int r
= powerdown_requested
;
7091 powerdown_requested
= 0;
7095 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7097 QEMUResetEntry
**pre
, *re
;
7099 pre
= &first_reset_entry
;
7100 while (*pre
!= NULL
)
7101 pre
= &(*pre
)->next
;
7102 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7104 re
->opaque
= opaque
;
7109 void qemu_system_reset(void)
7113 /* reset all devices */
7114 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7115 re
->func(re
->opaque
);
7119 void qemu_system_reset_request(void)
7122 shutdown_requested
= 1;
7124 reset_requested
= 1;
7127 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7130 void qemu_system_shutdown_request(void)
7132 shutdown_requested
= 1;
7134 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7137 void qemu_system_powerdown_request(void)
7139 powerdown_requested
= 1;
7141 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7144 void main_loop_wait(int timeout
)
7146 IOHandlerRecord
*ioh
;
7147 fd_set rfds
, wfds
, xfds
;
7156 /* XXX: need to suppress polling by better using win32 events */
7158 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7159 ret
|= pe
->func(pe
->opaque
);
7164 WaitObjects
*w
= &wait_objects
;
7166 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7167 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7168 if (w
->func
[ret
- WAIT_OBJECT_0
])
7169 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7171 /* Check for additional signaled events */
7172 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7174 /* Check if event is signaled */
7175 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7176 if(ret2
== WAIT_OBJECT_0
) {
7178 w
->func
[i
](w
->opaque
[i
]);
7179 } else if (ret2
== WAIT_TIMEOUT
) {
7181 err
= GetLastError();
7182 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7185 } else if (ret
== WAIT_TIMEOUT
) {
7187 err
= GetLastError();
7188 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7192 /* poll any events */
7193 /* XXX: separate device handlers from system ones */
7198 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7202 (!ioh
->fd_read_poll
||
7203 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7204 FD_SET(ioh
->fd
, &rfds
);
7208 if (ioh
->fd_write
) {
7209 FD_SET(ioh
->fd
, &wfds
);
7219 tv
.tv_usec
= timeout
* 1000;
7221 #if defined(CONFIG_SLIRP)
7223 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7226 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7228 IOHandlerRecord
**pioh
;
7230 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7231 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7232 ioh
->fd_read(ioh
->opaque
);
7234 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7235 ioh
->fd_write(ioh
->opaque
);
7239 /* remove deleted IO handlers */
7240 pioh
= &first_io_handler
;
7250 #if defined(CONFIG_SLIRP)
7257 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7263 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7264 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7265 qemu_get_clock(vm_clock
));
7266 /* run dma transfers, if any */
7270 /* real time timers */
7271 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7272 qemu_get_clock(rt_clock
));
7274 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7275 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7276 qemu_rearm_alarm_timer(alarm_timer
);
7279 /* Check bottom-halves last in case any of the earlier events triggered
7285 static int main_loop(void)
7288 #ifdef CONFIG_PROFILER
7293 cur_cpu
= first_cpu
;
7294 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7301 #ifdef CONFIG_PROFILER
7302 ti
= profile_getclock();
7307 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7308 env
->icount_decr
.u16
.low
= 0;
7309 env
->icount_extra
= 0;
7310 count
= qemu_next_deadline();
7311 count
= (count
+ (1 << icount_time_shift
) - 1)
7312 >> icount_time_shift
;
7313 qemu_icount
+= count
;
7314 decr
= (count
> 0xffff) ? 0xffff : count
;
7316 env
->icount_decr
.u16
.low
= decr
;
7317 env
->icount_extra
= count
;
7319 ret
= cpu_exec(env
);
7320 #ifdef CONFIG_PROFILER
7321 qemu_time
+= profile_getclock() - ti
;
7324 /* Fold pending instructions back into the
7325 instruction counter, and clear the interrupt flag. */
7326 qemu_icount
-= (env
->icount_decr
.u16
.low
7327 + env
->icount_extra
);
7328 env
->icount_decr
.u32
= 0;
7329 env
->icount_extra
= 0;
7331 next_cpu
= env
->next_cpu
?: first_cpu
;
7332 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7333 ret
= EXCP_INTERRUPT
;
7337 if (ret
== EXCP_HLT
) {
7338 /* Give the next CPU a chance to run. */
7342 if (ret
!= EXCP_HALTED
)
7344 /* all CPUs are halted ? */
7350 if (shutdown_requested
) {
7351 ret
= EXCP_INTERRUPT
;
7359 if (reset_requested
) {
7360 reset_requested
= 0;
7361 qemu_system_reset();
7362 ret
= EXCP_INTERRUPT
;
7364 if (powerdown_requested
) {
7365 powerdown_requested
= 0;
7366 qemu_system_powerdown();
7367 ret
= EXCP_INTERRUPT
;
7369 if (unlikely(ret
== EXCP_DEBUG
)) {
7370 vm_stop(EXCP_DEBUG
);
7372 /* If all cpus are halted then wait until the next IRQ */
7373 /* XXX: use timeout computed from timers */
7374 if (ret
== EXCP_HALTED
) {
7378 /* Advance virtual time to the next event. */
7379 if (use_icount
== 1) {
7380 /* When not using an adaptive execution frequency
7381 we tend to get badly out of sync with real time,
7382 so just delay for a reasonable amount of time. */
7385 delta
= cpu_get_icount() - cpu_get_clock();
7388 /* If virtual time is ahead of real time then just
7390 timeout
= (delta
/ 1000000) + 1;
7392 /* Wait for either IO to occur or the next
7394 add
= qemu_next_deadline();
7395 /* We advance the timer before checking for IO.
7396 Limit the amount we advance so that early IO
7397 activity won't get the guest too far ahead. */
7401 add
= (add
+ (1 << icount_time_shift
) - 1)
7402 >> icount_time_shift
;
7404 timeout
= delta
/ 1000000;
7417 #ifdef CONFIG_PROFILER
7418 ti
= profile_getclock();
7420 main_loop_wait(timeout
);
7421 #ifdef CONFIG_PROFILER
7422 dev_time
+= profile_getclock() - ti
;
7425 cpu_disable_ticks();
7429 static void help(int exitcode
)
7431 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7432 "usage: %s [options] [disk_image]\n"
7434 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7436 "Standard options:\n"
7437 "-M machine select emulated machine (-M ? for list)\n"
7438 "-cpu cpu select CPU (-cpu ? for list)\n"
7439 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7440 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7441 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7442 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7443 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7444 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7445 " [,cache=on|off][,format=f]\n"
7446 " use 'file' as a drive image\n"
7447 "-mtdblock file use 'file' as on-board Flash memory image\n"
7448 "-sd file use 'file' as SecureDigital card image\n"
7449 "-pflash file use 'file' as a parallel flash image\n"
7450 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7451 "-snapshot write to temporary files instead of disk image files\n"
7453 "-no-frame open SDL window without a frame and window decorations\n"
7454 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7455 "-no-quit disable SDL window close capability\n"
7458 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7460 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7461 "-smp n set the number of CPUs to 'n' [default=1]\n"
7462 "-nographic disable graphical output and redirect serial I/Os to console\n"
7463 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7465 "-k language use keyboard layout (for example \"fr\" for French)\n"
7468 "-audio-help print list of audio drivers and their options\n"
7469 "-soundhw c1,... enable audio support\n"
7470 " and only specified sound cards (comma separated list)\n"
7471 " use -soundhw ? to get the list of supported cards\n"
7472 " use -soundhw all to enable all of them\n"
7474 "-localtime set the real time clock to local time [default=utc]\n"
7475 "-full-screen start in full screen\n"
7477 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7479 "-usb enable the USB driver (will be the default soon)\n"
7480 "-usbdevice name add the host or guest USB device 'name'\n"
7481 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7482 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7484 "-name string set the name of the guest\n"
7486 "Network options:\n"
7487 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7488 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7490 "-net user[,vlan=n][,hostname=host]\n"
7491 " connect the user mode network stack to VLAN 'n' and send\n"
7492 " hostname 'host' to DHCP clients\n"
7495 "-net tap[,vlan=n],ifname=name\n"
7496 " connect the host TAP network interface to VLAN 'n'\n"
7498 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7499 " connect the host TAP network interface to VLAN 'n' and use the\n"
7500 " network scripts 'file' (default=%s)\n"
7501 " and 'dfile' (default=%s);\n"
7502 " use '[down]script=no' to disable script execution;\n"
7503 " use 'fd=h' to connect to an already opened TAP interface\n"
7505 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7506 " connect the vlan 'n' to another VLAN using a socket connection\n"
7507 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7508 " connect the vlan 'n' to multicast maddr and port\n"
7510 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7511 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7512 " on host and listening for incoming connections on 'socketpath'.\n"
7513 " Use group 'groupname' and mode 'octalmode' to change default\n"
7514 " ownership and permissions for communication port.\n"
7516 "-net none use it alone to have zero network devices; if no -net option\n"
7517 " is provided, the default is '-net nic -net user'\n"
7520 "-tftp dir allow tftp access to files in dir [-net user]\n"
7521 "-bootp file advertise file in BOOTP replies\n"
7523 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7525 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7526 " redirect TCP or UDP connections from host to guest [-net user]\n"
7529 "Linux boot specific:\n"
7530 "-kernel bzImage use 'bzImage' as kernel image\n"
7531 "-append cmdline use 'cmdline' as kernel command line\n"
7532 "-initrd file use 'file' as initial ram disk\n"
7534 "Debug/Expert options:\n"
7535 "-monitor dev redirect the monitor to char device 'dev'\n"
7536 "-serial dev redirect the serial port to char device 'dev'\n"
7537 "-parallel dev redirect the parallel port to char device 'dev'\n"
7538 "-pidfile file Write PID to 'file'\n"
7539 "-S freeze CPU at startup (use 'c' to start execution)\n"
7540 "-s wait gdb connection to port\n"
7541 "-p port set gdb connection port [default=%s]\n"
7542 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7543 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7544 " translation (t=none or lba) (usually qemu can guess them)\n"
7545 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7547 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7548 "-no-kqemu disable KQEMU kernel module usage\n"
7551 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7552 " (default is CL-GD5446 PCI VGA)\n"
7553 "-no-acpi disable ACPI\n"
7555 #ifdef CONFIG_CURSES
7556 "-curses use a curses/ncurses interface instead of SDL\n"
7558 "-no-reboot exit instead of rebooting\n"
7559 "-no-shutdown stop before shutdown\n"
7560 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7561 "-vnc display start a VNC server on display\n"
7563 "-daemonize daemonize QEMU after initializing\n"
7565 "-option-rom rom load a file, rom, into the option ROM space\n"
7567 "-prom-env variable=value set OpenBIOS nvram variables\n"
7569 "-clock force the use of the given methods for timer alarm.\n"
7570 " To see what timers are available use -clock ?\n"
7571 "-startdate select initial date of the clock\n"
7572 "-icount [N|auto]\n"
7573 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7575 "During emulation, the following keys are useful:\n"
7576 "ctrl-alt-f toggle full screen\n"
7577 "ctrl-alt-n switch to virtual console 'n'\n"
7578 "ctrl-alt toggle mouse and keyboard grab\n"
7580 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7585 DEFAULT_NETWORK_SCRIPT
,
7586 DEFAULT_NETWORK_DOWN_SCRIPT
,
7588 DEFAULT_GDBSTUB_PORT
,
7593 #define HAS_ARG 0x0001
7608 QEMU_OPTION_mtdblock
,
7612 QEMU_OPTION_snapshot
,
7614 QEMU_OPTION_no_fd_bootchk
,
7617 QEMU_OPTION_nographic
,
7618 QEMU_OPTION_portrait
,
7620 QEMU_OPTION_audio_help
,
7621 QEMU_OPTION_soundhw
,
7642 QEMU_OPTION_localtime
,
7643 QEMU_OPTION_cirrusvga
,
7646 QEMU_OPTION_std_vga
,
7648 QEMU_OPTION_monitor
,
7650 QEMU_OPTION_parallel
,
7652 QEMU_OPTION_full_screen
,
7653 QEMU_OPTION_no_frame
,
7654 QEMU_OPTION_alt_grab
,
7655 QEMU_OPTION_no_quit
,
7656 QEMU_OPTION_pidfile
,
7657 QEMU_OPTION_no_kqemu
,
7658 QEMU_OPTION_kernel_kqemu
,
7659 QEMU_OPTION_win2k_hack
,
7661 QEMU_OPTION_usbdevice
,
7664 QEMU_OPTION_no_acpi
,
7666 QEMU_OPTION_no_reboot
,
7667 QEMU_OPTION_no_shutdown
,
7668 QEMU_OPTION_show_cursor
,
7669 QEMU_OPTION_daemonize
,
7670 QEMU_OPTION_option_rom
,
7671 QEMU_OPTION_semihosting
,
7673 QEMU_OPTION_prom_env
,
7674 QEMU_OPTION_old_param
,
7676 QEMU_OPTION_startdate
,
7677 QEMU_OPTION_tb_size
,
7681 typedef struct QEMUOption
{
7687 const QEMUOption qemu_options
[] = {
7688 { "h", 0, QEMU_OPTION_h
},
7689 { "help", 0, QEMU_OPTION_h
},
7691 { "M", HAS_ARG
, QEMU_OPTION_M
},
7692 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7693 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7694 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7695 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7696 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7697 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7698 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7699 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7700 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7701 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7702 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7703 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7704 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7705 { "snapshot", 0, QEMU_OPTION_snapshot
},
7707 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7709 { "m", HAS_ARG
, QEMU_OPTION_m
},
7710 { "nographic", 0, QEMU_OPTION_nographic
},
7711 { "portrait", 0, QEMU_OPTION_portrait
},
7712 { "k", HAS_ARG
, QEMU_OPTION_k
},
7714 { "audio-help", 0, QEMU_OPTION_audio_help
},
7715 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7718 { "net", HAS_ARG
, QEMU_OPTION_net
},
7720 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7721 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7723 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7725 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7728 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7729 { "append", HAS_ARG
, QEMU_OPTION_append
},
7730 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7732 { "S", 0, QEMU_OPTION_S
},
7733 { "s", 0, QEMU_OPTION_s
},
7734 { "p", HAS_ARG
, QEMU_OPTION_p
},
7735 { "d", HAS_ARG
, QEMU_OPTION_d
},
7736 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7737 { "L", HAS_ARG
, QEMU_OPTION_L
},
7738 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7740 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7741 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7743 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7744 { "g", 1, QEMU_OPTION_g
},
7746 { "localtime", 0, QEMU_OPTION_localtime
},
7747 { "std-vga", 0, QEMU_OPTION_std_vga
},
7748 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7749 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7750 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7751 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7752 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7753 { "full-screen", 0, QEMU_OPTION_full_screen
},
7755 { "no-frame", 0, QEMU_OPTION_no_frame
},
7756 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7757 { "no-quit", 0, QEMU_OPTION_no_quit
},
7759 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7760 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7761 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7762 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7763 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7764 #ifdef CONFIG_CURSES
7765 { "curses", 0, QEMU_OPTION_curses
},
7768 /* temporary options */
7769 { "usb", 0, QEMU_OPTION_usb
},
7770 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7771 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7772 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7773 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7774 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7775 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7776 { "daemonize", 0, QEMU_OPTION_daemonize
},
7777 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7778 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7779 { "semihosting", 0, QEMU_OPTION_semihosting
},
7781 { "name", HAS_ARG
, QEMU_OPTION_name
},
7782 #if defined(TARGET_SPARC)
7783 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7785 #if defined(TARGET_ARM)
7786 { "old-param", 0, QEMU_OPTION_old_param
},
7788 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7789 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7790 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
7791 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
7795 /* password input */
7797 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
7802 if (!bdrv_is_encrypted(bs
))
7805 term_printf("%s is encrypted.\n", name
);
7806 for(i
= 0; i
< 3; i
++) {
7807 monitor_readline("Password: ", 1, password
, sizeof(password
));
7808 if (bdrv_set_key(bs
, password
) == 0)
7810 term_printf("invalid password\n");
7815 static BlockDriverState
*get_bdrv(int index
)
7817 if (index
> nb_drives
)
7819 return drives_table
[index
].bdrv
;
7822 static void read_passwords(void)
7824 BlockDriverState
*bs
;
7827 for(i
= 0; i
< 6; i
++) {
7830 qemu_key_check(bs
, bdrv_get_device_name(bs
));
7835 struct soundhw soundhw
[] = {
7836 #ifdef HAS_AUDIO_CHOICE
7837 #if defined(TARGET_I386) || defined(TARGET_MIPS)
7843 { .init_isa
= pcspk_audio_init
}
7848 "Creative Sound Blaster 16",
7851 { .init_isa
= SB16_init
}
7854 #ifdef CONFIG_CS4231A
7860 { .init_isa
= cs4231a_init
}
7868 "Yamaha YMF262 (OPL3)",
7870 "Yamaha YM3812 (OPL2)",
7874 { .init_isa
= Adlib_init
}
7881 "Gravis Ultrasound GF1",
7884 { .init_isa
= GUS_init
}
7891 "Intel 82801AA AC97 Audio",
7894 { .init_pci
= ac97_init
}
7900 "ENSONIQ AudioPCI ES1370",
7903 { .init_pci
= es1370_init
}
7907 { NULL
, NULL
, 0, 0, { NULL
} }
7910 static void select_soundhw (const char *optarg
)
7914 if (*optarg
== '?') {
7917 printf ("Valid sound card names (comma separated):\n");
7918 for (c
= soundhw
; c
->name
; ++c
) {
7919 printf ("%-11s %s\n", c
->name
, c
->descr
);
7921 printf ("\n-soundhw all will enable all of the above\n");
7922 exit (*optarg
!= '?');
7930 if (!strcmp (optarg
, "all")) {
7931 for (c
= soundhw
; c
->name
; ++c
) {
7939 e
= strchr (p
, ',');
7940 l
= !e
? strlen (p
) : (size_t) (e
- p
);
7942 for (c
= soundhw
; c
->name
; ++c
) {
7943 if (!strncmp (c
->name
, p
, l
)) {
7952 "Unknown sound card name (too big to show)\n");
7955 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
7960 p
+= l
+ (e
!= NULL
);
7964 goto show_valid_cards
;
7970 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
7972 exit(STATUS_CONTROL_C_EXIT
);
7977 #define MAX_NET_CLIENTS 32
7979 int main(int argc
, char **argv
)
7981 #ifdef CONFIG_GDBSTUB
7983 const char *gdbstub_port
;
7985 uint32_t boot_devices_bitmap
= 0;
7987 int snapshot
, linux_boot
, net_boot
;
7988 const char *initrd_filename
;
7989 const char *kernel_filename
, *kernel_cmdline
;
7990 const char *boot_devices
= "";
7991 DisplayState
*ds
= &display_state
;
7992 int cyls
, heads
, secs
, translation
;
7993 const char *net_clients
[MAX_NET_CLIENTS
];
7997 const char *r
, *optarg
;
7998 CharDriverState
*monitor_hd
;
7999 const char *monitor_device
;
8000 const char *serial_devices
[MAX_SERIAL_PORTS
];
8001 int serial_device_index
;
8002 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8003 int parallel_device_index
;
8004 const char *loadvm
= NULL
;
8005 QEMUMachine
*machine
;
8006 const char *cpu_model
;
8007 const char *usb_devices
[MAX_USB_CMDLINE
];
8008 int usb_devices_index
;
8011 const char *pid_file
= NULL
;
8014 LIST_INIT (&vm_change_state_head
);
8017 struct sigaction act
;
8018 sigfillset(&act
.sa_mask
);
8020 act
.sa_handler
= SIG_IGN
;
8021 sigaction(SIGPIPE
, &act
, NULL
);
8024 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8025 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8026 QEMU to run on a single CPU */
8031 h
= GetCurrentProcess();
8032 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8033 for(i
= 0; i
< 32; i
++) {
8034 if (mask
& (1 << i
))
8039 SetProcessAffinityMask(h
, mask
);
8045 register_machines();
8046 machine
= first_machine
;
8048 initrd_filename
= NULL
;
8050 vga_ram_size
= VGA_RAM_SIZE
;
8051 #ifdef CONFIG_GDBSTUB
8053 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8058 kernel_filename
= NULL
;
8059 kernel_cmdline
= "";
8060 cyls
= heads
= secs
= 0;
8061 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8062 monitor_device
= "vc";
8064 serial_devices
[0] = "vc:80Cx24C";
8065 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8066 serial_devices
[i
] = NULL
;
8067 serial_device_index
= 0;
8069 parallel_devices
[0] = "vc:640x480";
8070 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8071 parallel_devices
[i
] = NULL
;
8072 parallel_device_index
= 0;
8074 usb_devices_index
= 0;
8091 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8093 const QEMUOption
*popt
;
8096 /* Treat --foo the same as -foo. */
8099 popt
= qemu_options
;
8102 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8106 if (!strcmp(popt
->name
, r
+ 1))
8110 if (popt
->flags
& HAS_ARG
) {
8111 if (optind
>= argc
) {
8112 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8116 optarg
= argv
[optind
++];
8121 switch(popt
->index
) {
8123 machine
= find_machine(optarg
);
8126 printf("Supported machines are:\n");
8127 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8128 printf("%-10s %s%s\n",
8130 m
== first_machine
? " (default)" : "");
8132 exit(*optarg
!= '?');
8135 case QEMU_OPTION_cpu
:
8136 /* hw initialization will check this */
8137 if (*optarg
== '?') {
8138 /* XXX: implement xxx_cpu_list for targets that still miss it */
8139 #if defined(cpu_list)
8140 cpu_list(stdout
, &fprintf
);
8147 case QEMU_OPTION_initrd
:
8148 initrd_filename
= optarg
;
8150 case QEMU_OPTION_hda
:
8152 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8154 hda_index
= drive_add(optarg
, HD_ALIAS
8155 ",cyls=%d,heads=%d,secs=%d%s",
8156 0, cyls
, heads
, secs
,
8157 translation
== BIOS_ATA_TRANSLATION_LBA
?
8159 translation
== BIOS_ATA_TRANSLATION_NONE
?
8160 ",trans=none" : "");
8162 case QEMU_OPTION_hdb
:
8163 case QEMU_OPTION_hdc
:
8164 case QEMU_OPTION_hdd
:
8165 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8167 case QEMU_OPTION_drive
:
8168 drive_add(NULL
, "%s", optarg
);
8170 case QEMU_OPTION_mtdblock
:
8171 drive_add(optarg
, MTD_ALIAS
);
8173 case QEMU_OPTION_sd
:
8174 drive_add(optarg
, SD_ALIAS
);
8176 case QEMU_OPTION_pflash
:
8177 drive_add(optarg
, PFLASH_ALIAS
);
8179 case QEMU_OPTION_snapshot
:
8182 case QEMU_OPTION_hdachs
:
8186 cyls
= strtol(p
, (char **)&p
, 0);
8187 if (cyls
< 1 || cyls
> 16383)
8192 heads
= strtol(p
, (char **)&p
, 0);
8193 if (heads
< 1 || heads
> 16)
8198 secs
= strtol(p
, (char **)&p
, 0);
8199 if (secs
< 1 || secs
> 63)
8203 if (!strcmp(p
, "none"))
8204 translation
= BIOS_ATA_TRANSLATION_NONE
;
8205 else if (!strcmp(p
, "lba"))
8206 translation
= BIOS_ATA_TRANSLATION_LBA
;
8207 else if (!strcmp(p
, "auto"))
8208 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8211 } else if (*p
!= '\0') {
8213 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8216 if (hda_index
!= -1)
8217 snprintf(drives_opt
[hda_index
].opt
,
8218 sizeof(drives_opt
[hda_index
].opt
),
8219 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8220 0, cyls
, heads
, secs
,
8221 translation
== BIOS_ATA_TRANSLATION_LBA
?
8223 translation
== BIOS_ATA_TRANSLATION_NONE
?
8224 ",trans=none" : "");
8227 case QEMU_OPTION_nographic
:
8228 serial_devices
[0] = "stdio";
8229 parallel_devices
[0] = "null";
8230 monitor_device
= "stdio";
8233 #ifdef CONFIG_CURSES
8234 case QEMU_OPTION_curses
:
8238 case QEMU_OPTION_portrait
:
8241 case QEMU_OPTION_kernel
:
8242 kernel_filename
= optarg
;
8244 case QEMU_OPTION_append
:
8245 kernel_cmdline
= optarg
;
8247 case QEMU_OPTION_cdrom
:
8248 drive_add(optarg
, CDROM_ALIAS
);
8250 case QEMU_OPTION_boot
:
8251 boot_devices
= optarg
;
8252 /* We just do some generic consistency checks */
8254 /* Could easily be extended to 64 devices if needed */
8257 boot_devices_bitmap
= 0;
8258 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8259 /* Allowed boot devices are:
8260 * a b : floppy disk drives
8261 * c ... f : IDE disk drives
8262 * g ... m : machine implementation dependant drives
8263 * n ... p : network devices
8264 * It's up to each machine implementation to check
8265 * if the given boot devices match the actual hardware
8266 * implementation and firmware features.
8268 if (*p
< 'a' || *p
> 'q') {
8269 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8272 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8274 "Boot device '%c' was given twice\n",*p
);
8277 boot_devices_bitmap
|= 1 << (*p
- 'a');
8281 case QEMU_OPTION_fda
:
8282 case QEMU_OPTION_fdb
:
8283 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8286 case QEMU_OPTION_no_fd_bootchk
:
8290 case QEMU_OPTION_net
:
8291 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8292 fprintf(stderr
, "qemu: too many network clients\n");
8295 net_clients
[nb_net_clients
] = optarg
;
8299 case QEMU_OPTION_tftp
:
8300 tftp_prefix
= optarg
;
8302 case QEMU_OPTION_bootp
:
8303 bootp_filename
= optarg
;
8306 case QEMU_OPTION_smb
:
8307 net_slirp_smb(optarg
);
8310 case QEMU_OPTION_redir
:
8311 net_slirp_redir(optarg
);
8315 case QEMU_OPTION_audio_help
:
8319 case QEMU_OPTION_soundhw
:
8320 select_soundhw (optarg
);
8326 case QEMU_OPTION_m
: {
8330 value
= strtoul(optarg
, &ptr
, 10);
8332 case 0: case 'M': case 'm':
8339 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8343 /* On 32-bit hosts, QEMU is limited by virtual address space */
8344 if (value
> (2047 << 20)
8346 && HOST_LONG_BITS
== 32
8349 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8352 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8353 fprintf(stderr
, "qemu: ram size too large\n");
8364 mask
= cpu_str_to_log_mask(optarg
);
8366 printf("Log items (comma separated):\n");
8367 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8368 printf("%-10s %s\n", item
->name
, item
->help
);
8375 #ifdef CONFIG_GDBSTUB
8380 gdbstub_port
= optarg
;
8386 case QEMU_OPTION_bios
:
8393 keyboard_layout
= optarg
;
8395 case QEMU_OPTION_localtime
:
8398 case QEMU_OPTION_cirrusvga
:
8399 cirrus_vga_enabled
= 1;
8402 case QEMU_OPTION_vmsvga
:
8403 cirrus_vga_enabled
= 0;
8406 case QEMU_OPTION_std_vga
:
8407 cirrus_vga_enabled
= 0;
8415 w
= strtol(p
, (char **)&p
, 10);
8418 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8424 h
= strtol(p
, (char **)&p
, 10);
8429 depth
= strtol(p
, (char **)&p
, 10);
8430 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8431 depth
!= 24 && depth
!= 32)
8433 } else if (*p
== '\0') {
8434 depth
= graphic_depth
;
8441 graphic_depth
= depth
;
8444 case QEMU_OPTION_echr
:
8447 term_escape_char
= strtol(optarg
, &r
, 0);
8449 printf("Bad argument to echr\n");
8452 case QEMU_OPTION_monitor
:
8453 monitor_device
= optarg
;
8455 case QEMU_OPTION_serial
:
8456 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8457 fprintf(stderr
, "qemu: too many serial ports\n");
8460 serial_devices
[serial_device_index
] = optarg
;
8461 serial_device_index
++;
8463 case QEMU_OPTION_parallel
:
8464 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8465 fprintf(stderr
, "qemu: too many parallel ports\n");
8468 parallel_devices
[parallel_device_index
] = optarg
;
8469 parallel_device_index
++;
8471 case QEMU_OPTION_loadvm
:
8474 case QEMU_OPTION_full_screen
:
8478 case QEMU_OPTION_no_frame
:
8481 case QEMU_OPTION_alt_grab
:
8484 case QEMU_OPTION_no_quit
:
8488 case QEMU_OPTION_pidfile
:
8492 case QEMU_OPTION_win2k_hack
:
8493 win2k_install_hack
= 1;
8497 case QEMU_OPTION_no_kqemu
:
8500 case QEMU_OPTION_kernel_kqemu
:
8504 case QEMU_OPTION_usb
:
8507 case QEMU_OPTION_usbdevice
:
8509 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8510 fprintf(stderr
, "Too many USB devices\n");
8513 usb_devices
[usb_devices_index
] = optarg
;
8514 usb_devices_index
++;
8516 case QEMU_OPTION_smp
:
8517 smp_cpus
= atoi(optarg
);
8518 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8519 fprintf(stderr
, "Invalid number of CPUs\n");
8523 case QEMU_OPTION_vnc
:
8524 vnc_display
= optarg
;
8526 case QEMU_OPTION_no_acpi
:
8529 case QEMU_OPTION_no_reboot
:
8532 case QEMU_OPTION_no_shutdown
:
8535 case QEMU_OPTION_show_cursor
:
8538 case QEMU_OPTION_daemonize
:
8541 case QEMU_OPTION_option_rom
:
8542 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8543 fprintf(stderr
, "Too many option ROMs\n");
8546 option_rom
[nb_option_roms
] = optarg
;
8549 case QEMU_OPTION_semihosting
:
8550 semihosting_enabled
= 1;
8552 case QEMU_OPTION_name
:
8556 case QEMU_OPTION_prom_env
:
8557 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8558 fprintf(stderr
, "Too many prom variables\n");
8561 prom_envs
[nb_prom_envs
] = optarg
;
8566 case QEMU_OPTION_old_param
:
8570 case QEMU_OPTION_clock
:
8571 configure_alarms(optarg
);
8573 case QEMU_OPTION_startdate
:
8576 time_t rtc_start_date
;
8577 if (!strcmp(optarg
, "now")) {
8578 rtc_date_offset
= -1;
8580 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8588 } else if (sscanf(optarg
, "%d-%d-%d",
8591 &tm
.tm_mday
) == 3) {
8600 rtc_start_date
= mktimegm(&tm
);
8601 if (rtc_start_date
== -1) {
8603 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8604 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8607 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8611 case QEMU_OPTION_tb_size
:
8612 tb_size
= strtol(optarg
, NULL
, 0);
8616 case QEMU_OPTION_icount
:
8618 if (strcmp(optarg
, "auto") == 0) {
8619 icount_time_shift
= -1;
8621 icount_time_shift
= strtol(optarg
, NULL
, 0);
8629 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
8630 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
8637 if (pipe(fds
) == -1)
8648 len
= read(fds
[0], &status
, 1);
8649 if (len
== -1 && (errno
== EINTR
))
8654 else if (status
== 1) {
8655 fprintf(stderr
, "Could not acquire pidfile\n");
8673 signal(SIGTSTP
, SIG_IGN
);
8674 signal(SIGTTOU
, SIG_IGN
);
8675 signal(SIGTTIN
, SIG_IGN
);
8679 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8682 write(fds
[1], &status
, 1);
8684 fprintf(stderr
, "Could not acquire pid file\n");
8692 linux_boot
= (kernel_filename
!= NULL
);
8693 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8695 /* XXX: this should not be: some embedded targets just have flash */
8696 if (!linux_boot
&& net_boot
== 0 &&
8700 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8701 fprintf(stderr
, "-append only allowed with -kernel option\n");
8705 if (!linux_boot
&& initrd_filename
!= NULL
) {
8706 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8710 /* boot to floppy or the default cd if no hard disk defined yet */
8711 if (!boot_devices
[0]) {
8712 boot_devices
= "cad";
8714 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8719 if (use_icount
&& icount_time_shift
< 0) {
8721 /* 125MIPS seems a reasonable initial guess at the guest speed.
8722 It will be corrected fairly quickly anyway. */
8723 icount_time_shift
= 3;
8724 init_icount_adjust();
8731 /* init network clients */
8732 if (nb_net_clients
== 0) {
8733 /* if no clients, we use a default config */
8734 net_clients
[0] = "nic";
8735 net_clients
[1] = "user";
8739 for(i
= 0;i
< nb_net_clients
; i
++) {
8740 if (net_client_init(net_clients
[i
]) < 0)
8743 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8744 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8746 if (vlan
->nb_guest_devs
== 0) {
8747 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
8750 if (vlan
->nb_host_devs
== 0)
8752 "Warning: vlan %d is not connected to host network\n",
8757 /* XXX: this should be moved in the PC machine instantiation code */
8758 if (net_boot
!= 0) {
8760 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8761 const char *model
= nd_table
[i
].model
;
8763 if (net_boot
& (1 << i
)) {
8766 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
8767 if (get_image_size(buf
) > 0) {
8768 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8769 fprintf(stderr
, "Too many option ROMs\n");
8772 option_rom
[nb_option_roms
] = strdup(buf
);
8779 fprintf(stderr
, "No valid PXE rom found for network device\n");
8785 /* init the memory */
8786 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
8788 if (machine
->ram_require
& RAMSIZE_FIXED
) {
8790 if (ram_size
< phys_ram_size
) {
8791 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
8792 machine
->name
, (unsigned long long) phys_ram_size
);
8796 phys_ram_size
= ram_size
;
8798 ram_size
= phys_ram_size
;
8801 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
8803 phys_ram_size
+= ram_size
;
8806 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
8807 if (!phys_ram_base
) {
8808 fprintf(stderr
, "Could not allocate physical memory\n");
8812 /* init the dynamic translator */
8813 cpu_exec_init_all(tb_size
* 1024 * 1024);
8817 /* we always create the cdrom drive, even if no disk is there */
8819 if (nb_drives_opt
< MAX_DRIVES
)
8820 drive_add(NULL
, CDROM_ALIAS
);
8822 /* we always create at least one floppy */
8824 if (nb_drives_opt
< MAX_DRIVES
)
8825 drive_add(NULL
, FD_ALIAS
, 0);
8827 /* we always create one sd slot, even if no card is in it */
8829 if (nb_drives_opt
< MAX_DRIVES
)
8830 drive_add(NULL
, SD_ALIAS
);
8832 /* open the virtual block devices */
8834 for(i
= 0; i
< nb_drives_opt
; i
++)
8835 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
8838 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
8839 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
8844 memset(&display_state
, 0, sizeof(display_state
));
8847 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
8850 /* nearly nothing to do */
8851 dumb_display_init(ds
);
8852 } else if (vnc_display
!= NULL
) {
8853 vnc_display_init(ds
);
8854 if (vnc_display_open(ds
, vnc_display
) < 0)
8857 #if defined(CONFIG_CURSES)
8859 curses_display_init(ds
, full_screen
);
8863 #if defined(CONFIG_SDL)
8864 sdl_display_init(ds
, full_screen
, no_frame
);
8865 #elif defined(CONFIG_COCOA)
8866 cocoa_display_init(ds
, full_screen
);
8868 dumb_display_init(ds
);
8872 /* Maintain compatibility with multiple stdio monitors */
8873 if (!strcmp(monitor_device
,"stdio")) {
8874 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
8875 const char *devname
= serial_devices
[i
];
8876 if (devname
&& !strcmp(devname
,"mon:stdio")) {
8877 monitor_device
= NULL
;
8879 } else if (devname
&& !strcmp(devname
,"stdio")) {
8880 monitor_device
= NULL
;
8881 serial_devices
[i
] = "mon:stdio";
8886 if (monitor_device
) {
8887 monitor_hd
= qemu_chr_open(monitor_device
);
8889 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
8892 monitor_init(monitor_hd
, !nographic
);
8895 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
8896 const char *devname
= serial_devices
[i
];
8897 if (devname
&& strcmp(devname
, "none")) {
8898 serial_hds
[i
] = qemu_chr_open(devname
);
8899 if (!serial_hds
[i
]) {
8900 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
8904 if (strstart(devname
, "vc", 0))
8905 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
8909 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
8910 const char *devname
= parallel_devices
[i
];
8911 if (devname
&& strcmp(devname
, "none")) {
8912 parallel_hds
[i
] = qemu_chr_open(devname
);
8913 if (!parallel_hds
[i
]) {
8914 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
8918 if (strstart(devname
, "vc", 0))
8919 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
8923 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
8924 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
8926 /* init USB devices */
8928 for(i
= 0; i
< usb_devices_index
; i
++) {
8929 if (usb_device_add(usb_devices
[i
]) < 0) {
8930 fprintf(stderr
, "Warning: could not add USB device %s\n",
8936 if (display_state
.dpy_refresh
) {
8937 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
8938 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
8941 #ifdef CONFIG_GDBSTUB
8943 /* XXX: use standard host:port notation and modify options
8945 if (gdbserver_start(gdbstub_port
) < 0) {
8946 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
8957 /* XXX: simplify init */
8970 len
= write(fds
[1], &status
, 1);
8971 if (len
== -1 && (errno
== EINTR
))
8977 TFR(fd
= open("/dev/null", O_RDWR
));
8991 #if !defined(_WIN32)
8992 /* close network clients */
8993 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8994 VLANClientState
*vc
;
8996 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
8997 if (vc
->fd_read
== tap_receive
) {
8999 TAPState
*s
= vc
->opaque
;
9001 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9003 launch_script(s
->down_script
, ifname
, s
->fd
);
9005 #if defined(CONFIG_VDE)
9006 if (vc
->fd_read
== vde_from_qemu
) {
9007 VDEState
*s
= vc
->opaque
;