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"
40 #include "migration.h"
52 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
74 #include <linux/if_tun.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
103 #include <winsock2.h>
104 int inet_aton(const char *cp
, struct in_addr
*ia
);
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
119 #include "qemu_socket.h"
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
134 #include "exec-all.h"
136 #include "qemu-kvm.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 int extboot_drive
= -1;
173 /* point to the block driver where the snapshots are managed */
174 BlockDriverState
*bs_snapshots
;
176 static DisplayState display_state
;
179 const char* keyboard_layout
= NULL
;
180 int64_t ticks_per_sec
;
182 int pit_min_timer_count
= 0;
184 NICInfo nd_table
[MAX_NICS
];
186 static int rtc_utc
= 1;
187 static int rtc_date_offset
= -1; /* -1 means no change */
188 int cirrus_vga_enabled
= 1;
189 int vmsvga_enabled
= 0;
191 int graphic_width
= 1024;
192 int graphic_height
= 768;
193 int graphic_depth
= 8;
195 int graphic_width
= 800;
196 int graphic_height
= 600;
197 int graphic_depth
= 15;
202 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
203 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
205 int win2k_install_hack
= 0;
208 static VLANState
*first_vlan
;
210 const char *vnc_display
;
211 #if defined(TARGET_SPARC)
213 #elif defined(TARGET_I386)
215 #elif defined(TARGET_IA64)
220 int acpi_enabled
= 1;
225 int graphic_rotate
= 0;
227 const char *incoming
;
228 const char *option_rom
[MAX_OPTION_ROMS
];
230 int semihosting_enabled
= 0;
232 int time_drift_fix
= 0;
233 unsigned int kvm_shadow_memory
= 0;
234 const char *mem_path
= NULL
;
236 const char *cpu_vendor_string
;
240 const char *qemu_name
;
243 unsigned int nb_prom_envs
= 0;
244 const char *prom_envs
[MAX_PROM_ENVS
];
247 struct drive_opt drives_opt
[MAX_DRIVES
];
249 static CPUState
*cur_cpu
;
250 static CPUState
*next_cpu
;
251 static int event_pending
= 1;
252 /* Conversion factor from emulated instructions to virtual clock ticks. */
253 static int icount_time_shift
;
254 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
255 #define MAX_ICOUNT_SHIFT 10
256 /* Compensate for varying guest execution speed. */
257 static int64_t qemu_icount_bias
;
258 QEMUTimer
*icount_rt_timer
;
259 QEMUTimer
*icount_vm_timer
;
261 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
263 /* KVM runs the main loop in a separate thread. If we update one of the lists
264 * that are polled before or after select(), we need to make sure to break out
265 * of the select() to ensure the new item is serviced.
267 static void main_loop_break(void)
270 qemu_kvm_notify_work();
273 /***********************************************************/
274 /* x86 ISA bus support */
276 target_phys_addr_t isa_mem_base
= 0;
279 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
281 #ifdef DEBUG_UNUSED_IOPORT
282 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
287 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
289 #ifdef DEBUG_UNUSED_IOPORT
290 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
294 /* default is to make two byte accesses */
295 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
298 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
299 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
300 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
304 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
306 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
307 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
308 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
311 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
313 #ifdef DEBUG_UNUSED_IOPORT
314 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
319 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
321 #ifdef DEBUG_UNUSED_IOPORT
322 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
326 static void init_ioports(void)
330 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
331 ioport_read_table
[0][i
] = default_ioport_readb
;
332 ioport_write_table
[0][i
] = default_ioport_writeb
;
333 ioport_read_table
[1][i
] = default_ioport_readw
;
334 ioport_write_table
[1][i
] = default_ioport_writew
;
335 ioport_read_table
[2][i
] = default_ioport_readl
;
336 ioport_write_table
[2][i
] = default_ioport_writel
;
340 /* size is the word size in byte */
341 int register_ioport_read(int start
, int length
, int size
,
342 IOPortReadFunc
*func
, void *opaque
)
348 } else if (size
== 2) {
350 } else if (size
== 4) {
353 hw_error("register_ioport_read: invalid size");
356 for(i
= start
; i
< start
+ length
; i
+= size
) {
357 ioport_read_table
[bsize
][i
] = func
;
358 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
359 hw_error("register_ioport_read: invalid opaque");
360 ioport_opaque
[i
] = opaque
;
365 /* size is the word size in byte */
366 int register_ioport_write(int start
, int length
, int size
,
367 IOPortWriteFunc
*func
, void *opaque
)
373 } else if (size
== 2) {
375 } else if (size
== 4) {
378 hw_error("register_ioport_write: invalid size");
381 for(i
= start
; i
< start
+ length
; i
+= size
) {
382 ioport_write_table
[bsize
][i
] = func
;
383 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
384 hw_error("register_ioport_write: invalid opaque");
385 ioport_opaque
[i
] = opaque
;
390 void isa_unassign_ioport(int start
, int length
)
394 for(i
= start
; i
< start
+ length
; i
++) {
395 ioport_read_table
[0][i
] = default_ioport_readb
;
396 ioport_read_table
[1][i
] = default_ioport_readw
;
397 ioport_read_table
[2][i
] = default_ioport_readl
;
399 ioport_write_table
[0][i
] = default_ioport_writeb
;
400 ioport_write_table
[1][i
] = default_ioport_writew
;
401 ioport_write_table
[2][i
] = default_ioport_writel
;
403 ioport_opaque
[i
] = NULL
;
407 /***********************************************************/
409 void cpu_outb(CPUState
*env
, int addr
, int val
)
412 if (loglevel
& CPU_LOG_IOPORT
)
413 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
415 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
418 env
->last_io_time
= cpu_get_time_fast();
422 void cpu_outw(CPUState
*env
, int addr
, int val
)
425 if (loglevel
& CPU_LOG_IOPORT
)
426 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
428 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
431 env
->last_io_time
= cpu_get_time_fast();
435 void cpu_outl(CPUState
*env
, int addr
, int val
)
438 if (loglevel
& CPU_LOG_IOPORT
)
439 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
441 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
444 env
->last_io_time
= cpu_get_time_fast();
448 int cpu_inb(CPUState
*env
, int addr
)
451 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
453 if (loglevel
& CPU_LOG_IOPORT
)
454 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
458 env
->last_io_time
= cpu_get_time_fast();
463 int cpu_inw(CPUState
*env
, int addr
)
466 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
468 if (loglevel
& CPU_LOG_IOPORT
)
469 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
473 env
->last_io_time
= cpu_get_time_fast();
478 int cpu_inl(CPUState
*env
, int addr
)
481 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
483 if (loglevel
& CPU_LOG_IOPORT
)
484 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
488 env
->last_io_time
= cpu_get_time_fast();
493 /***********************************************************/
494 void hw_error(const char *fmt
, ...)
500 fprintf(stderr
, "qemu: hardware error: ");
501 vfprintf(stderr
, fmt
, ap
);
502 fprintf(stderr
, "\n");
503 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
504 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
506 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
508 cpu_dump_state(env
, stderr
, fprintf
, 0);
515 /***********************************************************/
518 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
519 static void *qemu_put_kbd_event_opaque
;
520 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
521 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
523 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
525 qemu_put_kbd_event_opaque
= opaque
;
526 qemu_put_kbd_event
= func
;
529 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
530 void *opaque
, int absolute
,
533 QEMUPutMouseEntry
*s
, *cursor
;
535 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
539 s
->qemu_put_mouse_event
= func
;
540 s
->qemu_put_mouse_event_opaque
= opaque
;
541 s
->qemu_put_mouse_event_absolute
= absolute
;
542 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
545 if (!qemu_put_mouse_event_head
) {
546 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
550 cursor
= qemu_put_mouse_event_head
;
551 while (cursor
->next
!= NULL
)
552 cursor
= cursor
->next
;
555 qemu_put_mouse_event_current
= s
;
560 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
562 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
564 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
567 cursor
= qemu_put_mouse_event_head
;
568 while (cursor
!= NULL
&& cursor
!= entry
) {
570 cursor
= cursor
->next
;
573 if (cursor
== NULL
) // does not exist or list empty
575 else if (prev
== NULL
) { // entry is head
576 qemu_put_mouse_event_head
= cursor
->next
;
577 if (qemu_put_mouse_event_current
== entry
)
578 qemu_put_mouse_event_current
= cursor
->next
;
579 qemu_free(entry
->qemu_put_mouse_event_name
);
584 prev
->next
= entry
->next
;
586 if (qemu_put_mouse_event_current
== entry
)
587 qemu_put_mouse_event_current
= prev
;
589 qemu_free(entry
->qemu_put_mouse_event_name
);
593 void kbd_put_keycode(int keycode
)
595 if (qemu_put_kbd_event
) {
596 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
600 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
602 QEMUPutMouseEvent
*mouse_event
;
603 void *mouse_event_opaque
;
606 if (!qemu_put_mouse_event_current
) {
611 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
613 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
616 if (graphic_rotate
) {
617 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
620 width
= graphic_width
- 1;
621 mouse_event(mouse_event_opaque
,
622 width
- dy
, dx
, dz
, buttons_state
);
624 mouse_event(mouse_event_opaque
,
625 dx
, dy
, dz
, buttons_state
);
629 int kbd_mouse_is_absolute(void)
631 if (!qemu_put_mouse_event_current
)
634 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
637 void do_info_mice(void)
639 QEMUPutMouseEntry
*cursor
;
642 if (!qemu_put_mouse_event_head
) {
643 term_printf("No mouse devices connected\n");
647 term_printf("Mouse devices available:\n");
648 cursor
= qemu_put_mouse_event_head
;
649 while (cursor
!= NULL
) {
650 term_printf("%c Mouse #%d: %s\n",
651 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
652 index
, cursor
->qemu_put_mouse_event_name
);
654 cursor
= cursor
->next
;
658 void do_mouse_set(int index
)
660 QEMUPutMouseEntry
*cursor
;
663 if (!qemu_put_mouse_event_head
) {
664 term_printf("No mouse devices connected\n");
668 cursor
= qemu_put_mouse_event_head
;
669 while (cursor
!= NULL
&& index
!= i
) {
671 cursor
= cursor
->next
;
675 qemu_put_mouse_event_current
= cursor
;
677 term_printf("Mouse at given index not found\n");
680 /* compute with 96 bit intermediate result: (a*b)/c */
681 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
686 #ifdef WORDS_BIGENDIAN
696 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
697 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
700 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
704 /***********************************************************/
705 /* real time host monotonic timer */
707 #define QEMU_TIMER_BASE 1000000000LL
711 static int64_t clock_freq
;
713 static void init_get_clock(void)
717 ret
= QueryPerformanceFrequency(&freq
);
719 fprintf(stderr
, "Could not calibrate ticks\n");
722 clock_freq
= freq
.QuadPart
;
725 static int64_t get_clock(void)
728 QueryPerformanceCounter(&ti
);
729 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
734 static int use_rt_clock
;
736 static void init_get_clock(void)
739 #if defined(__linux__)
742 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
749 static int64_t get_clock(void)
751 #if defined(__linux__)
754 clock_gettime(CLOCK_MONOTONIC
, &ts
);
755 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
759 /* XXX: using gettimeofday leads to problems if the date
760 changes, so it should be avoided. */
762 gettimeofday(&tv
, NULL
);
763 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
768 /* Return the virtual CPU time, based on the instruction counter. */
769 static int64_t cpu_get_icount(void)
772 CPUState
*env
= cpu_single_env
;;
773 icount
= qemu_icount
;
776 fprintf(stderr
, "Bad clock read\n");
777 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
779 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
782 /***********************************************************/
783 /* guest cycle counter */
785 static int64_t cpu_ticks_prev
;
786 static int64_t cpu_ticks_offset
;
787 static int64_t cpu_clock_offset
;
788 static int cpu_ticks_enabled
;
790 /* return the host CPU cycle counter and handle stop/restart */
791 int64_t cpu_get_ticks(void)
794 return cpu_get_icount();
796 if (!cpu_ticks_enabled
) {
797 return cpu_ticks_offset
;
800 ticks
= cpu_get_real_ticks();
801 if (cpu_ticks_prev
> ticks
) {
802 /* Note: non increasing ticks may happen if the host uses
804 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
806 cpu_ticks_prev
= ticks
;
807 return ticks
+ cpu_ticks_offset
;
811 /* return the host CPU monotonic timer and handle stop/restart */
812 static int64_t cpu_get_clock(void)
815 if (!cpu_ticks_enabled
) {
816 return cpu_clock_offset
;
819 return ti
+ cpu_clock_offset
;
823 /* enable cpu_get_ticks() */
824 void cpu_enable_ticks(void)
826 if (!cpu_ticks_enabled
) {
827 cpu_ticks_offset
-= cpu_get_real_ticks();
828 cpu_clock_offset
-= get_clock();
829 cpu_ticks_enabled
= 1;
833 /* disable cpu_get_ticks() : the clock is stopped. You must not call
834 cpu_get_ticks() after that. */
835 void cpu_disable_ticks(void)
837 if (cpu_ticks_enabled
) {
838 cpu_ticks_offset
= cpu_get_ticks();
839 cpu_clock_offset
= cpu_get_clock();
840 cpu_ticks_enabled
= 0;
844 /***********************************************************/
847 #define QEMU_TIMER_REALTIME 0
848 #define QEMU_TIMER_VIRTUAL 1
852 /* XXX: add frequency */
860 struct QEMUTimer
*next
;
863 struct qemu_alarm_timer
{
867 int (*start
)(struct qemu_alarm_timer
*t
);
868 void (*stop
)(struct qemu_alarm_timer
*t
);
869 void (*rearm
)(struct qemu_alarm_timer
*t
);
873 #define ALARM_FLAG_DYNTICKS 0x1
874 #define ALARM_FLAG_EXPIRED 0x2
876 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
878 return t
->flags
& ALARM_FLAG_DYNTICKS
;
881 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
883 if (!alarm_has_dynticks(t
))
889 /* TODO: MIN_TIMER_REARM_US should be optimized */
890 #define MIN_TIMER_REARM_US 250
892 static struct qemu_alarm_timer
*alarm_timer
;
896 struct qemu_alarm_win32
{
900 } alarm_win32_data
= {0, NULL
, -1};
902 static int win32_start_timer(struct qemu_alarm_timer
*t
);
903 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
904 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
908 static int unix_start_timer(struct qemu_alarm_timer
*t
);
909 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
913 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
914 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
915 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
917 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
918 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
920 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
921 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
923 #endif /* __linux__ */
927 /* Correlation between real and virtual time is always going to be
928 fairly approximate, so ignore small variation.
929 When the guest is idle real and virtual time will be aligned in
931 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
933 static void icount_adjust(void)
938 static int64_t last_delta
;
939 /* If the VM is not running, then do nothing. */
943 cur_time
= cpu_get_clock();
944 cur_icount
= qemu_get_clock(vm_clock
);
945 delta
= cur_icount
- cur_time
;
946 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
948 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
949 && icount_time_shift
> 0) {
950 /* The guest is getting too far ahead. Slow time down. */
954 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
955 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
956 /* The guest is getting too far behind. Speed time up. */
960 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
963 static void icount_adjust_rt(void * opaque
)
965 qemu_mod_timer(icount_rt_timer
,
966 qemu_get_clock(rt_clock
) + 1000);
970 static void icount_adjust_vm(void * opaque
)
972 qemu_mod_timer(icount_vm_timer
,
973 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
977 static void init_icount_adjust(void)
979 /* Have both realtime and virtual time triggers for speed adjustment.
980 The realtime trigger catches emulated time passing too slowly,
981 the virtual time trigger catches emulated time passing too fast.
982 Realtime triggers occur even when idle, so use them less frequently
984 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
985 qemu_mod_timer(icount_rt_timer
,
986 qemu_get_clock(rt_clock
) + 1000);
987 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
988 qemu_mod_timer(icount_vm_timer
,
989 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
992 static struct qemu_alarm_timer alarm_timers
[] = {
995 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
996 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
997 /* HPET - if available - is preferred */
998 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
999 /* ...otherwise try RTC */
1000 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1002 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1004 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1005 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1006 {"win32", 0, win32_start_timer
,
1007 win32_stop_timer
, NULL
, &alarm_win32_data
},
1012 static void show_available_alarms(void)
1016 printf("Available alarm timers, in order of precedence:\n");
1017 for (i
= 0; alarm_timers
[i
].name
; i
++)
1018 printf("%s\n", alarm_timers
[i
].name
);
1021 static void configure_alarms(char const *opt
)
1025 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1028 struct qemu_alarm_timer tmp
;
1030 if (!strcmp(opt
, "?")) {
1031 show_available_alarms();
1037 /* Reorder the array */
1038 name
= strtok(arg
, ",");
1040 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1041 if (!strcmp(alarm_timers
[i
].name
, name
))
1046 fprintf(stderr
, "Unknown clock %s\n", name
);
1055 tmp
= alarm_timers
[i
];
1056 alarm_timers
[i
] = alarm_timers
[cur
];
1057 alarm_timers
[cur
] = tmp
;
1061 name
= strtok(NULL
, ",");
1067 /* Disable remaining timers */
1068 for (i
= cur
; i
< count
; i
++)
1069 alarm_timers
[i
].name
= NULL
;
1071 show_available_alarms();
1076 QEMUClock
*rt_clock
;
1077 QEMUClock
*vm_clock
;
1079 static QEMUTimer
*active_timers
[2];
1081 static QEMUClock
*qemu_new_clock(int type
)
1084 clock
= qemu_mallocz(sizeof(QEMUClock
));
1091 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1095 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1098 ts
->opaque
= opaque
;
1102 void qemu_free_timer(QEMUTimer
*ts
)
1107 /* stop a timer, but do not dealloc it */
1108 void qemu_del_timer(QEMUTimer
*ts
)
1112 /* NOTE: this code must be signal safe because
1113 qemu_timer_expired() can be called from a signal. */
1114 pt
= &active_timers
[ts
->clock
->type
];
1127 /* modify the current timer so that it will be fired when current_time
1128 >= expire_time. The corresponding callback will be called. */
1129 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1135 /* add the timer in the sorted list */
1136 /* NOTE: this code must be signal safe because
1137 qemu_timer_expired() can be called from a signal. */
1138 pt
= &active_timers
[ts
->clock
->type
];
1143 if (t
->expire_time
> expire_time
)
1147 ts
->expire_time
= expire_time
;
1151 /* Rearm if necessary */
1152 if (pt
== &active_timers
[ts
->clock
->type
]) {
1153 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1154 qemu_rearm_alarm_timer(alarm_timer
);
1156 /* Interrupt execution to force deadline recalculation. */
1157 if (use_icount
&& cpu_single_env
) {
1158 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1163 int qemu_timer_pending(QEMUTimer
*ts
)
1166 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1173 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1177 return (timer_head
->expire_time
<= current_time
);
1180 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1186 if (!ts
|| ts
->expire_time
> current_time
)
1188 /* remove timer from the list before calling the callback */
1189 *ptimer_head
= ts
->next
;
1192 /* run the callback (the timer list can be modified) */
1197 int64_t qemu_get_clock(QEMUClock
*clock
)
1199 switch(clock
->type
) {
1200 case QEMU_TIMER_REALTIME
:
1201 return get_clock() / 1000000;
1203 case QEMU_TIMER_VIRTUAL
:
1205 return cpu_get_icount();
1207 return cpu_get_clock();
1212 static void init_timers(void)
1215 ticks_per_sec
= QEMU_TIMER_BASE
;
1216 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1217 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1221 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1223 uint64_t expire_time
;
1225 if (qemu_timer_pending(ts
)) {
1226 expire_time
= ts
->expire_time
;
1230 qemu_put_be64(f
, expire_time
);
1233 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1235 uint64_t expire_time
;
1237 expire_time
= qemu_get_be64(f
);
1238 if (expire_time
!= -1) {
1239 qemu_mod_timer(ts
, expire_time
);
1245 static void timer_save(QEMUFile
*f
, void *opaque
)
1247 if (cpu_ticks_enabled
) {
1248 hw_error("cannot save state if virtual timers are running");
1250 qemu_put_be64(f
, cpu_ticks_offset
);
1251 qemu_put_be64(f
, ticks_per_sec
);
1252 qemu_put_be64(f
, cpu_clock_offset
);
1255 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1257 if (version_id
!= 1 && version_id
!= 2)
1259 if (cpu_ticks_enabled
) {
1262 cpu_ticks_offset
=qemu_get_be64(f
);
1263 ticks_per_sec
=qemu_get_be64(f
);
1264 if (version_id
== 2) {
1265 cpu_clock_offset
=qemu_get_be64(f
);
1271 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1272 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1274 static void host_alarm_handler(int host_signum
)
1278 #define DISP_FREQ 1000
1280 static int64_t delta_min
= INT64_MAX
;
1281 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1283 ti
= qemu_get_clock(vm_clock
);
1284 if (last_clock
!= 0) {
1285 delta
= ti
- last_clock
;
1286 if (delta
< delta_min
)
1288 if (delta
> delta_max
)
1291 if (++count
== DISP_FREQ
) {
1292 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1293 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1294 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1295 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1296 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1298 delta_min
= INT64_MAX
;
1307 alarm_has_dynticks(alarm_timer
) ||
1309 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1310 qemu_get_clock(vm_clock
))) ||
1311 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1312 qemu_get_clock(rt_clock
))) {
1314 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1315 SetEvent(data
->host_alarm
);
1317 CPUState
*env
= next_cpu
;
1319 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1322 /* stop the currently executing cpu because a timer occured */
1323 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1325 if (env
->kqemu_enabled
) {
1326 kqemu_cpu_interrupt(env
);
1334 static int64_t qemu_next_deadline(void)
1338 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1339 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1340 qemu_get_clock(vm_clock
);
1342 /* To avoid problems with overflow limit this to 2^32. */
1352 static uint64_t qemu_next_deadline_dyntick(void)
1360 delta
= (qemu_next_deadline() + 999) / 1000;
1362 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1363 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1364 qemu_get_clock(rt_clock
))*1000;
1365 if (rtdelta
< delta
)
1369 if (delta
< MIN_TIMER_REARM_US
)
1370 delta
= MIN_TIMER_REARM_US
;
1377 #if defined(__linux__)
1379 #define RTC_FREQ 1024
1381 static void enable_sigio_timer(int fd
)
1383 struct sigaction act
;
1386 sigfillset(&act
.sa_mask
);
1388 act
.sa_handler
= host_alarm_handler
;
1390 sigaction(SIGIO
, &act
, NULL
);
1391 fcntl(fd
, F_SETFL
, O_ASYNC
);
1392 fcntl(fd
, F_SETOWN
, getpid());
1395 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1397 struct hpet_info info
;
1400 fd
= open("/dev/hpet", O_RDONLY
);
1405 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1407 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1408 "error, but for better emulation accuracy type:\n"
1409 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1413 /* Check capabilities */
1414 r
= ioctl(fd
, HPET_INFO
, &info
);
1418 /* Enable periodic mode */
1419 r
= ioctl(fd
, HPET_EPI
, 0);
1420 if (info
.hi_flags
&& (r
< 0))
1423 /* Enable interrupt */
1424 r
= ioctl(fd
, HPET_IE_ON
, 0);
1428 enable_sigio_timer(fd
);
1429 t
->priv
= (void *)(long)fd
;
1437 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1439 int fd
= (long)t
->priv
;
1444 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1447 unsigned long current_rtc_freq
= 0;
1449 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1452 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1453 if (current_rtc_freq
!= RTC_FREQ
&&
1454 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1455 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1456 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1457 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1460 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1466 enable_sigio_timer(rtc_fd
);
1468 t
->priv
= (void *)(long)rtc_fd
;
1473 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1475 int rtc_fd
= (long)t
->priv
;
1480 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1484 struct sigaction act
;
1486 sigfillset(&act
.sa_mask
);
1488 act
.sa_handler
= host_alarm_handler
;
1490 sigaction(SIGALRM
, &act
, NULL
);
1492 ev
.sigev_value
.sival_int
= 0;
1493 ev
.sigev_notify
= SIGEV_SIGNAL
;
1494 ev
.sigev_signo
= SIGALRM
;
1496 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1497 perror("timer_create");
1499 /* disable dynticks */
1500 fprintf(stderr
, "Dynamic Ticks disabled\n");
1505 t
->priv
= (void *)host_timer
;
1510 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1512 timer_t host_timer
= (timer_t
)t
->priv
;
1514 timer_delete(host_timer
);
1517 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1519 timer_t host_timer
= (timer_t
)t
->priv
;
1520 struct itimerspec timeout
;
1521 int64_t nearest_delta_us
= INT64_MAX
;
1524 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1525 !active_timers
[QEMU_TIMER_VIRTUAL
])
1528 nearest_delta_us
= qemu_next_deadline_dyntick();
1530 /* check whether a timer is already running */
1531 if (timer_gettime(host_timer
, &timeout
)) {
1533 fprintf(stderr
, "Internal timer error: aborting\n");
1536 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1537 if (current_us
&& current_us
<= nearest_delta_us
)
1540 timeout
.it_interval
.tv_sec
= 0;
1541 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1542 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1543 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1544 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1546 fprintf(stderr
, "Internal timer error: aborting\n");
1551 #endif /* defined(__linux__) */
1553 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1555 struct sigaction act
;
1556 struct itimerval itv
;
1560 sigfillset(&act
.sa_mask
);
1562 act
.sa_handler
= host_alarm_handler
;
1564 sigaction(SIGALRM
, &act
, NULL
);
1566 itv
.it_interval
.tv_sec
= 0;
1567 /* for i386 kernel 2.6 to get 1 ms */
1568 itv
.it_interval
.tv_usec
= 999;
1569 itv
.it_value
.tv_sec
= 0;
1570 itv
.it_value
.tv_usec
= 10 * 1000;
1572 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1579 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1581 struct itimerval itv
;
1583 memset(&itv
, 0, sizeof(itv
));
1584 setitimer(ITIMER_REAL
, &itv
, NULL
);
1587 #endif /* !defined(_WIN32) */
1591 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1594 struct qemu_alarm_win32
*data
= t
->priv
;
1597 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1598 if (!data
->host_alarm
) {
1599 perror("Failed CreateEvent");
1603 memset(&tc
, 0, sizeof(tc
));
1604 timeGetDevCaps(&tc
, sizeof(tc
));
1606 if (data
->period
< tc
.wPeriodMin
)
1607 data
->period
= tc
.wPeriodMin
;
1609 timeBeginPeriod(data
->period
);
1611 flags
= TIME_CALLBACK_FUNCTION
;
1612 if (alarm_has_dynticks(t
))
1613 flags
|= TIME_ONESHOT
;
1615 flags
|= TIME_PERIODIC
;
1617 data
->timerId
= timeSetEvent(1, // interval (ms)
1618 data
->period
, // resolution
1619 host_alarm_handler
, // function
1620 (DWORD
)t
, // parameter
1623 if (!data
->timerId
) {
1624 perror("Failed to initialize win32 alarm timer");
1626 timeEndPeriod(data
->period
);
1627 CloseHandle(data
->host_alarm
);
1631 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1636 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1638 struct qemu_alarm_win32
*data
= t
->priv
;
1640 timeKillEvent(data
->timerId
);
1641 timeEndPeriod(data
->period
);
1643 CloseHandle(data
->host_alarm
);
1646 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1648 struct qemu_alarm_win32
*data
= t
->priv
;
1649 uint64_t nearest_delta_us
;
1651 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1652 !active_timers
[QEMU_TIMER_VIRTUAL
])
1655 nearest_delta_us
= qemu_next_deadline_dyntick();
1656 nearest_delta_us
/= 1000;
1658 timeKillEvent(data
->timerId
);
1660 data
->timerId
= timeSetEvent(1,
1664 TIME_ONESHOT
| TIME_PERIODIC
);
1666 if (!data
->timerId
) {
1667 perror("Failed to re-arm win32 alarm timer");
1669 timeEndPeriod(data
->period
);
1670 CloseHandle(data
->host_alarm
);
1677 static void init_timer_alarm(void)
1679 struct qemu_alarm_timer
*t
;
1682 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1683 t
= &alarm_timers
[i
];
1691 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1692 fprintf(stderr
, "Terminating\n");
1699 static void quit_timers(void)
1701 alarm_timer
->stop(alarm_timer
);
1705 /***********************************************************/
1706 /* host time/date access */
1707 void qemu_get_timedate(struct tm
*tm
, int offset
)
1714 if (rtc_date_offset
== -1) {
1718 ret
= localtime(&ti
);
1720 ti
-= rtc_date_offset
;
1724 memcpy(tm
, ret
, sizeof(struct tm
));
1727 int qemu_timedate_diff(struct tm
*tm
)
1731 if (rtc_date_offset
== -1)
1733 seconds
= mktimegm(tm
);
1735 seconds
= mktime(tm
);
1737 seconds
= mktimegm(tm
) + rtc_date_offset
;
1739 return seconds
- time(NULL
);
1742 /***********************************************************/
1743 /* character device */
1745 static void qemu_chr_event(CharDriverState
*s
, int event
)
1749 s
->chr_event(s
->handler_opaque
, event
);
1752 static void qemu_chr_reset_bh(void *opaque
)
1754 CharDriverState
*s
= opaque
;
1755 qemu_chr_event(s
, CHR_EVENT_RESET
);
1756 qemu_bh_delete(s
->bh
);
1760 void qemu_chr_reset(CharDriverState
*s
)
1762 if (s
->bh
== NULL
) {
1763 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1764 qemu_bh_schedule(s
->bh
);
1768 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1770 return s
->chr_write(s
, buf
, len
);
1773 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1777 return s
->chr_ioctl(s
, cmd
, arg
);
1780 int qemu_chr_can_read(CharDriverState
*s
)
1782 if (!s
->chr_can_read
)
1784 return s
->chr_can_read(s
->handler_opaque
);
1787 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1789 s
->chr_read(s
->handler_opaque
, buf
, len
);
1792 void qemu_chr_accept_input(CharDriverState
*s
)
1794 if (s
->chr_accept_input
)
1795 s
->chr_accept_input(s
);
1798 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1803 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1804 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1808 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1810 if (s
->chr_send_event
)
1811 s
->chr_send_event(s
, event
);
1814 void qemu_chr_add_handlers(CharDriverState
*s
,
1815 IOCanRWHandler
*fd_can_read
,
1816 IOReadHandler
*fd_read
,
1817 IOEventHandler
*fd_event
,
1820 s
->chr_can_read
= fd_can_read
;
1821 s
->chr_read
= fd_read
;
1822 s
->chr_event
= fd_event
;
1823 s
->handler_opaque
= opaque
;
1824 if (s
->chr_update_read_handler
)
1825 s
->chr_update_read_handler(s
);
1828 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1833 static CharDriverState
*qemu_chr_open_null(void)
1835 CharDriverState
*chr
;
1837 chr
= qemu_mallocz(sizeof(CharDriverState
));
1840 chr
->chr_write
= null_chr_write
;
1844 /* MUX driver for serial I/O splitting */
1845 static int term_timestamps
;
1846 static int64_t term_timestamps_start
;
1848 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1849 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1851 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1852 IOReadHandler
*chr_read
[MAX_MUX
];
1853 IOEventHandler
*chr_event
[MAX_MUX
];
1854 void *ext_opaque
[MAX_MUX
];
1855 CharDriverState
*drv
;
1856 unsigned char buffer
[MUX_BUFFER_SIZE
];
1860 int term_got_escape
;
1865 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1867 MuxDriver
*d
= chr
->opaque
;
1869 if (!term_timestamps
) {
1870 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1875 for(i
= 0; i
< len
; i
++) {
1876 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1877 if (buf
[i
] == '\n') {
1883 if (term_timestamps_start
== -1)
1884 term_timestamps_start
= ti
;
1885 ti
-= term_timestamps_start
;
1886 secs
= ti
/ 1000000000;
1887 snprintf(buf1
, sizeof(buf1
),
1888 "[%02d:%02d:%02d.%03d] ",
1892 (int)((ti
/ 1000000) % 1000));
1893 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1900 static char *mux_help
[] = {
1901 "% h print this help\n\r",
1902 "% x exit emulator\n\r",
1903 "% s save disk data back to file (if -snapshot)\n\r",
1904 "% t toggle console timestamps\n\r"
1905 "% b send break (magic sysrq)\n\r",
1906 "% c switch between console and monitor\n\r",
1911 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1912 static void mux_print_help(CharDriverState
*chr
)
1915 char ebuf
[15] = "Escape-Char";
1916 char cbuf
[50] = "\n\r";
1918 if (term_escape_char
> 0 && term_escape_char
< 26) {
1919 sprintf(cbuf
,"\n\r");
1920 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1922 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1925 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1926 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1927 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1928 if (mux_help
[i
][j
] == '%')
1929 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1931 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1936 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1938 if (d
->term_got_escape
) {
1939 d
->term_got_escape
= 0;
1940 if (ch
== term_escape_char
)
1945 mux_print_help(chr
);
1949 char *term
= "QEMU: Terminated\n\r";
1950 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1957 for (i
= 0; i
< nb_drives
; i
++) {
1958 bdrv_commit(drives_table
[i
].bdrv
);
1963 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1966 /* Switch to the next registered device */
1968 if (chr
->focus
>= d
->mux_cnt
)
1972 term_timestamps
= !term_timestamps
;
1973 term_timestamps_start
= -1;
1976 } else if (ch
== term_escape_char
) {
1977 d
->term_got_escape
= 1;
1985 static void mux_chr_accept_input(CharDriverState
*chr
)
1988 MuxDriver
*d
= chr
->opaque
;
1990 while (d
->prod
!= d
->cons
&&
1991 d
->chr_can_read
[m
] &&
1992 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1993 d
->chr_read
[m
](d
->ext_opaque
[m
],
1994 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1998 static int mux_chr_can_read(void *opaque
)
2000 CharDriverState
*chr
= opaque
;
2001 MuxDriver
*d
= chr
->opaque
;
2003 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2005 if (d
->chr_can_read
[chr
->focus
])
2006 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2010 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2012 CharDriverState
*chr
= opaque
;
2013 MuxDriver
*d
= chr
->opaque
;
2017 mux_chr_accept_input (opaque
);
2019 for(i
= 0; i
< size
; i
++)
2020 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2021 if (d
->prod
== d
->cons
&&
2022 d
->chr_can_read
[m
] &&
2023 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2024 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2026 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2030 static void mux_chr_event(void *opaque
, int event
)
2032 CharDriverState
*chr
= opaque
;
2033 MuxDriver
*d
= chr
->opaque
;
2036 /* Send the event to all registered listeners */
2037 for (i
= 0; i
< d
->mux_cnt
; i
++)
2038 if (d
->chr_event
[i
])
2039 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2042 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2044 MuxDriver
*d
= chr
->opaque
;
2046 if (d
->mux_cnt
>= MAX_MUX
) {
2047 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2050 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2051 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2052 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2053 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2054 /* Fix up the real driver with mux routines */
2055 if (d
->mux_cnt
== 0) {
2056 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2057 mux_chr_event
, chr
);
2059 chr
->focus
= d
->mux_cnt
;
2063 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2065 CharDriverState
*chr
;
2068 chr
= qemu_mallocz(sizeof(CharDriverState
));
2071 d
= qemu_mallocz(sizeof(MuxDriver
));
2080 chr
->chr_write
= mux_chr_write
;
2081 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2082 chr
->chr_accept_input
= mux_chr_accept_input
;
2089 static void socket_cleanup(void)
2094 static int socket_init(void)
2099 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2101 err
= WSAGetLastError();
2102 fprintf(stderr
, "WSAStartup: %d\n", err
);
2105 atexit(socket_cleanup
);
2109 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2115 ret
= send(fd
, buf
, len
, 0);
2118 errno
= WSAGetLastError();
2119 if (errno
!= WSAEWOULDBLOCK
) {
2122 } else if (ret
== 0) {
2132 void socket_set_nonblock(int fd
)
2134 unsigned long opt
= 1;
2135 ioctlsocket(fd
, FIONBIO
, &opt
);
2140 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2146 ret
= write(fd
, buf
, len
);
2148 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2150 } else if (ret
== 0) {
2160 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2162 return unix_write(fd
, buf
, len1
);
2165 void socket_set_nonblock(int fd
)
2167 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2169 #endif /* !_WIN32 */
2178 #define STDIO_MAX_CLIENTS 1
2179 static int stdio_nb_clients
= 0;
2181 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2183 FDCharDriver
*s
= chr
->opaque
;
2184 return unix_write(s
->fd_out
, buf
, len
);
2187 static int fd_chr_read_poll(void *opaque
)
2189 CharDriverState
*chr
= opaque
;
2190 FDCharDriver
*s
= chr
->opaque
;
2192 s
->max_size
= qemu_chr_can_read(chr
);
2196 static void fd_chr_read(void *opaque
)
2198 CharDriverState
*chr
= opaque
;
2199 FDCharDriver
*s
= chr
->opaque
;
2204 if (len
> s
->max_size
)
2208 size
= read(s
->fd_in
, buf
, len
);
2210 /* FD has been closed. Remove it from the active list. */
2211 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2215 qemu_chr_read(chr
, buf
, size
);
2219 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2221 FDCharDriver
*s
= chr
->opaque
;
2223 if (s
->fd_in
>= 0) {
2224 if (nographic
&& s
->fd_in
== 0) {
2226 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2227 fd_chr_read
, NULL
, chr
);
2232 static void fd_chr_close(struct CharDriverState
*chr
)
2234 FDCharDriver
*s
= chr
->opaque
;
2236 if (s
->fd_in
>= 0) {
2237 if (nographic
&& s
->fd_in
== 0) {
2239 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2246 /* open a character device to a unix fd */
2247 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2249 CharDriverState
*chr
;
2252 chr
= qemu_mallocz(sizeof(CharDriverState
));
2255 s
= qemu_mallocz(sizeof(FDCharDriver
));
2263 chr
->chr_write
= fd_chr_write
;
2264 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2265 chr
->chr_close
= fd_chr_close
;
2267 qemu_chr_reset(chr
);
2272 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2276 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2279 return qemu_chr_open_fd(-1, fd_out
);
2282 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2285 char filename_in
[256], filename_out
[256];
2287 snprintf(filename_in
, 256, "%s.in", filename
);
2288 snprintf(filename_out
, 256, "%s.out", filename
);
2289 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2290 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2291 if (fd_in
< 0 || fd_out
< 0) {
2296 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2300 return qemu_chr_open_fd(fd_in
, fd_out
);
2304 /* for STDIO, we handle the case where several clients use it
2307 #define TERM_FIFO_MAX_SIZE 1
2309 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2310 static int term_fifo_size
;
2312 static int stdio_read_poll(void *opaque
)
2314 CharDriverState
*chr
= opaque
;
2316 /* try to flush the queue if needed */
2317 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2318 qemu_chr_read(chr
, term_fifo
, 1);
2321 /* see if we can absorb more chars */
2322 if (term_fifo_size
== 0)
2328 static void stdio_read(void *opaque
)
2332 CharDriverState
*chr
= opaque
;
2334 size
= read(0, buf
, 1);
2336 /* stdin has been closed. Remove it from the active list. */
2337 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2341 if (qemu_chr_can_read(chr
) > 0) {
2342 qemu_chr_read(chr
, buf
, 1);
2343 } else if (term_fifo_size
== 0) {
2344 term_fifo
[term_fifo_size
++] = buf
[0];
2349 /* init terminal so that we can grab keys */
2350 static struct termios oldtty
;
2351 static int old_fd0_flags
;
2352 static int term_atexit_done
;
2354 static void term_exit(void)
2356 tcsetattr (0, TCSANOW
, &oldtty
);
2357 fcntl(0, F_SETFL
, old_fd0_flags
);
2360 static void term_init(void)
2364 tcgetattr (0, &tty
);
2366 old_fd0_flags
= fcntl(0, F_GETFL
);
2368 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2369 |INLCR
|IGNCR
|ICRNL
|IXON
);
2370 tty
.c_oflag
|= OPOST
;
2371 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2372 /* if graphical mode, we allow Ctrl-C handling */
2374 tty
.c_lflag
&= ~ISIG
;
2375 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2378 tty
.c_cc
[VTIME
] = 0;
2380 tcsetattr (0, TCSANOW
, &tty
);
2382 if (!term_atexit_done
++)
2385 fcntl(0, F_SETFL
, O_NONBLOCK
);
2388 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2392 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2396 static CharDriverState
*qemu_chr_open_stdio(void)
2398 CharDriverState
*chr
;
2400 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2402 chr
= qemu_chr_open_fd(0, 1);
2403 chr
->chr_close
= qemu_chr_close_stdio
;
2404 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2412 /* Once Solaris has openpty(), this is going to be removed. */
2413 int openpty(int *amaster
, int *aslave
, char *name
,
2414 struct termios
*termp
, struct winsize
*winp
)
2417 int mfd
= -1, sfd
= -1;
2419 *amaster
= *aslave
= -1;
2421 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2425 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2428 if ((slave
= ptsname(mfd
)) == NULL
)
2431 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2434 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2435 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2443 ioctl(sfd
, TIOCSWINSZ
, winp
);
2454 void cfmakeraw (struct termios
*termios_p
)
2456 termios_p
->c_iflag
&=
2457 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2458 termios_p
->c_oflag
&= ~OPOST
;
2459 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2460 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2461 termios_p
->c_cflag
|= CS8
;
2463 termios_p
->c_cc
[VMIN
] = 0;
2464 termios_p
->c_cc
[VTIME
] = 0;
2468 #if defined(__linux__) || defined(__sun__)
2469 static CharDriverState
*qemu_chr_open_pty(void)
2472 int master_fd
, slave_fd
;
2474 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2478 /* Set raw attributes on the pty. */
2480 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2482 fprintf(stderr
, "char device redirected to %s\n", ptsname(master_fd
));
2483 return qemu_chr_open_fd(master_fd
, master_fd
);
2486 static void tty_serial_init(int fd
, int speed
,
2487 int parity
, int data_bits
, int stop_bits
)
2493 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2494 speed
, parity
, data_bits
, stop_bits
);
2496 tcgetattr (fd
, &tty
);
2499 if (speed
<= 50 * MARGIN
)
2501 else if (speed
<= 75 * MARGIN
)
2503 else if (speed
<= 300 * MARGIN
)
2505 else if (speed
<= 600 * MARGIN
)
2507 else if (speed
<= 1200 * MARGIN
)
2509 else if (speed
<= 2400 * MARGIN
)
2511 else if (speed
<= 4800 * MARGIN
)
2513 else if (speed
<= 9600 * MARGIN
)
2515 else if (speed
<= 19200 * MARGIN
)
2517 else if (speed
<= 38400 * MARGIN
)
2519 else if (speed
<= 57600 * MARGIN
)
2521 else if (speed
<= 115200 * MARGIN
)
2526 cfsetispeed(&tty
, spd
);
2527 cfsetospeed(&tty
, spd
);
2529 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2530 |INLCR
|IGNCR
|ICRNL
|IXON
);
2531 tty
.c_oflag
|= OPOST
;
2532 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2533 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2554 tty
.c_cflag
|= PARENB
;
2557 tty
.c_cflag
|= PARENB
| PARODD
;
2561 tty
.c_cflag
|= CSTOPB
;
2563 tcsetattr (fd
, TCSANOW
, &tty
);
2566 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2568 FDCharDriver
*s
= chr
->opaque
;
2571 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2573 QEMUSerialSetParams
*ssp
= arg
;
2574 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2575 ssp
->data_bits
, ssp
->stop_bits
);
2578 case CHR_IOCTL_SERIAL_SET_BREAK
:
2580 int enable
= *(int *)arg
;
2582 tcsendbreak(s
->fd_in
, 1);
2591 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2593 CharDriverState
*chr
;
2596 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2597 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2598 tty_serial_init(fd
, 115200, 'N', 8, 1);
2599 chr
= qemu_chr_open_fd(fd
, fd
);
2604 chr
->chr_ioctl
= tty_serial_ioctl
;
2605 qemu_chr_reset(chr
);
2608 #else /* ! __linux__ && ! __sun__ */
2609 static CharDriverState
*qemu_chr_open_pty(void)
2613 #endif /* __linux__ || __sun__ */
2615 #if defined(__linux__)
2619 } ParallelCharDriver
;
2621 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2623 if (s
->mode
!= mode
) {
2625 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2632 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2634 ParallelCharDriver
*drv
= chr
->opaque
;
2639 case CHR_IOCTL_PP_READ_DATA
:
2640 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2642 *(uint8_t *)arg
= b
;
2644 case CHR_IOCTL_PP_WRITE_DATA
:
2645 b
= *(uint8_t *)arg
;
2646 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2649 case CHR_IOCTL_PP_READ_CONTROL
:
2650 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2652 /* Linux gives only the lowest bits, and no way to know data
2653 direction! For better compatibility set the fixed upper
2655 *(uint8_t *)arg
= b
| 0xc0;
2657 case CHR_IOCTL_PP_WRITE_CONTROL
:
2658 b
= *(uint8_t *)arg
;
2659 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2662 case CHR_IOCTL_PP_READ_STATUS
:
2663 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2665 *(uint8_t *)arg
= b
;
2667 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2668 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2669 struct ParallelIOArg
*parg
= arg
;
2670 int n
= read(fd
, parg
->buffer
, parg
->count
);
2671 if (n
!= parg
->count
) {
2676 case CHR_IOCTL_PP_EPP_READ
:
2677 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2678 struct ParallelIOArg
*parg
= arg
;
2679 int n
= read(fd
, parg
->buffer
, parg
->count
);
2680 if (n
!= parg
->count
) {
2685 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2686 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2687 struct ParallelIOArg
*parg
= arg
;
2688 int n
= write(fd
, parg
->buffer
, parg
->count
);
2689 if (n
!= parg
->count
) {
2694 case CHR_IOCTL_PP_EPP_WRITE
:
2695 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2696 struct ParallelIOArg
*parg
= arg
;
2697 int n
= write(fd
, parg
->buffer
, parg
->count
);
2698 if (n
!= parg
->count
) {
2709 static void pp_close(CharDriverState
*chr
)
2711 ParallelCharDriver
*drv
= chr
->opaque
;
2714 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2715 ioctl(fd
, PPRELEASE
);
2720 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2722 CharDriverState
*chr
;
2723 ParallelCharDriver
*drv
;
2726 TFR(fd
= open(filename
, O_RDWR
));
2730 if (ioctl(fd
, PPCLAIM
) < 0) {
2735 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2741 drv
->mode
= IEEE1284_MODE_COMPAT
;
2743 chr
= qemu_mallocz(sizeof(CharDriverState
));
2749 chr
->chr_write
= null_chr_write
;
2750 chr
->chr_ioctl
= pp_ioctl
;
2751 chr
->chr_close
= pp_close
;
2754 qemu_chr_reset(chr
);
2758 #endif /* __linux__ */
2764 HANDLE hcom
, hrecv
, hsend
;
2765 OVERLAPPED orecv
, osend
;
2770 #define NSENDBUF 2048
2771 #define NRECVBUF 2048
2772 #define MAXCONNECT 1
2773 #define NTIMEOUT 5000
2775 static int win_chr_poll(void *opaque
);
2776 static int win_chr_pipe_poll(void *opaque
);
2778 static void win_chr_close(CharDriverState
*chr
)
2780 WinCharState
*s
= chr
->opaque
;
2783 CloseHandle(s
->hsend
);
2787 CloseHandle(s
->hrecv
);
2791 CloseHandle(s
->hcom
);
2795 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2797 qemu_del_polling_cb(win_chr_poll
, chr
);
2800 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2802 WinCharState
*s
= chr
->opaque
;
2804 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2809 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2811 fprintf(stderr
, "Failed CreateEvent\n");
2814 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2816 fprintf(stderr
, "Failed CreateEvent\n");
2820 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2821 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2822 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2823 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2828 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2829 fprintf(stderr
, "Failed SetupComm\n");
2833 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2834 size
= sizeof(COMMCONFIG
);
2835 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2836 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2837 CommConfigDialog(filename
, NULL
, &comcfg
);
2839 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2840 fprintf(stderr
, "Failed SetCommState\n");
2844 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2845 fprintf(stderr
, "Failed SetCommMask\n");
2849 cto
.ReadIntervalTimeout
= MAXDWORD
;
2850 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2851 fprintf(stderr
, "Failed SetCommTimeouts\n");
2855 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2856 fprintf(stderr
, "Failed ClearCommError\n");
2859 qemu_add_polling_cb(win_chr_poll
, chr
);
2867 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2869 WinCharState
*s
= chr
->opaque
;
2870 DWORD len
, ret
, size
, err
;
2873 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2874 s
->osend
.hEvent
= s
->hsend
;
2877 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2879 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2881 err
= GetLastError();
2882 if (err
== ERROR_IO_PENDING
) {
2883 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2901 static int win_chr_read_poll(CharDriverState
*chr
)
2903 WinCharState
*s
= chr
->opaque
;
2905 s
->max_size
= qemu_chr_can_read(chr
);
2909 static void win_chr_readfile(CharDriverState
*chr
)
2911 WinCharState
*s
= chr
->opaque
;
2916 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2917 s
->orecv
.hEvent
= s
->hrecv
;
2918 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2920 err
= GetLastError();
2921 if (err
== ERROR_IO_PENDING
) {
2922 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2927 qemu_chr_read(chr
, buf
, size
);
2931 static void win_chr_read(CharDriverState
*chr
)
2933 WinCharState
*s
= chr
->opaque
;
2935 if (s
->len
> s
->max_size
)
2936 s
->len
= s
->max_size
;
2940 win_chr_readfile(chr
);
2943 static int win_chr_poll(void *opaque
)
2945 CharDriverState
*chr
= opaque
;
2946 WinCharState
*s
= chr
->opaque
;
2950 ClearCommError(s
->hcom
, &comerr
, &status
);
2951 if (status
.cbInQue
> 0) {
2952 s
->len
= status
.cbInQue
;
2953 win_chr_read_poll(chr
);
2960 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2962 CharDriverState
*chr
;
2965 chr
= qemu_mallocz(sizeof(CharDriverState
));
2968 s
= qemu_mallocz(sizeof(WinCharState
));
2974 chr
->chr_write
= win_chr_write
;
2975 chr
->chr_close
= win_chr_close
;
2977 if (win_chr_init(chr
, filename
) < 0) {
2982 qemu_chr_reset(chr
);
2986 static int win_chr_pipe_poll(void *opaque
)
2988 CharDriverState
*chr
= opaque
;
2989 WinCharState
*s
= chr
->opaque
;
2992 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2995 win_chr_read_poll(chr
);
3002 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3004 WinCharState
*s
= chr
->opaque
;
3012 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3014 fprintf(stderr
, "Failed CreateEvent\n");
3017 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3019 fprintf(stderr
, "Failed CreateEvent\n");
3023 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3024 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3025 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3027 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3028 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3029 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3034 ZeroMemory(&ov
, sizeof(ov
));
3035 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3036 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3038 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3042 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3044 fprintf(stderr
, "Failed GetOverlappedResult\n");
3046 CloseHandle(ov
.hEvent
);
3053 CloseHandle(ov
.hEvent
);
3056 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3065 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3067 CharDriverState
*chr
;
3070 chr
= qemu_mallocz(sizeof(CharDriverState
));
3073 s
= qemu_mallocz(sizeof(WinCharState
));
3079 chr
->chr_write
= win_chr_write
;
3080 chr
->chr_close
= win_chr_close
;
3082 if (win_chr_pipe_init(chr
, filename
) < 0) {
3087 qemu_chr_reset(chr
);
3091 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3093 CharDriverState
*chr
;
3096 chr
= qemu_mallocz(sizeof(CharDriverState
));
3099 s
= qemu_mallocz(sizeof(WinCharState
));
3106 chr
->chr_write
= win_chr_write
;
3107 qemu_chr_reset(chr
);
3111 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3113 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3116 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3120 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3121 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3122 if (fd_out
== INVALID_HANDLE_VALUE
)
3125 return qemu_chr_open_win_file(fd_out
);
3127 #endif /* !_WIN32 */
3129 /***********************************************************/
3130 /* UDP Net console */
3134 struct sockaddr_in daddr
;
3141 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3143 NetCharDriver
*s
= chr
->opaque
;
3145 return sendto(s
->fd
, buf
, len
, 0,
3146 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3149 static int udp_chr_read_poll(void *opaque
)
3151 CharDriverState
*chr
= opaque
;
3152 NetCharDriver
*s
= chr
->opaque
;
3154 s
->max_size
= qemu_chr_can_read(chr
);
3156 /* If there were any stray characters in the queue process them
3159 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3160 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3162 s
->max_size
= qemu_chr_can_read(chr
);
3167 static void udp_chr_read(void *opaque
)
3169 CharDriverState
*chr
= opaque
;
3170 NetCharDriver
*s
= chr
->opaque
;
3172 if (s
->max_size
== 0)
3174 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3175 s
->bufptr
= s
->bufcnt
;
3180 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3181 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3183 s
->max_size
= qemu_chr_can_read(chr
);
3187 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3189 NetCharDriver
*s
= chr
->opaque
;
3192 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3193 udp_chr_read
, NULL
, chr
);
3198 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3200 int parse_host_src_port(struct sockaddr_in
*haddr
,
3201 struct sockaddr_in
*saddr
,
3204 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3206 CharDriverState
*chr
= NULL
;
3207 NetCharDriver
*s
= NULL
;
3209 struct sockaddr_in saddr
;
3211 chr
= qemu_mallocz(sizeof(CharDriverState
));
3214 s
= qemu_mallocz(sizeof(NetCharDriver
));
3218 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3220 perror("socket(PF_INET, SOCK_DGRAM)");
3224 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3225 printf("Could not parse: %s\n", def
);
3229 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3239 chr
->chr_write
= udp_chr_write
;
3240 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3253 /***********************************************************/
3254 /* TCP Net console */
3265 static void tcp_chr_accept(void *opaque
);
3267 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3269 TCPCharDriver
*s
= chr
->opaque
;
3271 return send_all(s
->fd
, buf
, len
);
3273 /* XXX: indicate an error ? */
3278 static int tcp_chr_read_poll(void *opaque
)
3280 CharDriverState
*chr
= opaque
;
3281 TCPCharDriver
*s
= chr
->opaque
;
3284 s
->max_size
= qemu_chr_can_read(chr
);
3289 #define IAC_BREAK 243
3290 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3292 uint8_t *buf
, int *size
)
3294 /* Handle any telnet client's basic IAC options to satisfy char by
3295 * char mode with no echo. All IAC options will be removed from
3296 * the buf and the do_telnetopt variable will be used to track the
3297 * state of the width of the IAC information.
3299 * IAC commands come in sets of 3 bytes with the exception of the
3300 * "IAC BREAK" command and the double IAC.
3306 for (i
= 0; i
< *size
; i
++) {
3307 if (s
->do_telnetopt
> 1) {
3308 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3309 /* Double IAC means send an IAC */
3313 s
->do_telnetopt
= 1;
3315 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3316 /* Handle IAC break commands by sending a serial break */
3317 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3322 if (s
->do_telnetopt
>= 4) {
3323 s
->do_telnetopt
= 1;
3326 if ((unsigned char)buf
[i
] == IAC
) {
3327 s
->do_telnetopt
= 2;
3338 static void tcp_chr_read(void *opaque
)
3340 CharDriverState
*chr
= opaque
;
3341 TCPCharDriver
*s
= chr
->opaque
;
3345 if (!s
->connected
|| s
->max_size
<= 0)
3348 if (len
> s
->max_size
)
3350 size
= recv(s
->fd
, buf
, len
, 0);
3352 /* connection closed */
3354 if (s
->listen_fd
>= 0) {
3355 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3357 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3360 } else if (size
> 0) {
3361 if (s
->do_telnetopt
)
3362 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3364 qemu_chr_read(chr
, buf
, size
);
3368 static void tcp_chr_connect(void *opaque
)
3370 CharDriverState
*chr
= opaque
;
3371 TCPCharDriver
*s
= chr
->opaque
;
3374 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3375 tcp_chr_read
, NULL
, chr
);
3376 qemu_chr_reset(chr
);
3379 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3380 static void tcp_chr_telnet_init(int fd
)
3383 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3384 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3385 send(fd
, (char *)buf
, 3, 0);
3386 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3387 send(fd
, (char *)buf
, 3, 0);
3388 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3389 send(fd
, (char *)buf
, 3, 0);
3390 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3391 send(fd
, (char *)buf
, 3, 0);
3394 static void socket_set_nodelay(int fd
)
3397 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3400 static void tcp_chr_accept(void *opaque
)
3402 CharDriverState
*chr
= opaque
;
3403 TCPCharDriver
*s
= chr
->opaque
;
3404 struct sockaddr_in saddr
;
3406 struct sockaddr_un uaddr
;
3408 struct sockaddr
*addr
;
3415 len
= sizeof(uaddr
);
3416 addr
= (struct sockaddr
*)&uaddr
;
3420 len
= sizeof(saddr
);
3421 addr
= (struct sockaddr
*)&saddr
;
3423 fd
= accept(s
->listen_fd
, addr
, &len
);
3424 if (fd
< 0 && errno
!= EINTR
) {
3426 } else if (fd
>= 0) {
3427 if (s
->do_telnetopt
)
3428 tcp_chr_telnet_init(fd
);
3432 socket_set_nonblock(fd
);
3434 socket_set_nodelay(fd
);
3436 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3437 tcp_chr_connect(chr
);
3440 static void tcp_chr_close(CharDriverState
*chr
)
3442 TCPCharDriver
*s
= chr
->opaque
;
3445 if (s
->listen_fd
>= 0)
3446 closesocket(s
->listen_fd
);
3450 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3454 CharDriverState
*chr
= NULL
;
3455 TCPCharDriver
*s
= NULL
;
3456 int fd
= -1, ret
, err
, val
;
3458 int is_waitconnect
= 1;
3461 struct sockaddr_in saddr
;
3463 struct sockaddr_un uaddr
;
3465 struct sockaddr
*addr
;
3470 addr
= (struct sockaddr
*)&uaddr
;
3471 addrlen
= sizeof(uaddr
);
3472 if (parse_unix_path(&uaddr
, host_str
) < 0)
3477 addr
= (struct sockaddr
*)&saddr
;
3478 addrlen
= sizeof(saddr
);
3479 if (parse_host_port(&saddr
, host_str
) < 0)
3484 while((ptr
= strchr(ptr
,','))) {
3486 if (!strncmp(ptr
,"server",6)) {
3488 } else if (!strncmp(ptr
,"nowait",6)) {
3490 } else if (!strncmp(ptr
,"nodelay",6)) {
3493 printf("Unknown option: %s\n", ptr
);
3500 chr
= qemu_mallocz(sizeof(CharDriverState
));
3503 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3509 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3512 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3517 if (!is_waitconnect
)
3518 socket_set_nonblock(fd
);
3523 s
->is_unix
= is_unix
;
3524 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3527 chr
->chr_write
= tcp_chr_write
;
3528 chr
->chr_close
= tcp_chr_close
;
3531 /* allow fast reuse */
3535 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3541 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3544 ret
= bind(fd
, addr
, addrlen
);
3548 ret
= listen(fd
, 0);
3553 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3555 s
->do_telnetopt
= 1;
3558 ret
= connect(fd
, addr
, addrlen
);
3560 err
= socket_error();
3561 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3562 } else if (err
== EINPROGRESS
) {
3565 } else if (err
== WSAEALREADY
) {
3577 socket_set_nodelay(fd
);
3579 tcp_chr_connect(chr
);
3581 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3584 if (is_listen
&& is_waitconnect
) {
3585 printf("QEMU waiting for connection on: %s\n", host_str
);
3586 tcp_chr_accept(chr
);
3587 socket_set_nonblock(s
->listen_fd
);
3599 CharDriverState
*qemu_chr_open(const char *filename
)
3603 if (!strcmp(filename
, "vc")) {
3604 return text_console_init(&display_state
, 0);
3605 } else if (strstart(filename
, "vc:", &p
)) {
3606 return text_console_init(&display_state
, p
);
3607 } else if (!strcmp(filename
, "null")) {
3608 return qemu_chr_open_null();
3610 if (strstart(filename
, "tcp:", &p
)) {
3611 return qemu_chr_open_tcp(p
, 0, 0);
3613 if (strstart(filename
, "telnet:", &p
)) {
3614 return qemu_chr_open_tcp(p
, 1, 0);
3616 if (strstart(filename
, "udp:", &p
)) {
3617 return qemu_chr_open_udp(p
);
3619 if (strstart(filename
, "mon:", &p
)) {
3620 CharDriverState
*drv
= qemu_chr_open(p
);
3622 drv
= qemu_chr_open_mux(drv
);
3623 monitor_init(drv
, !nographic
);
3626 printf("Unable to open driver: %s\n", p
);
3630 if (strstart(filename
, "unix:", &p
)) {
3631 return qemu_chr_open_tcp(p
, 0, 1);
3632 } else if (strstart(filename
, "file:", &p
)) {
3633 return qemu_chr_open_file_out(p
);
3634 } else if (strstart(filename
, "pipe:", &p
)) {
3635 return qemu_chr_open_pipe(p
);
3636 } else if (!strcmp(filename
, "pty")) {
3637 return qemu_chr_open_pty();
3638 } else if (!strcmp(filename
, "stdio")) {
3639 return qemu_chr_open_stdio();
3641 #if defined(__linux__)
3642 if (strstart(filename
, "/dev/parport", NULL
)) {
3643 return qemu_chr_open_pp(filename
);
3646 #if defined(__linux__) || defined(__sun__)
3647 if (strstart(filename
, "/dev/", NULL
)) {
3648 return qemu_chr_open_tty(filename
);
3652 if (strstart(filename
, "COM", NULL
)) {
3653 return qemu_chr_open_win(filename
);
3655 if (strstart(filename
, "pipe:", &p
)) {
3656 return qemu_chr_open_win_pipe(p
);
3658 if (strstart(filename
, "con:", NULL
)) {
3659 return qemu_chr_open_win_con(filename
);
3661 if (strstart(filename
, "file:", &p
)) {
3662 return qemu_chr_open_win_file_out(p
);
3665 #ifdef CONFIG_BRLAPI
3666 if (!strcmp(filename
, "braille")) {
3667 return chr_baum_init();
3675 void qemu_chr_close(CharDriverState
*chr
)
3678 chr
->chr_close(chr
);
3682 /***********************************************************/
3683 /* network device redirectors */
3685 __attribute__ (( unused
))
3686 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3690 for(i
=0;i
<size
;i
+=16) {
3694 fprintf(f
, "%08x ", i
);
3697 fprintf(f
, " %02x", buf
[i
+j
]);
3702 for(j
=0;j
<len
;j
++) {
3704 if (c
< ' ' || c
> '~')
3706 fprintf(f
, "%c", c
);
3712 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3719 offset
= strtol(p
, &last_char
, 0);
3720 if (0 == errno
&& '\0' == *last_char
&&
3721 offset
>= 0 && offset
<= 0xFFFFFF) {
3722 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3723 macaddr
[4] = (offset
& 0xFF00) >> 8;
3724 macaddr
[5] = offset
& 0xFF;
3727 for(i
= 0; i
< 6; i
++) {
3728 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3733 if (*p
!= ':' && *p
!= '-')
3744 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3749 p1
= strchr(p
, sep
);
3755 if (len
> buf_size
- 1)
3757 memcpy(buf
, p
, len
);
3764 int parse_host_src_port(struct sockaddr_in
*haddr
,
3765 struct sockaddr_in
*saddr
,
3766 const char *input_str
)
3768 char *str
= strdup(input_str
);
3769 char *host_str
= str
;
3774 * Chop off any extra arguments at the end of the string which
3775 * would start with a comma, then fill in the src port information
3776 * if it was provided else use the "any address" and "any port".
3778 if ((ptr
= strchr(str
,',')))
3781 if ((src_str
= strchr(input_str
,'@'))) {
3786 if (parse_host_port(haddr
, host_str
) < 0)
3789 if (!src_str
|| *src_str
== '\0')
3792 if (parse_host_port(saddr
, src_str
) < 0)
3803 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3811 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3813 saddr
->sin_family
= AF_INET
;
3814 if (buf
[0] == '\0') {
3815 saddr
->sin_addr
.s_addr
= 0;
3817 if (isdigit(buf
[0])) {
3818 if (!inet_aton(buf
, &saddr
->sin_addr
))
3821 if ((he
= gethostbyname(buf
)) == NULL
)
3823 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3826 port
= strtol(p
, (char **)&r
, 0);
3829 saddr
->sin_port
= htons(port
);
3834 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3839 len
= MIN(108, strlen(str
));
3840 p
= strchr(str
, ',');
3842 len
= MIN(len
, p
- str
);
3844 memset(uaddr
, 0, sizeof(*uaddr
));
3846 uaddr
->sun_family
= AF_UNIX
;
3847 memcpy(uaddr
->sun_path
, str
, len
);
3853 /* find or alloc a new VLAN */
3854 VLANState
*qemu_find_vlan(int id
)
3856 VLANState
**pvlan
, *vlan
;
3857 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3861 vlan
= qemu_mallocz(sizeof(VLANState
));
3866 pvlan
= &first_vlan
;
3867 while (*pvlan
!= NULL
)
3868 pvlan
= &(*pvlan
)->next
;
3873 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3874 IOReadHandler
*fd_read
,
3875 IOCanRWHandler
*fd_can_read
,
3878 VLANClientState
*vc
, **pvc
;
3879 vc
= qemu_mallocz(sizeof(VLANClientState
));
3882 vc
->fd_read
= fd_read
;
3883 vc
->fd_can_read
= fd_can_read
;
3884 vc
->opaque
= opaque
;
3888 pvc
= &vlan
->first_client
;
3889 while (*pvc
!= NULL
)
3890 pvc
= &(*pvc
)->next
;
3895 int qemu_can_send_packet(VLANClientState
*vc1
)
3897 VLANState
*vlan
= vc1
->vlan
;
3898 VLANClientState
*vc
;
3900 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3902 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
3909 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3911 VLANState
*vlan
= vc1
->vlan
;
3912 VLANClientState
*vc
;
3916 printf("vlan %d send:\n", vlan
->id
);
3917 hex_dump(stdout
, buf
, size
);
3919 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3921 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
3922 vc
->fd_read(vc
->opaque
, buf
, size
);
3931 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
3938 for (i
= 0; i
< iovcnt
; i
++) {
3941 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
3942 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
3946 vc
->fd_read(vc
->opaque
, buffer
, offset
);
3951 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
3954 VLANState
*vlan
= vc1
->vlan
;
3955 VLANClientState
*vc
;
3956 ssize_t max_len
= 0;
3958 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3965 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
3966 else if (vc
->fd_read
)
3967 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
3969 max_len
= MAX(max_len
, len
);
3975 #if defined(CONFIG_SLIRP)
3977 /* slirp network adapter */
3979 static int slirp_inited
;
3980 static VLANClientState
*slirp_vc
;
3982 int slirp_can_output(void)
3984 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3987 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3990 printf("slirp output:\n");
3991 hex_dump(stdout
, pkt
, pkt_len
);
3995 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3998 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4001 printf("slirp input:\n");
4002 hex_dump(stdout
, buf
, size
);
4004 slirp_input(buf
, size
);
4007 static int net_slirp_init(VLANState
*vlan
)
4009 if (!slirp_inited
) {
4013 slirp_vc
= qemu_new_vlan_client(vlan
,
4014 slirp_receive
, NULL
, NULL
);
4015 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4019 static void net_slirp_redir(const char *redir_str
)
4024 struct in_addr guest_addr
;
4025 int host_port
, guest_port
;
4027 if (!slirp_inited
) {
4033 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4035 if (!strcmp(buf
, "tcp")) {
4037 } else if (!strcmp(buf
, "udp")) {
4043 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4045 host_port
= strtol(buf
, &r
, 0);
4049 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4051 if (buf
[0] == '\0') {
4052 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4054 if (!inet_aton(buf
, &guest_addr
))
4057 guest_port
= strtol(p
, &r
, 0);
4061 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4062 fprintf(stderr
, "qemu: could not set up redirection\n");
4067 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4075 static void erase_dir(char *dir_name
)
4079 char filename
[1024];
4081 /* erase all the files in the directory */
4082 if ((d
= opendir(dir_name
)) != 0) {
4087 if (strcmp(de
->d_name
, ".") != 0 &&
4088 strcmp(de
->d_name
, "..") != 0) {
4089 snprintf(filename
, sizeof(filename
), "%s/%s",
4090 smb_dir
, de
->d_name
);
4091 if (unlink(filename
) != 0) /* is it a directory? */
4092 erase_dir(filename
);
4100 /* automatic user mode samba server configuration */
4101 static void smb_exit(void)
4106 /* automatic user mode samba server configuration */
4107 static void net_slirp_smb(const char *exported_dir
)
4109 char smb_conf
[1024];
4110 char smb_cmdline
[1024];
4113 if (!slirp_inited
) {
4118 /* XXX: better tmp dir construction */
4119 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4120 if (mkdir(smb_dir
, 0700) < 0) {
4121 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4124 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4126 f
= fopen(smb_conf
, "w");
4128 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4135 "socket address=127.0.0.1\n"
4136 "pid directory=%s\n"
4137 "lock directory=%s\n"
4138 "log file=%s/log.smbd\n"
4139 "smb passwd file=%s/smbpasswd\n"
4140 "security = share\n"
4155 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4156 SMBD_COMMAND
, smb_conf
);
4158 slirp_add_exec(0, smb_cmdline
, 4, 139);
4161 #endif /* !defined(_WIN32) */
4162 void do_info_slirp(void)
4167 #endif /* CONFIG_SLIRP */
4169 #if !defined(_WIN32)
4171 typedef struct TAPState
{
4172 VLANClientState
*vc
;
4174 char down_script
[1024];
4179 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4181 TAPState
*s
= opaque
;
4184 ret
= write(s
->fd
, buf
, size
);
4185 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4192 static ssize_t
tap_readv(void *opaque
, const struct iovec
*iov
,
4195 TAPState
*s
= opaque
;
4199 len
= writev(s
->fd
, iov
, iovcnt
);
4200 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4205 static int tap_can_send(void *opaque
)
4207 TAPState
*s
= opaque
;
4208 VLANClientState
*vc
;
4209 int can_receive
= 0;
4211 /* Check to see if any of our clients can receive a packet */
4212 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4213 /* Skip ourselves */
4217 if (!vc
->fd_can_read
) {
4218 /* no fd_can_read handler, they always can receive */
4221 can_receive
= vc
->fd_can_read(vc
->opaque
);
4223 /* Once someone can receive, we try to send a packet */
4231 static void tap_send(void *opaque
)
4233 TAPState
*s
= opaque
;
4235 /* First try to send any buffered packet */
4239 /* If noone can receive the packet, buffer it */
4240 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4245 /* Read packets until we hit EAGAIN */
4250 sbuf
.maxlen
= sizeof(s
->buf
);
4252 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4254 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4257 if (s
->size
== -1 && errno
== EINTR
)
4263 /* If noone can receive the packet, buffer it */
4264 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4268 } while (s
->size
> 0);
4273 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4277 s
= qemu_mallocz(sizeof(TAPState
));
4281 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4282 s
->vc
->fd_readv
= tap_readv
;
4283 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4284 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4288 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4289 static int tap_open(char *ifname
, int ifname_size
)
4295 TFR(fd
= open("/dev/tap", O_RDWR
));
4297 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4302 dev
= devname(s
.st_rdev
, S_IFCHR
);
4303 pstrcpy(ifname
, ifname_size
, dev
);
4305 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4308 #elif defined(__sun__)
4309 #define TUNNEWPPA (('T'<<16) | 0x0001)
4311 * Allocate TAP device, returns opened fd.
4312 * Stores dev name in the first arg(must be large enough).
4314 int tap_alloc(char *dev
)
4316 int tap_fd
, if_fd
, ppa
= -1;
4317 static int ip_fd
= 0;
4320 static int arp_fd
= 0;
4321 int ip_muxid
, arp_muxid
;
4322 struct strioctl strioc_if
, strioc_ppa
;
4323 int link_type
= I_PLINK
;;
4325 char actual_name
[32] = "";
4327 memset(&ifr
, 0x0, sizeof(ifr
));
4331 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4335 /* Check if IP device was opened */
4339 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4341 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4345 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4347 syslog(LOG_ERR
, "Can't open /dev/tap");
4351 /* Assign a new PPA and get its unit number. */
4352 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4353 strioc_ppa
.ic_timout
= 0;
4354 strioc_ppa
.ic_len
= sizeof(ppa
);
4355 strioc_ppa
.ic_dp
= (char *)&ppa
;
4356 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4357 syslog (LOG_ERR
, "Can't assign new interface");
4359 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4361 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4364 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4365 syslog(LOG_ERR
, "Can't push IP module");
4369 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4370 syslog(LOG_ERR
, "Can't get flags\n");
4372 snprintf (actual_name
, 32, "tap%d", ppa
);
4373 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4376 /* Assign ppa according to the unit number returned by tun device */
4378 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4379 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4380 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4381 syslog (LOG_ERR
, "Can't get flags\n");
4382 /* Push arp module to if_fd */
4383 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4384 syslog (LOG_ERR
, "Can't push ARP module (2)");
4386 /* Push arp module to ip_fd */
4387 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4388 syslog (LOG_ERR
, "I_POP failed\n");
4389 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4390 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4392 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4394 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4396 /* Set ifname to arp */
4397 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4398 strioc_if
.ic_timout
= 0;
4399 strioc_if
.ic_len
= sizeof(ifr
);
4400 strioc_if
.ic_dp
= (char *)&ifr
;
4401 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4402 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4405 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4406 syslog(LOG_ERR
, "Can't link TAP device to IP");
4410 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4411 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4415 memset(&ifr
, 0x0, sizeof(ifr
));
4416 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4417 ifr
.lifr_ip_muxid
= ip_muxid
;
4418 ifr
.lifr_arp_muxid
= arp_muxid
;
4420 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4422 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4423 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4424 syslog (LOG_ERR
, "Can't set multiplexor id");
4427 sprintf(dev
, "tap%d", ppa
);
4431 static int tap_open(char *ifname
, int ifname_size
)
4435 if( (fd
= tap_alloc(dev
)) < 0 ){
4436 fprintf(stderr
, "Cannot allocate TAP device\n");
4439 pstrcpy(ifname
, ifname_size
, dev
);
4440 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4444 static int tap_open(char *ifname
, int ifname_size
)
4449 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4451 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4454 memset(&ifr
, 0, sizeof(ifr
));
4455 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4456 if (ifname
[0] != '\0')
4457 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4459 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4460 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4462 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4466 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4467 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4472 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4478 /* try to launch network script */
4482 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4483 for (i
= 0; i
< open_max
; i
++)
4484 if (i
!= STDIN_FILENO
&&
4485 i
!= STDOUT_FILENO
&&
4486 i
!= STDERR_FILENO
&&
4491 *parg
++ = (char *)setup_script
;
4492 *parg
++ = (char *)ifname
;
4494 execv(setup_script
, args
);
4497 while (waitpid(pid
, &status
, 0) != pid
);
4498 if (!WIFEXITED(status
) ||
4499 WEXITSTATUS(status
) != 0) {
4500 fprintf(stderr
, "%s: could not launch network script\n",
4508 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4509 const char *setup_script
, const char *down_script
)
4515 if (ifname1
!= NULL
)
4516 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4519 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4523 if (!setup_script
|| !strcmp(setup_script
, "no"))
4525 if (setup_script
[0] != '\0') {
4526 if (launch_script(setup_script
, ifname
, fd
))
4529 s
= net_tap_fd_init(vlan
, fd
);
4532 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4533 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4534 if (down_script
&& strcmp(down_script
, "no"))
4535 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4539 #endif /* !_WIN32 */
4541 /* network connection */
4542 typedef struct NetSocketState
{
4543 VLANClientState
*vc
;
4545 int state
; /* 0 = getting length, 1 = getting data */
4549 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4552 typedef struct NetSocketListenState
{
4555 } NetSocketListenState
;
4557 /* XXX: we consider we can send the whole packet without blocking */
4558 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4560 NetSocketState
*s
= opaque
;
4564 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4565 send_all(s
->fd
, buf
, size
);
4568 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4570 NetSocketState
*s
= opaque
;
4571 sendto(s
->fd
, buf
, size
, 0,
4572 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4575 static void net_socket_send(void *opaque
)
4577 NetSocketState
*s
= opaque
;
4582 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4584 err
= socket_error();
4585 if (err
!= EWOULDBLOCK
)
4587 } else if (size
== 0) {
4588 /* end of connection */
4590 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4596 /* reassemble a packet from the network */
4602 memcpy(s
->buf
+ s
->index
, buf
, l
);
4606 if (s
->index
== 4) {
4608 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4614 l
= s
->packet_len
- s
->index
;
4617 memcpy(s
->buf
+ s
->index
, buf
, l
);
4621 if (s
->index
>= s
->packet_len
) {
4622 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4631 static void net_socket_send_dgram(void *opaque
)
4633 NetSocketState
*s
= opaque
;
4636 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4640 /* end of connection */
4641 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4644 qemu_send_packet(s
->vc
, s
->buf
, size
);
4647 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4652 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4653 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4654 inet_ntoa(mcastaddr
->sin_addr
),
4655 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4659 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4661 perror("socket(PF_INET, SOCK_DGRAM)");
4666 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4667 (const char *)&val
, sizeof(val
));
4669 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4673 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4679 /* Add host to multicast group */
4680 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4681 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4683 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4684 (const char *)&imr
, sizeof(struct ip_mreq
));
4686 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4690 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4692 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4693 (const char *)&val
, sizeof(val
));
4695 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4699 socket_set_nonblock(fd
);
4707 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4710 struct sockaddr_in saddr
;
4712 socklen_t saddr_len
;
4715 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4716 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4717 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4721 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4723 if (saddr
.sin_addr
.s_addr
==0) {
4724 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4728 /* clone dgram socket */
4729 newfd
= net_socket_mcast_create(&saddr
);
4731 /* error already reported by net_socket_mcast_create() */
4735 /* clone newfd to fd, close newfd */
4740 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4741 fd
, strerror(errno
));
4746 s
= qemu_mallocz(sizeof(NetSocketState
));
4751 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4752 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4754 /* mcast: save bound address as dst */
4755 if (is_connected
) s
->dgram_dst
=saddr
;
4757 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4758 "socket: fd=%d (%s mcast=%s:%d)",
4759 fd
, is_connected
? "cloned" : "",
4760 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4764 static void net_socket_connect(void *opaque
)
4766 NetSocketState
*s
= opaque
;
4767 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4770 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4774 s
= qemu_mallocz(sizeof(NetSocketState
));
4778 s
->vc
= qemu_new_vlan_client(vlan
,
4779 net_socket_receive
, NULL
, s
);
4780 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4781 "socket: fd=%d", fd
);
4783 net_socket_connect(s
);
4785 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4790 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4793 int so_type
=-1, optlen
=sizeof(so_type
);
4795 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4796 (socklen_t
*)&optlen
)< 0) {
4797 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4802 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4804 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4806 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4807 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4808 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4813 static void net_socket_accept(void *opaque
)
4815 NetSocketListenState
*s
= opaque
;
4817 struct sockaddr_in saddr
;
4822 len
= sizeof(saddr
);
4823 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4824 if (fd
< 0 && errno
!= EINTR
) {
4826 } else if (fd
>= 0) {
4830 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4834 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4835 "socket: connection from %s:%d",
4836 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4840 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4842 NetSocketListenState
*s
;
4844 struct sockaddr_in saddr
;
4846 if (parse_host_port(&saddr
, host_str
) < 0)
4849 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4853 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4858 socket_set_nonblock(fd
);
4860 /* allow fast reuse */
4862 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4864 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4869 ret
= listen(fd
, 0);
4876 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4880 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4883 int fd
, connected
, ret
, err
;
4884 struct sockaddr_in saddr
;
4886 if (parse_host_port(&saddr
, host_str
) < 0)
4889 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4894 socket_set_nonblock(fd
);
4898 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4900 err
= socket_error();
4901 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4902 } else if (err
== EINPROGRESS
) {
4905 } else if (err
== WSAEALREADY
) {
4918 s
= net_socket_fd_init(vlan
, fd
, connected
);
4921 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4922 "socket: connect to %s:%d",
4923 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4927 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4931 struct sockaddr_in saddr
;
4933 if (parse_host_port(&saddr
, host_str
) < 0)
4937 fd
= net_socket_mcast_create(&saddr
);
4941 s
= net_socket_fd_init(vlan
, fd
, 0);
4945 s
->dgram_dst
= saddr
;
4947 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4948 "socket: mcast=%s:%d",
4949 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4954 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
4959 while (*p
!= '\0' && *p
!= '=') {
4960 if (q
&& (q
- buf
) < buf_size
- 1)
4970 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
4975 while (*p
!= '\0') {
4977 if (*(p
+ 1) != ',')
4981 if (q
&& (q
- buf
) < buf_size
- 1)
4991 int get_param_value(char *buf
, int buf_size
,
4992 const char *tag
, const char *str
)
4999 p
= get_opt_name(option
, sizeof(option
), p
);
5003 if (!strcmp(tag
, option
)) {
5004 (void)get_opt_value(buf
, buf_size
, p
);
5007 p
= get_opt_value(NULL
, 0, p
);
5016 int check_params(char *buf
, int buf_size
,
5017 char **params
, const char *str
)
5024 p
= get_opt_name(buf
, buf_size
, p
);
5028 for(i
= 0; params
[i
] != NULL
; i
++)
5029 if (!strcmp(params
[i
], buf
))
5031 if (params
[i
] == NULL
)
5033 p
= get_opt_value(NULL
, 0, p
);
5041 static int nic_get_free_idx(void)
5045 for (index
= 0; index
< MAX_NICS
; index
++)
5046 if (!nd_table
[index
].used
)
5051 int net_client_init(const char *str
)
5062 while (*p
!= '\0' && *p
!= ',') {
5063 if ((q
- device
) < sizeof(device
) - 1)
5071 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5072 vlan_id
= strtol(buf
, NULL
, 0);
5074 vlan
= qemu_find_vlan(vlan_id
);
5076 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5079 if (!strcmp(device
, "nic")) {
5082 int idx
= nic_get_free_idx();
5084 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5085 fprintf(stderr
, "Too Many NICs\n");
5088 nd
= &nd_table
[idx
];
5089 macaddr
= nd
->macaddr
;
5095 macaddr
[5] = 0x56 + idx
;
5097 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5098 if (parse_macaddr(macaddr
, buf
) < 0) {
5099 fprintf(stderr
, "invalid syntax for ethernet address\n");
5103 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5104 nd
->model
= strdup(buf
);
5109 vlan
->nb_guest_devs
++;
5112 if (!strcmp(device
, "none")) {
5113 /* does nothing. It is needed to signal that no network cards
5118 if (!strcmp(device
, "user")) {
5119 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5120 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5122 vlan
->nb_host_devs
++;
5123 ret
= net_slirp_init(vlan
);
5127 if (!strcmp(device
, "tap")) {
5129 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5130 fprintf(stderr
, "tap: no interface name\n");
5133 vlan
->nb_host_devs
++;
5134 ret
= tap_win32_init(vlan
, ifname
);
5137 if (!strcmp(device
, "tap")) {
5139 char setup_script
[1024], down_script
[1024];
5141 vlan
->nb_host_devs
++;
5142 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5143 fd
= strtol(buf
, NULL
, 0);
5144 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5146 if (net_tap_fd_init(vlan
, fd
))
5149 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5152 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5153 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5155 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5156 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5158 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5162 if (!strcmp(device
, "socket")) {
5163 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5165 fd
= strtol(buf
, NULL
, 0);
5167 if (net_socket_fd_init(vlan
, fd
, 1))
5169 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5170 ret
= net_socket_listen_init(vlan
, buf
);
5171 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5172 ret
= net_socket_connect_init(vlan
, buf
);
5173 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5174 ret
= net_socket_mcast_init(vlan
, buf
);
5176 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5179 vlan
->nb_host_devs
++;
5182 fprintf(stderr
, "Unknown network device: %s\n", device
);
5186 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5192 void net_client_uninit(NICInfo
*nd
)
5194 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5197 free((void *)nd
->model
);
5200 void do_info_network(void)
5203 VLANClientState
*vc
;
5205 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5206 term_printf("VLAN %d devices:\n", vlan
->id
);
5207 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5208 term_printf(" %s\n", vc
->info_str
);
5212 #define HD_ALIAS "index=%d,media=disk"
5214 #define CDROM_ALIAS "index=1,media=cdrom"
5216 #define CDROM_ALIAS "index=2,media=cdrom"
5218 #define FD_ALIAS "index=%d,if=floppy"
5219 #define PFLASH_ALIAS "if=pflash"
5220 #define MTD_ALIAS "if=mtd"
5221 #define SD_ALIAS "index=0,if=sd"
5223 static int drive_opt_get_free_idx(void)
5227 for (index
= 0; index
< MAX_DRIVES
; index
++)
5228 if (!drives_opt
[index
].used
) {
5229 drives_opt
[index
].used
= 1;
5236 static int drive_get_free_idx(void)
5240 for (index
= 0; index
< MAX_DRIVES
; index
++)
5241 if (!drives_table
[index
].used
) {
5242 drives_table
[index
].used
= 1;
5249 int drive_add(const char *file
, const char *fmt
, ...)
5252 int index
= drive_opt_get_free_idx();
5254 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5255 fprintf(stderr
, "qemu: too many drives\n");
5259 drives_opt
[index
].file
= file
;
5261 vsnprintf(drives_opt
[index
].opt
,
5262 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5269 void drive_remove(int index
)
5271 drives_opt
[index
].used
= 0;
5275 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5279 /* seek interface, bus and unit */
5281 for (index
= 0; index
< MAX_DRIVES
; index
++)
5282 if (drives_table
[index
].type
== type
&&
5283 drives_table
[index
].bus
== bus
&&
5284 drives_table
[index
].unit
== unit
&&
5285 drives_table
[index
].used
)
5291 int drive_get_max_bus(BlockInterfaceType type
)
5297 for (index
= 0; index
< nb_drives
; index
++) {
5298 if(drives_table
[index
].type
== type
&&
5299 drives_table
[index
].bus
> max_bus
)
5300 max_bus
= drives_table
[index
].bus
;
5305 static void bdrv_format_print(void *opaque
, const char *name
)
5307 fprintf(stderr
, " %s", name
);
5310 void drive_uninit(BlockDriverState
*bdrv
)
5314 for (i
= 0; i
< MAX_DRIVES
; i
++)
5315 if (drives_table
[i
].bdrv
== bdrv
) {
5316 drives_table
[i
].bdrv
= NULL
;
5317 drives_table
[i
].used
= 0;
5318 drive_remove(drives_table
[i
].drive_opt_idx
);
5324 int drive_init(struct drive_opt
*arg
, int snapshot
,
5325 QEMUMachine
*machine
)
5330 const char *mediastr
= "";
5331 BlockInterfaceType type
;
5332 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5333 int bus_id
, unit_id
;
5334 int cyls
, heads
, secs
, translation
;
5335 BlockDriverState
*bdrv
;
5336 BlockDriver
*drv
= NULL
;
5341 int drives_table_idx
;
5342 char *str
= arg
->opt
;
5343 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5344 "secs", "trans", "media", "snapshot", "file",
5345 "cache", "format", "boot", NULL
};
5347 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5348 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5354 cyls
= heads
= secs
= 0;
5357 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5361 if (!strcmp(machine
->name
, "realview") ||
5362 !strcmp(machine
->name
, "SS-5") ||
5363 !strcmp(machine
->name
, "SS-10") ||
5364 !strcmp(machine
->name
, "SS-600MP") ||
5365 !strcmp(machine
->name
, "versatilepb") ||
5366 !strcmp(machine
->name
, "versatileab")) {
5368 max_devs
= MAX_SCSI_DEVS
;
5369 strcpy(devname
, "scsi");
5372 max_devs
= MAX_IDE_DEVS
;
5373 strcpy(devname
, "ide");
5377 /* extract parameters */
5379 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5380 bus_id
= strtol(buf
, NULL
, 0);
5382 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5387 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5388 unit_id
= strtol(buf
, NULL
, 0);
5390 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5395 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5396 pstrcpy(devname
, sizeof(devname
), buf
);
5397 if (!strcmp(buf
, "ide")) {
5399 max_devs
= MAX_IDE_DEVS
;
5400 } else if (!strcmp(buf
, "scsi")) {
5402 max_devs
= MAX_SCSI_DEVS
;
5403 } else if (!strcmp(buf
, "floppy")) {
5406 } else if (!strcmp(buf
, "pflash")) {
5409 } else if (!strcmp(buf
, "mtd")) {
5412 } else if (!strcmp(buf
, "sd")) {
5415 } else if (!strcmp(buf
, "virtio")) {
5419 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5424 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5425 index
= strtol(buf
, NULL
, 0);
5427 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5432 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5433 cyls
= strtol(buf
, NULL
, 0);
5436 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5437 heads
= strtol(buf
, NULL
, 0);
5440 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5441 secs
= strtol(buf
, NULL
, 0);
5444 if (cyls
|| heads
|| secs
) {
5445 if (cyls
< 1 || cyls
> 16383) {
5446 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5449 if (heads
< 1 || heads
> 16) {
5450 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5453 if (secs
< 1 || secs
> 63) {
5454 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5459 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5462 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5466 if (!strcmp(buf
, "none"))
5467 translation
= BIOS_ATA_TRANSLATION_NONE
;
5468 else if (!strcmp(buf
, "lba"))
5469 translation
= BIOS_ATA_TRANSLATION_LBA
;
5470 else if (!strcmp(buf
, "auto"))
5471 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5473 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5478 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5479 if (!strcmp(buf
, "disk")) {
5481 } else if (!strcmp(buf
, "cdrom")) {
5482 if (cyls
|| secs
|| heads
) {
5484 "qemu: '%s' invalid physical CHS format\n", str
);
5487 media
= MEDIA_CDROM
;
5489 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5494 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5495 if (!strcmp(buf
, "on"))
5497 else if (!strcmp(buf
, "off"))
5500 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5505 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5506 if (!strcmp(buf
, "off"))
5508 else if (!strcmp(buf
, "on"))
5511 fprintf(stderr
, "qemu: invalid cache option\n");
5516 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5517 if (strcmp(buf
, "?") == 0) {
5518 fprintf(stderr
, "qemu: Supported formats:");
5519 bdrv_iterate_format(bdrv_format_print
, NULL
);
5520 fprintf(stderr
, "\n");
5523 drv
= bdrv_find_format(buf
);
5525 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5530 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5531 if (!strcmp(buf
, "on")) {
5532 if (extboot_drive
!= -1) {
5533 fprintf(stderr
, "qemu: two bootable drives specified\n");
5536 extboot_drive
= nb_drives
;
5537 } else if (strcmp(buf
, "off")) {
5538 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5543 if (arg
->file
== NULL
)
5544 get_param_value(file
, sizeof(file
), "file", str
);
5546 pstrcpy(file
, sizeof(file
), arg
->file
);
5548 /* compute bus and unit according index */
5551 if (bus_id
!= 0 || unit_id
!= -1) {
5553 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5561 unit_id
= index
% max_devs
;
5562 bus_id
= index
/ max_devs
;
5566 /* if user doesn't specify a unit_id,
5567 * try to find the first free
5570 if (unit_id
== -1) {
5572 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5574 if (max_devs
&& unit_id
>= max_devs
) {
5575 unit_id
-= max_devs
;
5583 if (max_devs
&& unit_id
>= max_devs
) {
5584 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5585 str
, unit_id
, max_devs
- 1);
5590 * ignore multiple definitions
5593 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5598 if (type
== IF_IDE
|| type
== IF_SCSI
)
5599 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5601 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5602 devname
, bus_id
, mediastr
, unit_id
);
5604 snprintf(buf
, sizeof(buf
), "%s%s%i",
5605 devname
, mediastr
, unit_id
);
5606 bdrv
= bdrv_new(buf
);
5607 drives_table_idx
= drive_get_free_idx();
5608 drives_table
[drives_table_idx
].bdrv
= bdrv
;
5609 drives_table
[drives_table_idx
].type
= type
;
5610 drives_table
[drives_table_idx
].bus
= bus_id
;
5611 drives_table
[drives_table_idx
].unit
= unit_id
;
5612 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
5621 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5622 bdrv_set_translation_hint(bdrv
, translation
);
5626 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5631 /* FIXME: This isn't really a floppy, but it's a reasonable
5634 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5645 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5647 bdrv_flags
|= BDRV_O_DIRECT
;
5648 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5649 fprintf(stderr
, "qemu: could not open disk image %s\n",
5653 return drives_table_idx
;
5656 /***********************************************************/
5659 static USBPort
*used_usb_ports
;
5660 static USBPort
*free_usb_ports
;
5662 /* ??? Maybe change this to register a hub to keep track of the topology. */
5663 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5664 usb_attachfn attach
)
5666 port
->opaque
= opaque
;
5667 port
->index
= index
;
5668 port
->attach
= attach
;
5669 port
->next
= free_usb_ports
;
5670 free_usb_ports
= port
;
5673 static int usb_device_add(const char *devname
)
5679 if (!free_usb_ports
)
5682 if (strstart(devname
, "host:", &p
)) {
5683 dev
= usb_host_device_open(p
);
5684 } else if (!strcmp(devname
, "mouse")) {
5685 dev
= usb_mouse_init();
5686 } else if (!strcmp(devname
, "tablet")) {
5687 dev
= usb_tablet_init();
5688 } else if (!strcmp(devname
, "keyboard")) {
5689 dev
= usb_keyboard_init();
5690 } else if (strstart(devname
, "disk:", &p
)) {
5691 dev
= usb_msd_init(p
);
5692 } else if (!strcmp(devname
, "wacom-tablet")) {
5693 dev
= usb_wacom_init();
5694 } else if (strstart(devname
, "serial:", &p
)) {
5695 dev
= usb_serial_init(p
);
5696 #ifdef CONFIG_BRLAPI
5697 } else if (!strcmp(devname
, "braille")) {
5698 dev
= usb_baum_init();
5706 /* Find a USB port to add the device to. */
5707 port
= free_usb_ports
;
5711 /* Create a new hub and chain it on. */
5712 free_usb_ports
= NULL
;
5713 port
->next
= used_usb_ports
;
5714 used_usb_ports
= port
;
5716 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5717 usb_attach(port
, hub
);
5718 port
= free_usb_ports
;
5721 free_usb_ports
= port
->next
;
5722 port
->next
= used_usb_ports
;
5723 used_usb_ports
= port
;
5724 usb_attach(port
, dev
);
5728 static int usb_device_del(const char *devname
)
5736 if (!used_usb_ports
)
5739 p
= strchr(devname
, '.');
5742 bus_num
= strtoul(devname
, NULL
, 0);
5743 addr
= strtoul(p
+ 1, NULL
, 0);
5747 lastp
= &used_usb_ports
;
5748 port
= used_usb_ports
;
5749 while (port
&& port
->dev
->addr
!= addr
) {
5750 lastp
= &port
->next
;
5758 *lastp
= port
->next
;
5759 usb_attach(port
, NULL
);
5760 dev
->handle_destroy(dev
);
5761 port
->next
= free_usb_ports
;
5762 free_usb_ports
= port
;
5766 void do_usb_add(const char *devname
)
5769 ret
= usb_device_add(devname
);
5771 term_printf("Could not add USB device '%s'\n", devname
);
5774 void do_usb_del(const char *devname
)
5777 ret
= usb_device_del(devname
);
5779 term_printf("Could not remove USB device '%s'\n", devname
);
5786 const char *speed_str
;
5789 term_printf("USB support not enabled\n");
5793 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5797 switch(dev
->speed
) {
5801 case USB_SPEED_FULL
:
5804 case USB_SPEED_HIGH
:
5811 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5812 0, dev
->addr
, speed_str
, dev
->devname
);
5816 /***********************************************************/
5817 /* PCMCIA/Cardbus */
5819 static struct pcmcia_socket_entry_s
{
5820 struct pcmcia_socket_s
*socket
;
5821 struct pcmcia_socket_entry_s
*next
;
5822 } *pcmcia_sockets
= 0;
5824 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5826 struct pcmcia_socket_entry_s
*entry
;
5828 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5829 entry
->socket
= socket
;
5830 entry
->next
= pcmcia_sockets
;
5831 pcmcia_sockets
= entry
;
5834 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5836 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5838 ptr
= &pcmcia_sockets
;
5839 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5840 if (entry
->socket
== socket
) {
5846 void pcmcia_info(void)
5848 struct pcmcia_socket_entry_s
*iter
;
5849 if (!pcmcia_sockets
)
5850 term_printf("No PCMCIA sockets\n");
5852 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5853 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5854 iter
->socket
->attached
? iter
->socket
->card_string
:
5858 /***********************************************************/
5861 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5865 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5869 static void dumb_refresh(DisplayState
*ds
)
5871 #if defined(CONFIG_SDL)
5876 static void dumb_display_init(DisplayState
*ds
)
5881 ds
->dpy_update
= dumb_update
;
5882 ds
->dpy_resize
= dumb_resize
;
5883 ds
->dpy_refresh
= dumb_refresh
;
5886 /***********************************************************/
5889 #define MAX_IO_HANDLERS 64
5891 typedef struct IOHandlerRecord
{
5893 IOCanRWHandler
*fd_read_poll
;
5895 IOHandler
*fd_write
;
5898 /* temporary data */
5900 struct IOHandlerRecord
*next
;
5903 static IOHandlerRecord
*first_io_handler
;
5905 /* XXX: fd_read_poll should be suppressed, but an API change is
5906 necessary in the character devices to suppress fd_can_read(). */
5907 int qemu_set_fd_handler2(int fd
,
5908 IOCanRWHandler
*fd_read_poll
,
5910 IOHandler
*fd_write
,
5913 IOHandlerRecord
**pioh
, *ioh
;
5915 if (!fd_read
&& !fd_write
) {
5916 pioh
= &first_io_handler
;
5921 if (ioh
->fd
== fd
) {
5928 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5932 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5935 ioh
->next
= first_io_handler
;
5936 first_io_handler
= ioh
;
5939 ioh
->fd_read_poll
= fd_read_poll
;
5940 ioh
->fd_read
= fd_read
;
5941 ioh
->fd_write
= fd_write
;
5942 ioh
->opaque
= opaque
;
5949 int qemu_set_fd_handler(int fd
,
5951 IOHandler
*fd_write
,
5954 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5957 /***********************************************************/
5958 /* Polling handling */
5960 typedef struct PollingEntry
{
5963 struct PollingEntry
*next
;
5966 static PollingEntry
*first_polling_entry
;
5968 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5970 PollingEntry
**ppe
, *pe
;
5971 pe
= qemu_mallocz(sizeof(PollingEntry
));
5975 pe
->opaque
= opaque
;
5976 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5981 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5983 PollingEntry
**ppe
, *pe
;
5984 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5986 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5995 /***********************************************************/
5996 /* Wait objects support */
5997 typedef struct WaitObjects
{
5999 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6000 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6001 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6004 static WaitObjects wait_objects
= {0};
6006 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6008 WaitObjects
*w
= &wait_objects
;
6010 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6012 w
->events
[w
->num
] = handle
;
6013 w
->func
[w
->num
] = func
;
6014 w
->opaque
[w
->num
] = opaque
;
6019 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6022 WaitObjects
*w
= &wait_objects
;
6025 for (i
= 0; i
< w
->num
; i
++) {
6026 if (w
->events
[i
] == handle
)
6029 w
->events
[i
] = w
->events
[i
+ 1];
6030 w
->func
[i
] = w
->func
[i
+ 1];
6031 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6039 #define SELF_ANNOUNCE_ROUNDS 5
6040 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6041 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6042 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6044 static int announce_self_create(uint8_t *buf
,
6047 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6048 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6050 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6052 memset(buf
, 0xff, 6); /* h_dst */
6053 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6054 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6055 memcpy(buf
+ 14, &magic
, 4); /* magic */
6057 return 18; /* len */
6060 static void qemu_announce_self(void)
6064 VLANClientState
*vc
;
6067 for (i
= 0; i
< nb_nics
; i
++) {
6068 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6069 vlan
= nd_table
[i
].vlan
;
6070 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6071 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6072 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6073 vc
->fd_read(vc
->opaque
, buf
, len
);
6078 /***********************************************************/
6079 /* savevm/loadvm support */
6081 #define IO_BUF_SIZE 32768
6084 QEMUFilePutBufferFunc
*put_buffer
;
6085 QEMUFileGetBufferFunc
*get_buffer
;
6086 QEMUFileCloseFunc
*close
;
6089 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6092 int buf_size
; /* 0 when writing */
6093 uint8_t buf
[IO_BUF_SIZE
];
6096 typedef struct QEMUFileFD
6101 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6103 QEMUFileFD
*s
= opaque
;
6108 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6110 if (errno
== EINTR
|| errno
== EAGAIN
)
6117 QEMUFile
*qemu_fopen_fd(int fd
)
6119 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6121 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6124 typedef struct QEMUFileUnix
6129 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6131 QEMUFileUnix
*s
= opaque
;
6132 fseek(s
->outfile
, pos
, SEEK_SET
);
6133 fwrite(buf
, 1, size
, s
->outfile
);
6136 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6138 QEMUFileUnix
*s
= opaque
;
6139 fseek(s
->outfile
, pos
, SEEK_SET
);
6140 return fread(buf
, 1, size
, s
->outfile
);
6143 static void file_close(void *opaque
)
6145 QEMUFileUnix
*s
= opaque
;
6150 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6154 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6158 s
->outfile
= fopen(filename
, mode
);
6162 if (!strcmp(mode
, "wb"))
6163 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6164 else if (!strcmp(mode
, "rb"))
6165 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6174 typedef struct QEMUFileBdrv
6176 BlockDriverState
*bs
;
6177 int64_t base_offset
;
6180 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6182 QEMUFileBdrv
*s
= opaque
;
6183 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6186 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6188 QEMUFileBdrv
*s
= opaque
;
6189 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6192 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6196 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6201 s
->base_offset
= offset
;
6204 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6206 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6209 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6210 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6214 f
= qemu_mallocz(sizeof(QEMUFile
));
6219 f
->put_buffer
= put_buffer
;
6220 f
->get_buffer
= get_buffer
;
6226 void qemu_fflush(QEMUFile
*f
)
6231 if (f
->buf_index
> 0) {
6232 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6233 f
->buf_offset
+= f
->buf_index
;
6238 static void qemu_fill_buffer(QEMUFile
*f
)
6245 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6251 f
->buf_offset
+= len
;
6254 void qemu_fclose(QEMUFile
*f
)
6258 f
->close(f
->opaque
);
6262 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6266 l
= IO_BUF_SIZE
- f
->buf_index
;
6269 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6273 if (f
->buf_index
>= IO_BUF_SIZE
)
6278 void qemu_put_byte(QEMUFile
*f
, int v
)
6280 f
->buf
[f
->buf_index
++] = v
;
6281 if (f
->buf_index
>= IO_BUF_SIZE
)
6285 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6291 l
= f
->buf_size
- f
->buf_index
;
6293 qemu_fill_buffer(f
);
6294 l
= f
->buf_size
- f
->buf_index
;
6300 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6305 return size1
- size
;
6308 int qemu_get_byte(QEMUFile
*f
)
6310 if (f
->buf_index
>= f
->buf_size
) {
6311 qemu_fill_buffer(f
);
6312 if (f
->buf_index
>= f
->buf_size
)
6315 return f
->buf
[f
->buf_index
++];
6318 int64_t qemu_ftell(QEMUFile
*f
)
6320 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6323 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6325 if (whence
== SEEK_SET
) {
6327 } else if (whence
== SEEK_CUR
) {
6328 pos
+= qemu_ftell(f
);
6330 /* SEEK_END not supported */
6333 if (f
->put_buffer
) {
6335 f
->buf_offset
= pos
;
6337 f
->buf_offset
= pos
;
6344 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6346 qemu_put_byte(f
, v
>> 8);
6347 qemu_put_byte(f
, v
);
6350 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6352 qemu_put_byte(f
, v
>> 24);
6353 qemu_put_byte(f
, v
>> 16);
6354 qemu_put_byte(f
, v
>> 8);
6355 qemu_put_byte(f
, v
);
6358 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6360 qemu_put_be32(f
, v
>> 32);
6361 qemu_put_be32(f
, v
);
6364 unsigned int qemu_get_be16(QEMUFile
*f
)
6367 v
= qemu_get_byte(f
) << 8;
6368 v
|= qemu_get_byte(f
);
6372 unsigned int qemu_get_be32(QEMUFile
*f
)
6375 v
= qemu_get_byte(f
) << 24;
6376 v
|= qemu_get_byte(f
) << 16;
6377 v
|= qemu_get_byte(f
) << 8;
6378 v
|= qemu_get_byte(f
);
6382 uint64_t qemu_get_be64(QEMUFile
*f
)
6385 v
= (uint64_t)qemu_get_be32(f
) << 32;
6386 v
|= qemu_get_be32(f
);
6390 typedef struct SaveStateEntry
{
6394 SaveStateHandler
*save_state
;
6395 LoadStateHandler
*load_state
;
6397 struct SaveStateEntry
*next
;
6400 static SaveStateEntry
*first_se
;
6402 /* TODO: Individual devices generally have very little idea about the rest
6403 of the system, so instance_id should be removed/replaced. */
6404 int register_savevm(const char *idstr
,
6407 SaveStateHandler
*save_state
,
6408 LoadStateHandler
*load_state
,
6411 SaveStateEntry
*se
, **pse
;
6413 se
= qemu_malloc(sizeof(SaveStateEntry
));
6416 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6417 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6418 se
->version_id
= version_id
;
6419 se
->save_state
= save_state
;
6420 se
->load_state
= load_state
;
6421 se
->opaque
= opaque
;
6424 /* add at the end of list */
6426 while (*pse
!= NULL
) {
6427 if (instance_id
== -1
6428 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6429 && se
->instance_id
<= (*pse
)->instance_id
)
6430 se
->instance_id
= (*pse
)->instance_id
+ 1;
6431 pse
= &(*pse
)->next
;
6437 #define QEMU_VM_FILE_MAGIC 0x5145564d
6438 #define QEMU_VM_FILE_VERSION 0x00000002
6440 static int qemu_savevm_state(QEMUFile
*f
)
6444 int64_t cur_pos
, len_pos
, total_len_pos
;
6446 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6447 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6448 total_len_pos
= qemu_ftell(f
);
6449 qemu_put_be64(f
, 0); /* total size */
6451 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6452 if (se
->save_state
== NULL
)
6453 /* this one has a loader only, for backwards compatibility */
6457 len
= strlen(se
->idstr
);
6458 qemu_put_byte(f
, len
);
6459 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6461 qemu_put_be32(f
, se
->instance_id
);
6462 qemu_put_be32(f
, se
->version_id
);
6464 /* record size: filled later */
6465 len_pos
= qemu_ftell(f
);
6466 qemu_put_be32(f
, 0);
6467 se
->save_state(f
, se
->opaque
);
6469 /* fill record size */
6470 cur_pos
= qemu_ftell(f
);
6471 len
= cur_pos
- len_pos
- 4;
6472 qemu_fseek(f
, len_pos
, SEEK_SET
);
6473 qemu_put_be32(f
, len
);
6474 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6476 cur_pos
= qemu_ftell(f
);
6477 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6478 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6479 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6485 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6489 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6490 if (!strcmp(se
->idstr
, idstr
) &&
6491 instance_id
== se
->instance_id
)
6497 static int qemu_loadvm_state(QEMUFile
*f
)
6500 int len
, ret
, instance_id
, record_len
, version_id
;
6501 int64_t total_len
, end_pos
, cur_pos
;
6505 v
= qemu_get_be32(f
);
6506 if (v
!= QEMU_VM_FILE_MAGIC
)
6508 v
= qemu_get_be32(f
);
6509 if (v
!= QEMU_VM_FILE_VERSION
) {
6514 total_len
= qemu_get_be64(f
);
6515 end_pos
= total_len
+ qemu_ftell(f
);
6517 if (qemu_ftell(f
) >= end_pos
)
6519 len
= qemu_get_byte(f
);
6520 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6522 instance_id
= qemu_get_be32(f
);
6523 version_id
= qemu_get_be32(f
);
6524 record_len
= qemu_get_be32(f
);
6526 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6527 idstr
, instance_id
, version_id
, record_len
);
6529 cur_pos
= qemu_ftell(f
);
6530 se
= find_se(idstr
, instance_id
);
6532 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6533 instance_id
, idstr
);
6535 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6537 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6538 instance_id
, idstr
);
6542 /* always seek to exact end of record */
6543 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6550 int qemu_live_savevm_state(QEMUFile
*f
)
6555 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6556 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6558 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6559 len
= strlen(se
->idstr
);
6561 qemu_put_byte(f
, len
);
6562 qemu_put_buffer(f
, se
->idstr
, len
);
6563 qemu_put_be32(f
, se
->instance_id
);
6564 qemu_put_be32(f
, se
->version_id
);
6566 se
->save_state(f
, se
->opaque
);
6569 qemu_put_byte(f
, 0);
6575 int qemu_live_loadvm_state(QEMUFile
*f
)
6578 int len
, ret
, instance_id
, version_id
;
6582 v
= qemu_get_be32(f
);
6583 if (v
!= QEMU_VM_FILE_MAGIC
)
6585 v
= qemu_get_be32(f
);
6586 if (v
!= QEMU_VM_FILE_VERSION
) {
6593 len
= qemu_get_byte(f
);
6596 qemu_get_buffer(f
, idstr
, len
);
6598 instance_id
= qemu_get_be32(f
);
6599 version_id
= qemu_get_be32(f
);
6600 se
= find_se(idstr
, instance_id
);
6602 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6603 instance_id
, idstr
);
6605 if (version_id
> se
->version_id
) { /* src version > dst version */
6606 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6607 idstr
, version_id
, se
->version_id
);
6611 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6613 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6614 instance_id
, idstr
);
6621 qemu_announce_self();
6627 /* device can contain snapshots */
6628 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6631 !bdrv_is_removable(bs
) &&
6632 !bdrv_is_read_only(bs
));
6635 /* device must be snapshots in order to have a reliable snapshot */
6636 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6639 !bdrv_is_removable(bs
) &&
6640 !bdrv_is_read_only(bs
));
6643 static BlockDriverState
*get_bs_snapshots(void)
6645 BlockDriverState
*bs
;
6649 return bs_snapshots
;
6650 for(i
= 0; i
<= nb_drives
; i
++) {
6651 bs
= drives_table
[i
].bdrv
;
6652 if (bdrv_can_snapshot(bs
))
6661 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6664 QEMUSnapshotInfo
*sn_tab
, *sn
;
6668 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6671 for(i
= 0; i
< nb_sns
; i
++) {
6673 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6683 void do_savevm(const char *name
)
6685 BlockDriverState
*bs
, *bs1
;
6686 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6687 int must_delete
, ret
, i
;
6688 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6690 int saved_vm_running
;
6697 bs
= get_bs_snapshots();
6699 term_printf("No block device can accept snapshots\n");
6703 /* ??? Should this occur after vm_stop? */
6706 saved_vm_running
= vm_running
;
6711 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6716 memset(sn
, 0, sizeof(*sn
));
6718 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6719 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6722 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6725 /* fill auxiliary fields */
6728 sn
->date_sec
= tb
.time
;
6729 sn
->date_nsec
= tb
.millitm
* 1000000;
6731 gettimeofday(&tv
, NULL
);
6732 sn
->date_sec
= tv
.tv_sec
;
6733 sn
->date_nsec
= tv
.tv_usec
* 1000;
6735 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6737 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6738 term_printf("Device %s does not support VM state snapshots\n",
6739 bdrv_get_device_name(bs
));
6743 /* save the VM state */
6744 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6746 term_printf("Could not open VM state file\n");
6749 ret
= qemu_savevm_state(f
);
6750 sn
->vm_state_size
= qemu_ftell(f
);
6753 term_printf("Error %d while writing VM\n", ret
);
6757 /* create the snapshots */
6759 for(i
= 0; i
< nb_drives
; i
++) {
6760 bs1
= drives_table
[i
].bdrv
;
6761 if (bdrv_has_snapshot(bs1
)) {
6763 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6765 term_printf("Error while deleting snapshot on '%s'\n",
6766 bdrv_get_device_name(bs1
));
6769 ret
= bdrv_snapshot_create(bs1
, sn
);
6771 term_printf("Error while creating snapshot on '%s'\n",
6772 bdrv_get_device_name(bs1
));
6778 if (saved_vm_running
)
6782 void do_loadvm(const char *name
)
6784 BlockDriverState
*bs
, *bs1
;
6785 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6788 int saved_vm_running
;
6790 bs
= get_bs_snapshots();
6792 term_printf("No block device supports snapshots\n");
6796 /* Flush all IO requests so they don't interfere with the new state. */
6799 saved_vm_running
= vm_running
;
6802 for(i
= 0; i
<= nb_drives
; i
++) {
6803 bs1
= drives_table
[i
].bdrv
;
6804 if (bdrv_has_snapshot(bs1
)) {
6805 ret
= bdrv_snapshot_goto(bs1
, name
);
6808 term_printf("Warning: ");
6811 term_printf("Snapshots not supported on device '%s'\n",
6812 bdrv_get_device_name(bs1
));
6815 term_printf("Could not find snapshot '%s' on device '%s'\n",
6816 name
, bdrv_get_device_name(bs1
));
6819 term_printf("Error %d while activating snapshot on '%s'\n",
6820 ret
, bdrv_get_device_name(bs1
));
6823 /* fatal on snapshot block device */
6830 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6831 term_printf("Device %s does not support VM state snapshots\n",
6832 bdrv_get_device_name(bs
));
6836 /* restore the VM state */
6837 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6839 term_printf("Could not open VM state file\n");
6842 ret
= qemu_loadvm_state(f
);
6845 term_printf("Error %d while loading VM state\n", ret
);
6848 if (saved_vm_running
)
6852 void do_delvm(const char *name
)
6854 BlockDriverState
*bs
, *bs1
;
6857 bs
= get_bs_snapshots();
6859 term_printf("No block device supports snapshots\n");
6863 for(i
= 0; i
<= nb_drives
; i
++) {
6864 bs1
= drives_table
[i
].bdrv
;
6865 if (bdrv_has_snapshot(bs1
)) {
6866 ret
= bdrv_snapshot_delete(bs1
, name
);
6868 if (ret
== -ENOTSUP
)
6869 term_printf("Snapshots not supported on device '%s'\n",
6870 bdrv_get_device_name(bs1
));
6872 term_printf("Error %d while deleting snapshot on '%s'\n",
6873 ret
, bdrv_get_device_name(bs1
));
6879 void do_info_snapshots(void)
6881 BlockDriverState
*bs
, *bs1
;
6882 QEMUSnapshotInfo
*sn_tab
, *sn
;
6886 bs
= get_bs_snapshots();
6888 term_printf("No available block device supports snapshots\n");
6891 term_printf("Snapshot devices:");
6892 for(i
= 0; i
<= nb_drives
; i
++) {
6893 bs1
= drives_table
[i
].bdrv
;
6894 if (bdrv_has_snapshot(bs1
)) {
6896 term_printf(" %s", bdrv_get_device_name(bs1
));
6901 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6903 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6906 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6907 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6908 for(i
= 0; i
< nb_sns
; i
++) {
6910 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6915 /***********************************************************/
6916 /* ram save/restore */
6918 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6922 v
= qemu_get_byte(f
);
6925 if (qemu_get_buffer(f
, buf
, len
) != len
)
6929 v
= qemu_get_byte(f
);
6930 memset(buf
, v
, len
);
6938 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6943 if (qemu_get_be32(f
) != phys_ram_size
)
6945 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6946 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6948 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6955 #define BDRV_HASH_BLOCK_SIZE 1024
6956 #define IOBUF_SIZE 4096
6957 #define RAM_CBLOCK_MAGIC 0xfabe
6959 typedef struct RamCompressState
{
6962 uint8_t buf
[IOBUF_SIZE
];
6965 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6968 memset(s
, 0, sizeof(*s
));
6970 ret
= deflateInit2(&s
->zstream
, 1,
6972 9, Z_DEFAULT_STRATEGY
);
6975 s
->zstream
.avail_out
= IOBUF_SIZE
;
6976 s
->zstream
.next_out
= s
->buf
;
6980 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6982 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6983 qemu_put_be16(s
->f
, len
);
6984 qemu_put_buffer(s
->f
, buf
, len
);
6987 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6991 s
->zstream
.avail_in
= len
;
6992 s
->zstream
.next_in
= (uint8_t *)buf
;
6993 while (s
->zstream
.avail_in
> 0) {
6994 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6997 if (s
->zstream
.avail_out
== 0) {
6998 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6999 s
->zstream
.avail_out
= IOBUF_SIZE
;
7000 s
->zstream
.next_out
= s
->buf
;
7006 static void ram_compress_close(RamCompressState
*s
)
7010 /* compress last bytes */
7012 ret
= deflate(&s
->zstream
, Z_FINISH
);
7013 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7014 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7016 ram_put_cblock(s
, s
->buf
, len
);
7018 s
->zstream
.avail_out
= IOBUF_SIZE
;
7019 s
->zstream
.next_out
= s
->buf
;
7020 if (ret
== Z_STREAM_END
)
7027 deflateEnd(&s
->zstream
);
7030 typedef struct RamDecompressState
{
7033 uint8_t buf
[IOBUF_SIZE
];
7034 } RamDecompressState
;
7036 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7039 memset(s
, 0, sizeof(*s
));
7041 ret
= inflateInit(&s
->zstream
);
7047 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7051 s
->zstream
.avail_out
= len
;
7052 s
->zstream
.next_out
= buf
;
7053 while (s
->zstream
.avail_out
> 0) {
7054 if (s
->zstream
.avail_in
== 0) {
7055 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7057 clen
= qemu_get_be16(s
->f
);
7058 if (clen
> IOBUF_SIZE
)
7060 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7061 s
->zstream
.avail_in
= clen
;
7062 s
->zstream
.next_in
= s
->buf
;
7064 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7065 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7072 static void ram_decompress_close(RamDecompressState
*s
)
7074 inflateEnd(&s
->zstream
);
7077 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7081 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7082 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7084 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7085 qemu_put_be32(f
, addr
);
7086 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7089 qemu_put_be32(f
, 1);
7092 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7095 RamCompressState s1
, *s
= &s1
;
7098 qemu_put_be32(f
, phys_ram_size
);
7099 if (ram_compress_open(s
, f
) < 0)
7101 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7102 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7105 if (tight_savevm_enabled
) {
7109 /* find if the memory block is available on a virtual
7112 for(j
= 0; j
< nb_drives
; j
++) {
7113 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7115 BDRV_HASH_BLOCK_SIZE
);
7116 if (sector_num
>= 0)
7120 goto normal_compress
;
7123 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7124 ram_compress_buf(s
, buf
, 10);
7130 ram_compress_buf(s
, buf
, 1);
7131 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7134 ram_compress_close(s
);
7137 static void ram_save(QEMUFile
*f
, void *opaque
)
7139 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7141 qemu_put_byte(f
, in_migration
);
7144 ram_save_live(f
, opaque
);
7146 ram_save_static(f
, opaque
);
7149 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7154 addr
= qemu_get_be32(f
);
7158 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7164 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7166 RamDecompressState s1
, *s
= &s1
;
7170 if (qemu_get_be32(f
) != phys_ram_size
)
7172 if (ram_decompress_open(s
, f
) < 0)
7174 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7175 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7177 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7178 fprintf(stderr
, "Error while reading ram block header\n");
7182 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7183 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7192 ram_decompress_buf(s
, buf
+ 1, 9);
7194 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7195 if (bs_index
>= nb_drives
) {
7196 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7199 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7201 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7202 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7203 bs_index
, sector_num
);
7210 printf("Error block header\n");
7214 ram_decompress_close(s
);
7218 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7222 switch (version_id
) {
7224 ret
= ram_load_v1(f
, opaque
);
7227 if (qemu_get_byte(f
)) {
7228 ret
= ram_load_live(f
, opaque
);
7232 ret
= ram_load_static(f
, opaque
);
7242 /***********************************************************/
7243 /* bottom halves (can be seen as timers which expire ASAP) */
7252 static QEMUBH
*first_bh
= NULL
;
7254 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7257 bh
= qemu_mallocz(sizeof(QEMUBH
));
7261 bh
->opaque
= opaque
;
7265 int qemu_bh_poll(void)
7284 void qemu_bh_schedule(QEMUBH
*bh
)
7286 CPUState
*env
= cpu_single_env
;
7290 bh
->next
= first_bh
;
7293 /* stop the currently executing CPU to execute the BH ASAP */
7295 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7300 void qemu_bh_cancel(QEMUBH
*bh
)
7303 if (bh
->scheduled
) {
7306 pbh
= &(*pbh
)->next
;
7312 void qemu_bh_delete(QEMUBH
*bh
)
7318 /***********************************************************/
7319 /* machine registration */
7321 QEMUMachine
*first_machine
= NULL
;
7322 QEMUMachine
*current_machine
= NULL
;
7324 int qemu_register_machine(QEMUMachine
*m
)
7327 pm
= &first_machine
;
7335 static QEMUMachine
*find_machine(const char *name
)
7339 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7340 if (!strcmp(m
->name
, name
))
7346 /***********************************************************/
7347 /* main execution loop */
7349 static void gui_update(void *opaque
)
7351 DisplayState
*ds
= opaque
;
7352 ds
->dpy_refresh(ds
);
7353 qemu_mod_timer(ds
->gui_timer
,
7354 (ds
->gui_timer_interval
?
7355 ds
->gui_timer_interval
:
7356 GUI_REFRESH_INTERVAL
)
7357 + qemu_get_clock(rt_clock
));
7360 struct vm_change_state_entry
{
7361 VMChangeStateHandler
*cb
;
7363 LIST_ENTRY (vm_change_state_entry
) entries
;
7366 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7368 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7371 VMChangeStateEntry
*e
;
7373 e
= qemu_mallocz(sizeof (*e
));
7379 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7383 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7385 LIST_REMOVE (e
, entries
);
7389 static void vm_state_notify(int running
)
7391 VMChangeStateEntry
*e
;
7393 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7394 e
->cb(e
->opaque
, running
);
7398 /* XXX: support several handlers */
7399 static VMStopHandler
*vm_stop_cb
;
7400 static void *vm_stop_opaque
;
7402 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7405 vm_stop_opaque
= opaque
;
7409 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7420 qemu_rearm_alarm_timer(alarm_timer
);
7424 void vm_stop(int reason
)
7427 cpu_disable_ticks();
7431 vm_stop_cb(vm_stop_opaque
, reason
);
7438 /* reset/shutdown handler */
7440 typedef struct QEMUResetEntry
{
7441 QEMUResetHandler
*func
;
7443 struct QEMUResetEntry
*next
;
7446 static QEMUResetEntry
*first_reset_entry
;
7447 static int reset_requested
;
7448 static int shutdown_requested
;
7449 static int powerdown_requested
;
7451 int qemu_shutdown_requested(void)
7453 int r
= shutdown_requested
;
7454 shutdown_requested
= 0;
7458 int qemu_reset_requested(void)
7460 int r
= reset_requested
;
7461 reset_requested
= 0;
7465 int qemu_powerdown_requested(void)
7467 int r
= powerdown_requested
;
7468 powerdown_requested
= 0;
7472 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7474 QEMUResetEntry
**pre
, *re
;
7476 pre
= &first_reset_entry
;
7477 while (*pre
!= NULL
)
7478 pre
= &(*pre
)->next
;
7479 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7481 re
->opaque
= opaque
;
7486 void qemu_system_reset(void)
7490 /* reset all devices */
7491 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7492 re
->func(re
->opaque
);
7496 void qemu_system_reset_request(void)
7499 shutdown_requested
= 1;
7501 reset_requested
= 1;
7504 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7508 void qemu_system_shutdown_request(void)
7510 shutdown_requested
= 1;
7512 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7515 void qemu_system_powerdown_request(void)
7517 powerdown_requested
= 1;
7519 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7522 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
7527 /* KVM holds a mutex while QEMU code is running, we need hooks to
7528 release the mutex whenever QEMU code sleeps. */
7532 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
7539 void main_loop_wait(int timeout
)
7541 IOHandlerRecord
*ioh
;
7542 fd_set rfds
, wfds
, xfds
;
7551 /* XXX: need to suppress polling by better using win32 events */
7553 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7554 ret
|= pe
->func(pe
->opaque
);
7559 WaitObjects
*w
= &wait_objects
;
7561 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7562 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7563 if (w
->func
[ret
- WAIT_OBJECT_0
])
7564 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7566 /* Check for additional signaled events */
7567 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7569 /* Check if event is signaled */
7570 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7571 if(ret2
== WAIT_OBJECT_0
) {
7573 w
->func
[i
](w
->opaque
[i
]);
7574 } else if (ret2
== WAIT_TIMEOUT
) {
7576 err
= GetLastError();
7577 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7580 } else if (ret
== WAIT_TIMEOUT
) {
7582 err
= GetLastError();
7583 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7587 /* poll any events */
7588 /* XXX: separate device handlers from system ones */
7593 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7597 (!ioh
->fd_read_poll
||
7598 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7599 FD_SET(ioh
->fd
, &rfds
);
7603 if (ioh
->fd_write
) {
7604 FD_SET(ioh
->fd
, &wfds
);
7614 tv
.tv_sec
= timeout
/ 1000;
7615 tv
.tv_usec
= (timeout
% 1000) * 1000;
7617 #if defined(CONFIG_SLIRP)
7619 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7622 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7624 IOHandlerRecord
**pioh
;
7626 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7627 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7628 ioh
->fd_read(ioh
->opaque
);
7629 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
7630 FD_CLR(ioh
->fd
, &rfds
);
7632 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7633 ioh
->fd_write(ioh
->opaque
);
7637 /* remove deleted IO handlers */
7638 pioh
= &first_io_handler
;
7648 #if defined(CONFIG_SLIRP)
7655 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7660 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7661 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7662 qemu_get_clock(vm_clock
));
7663 /* run dma transfers, if any */
7667 /* real time timers */
7668 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7669 qemu_get_clock(rt_clock
));
7671 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7672 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7673 qemu_rearm_alarm_timer(alarm_timer
);
7676 /* Check bottom-halves last in case any of the earlier events triggered
7682 static int main_loop(void)
7685 #ifdef CONFIG_PROFILER
7691 if (kvm_enabled()) {
7693 cpu_disable_ticks();
7697 cur_cpu
= first_cpu
;
7698 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7705 #ifdef CONFIG_PROFILER
7706 ti
= profile_getclock();
7711 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7712 env
->icount_decr
.u16
.low
= 0;
7713 env
->icount_extra
= 0;
7714 count
= qemu_next_deadline();
7715 count
= (count
+ (1 << icount_time_shift
) - 1)
7716 >> icount_time_shift
;
7717 qemu_icount
+= count
;
7718 decr
= (count
> 0xffff) ? 0xffff : count
;
7720 env
->icount_decr
.u16
.low
= decr
;
7721 env
->icount_extra
= count
;
7723 ret
= cpu_exec(env
);
7724 #ifdef CONFIG_PROFILER
7725 qemu_time
+= profile_getclock() - ti
;
7728 /* Fold pending instructions back into the
7729 instruction counter, and clear the interrupt flag. */
7730 qemu_icount
-= (env
->icount_decr
.u16
.low
7731 + env
->icount_extra
);
7732 env
->icount_decr
.u32
= 0;
7733 env
->icount_extra
= 0;
7735 next_cpu
= env
->next_cpu
?: first_cpu
;
7736 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7737 ret
= EXCP_INTERRUPT
;
7741 if (ret
== EXCP_HLT
) {
7742 /* Give the next CPU a chance to run. */
7746 if (ret
!= EXCP_HALTED
)
7748 /* all CPUs are halted ? */
7754 if (shutdown_requested
) {
7755 ret
= EXCP_INTERRUPT
;
7763 if (reset_requested
) {
7764 reset_requested
= 0;
7765 qemu_system_reset();
7767 kvm_load_registers(env
);
7768 ret
= EXCP_INTERRUPT
;
7770 if (powerdown_requested
) {
7771 powerdown_requested
= 0;
7772 qemu_system_powerdown();
7773 ret
= EXCP_INTERRUPT
;
7775 if (unlikely(ret
== EXCP_DEBUG
)) {
7776 vm_stop(EXCP_DEBUG
);
7778 /* If all cpus are halted then wait until the next IRQ */
7779 /* XXX: use timeout computed from timers */
7780 if (ret
== EXCP_HALTED
) {
7784 /* Advance virtual time to the next event. */
7785 if (use_icount
== 1) {
7786 /* When not using an adaptive execution frequency
7787 we tend to get badly out of sync with real time,
7788 so just delay for a reasonable amount of time. */
7791 delta
= cpu_get_icount() - cpu_get_clock();
7794 /* If virtual time is ahead of real time then just
7796 timeout
= (delta
/ 1000000) + 1;
7798 /* Wait for either IO to occur or the next
7800 add
= qemu_next_deadline();
7801 /* We advance the timer before checking for IO.
7802 Limit the amount we advance so that early IO
7803 activity won't get the guest too far ahead. */
7807 add
= (add
+ (1 << icount_time_shift
) - 1)
7808 >> icount_time_shift
;
7810 timeout
= delta
/ 1000000;
7823 #ifdef CONFIG_PROFILER
7824 ti
= profile_getclock();
7826 main_loop_wait(timeout
);
7827 #ifdef CONFIG_PROFILER
7828 dev_time
+= profile_getclock() - ti
;
7831 cpu_disable_ticks();
7835 static void help(int exitcode
)
7837 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
7838 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7839 "usage: %s [options] [disk_image]\n"
7841 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7843 "Standard options:\n"
7844 "-M machine select emulated machine (-M ? for list)\n"
7845 "-cpu cpu select CPU (-cpu ? for list)\n"
7846 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7847 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7848 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7849 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7850 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7851 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7852 " [,cache=on|off][,format=f][,boot=on|off]\n"
7853 " use 'file' as a drive image\n"
7854 "-mtdblock file use 'file' as on-board Flash memory image\n"
7855 "-sd file use 'file' as SecureDigital card image\n"
7856 "-pflash file use 'file' as a parallel flash image\n"
7857 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7858 "-snapshot write to temporary files instead of disk image files\n"
7860 "-no-frame open SDL window without a frame and window decorations\n"
7861 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7862 "-no-quit disable SDL window close capability\n"
7865 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7867 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7868 "-smp n set the number of CPUs to 'n' [default=1]\n"
7869 "-nographic disable graphical output and redirect serial I/Os to console\n"
7870 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7872 "-k language use keyboard layout (for example \"fr\" for French)\n"
7875 "-audio-help print list of audio drivers and their options\n"
7876 "-soundhw c1,... enable audio support\n"
7877 " and only specified sound cards (comma separated list)\n"
7878 " use -soundhw ? to get the list of supported cards\n"
7879 " use -soundhw all to enable all of them\n"
7881 "-localtime set the real time clock to local time [default=utc]\n"
7882 "-full-screen start in full screen\n"
7884 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7886 "-usb enable the USB driver (will be the default soon)\n"
7887 "-usbdevice name add the host or guest USB device 'name'\n"
7888 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7889 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7891 "-name string set the name of the guest\n"
7893 "Network options:\n"
7894 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7895 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7897 "-net user[,vlan=n][,hostname=host]\n"
7898 " connect the user mode network stack to VLAN 'n' and send\n"
7899 " hostname 'host' to DHCP clients\n"
7902 "-net tap[,vlan=n],ifname=name\n"
7903 " connect the host TAP network interface to VLAN 'n'\n"
7905 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7906 " connect the host TAP network interface to VLAN 'n' and use the\n"
7907 " network scripts 'file' (default=%s)\n"
7908 " and 'dfile' (default=%s);\n"
7909 " use '[down]script=no' to disable script execution;\n"
7910 " use 'fd=h' to connect to an already opened TAP interface\n"
7912 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7913 " connect the vlan 'n' to another VLAN using a socket connection\n"
7914 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7915 " connect the vlan 'n' to multicast maddr and port\n"
7916 "-net none use it alone to have zero network devices; if no -net option\n"
7917 " is provided, the default is '-net nic -net user'\n"
7920 "-tftp dir allow tftp access to files in dir [-net user]\n"
7921 "-bootp file advertise file in BOOTP replies\n"
7923 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7925 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7926 " redirect TCP or UDP connections from host to guest [-net user]\n"
7929 "Linux boot specific:\n"
7930 "-kernel bzImage use 'bzImage' as kernel image\n"
7931 "-append cmdline use 'cmdline' as kernel command line\n"
7932 "-initrd file use 'file' as initial ram disk\n"
7934 "Debug/Expert options:\n"
7935 "-monitor dev redirect the monitor to char device 'dev'\n"
7936 "-serial dev redirect the serial port to char device 'dev'\n"
7937 "-parallel dev redirect the parallel port to char device 'dev'\n"
7938 "-pidfile file Write PID to 'file'\n"
7939 "-S freeze CPU at startup (use 'c' to start execution)\n"
7940 "-s wait gdb connection to port\n"
7941 "-p port set gdb connection port [default=%s]\n"
7942 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7943 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7944 " translation (t=none or lba) (usually qemu can guess them)\n"
7945 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7947 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7948 "-no-kqemu disable KQEMU kernel module usage\n"
7951 #ifndef NO_CPU_EMULATION
7952 "-no-kvm disable KVM hardware virtualization\n"
7954 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7955 "-no-kvm-pit disable KVM kernel mode PIT\n"
7958 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7959 " (default is CL-GD5446 PCI VGA)\n"
7960 "-no-acpi disable ACPI\n"
7962 #ifdef CONFIG_CURSES
7963 "-curses use a curses/ncurses interface instead of SDL\n"
7965 "-no-reboot exit instead of rebooting\n"
7966 "-no-shutdown stop before shutdown\n"
7967 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7968 "-vnc display start a VNC server on display\n"
7970 "-daemonize daemonize QEMU after initializing\n"
7972 "-tdf inject timer interrupts that got lost\n"
7973 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7974 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
7975 "-option-rom rom load a file, rom, into the option ROM space\n"
7977 "-prom-env variable=value set OpenBIOS nvram variables\n"
7979 "-clock force the use of the given methods for timer alarm.\n"
7980 " To see what timers are available use -clock ?\n"
7981 "-startdate select initial date of the clock\n"
7982 "-icount [N|auto]\n"
7983 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7985 "During emulation, the following keys are useful:\n"
7986 "ctrl-alt-f toggle full screen\n"
7987 "ctrl-alt-n switch to virtual console 'n'\n"
7988 "ctrl-alt toggle mouse and keyboard grab\n"
7990 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7995 DEFAULT_NETWORK_SCRIPT
,
7996 DEFAULT_NETWORK_DOWN_SCRIPT
,
7998 DEFAULT_GDBSTUB_PORT
,
8003 #define HAS_ARG 0x0001
8018 QEMU_OPTION_mtdblock
,
8022 QEMU_OPTION_snapshot
,
8024 QEMU_OPTION_no_fd_bootchk
,
8027 QEMU_OPTION_nographic
,
8028 QEMU_OPTION_portrait
,
8030 QEMU_OPTION_audio_help
,
8031 QEMU_OPTION_soundhw
,
8052 QEMU_OPTION_localtime
,
8053 QEMU_OPTION_cirrusvga
,
8056 QEMU_OPTION_std_vga
,
8058 QEMU_OPTION_monitor
,
8060 QEMU_OPTION_parallel
,
8062 QEMU_OPTION_full_screen
,
8063 QEMU_OPTION_no_frame
,
8064 QEMU_OPTION_alt_grab
,
8065 QEMU_OPTION_no_quit
,
8066 QEMU_OPTION_pidfile
,
8067 QEMU_OPTION_no_kqemu
,
8068 QEMU_OPTION_kernel_kqemu
,
8069 QEMU_OPTION_win2k_hack
,
8071 QEMU_OPTION_usbdevice
,
8074 QEMU_OPTION_no_acpi
,
8077 QEMU_OPTION_no_kvm_irqchip
,
8078 QEMU_OPTION_no_kvm_pit
,
8079 QEMU_OPTION_no_reboot
,
8080 QEMU_OPTION_no_shutdown
,
8081 QEMU_OPTION_show_cursor
,
8082 QEMU_OPTION_daemonize
,
8083 QEMU_OPTION_option_rom
,
8084 QEMU_OPTION_semihosting
,
8085 QEMU_OPTION_cpu_vendor
,
8087 QEMU_OPTION_prom_env
,
8088 QEMU_OPTION_old_param
,
8090 QEMU_OPTION_startdate
,
8091 QEMU_OPTION_tb_size
,
8093 QEMU_OPTION_translation
,
8094 QEMU_OPTION_incoming
,
8096 QEMU_OPTION_kvm_shadow_memory
,
8097 QEMU_OPTION_mempath
,
8100 typedef struct QEMUOption
{
8106 const QEMUOption qemu_options
[] = {
8107 { "h", 0, QEMU_OPTION_h
},
8108 { "help", 0, QEMU_OPTION_h
},
8110 { "M", HAS_ARG
, QEMU_OPTION_M
},
8111 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8112 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8113 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8114 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8115 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8116 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8117 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8118 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8119 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8120 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8121 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8122 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8123 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8124 { "snapshot", 0, QEMU_OPTION_snapshot
},
8126 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8128 { "m", HAS_ARG
, QEMU_OPTION_m
},
8129 { "nographic", 0, QEMU_OPTION_nographic
},
8130 { "portrait", 0, QEMU_OPTION_portrait
},
8131 { "k", HAS_ARG
, QEMU_OPTION_k
},
8133 { "audio-help", 0, QEMU_OPTION_audio_help
},
8134 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8137 { "net", HAS_ARG
, QEMU_OPTION_net
},
8139 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8140 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8142 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8144 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8147 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8148 { "append", HAS_ARG
, QEMU_OPTION_append
},
8149 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8151 { "S", 0, QEMU_OPTION_S
},
8152 { "s", 0, QEMU_OPTION_s
},
8153 { "p", HAS_ARG
, QEMU_OPTION_p
},
8154 { "d", HAS_ARG
, QEMU_OPTION_d
},
8155 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8156 { "L", HAS_ARG
, QEMU_OPTION_L
},
8157 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8159 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8160 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8163 #ifndef NO_CPU_EMULATION
8164 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8166 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8167 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8169 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8170 { "g", 1, QEMU_OPTION_g
},
8172 { "localtime", 0, QEMU_OPTION_localtime
},
8173 { "std-vga", 0, QEMU_OPTION_std_vga
},
8174 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8175 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8176 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8177 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8178 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8179 { "incoming", 1, QEMU_OPTION_incoming
},
8180 { "full-screen", 0, QEMU_OPTION_full_screen
},
8182 { "no-frame", 0, QEMU_OPTION_no_frame
},
8183 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8184 { "no-quit", 0, QEMU_OPTION_no_quit
},
8186 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8187 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8188 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8189 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8190 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8191 #ifdef CONFIG_CURSES
8192 { "curses", 0, QEMU_OPTION_curses
},
8195 /* temporary options */
8196 { "usb", 0, QEMU_OPTION_usb
},
8197 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8198 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8199 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8200 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8201 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8202 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8203 { "daemonize", 0, QEMU_OPTION_daemonize
},
8204 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8205 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8206 { "semihosting", 0, QEMU_OPTION_semihosting
},
8208 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8209 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8210 { "name", HAS_ARG
, QEMU_OPTION_name
},
8211 #if defined(TARGET_SPARC)
8212 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8214 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8215 #if defined(TARGET_ARM)
8216 { "old-param", 0, QEMU_OPTION_old_param
},
8218 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8219 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8220 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8221 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8222 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8226 /* password input */
8228 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8233 if (!bdrv_is_encrypted(bs
))
8236 term_printf("%s is encrypted.\n", name
);
8237 for(i
= 0; i
< 3; i
++) {
8238 monitor_readline("Password: ", 1, password
, sizeof(password
));
8239 if (bdrv_set_key(bs
, password
) == 0)
8241 term_printf("invalid password\n");
8246 static BlockDriverState
*get_bdrv(int index
)
8248 if (index
> nb_drives
)
8250 return drives_table
[index
].bdrv
;
8253 static void read_passwords(void)
8255 BlockDriverState
*bs
;
8258 for(i
= 0; i
< 6; i
++) {
8261 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8266 struct soundhw soundhw
[] = {
8267 #ifdef HAS_AUDIO_CHOICE
8268 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8274 { .init_isa
= pcspk_audio_init
}
8279 "Creative Sound Blaster 16",
8282 { .init_isa
= SB16_init
}
8285 #ifdef CONFIG_CS4231A
8291 { .init_isa
= cs4231a_init
}
8299 "Yamaha YMF262 (OPL3)",
8301 "Yamaha YM3812 (OPL2)",
8305 { .init_isa
= Adlib_init
}
8312 "Gravis Ultrasound GF1",
8315 { .init_isa
= GUS_init
}
8322 "Intel 82801AA AC97 Audio",
8325 { .init_pci
= ac97_init
}
8331 "ENSONIQ AudioPCI ES1370",
8334 { .init_pci
= es1370_init
}
8338 { NULL
, NULL
, 0, 0, { NULL
} }
8341 static void select_soundhw (const char *optarg
)
8345 if (*optarg
== '?') {
8348 printf ("Valid sound card names (comma separated):\n");
8349 for (c
= soundhw
; c
->name
; ++c
) {
8350 printf ("%-11s %s\n", c
->name
, c
->descr
);
8352 printf ("\n-soundhw all will enable all of the above\n");
8353 exit (*optarg
!= '?');
8361 if (!strcmp (optarg
, "all")) {
8362 for (c
= soundhw
; c
->name
; ++c
) {
8370 e
= strchr (p
, ',');
8371 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8373 for (c
= soundhw
; c
->name
; ++c
) {
8374 if (!strncmp (c
->name
, p
, l
)) {
8383 "Unknown sound card name (too big to show)\n");
8386 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8391 p
+= l
+ (e
!= NULL
);
8395 goto show_valid_cards
;
8401 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8403 exit(STATUS_CONTROL_C_EXIT
);
8408 #define MAX_NET_CLIENTS 32
8410 static int saved_argc
;
8411 static char **saved_argv
;
8413 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8417 *opt_daemonize
= daemonize
;
8418 *opt_incoming
= incoming
;
8422 static int gethugepagesize(void)
8426 char *needle
= "Hugepagesize:";
8428 unsigned long hugepagesize
;
8430 fd
= open("/proc/meminfo", O_RDONLY
);
8436 ret
= read(fd
, buf
, sizeof(buf
));
8442 size
= strstr(buf
, needle
);
8445 size
+= strlen(needle
);
8446 hugepagesize
= strtol(size
, NULL
, 0);
8447 return hugepagesize
;
8450 void *alloc_mem_area(unsigned long memory
, const char *path
)
8456 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8459 hpagesize
= gethugepagesize() * 1024;
8463 fd
= mkstemp(filename
);
8472 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8475 * ftruncate is not supported by hugetlbfs in older
8476 * hosts, so don't bother checking for errors.
8477 * If anything goes wrong with it under other filesystems,
8480 ftruncate(fd
, memory
);
8482 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8483 if (area
== MAP_FAILED
) {
8492 void *qemu_alloc_physram(unsigned long memory
)
8497 area
= alloc_mem_area(memory
, mem_path
);
8499 area
= qemu_vmalloc(memory
);
8504 int main(int argc
, char **argv
)
8506 #ifdef CONFIG_GDBSTUB
8508 const char *gdbstub_port
;
8510 uint32_t boot_devices_bitmap
= 0;
8512 int snapshot
, linux_boot
, net_boot
;
8513 const char *initrd_filename
;
8514 const char *kernel_filename
, *kernel_cmdline
;
8515 const char *boot_devices
= "";
8516 DisplayState
*ds
= &display_state
;
8517 int cyls
, heads
, secs
, translation
;
8518 const char *net_clients
[MAX_NET_CLIENTS
];
8522 const char *r
, *optarg
;
8523 CharDriverState
*monitor_hd
;
8524 const char *monitor_device
;
8525 const char *serial_devices
[MAX_SERIAL_PORTS
];
8526 int serial_device_index
;
8527 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8528 int parallel_device_index
;
8529 const char *loadvm
= NULL
;
8530 QEMUMachine
*machine
;
8531 const char *cpu_model
;
8532 const char *usb_devices
[MAX_USB_CMDLINE
];
8533 int usb_devices_index
;
8536 const char *pid_file
= NULL
;
8542 LIST_INIT (&vm_change_state_head
);
8545 struct sigaction act
;
8546 sigfillset(&act
.sa_mask
);
8548 act
.sa_handler
= SIG_IGN
;
8549 sigaction(SIGPIPE
, &act
, NULL
);
8552 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8553 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8554 QEMU to run on a single CPU */
8559 h
= GetCurrentProcess();
8560 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8561 for(i
= 0; i
< 32; i
++) {
8562 if (mask
& (1 << i
))
8567 SetProcessAffinityMask(h
, mask
);
8573 register_machines();
8574 machine
= first_machine
;
8576 initrd_filename
= NULL
;
8578 vga_ram_size
= VGA_RAM_SIZE
;
8579 #ifdef CONFIG_GDBSTUB
8581 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8586 kernel_filename
= NULL
;
8587 kernel_cmdline
= "";
8588 cyls
= heads
= secs
= 0;
8589 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8590 monitor_device
= "vc";
8592 serial_devices
[0] = "vc:80Cx24C";
8593 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8594 serial_devices
[i
] = NULL
;
8595 serial_device_index
= 0;
8597 parallel_devices
[0] = "vc:640x480";
8598 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8599 parallel_devices
[i
] = NULL
;
8600 parallel_device_index
= 0;
8602 usb_devices_index
= 0;
8619 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8621 const QEMUOption
*popt
;
8624 /* Treat --foo the same as -foo. */
8627 popt
= qemu_options
;
8630 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8634 if (!strcmp(popt
->name
, r
+ 1))
8638 if (popt
->flags
& HAS_ARG
) {
8639 if (optind
>= argc
) {
8640 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8644 optarg
= argv
[optind
++];
8649 switch(popt
->index
) {
8651 machine
= find_machine(optarg
);
8654 printf("Supported machines are:\n");
8655 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8656 printf("%-10s %s%s\n",
8658 m
== first_machine
? " (default)" : "");
8660 exit(*optarg
!= '?');
8663 case QEMU_OPTION_cpu
:
8664 /* hw initialization will check this */
8665 if (*optarg
== '?') {
8666 /* XXX: implement xxx_cpu_list for targets that still miss it */
8667 #if defined(cpu_list)
8668 cpu_list(stdout
, &fprintf
);
8675 case QEMU_OPTION_initrd
:
8676 initrd_filename
= optarg
;
8678 case QEMU_OPTION_hda
:
8680 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8682 hda_index
= drive_add(optarg
, HD_ALIAS
8683 ",cyls=%d,heads=%d,secs=%d%s",
8684 0, cyls
, heads
, secs
,
8685 translation
== BIOS_ATA_TRANSLATION_LBA
?
8687 translation
== BIOS_ATA_TRANSLATION_NONE
?
8688 ",trans=none" : "");
8690 case QEMU_OPTION_hdb
:
8691 case QEMU_OPTION_hdc
:
8692 case QEMU_OPTION_hdd
:
8693 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8695 case QEMU_OPTION_drive
:
8696 drive_add(NULL
, "%s", optarg
);
8698 case QEMU_OPTION_mtdblock
:
8699 drive_add(optarg
, MTD_ALIAS
);
8701 case QEMU_OPTION_sd
:
8702 drive_add(optarg
, SD_ALIAS
);
8704 case QEMU_OPTION_pflash
:
8705 drive_add(optarg
, PFLASH_ALIAS
);
8707 case QEMU_OPTION_snapshot
:
8710 case QEMU_OPTION_hdachs
:
8714 cyls
= strtol(p
, (char **)&p
, 0);
8715 if (cyls
< 1 || cyls
> 16383)
8720 heads
= strtol(p
, (char **)&p
, 0);
8721 if (heads
< 1 || heads
> 16)
8726 secs
= strtol(p
, (char **)&p
, 0);
8727 if (secs
< 1 || secs
> 63)
8731 if (!strcmp(p
, "none"))
8732 translation
= BIOS_ATA_TRANSLATION_NONE
;
8733 else if (!strcmp(p
, "lba"))
8734 translation
= BIOS_ATA_TRANSLATION_LBA
;
8735 else if (!strcmp(p
, "auto"))
8736 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8739 } else if (*p
!= '\0') {
8741 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8744 if (hda_index
!= -1)
8745 snprintf(drives_opt
[hda_index
].opt
,
8746 sizeof(drives_opt
[hda_index
].opt
),
8747 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8748 0, cyls
, heads
, secs
,
8749 translation
== BIOS_ATA_TRANSLATION_LBA
?
8751 translation
== BIOS_ATA_TRANSLATION_NONE
?
8752 ",trans=none" : "");
8755 case QEMU_OPTION_nographic
:
8756 serial_devices
[0] = "stdio";
8757 parallel_devices
[0] = "null";
8758 monitor_device
= "stdio";
8761 #ifdef CONFIG_CURSES
8762 case QEMU_OPTION_curses
:
8766 case QEMU_OPTION_portrait
:
8769 case QEMU_OPTION_kernel
:
8770 kernel_filename
= optarg
;
8772 case QEMU_OPTION_append
:
8773 kernel_cmdline
= optarg
;
8775 case QEMU_OPTION_cdrom
:
8776 drive_add(optarg
, CDROM_ALIAS
);
8778 case QEMU_OPTION_boot
:
8779 boot_devices
= optarg
;
8780 /* We just do some generic consistency checks */
8782 /* Could easily be extended to 64 devices if needed */
8785 boot_devices_bitmap
= 0;
8786 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8787 /* Allowed boot devices are:
8788 * a b : floppy disk drives
8789 * c ... f : IDE disk drives
8790 * g ... m : machine implementation dependant drives
8791 * n ... p : network devices
8792 * It's up to each machine implementation to check
8793 * if the given boot devices match the actual hardware
8794 * implementation and firmware features.
8796 if (*p
< 'a' || *p
> 'q') {
8797 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8800 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8802 "Boot device '%c' was given twice\n",*p
);
8805 boot_devices_bitmap
|= 1 << (*p
- 'a');
8809 case QEMU_OPTION_fda
:
8810 case QEMU_OPTION_fdb
:
8811 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8814 case QEMU_OPTION_no_fd_bootchk
:
8818 case QEMU_OPTION_net
:
8819 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8820 fprintf(stderr
, "qemu: too many network clients\n");
8823 net_clients
[nb_net_clients
] = optarg
;
8827 case QEMU_OPTION_tftp
:
8828 tftp_prefix
= optarg
;
8830 case QEMU_OPTION_bootp
:
8831 bootp_filename
= optarg
;
8834 case QEMU_OPTION_smb
:
8835 net_slirp_smb(optarg
);
8838 case QEMU_OPTION_redir
:
8839 net_slirp_redir(optarg
);
8843 case QEMU_OPTION_audio_help
:
8847 case QEMU_OPTION_soundhw
:
8848 select_soundhw (optarg
);
8854 case QEMU_OPTION_m
: {
8858 value
= strtoul(optarg
, &ptr
, 10);
8860 case 0: case 'M': case 'm':
8867 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8871 /* On 32-bit hosts, QEMU is limited by virtual address space */
8872 if (value
> (2047 << 20)
8874 && HOST_LONG_BITS
== 32
8877 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8880 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8881 fprintf(stderr
, "qemu: ram size too large\n");
8892 mask
= cpu_str_to_log_mask(optarg
);
8894 printf("Log items (comma separated):\n");
8895 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8896 printf("%-10s %s\n", item
->name
, item
->help
);
8903 #ifdef CONFIG_GDBSTUB
8908 gdbstub_port
= optarg
;
8914 case QEMU_OPTION_bios
:
8921 keyboard_layout
= optarg
;
8923 case QEMU_OPTION_localtime
:
8926 case QEMU_OPTION_cirrusvga
:
8927 cirrus_vga_enabled
= 1;
8930 case QEMU_OPTION_vmsvga
:
8931 cirrus_vga_enabled
= 0;
8934 case QEMU_OPTION_std_vga
:
8935 cirrus_vga_enabled
= 0;
8943 w
= strtol(p
, (char **)&p
, 10);
8946 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8952 h
= strtol(p
, (char **)&p
, 10);
8957 depth
= strtol(p
, (char **)&p
, 10);
8958 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8959 depth
!= 24 && depth
!= 32)
8961 } else if (*p
== '\0') {
8962 depth
= graphic_depth
;
8969 graphic_depth
= depth
;
8972 case QEMU_OPTION_echr
:
8975 term_escape_char
= strtol(optarg
, &r
, 0);
8977 printf("Bad argument to echr\n");
8980 case QEMU_OPTION_monitor
:
8981 monitor_device
= optarg
;
8983 case QEMU_OPTION_serial
:
8984 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8985 fprintf(stderr
, "qemu: too many serial ports\n");
8988 serial_devices
[serial_device_index
] = optarg
;
8989 serial_device_index
++;
8991 case QEMU_OPTION_parallel
:
8992 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8993 fprintf(stderr
, "qemu: too many parallel ports\n");
8996 parallel_devices
[parallel_device_index
] = optarg
;
8997 parallel_device_index
++;
8999 case QEMU_OPTION_loadvm
:
9002 case QEMU_OPTION_incoming
:
9005 case QEMU_OPTION_full_screen
:
9009 case QEMU_OPTION_no_frame
:
9012 case QEMU_OPTION_alt_grab
:
9015 case QEMU_OPTION_no_quit
:
9019 case QEMU_OPTION_pidfile
:
9023 case QEMU_OPTION_win2k_hack
:
9024 win2k_install_hack
= 1;
9028 case QEMU_OPTION_no_kqemu
:
9031 case QEMU_OPTION_kernel_kqemu
:
9036 case QEMU_OPTION_no_kvm
:
9039 case QEMU_OPTION_no_kvm_irqchip
: {
9040 extern int kvm_irqchip
, kvm_pit
;
9045 case QEMU_OPTION_no_kvm_pit
: {
9051 case QEMU_OPTION_usb
:
9054 case QEMU_OPTION_usbdevice
:
9056 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9057 fprintf(stderr
, "Too many USB devices\n");
9060 usb_devices
[usb_devices_index
] = optarg
;
9061 usb_devices_index
++;
9063 case QEMU_OPTION_smp
:
9064 smp_cpus
= atoi(optarg
);
9065 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9066 fprintf(stderr
, "Invalid number of CPUs\n");
9070 case QEMU_OPTION_vnc
:
9071 vnc_display
= optarg
;
9073 case QEMU_OPTION_no_acpi
:
9076 case QEMU_OPTION_no_reboot
:
9079 case QEMU_OPTION_no_shutdown
:
9082 case QEMU_OPTION_show_cursor
:
9085 case QEMU_OPTION_daemonize
:
9088 case QEMU_OPTION_option_rom
:
9089 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9090 fprintf(stderr
, "Too many option ROMs\n");
9093 option_rom
[nb_option_roms
] = optarg
;
9096 case QEMU_OPTION_semihosting
:
9097 semihosting_enabled
= 1;
9099 case QEMU_OPTION_tdf
:
9102 case QEMU_OPTION_kvm_shadow_memory
:
9103 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9105 case QEMU_OPTION_mempath
:
9108 case QEMU_OPTION_name
:
9112 case QEMU_OPTION_prom_env
:
9113 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9114 fprintf(stderr
, "Too many prom variables\n");
9117 prom_envs
[nb_prom_envs
] = optarg
;
9121 case QEMU_OPTION_cpu_vendor
:
9122 cpu_vendor_string
= optarg
;
9125 case QEMU_OPTION_old_param
:
9129 case QEMU_OPTION_clock
:
9130 configure_alarms(optarg
);
9132 case QEMU_OPTION_startdate
:
9135 time_t rtc_start_date
;
9136 if (!strcmp(optarg
, "now")) {
9137 rtc_date_offset
= -1;
9139 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9147 } else if (sscanf(optarg
, "%d-%d-%d",
9150 &tm
.tm_mday
) == 3) {
9159 rtc_start_date
= mktimegm(&tm
);
9160 if (rtc_start_date
== -1) {
9162 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9163 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9166 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9170 case QEMU_OPTION_tb_size
:
9171 tb_size
= strtol(optarg
, NULL
, 0);
9175 case QEMU_OPTION_icount
:
9177 if (strcmp(optarg
, "auto") == 0) {
9178 icount_time_shift
= -1;
9180 icount_time_shift
= strtol(optarg
, NULL
, 0);
9191 if (pipe(fds
) == -1)
9202 len
= read(fds
[0], &status
, 1);
9203 if (len
== -1 && (errno
== EINTR
))
9208 else if (status
== 1) {
9209 fprintf(stderr
, "Could not acquire pidfile\n");
9226 signal(SIGTSTP
, SIG_IGN
);
9227 signal(SIGTTOU
, SIG_IGN
);
9228 signal(SIGTTIN
, SIG_IGN
);
9233 if (kvm_enabled()) {
9234 if (kvm_qemu_init() < 0) {
9235 extern int kvm_allowed
;
9236 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9237 #ifdef NO_CPU_EMULATION
9238 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9246 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9249 write(fds
[1], &status
, 1);
9251 fprintf(stderr
, "Could not acquire pid file\n");
9259 linux_boot
= (kernel_filename
!= NULL
);
9260 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9262 /* XXX: this should not be: some embedded targets just have flash */
9263 if (!linux_boot
&& net_boot
== 0 &&
9267 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9268 fprintf(stderr
, "-append only allowed with -kernel option\n");
9272 if (!linux_boot
&& initrd_filename
!= NULL
) {
9273 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9277 /* boot to floppy or the default cd if no hard disk defined yet */
9278 if (!boot_devices
[0]) {
9279 boot_devices
= "cad";
9281 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9286 if (use_icount
&& icount_time_shift
< 0) {
9288 /* 125MIPS seems a reasonable initial guess at the guest speed.
9289 It will be corrected fairly quickly anyway. */
9290 icount_time_shift
= 3;
9291 init_icount_adjust();
9298 /* init network clients */
9299 if (nb_net_clients
== 0) {
9300 /* if no clients, we use a default config */
9301 net_clients
[0] = "nic";
9302 net_clients
[1] = "user";
9306 for(i
= 0;i
< nb_net_clients
; i
++) {
9307 if (net_client_init(net_clients
[i
]) < 0)
9310 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9311 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9313 if (vlan
->nb_guest_devs
== 0) {
9314 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
9317 if (vlan
->nb_host_devs
== 0)
9319 "Warning: vlan %d is not connected to host network\n",
9324 /* XXX: this should be moved in the PC machine instantiation code */
9325 if (net_boot
!= 0) {
9327 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9328 const char *model
= nd_table
[i
].model
;
9330 if (net_boot
& (1 << i
)) {
9333 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9334 if (get_image_size(buf
) > 0) {
9335 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9336 fprintf(stderr
, "Too many option ROMs\n");
9339 option_rom
[nb_option_roms
] = strdup(buf
);
9346 fprintf(stderr
, "No valid PXE rom found for network device\n");
9352 /* init the memory */
9353 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9355 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9357 if (ram_size
< phys_ram_size
) {
9358 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9359 machine
->name
, (unsigned long long) phys_ram_size
);
9363 phys_ram_size
= ram_size
;
9365 ram_size
= phys_ram_size
;
9368 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9370 phys_ram_size
+= ram_size
;
9373 /* Initialize kvm */
9374 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9375 #define KVM_EXTRA_PAGES 3
9377 #define KVM_EXTRA_PAGES 0
9379 if (kvm_enabled()) {
9380 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9381 if (kvm_qemu_create_context() < 0) {
9382 fprintf(stderr
, "Could not create KVM context\n");
9385 #ifdef KVM_CAP_USER_MEMORY
9389 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9391 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9392 if (!phys_ram_base
) {
9393 fprintf(stderr
, "Could not allocate physical memory\n");
9400 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9401 if (!phys_ram_base
) {
9402 fprintf(stderr
, "Could not allocate physical memory\n");
9407 /* init the dynamic translator */
9408 cpu_exec_init_all(tb_size
* 1024 * 1024);
9412 /* we always create the cdrom drive, even if no disk is there */
9414 if (nb_drives_opt
< MAX_DRIVES
)
9415 drive_add(NULL
, CDROM_ALIAS
);
9417 /* we always create at least one floppy */
9419 if (nb_drives_opt
< MAX_DRIVES
)
9420 drive_add(NULL
, FD_ALIAS
, 0);
9422 /* we always create one sd slot, even if no card is in it */
9424 if (nb_drives_opt
< MAX_DRIVES
)
9425 drive_add(NULL
, SD_ALIAS
);
9427 /* open the virtual block devices
9428 * note that migration with device
9429 * hot add/remove is broken.
9431 for(i
= 0; i
< nb_drives_opt
; i
++)
9432 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9435 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9436 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9441 memset(&display_state
, 0, sizeof(display_state
));
9444 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9447 /* nearly nothing to do */
9448 dumb_display_init(ds
);
9449 } else if (vnc_display
!= NULL
) {
9450 vnc_display_init(ds
);
9451 if (vnc_display_open(ds
, vnc_display
) < 0)
9454 #if defined(CONFIG_CURSES)
9456 curses_display_init(ds
, full_screen
);
9460 #if defined(CONFIG_SDL)
9461 sdl_display_init(ds
, full_screen
, no_frame
);
9462 #elif defined(CONFIG_COCOA)
9463 cocoa_display_init(ds
, full_screen
);
9465 dumb_display_init(ds
);
9469 /* Maintain compatibility with multiple stdio monitors */
9470 if (!strcmp(monitor_device
,"stdio")) {
9471 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9472 const char *devname
= serial_devices
[i
];
9473 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9474 monitor_device
= NULL
;
9476 } else if (devname
&& !strcmp(devname
,"stdio")) {
9477 monitor_device
= NULL
;
9478 serial_devices
[i
] = "mon:stdio";
9483 if (monitor_device
) {
9484 monitor_hd
= qemu_chr_open(monitor_device
);
9486 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9489 monitor_init(monitor_hd
, !nographic
);
9492 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9493 const char *devname
= serial_devices
[i
];
9494 if (devname
&& strcmp(devname
, "none")) {
9495 serial_hds
[i
] = qemu_chr_open(devname
);
9496 if (!serial_hds
[i
]) {
9497 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9501 if (strstart(devname
, "vc", 0))
9502 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9506 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9507 const char *devname
= parallel_devices
[i
];
9508 if (devname
&& strcmp(devname
, "none")) {
9509 parallel_hds
[i
] = qemu_chr_open(devname
);
9510 if (!parallel_hds
[i
]) {
9511 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9515 if (strstart(devname
, "vc", 0))
9516 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9523 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9524 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9526 current_machine
= machine
;
9528 /* init USB devices */
9530 for(i
= 0; i
< usb_devices_index
; i
++) {
9531 if (usb_device_add(usb_devices
[i
]) < 0) {
9532 fprintf(stderr
, "Warning: could not add USB device %s\n",
9538 if (display_state
.dpy_refresh
) {
9539 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9540 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9543 #ifdef CONFIG_GDBSTUB
9545 /* XXX: use standard host:port notation and modify options
9547 if (gdbserver_start(gdbstub_port
) < 0) {
9548 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9560 rc
= migrate_incoming(incoming
);
9562 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
9568 /* XXX: simplify init */
9581 len
= write(fds
[1], &status
, 1);
9582 if (len
== -1 && (errno
== EINTR
))
9589 TFR(fd
= open("/dev/null", O_RDWR
));
9603 #if !defined(_WIN32)
9604 /* close network clients */
9605 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9606 VLANClientState
*vc
;
9608 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9609 if (vc
->fd_read
== tap_receive
) {
9611 TAPState
*s
= vc
->opaque
;
9613 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9615 launch_script(s
->down_script
, ifname
, s
->fd
);