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"
53 #include <sys/times.h>
58 #include <sys/ioctl.h>
59 #include <sys/socket.h>
60 #include <netinet/in.h>
63 #include <sys/select.h>
64 #include <arpa/inet.h>
67 #if !defined(__APPLE__) && !defined(__OpenBSD__)
73 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
74 #include <freebsd/stdlib.h>
78 #include <linux/if_tun.h>
81 #include <linux/rtc.h>
83 /* For the benefit of older linux systems which don't supply it,
84 we use a local copy of hpet.h. */
85 /* #include <linux/hpet.h> */
88 #include <linux/ppdev.h>
89 #include <linux/parport.h>
92 #include <sys/ethernet.h>
93 #include <sys/sockio.h>
94 #include <netinet/arp.h>
95 #include <netinet/in.h>
96 #include <netinet/in_systm.h>
97 #include <netinet/ip.h>
98 #include <netinet/ip_icmp.h> // must come after ip.h
99 #include <netinet/udp.h>
100 #include <netinet/tcp.h>
107 #include <winsock2.h>
108 int inet_aton(const char *cp
, struct in_addr
*ia
);
111 #if defined(CONFIG_SLIRP)
112 #include "libslirp.h"
115 #if defined(__OpenBSD__)
119 #if defined(CONFIG_VDE)
120 #include <libvdeplug.h>
125 #include <sys/timeb.h>
126 #include <mmsystem.h>
127 #define getopt_long_only getopt_long
128 #define memalign(align, size) malloc(size)
131 #include "qemu_socket.h"
137 #endif /* CONFIG_SDL */
141 #define main qemu_main
142 #endif /* CONFIG_COCOA */
146 #include "exec-all.h"
148 #include "qemu-kvm.h"
150 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
151 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
153 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
155 #define SMBD_COMMAND "/usr/sbin/smbd"
158 //#define DEBUG_UNUSED_IOPORT
159 //#define DEBUG_IOPORT
162 #define DEFAULT_RAM_SIZE 144
164 #define DEFAULT_RAM_SIZE 128
167 /* Max number of USB devices that can be specified on the commandline. */
168 #define MAX_USB_CMDLINE 8
170 /* XXX: use a two level table to limit memory usage */
171 #define MAX_IOPORTS 65536
173 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
174 const char *bios_name
= NULL
;
175 void *ioport_opaque
[MAX_IOPORTS
];
176 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
177 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
178 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
179 to store the VM snapshots */
180 DriveInfo drives_table
[MAX_DRIVES
+1];
182 int extboot_drive
= -1;
183 /* point to the block driver where the snapshots are managed */
184 BlockDriverState
*bs_snapshots
;
186 static DisplayState display_state
;
189 const char* keyboard_layout
= NULL
;
190 int64_t ticks_per_sec
;
192 int pit_min_timer_count
= 0;
194 NICInfo nd_table
[MAX_NICS
];
196 static int rtc_utc
= 1;
197 static int rtc_date_offset
= -1; /* -1 means no change */
198 int cirrus_vga_enabled
= 1;
199 int vmsvga_enabled
= 0;
201 int graphic_width
= 1024;
202 int graphic_height
= 768;
203 int graphic_depth
= 8;
205 int graphic_width
= 800;
206 int graphic_height
= 600;
207 int graphic_depth
= 15;
212 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
213 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
215 int win2k_install_hack
= 0;
218 static VLANState
*first_vlan
;
220 const char *vnc_display
;
221 #if defined(TARGET_SPARC)
223 #elif defined(TARGET_I386)
225 #elif defined(TARGET_IA64)
230 int acpi_enabled
= 1;
235 int graphic_rotate
= 0;
237 const char *incoming
;
238 const char *option_rom
[MAX_OPTION_ROMS
];
240 int semihosting_enabled
= 0;
242 int time_drift_fix
= 0;
243 unsigned int kvm_shadow_memory
= 0;
244 const char *mem_path
= NULL
;
246 const char *cpu_vendor_string
;
250 const char *qemu_name
;
253 unsigned int nb_prom_envs
= 0;
254 const char *prom_envs
[MAX_PROM_ENVS
];
257 struct drive_opt drives_opt
[MAX_DRIVES
];
259 static CPUState
*cur_cpu
;
260 static CPUState
*next_cpu
;
261 static int event_pending
= 1;
262 /* Conversion factor from emulated instructions to virtual clock ticks. */
263 static int icount_time_shift
;
264 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
265 #define MAX_ICOUNT_SHIFT 10
266 /* Compensate for varying guest execution speed. */
267 static int64_t qemu_icount_bias
;
268 QEMUTimer
*icount_rt_timer
;
269 QEMUTimer
*icount_vm_timer
;
271 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
273 /* KVM runs the main loop in a separate thread. If we update one of the lists
274 * that are polled before or after select(), we need to make sure to break out
275 * of the select() to ensure the new item is serviced.
277 static void main_loop_break(void)
280 qemu_kvm_notify_work();
283 /***********************************************************/
284 /* x86 ISA bus support */
286 target_phys_addr_t isa_mem_base
= 0;
289 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
290 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
292 static uint32_t ioport_read(int index
, uint32_t address
)
294 static IOPortReadFunc
*default_func
[3] = {
295 default_ioport_readb
,
296 default_ioport_readw
,
299 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
301 func
= default_func
[index
];
302 return func(ioport_opaque
[address
], address
);
305 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
307 static IOPortWriteFunc
*default_func
[3] = {
308 default_ioport_writeb
,
309 default_ioport_writew
,
310 default_ioport_writel
312 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
314 func
= default_func
[index
];
315 func(ioport_opaque
[address
], address
, data
);
318 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
320 #ifdef DEBUG_UNUSED_IOPORT
321 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
326 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
328 #ifdef DEBUG_UNUSED_IOPORT
329 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
333 /* default is to make two byte accesses */
334 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
337 data
= ioport_read(0, address
);
338 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
339 data
|= ioport_read(0, address
) << 8;
343 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
345 ioport_write(0, address
, data
& 0xff);
346 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
347 ioport_write(0, address
, (data
>> 8) & 0xff);
350 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
352 #ifdef DEBUG_UNUSED_IOPORT
353 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
358 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
360 #ifdef DEBUG_UNUSED_IOPORT
361 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
365 /* size is the word size in byte */
366 int register_ioport_read(int start
, int length
, int size
,
367 IOPortReadFunc
*func
, void *opaque
)
373 } else if (size
== 2) {
375 } else if (size
== 4) {
378 hw_error("register_ioport_read: invalid size");
381 for(i
= start
; i
< start
+ length
; i
+= size
) {
382 ioport_read_table
[bsize
][i
] = func
;
383 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
384 hw_error("register_ioport_read: invalid opaque");
385 ioport_opaque
[i
] = opaque
;
390 /* size is the word size in byte */
391 int register_ioport_write(int start
, int length
, int size
,
392 IOPortWriteFunc
*func
, void *opaque
)
398 } else if (size
== 2) {
400 } else if (size
== 4) {
403 hw_error("register_ioport_write: invalid size");
406 for(i
= start
; i
< start
+ length
; i
+= size
) {
407 ioport_write_table
[bsize
][i
] = func
;
408 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
409 hw_error("register_ioport_write: invalid opaque");
410 ioport_opaque
[i
] = opaque
;
415 void isa_unassign_ioport(int start
, int length
)
419 for(i
= start
; i
< start
+ length
; i
++) {
420 ioport_read_table
[0][i
] = default_ioport_readb
;
421 ioport_read_table
[1][i
] = default_ioport_readw
;
422 ioport_read_table
[2][i
] = default_ioport_readl
;
424 ioport_write_table
[0][i
] = default_ioport_writeb
;
425 ioport_write_table
[1][i
] = default_ioport_writew
;
426 ioport_write_table
[2][i
] = default_ioport_writel
;
428 ioport_opaque
[i
] = NULL
;
432 /***********************************************************/
434 void cpu_outb(CPUState
*env
, int addr
, int val
)
437 if (loglevel
& CPU_LOG_IOPORT
)
438 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
440 ioport_write(0, addr
, val
);
443 env
->last_io_time
= cpu_get_time_fast();
447 void cpu_outw(CPUState
*env
, int addr
, int val
)
450 if (loglevel
& CPU_LOG_IOPORT
)
451 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
453 ioport_write(1, addr
, val
);
456 env
->last_io_time
= cpu_get_time_fast();
460 void cpu_outl(CPUState
*env
, int addr
, int val
)
463 if (loglevel
& CPU_LOG_IOPORT
)
464 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
466 ioport_write(2, addr
, val
);
469 env
->last_io_time
= cpu_get_time_fast();
473 int cpu_inb(CPUState
*env
, int addr
)
476 val
= ioport_read(0, addr
);
478 if (loglevel
& CPU_LOG_IOPORT
)
479 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
483 env
->last_io_time
= cpu_get_time_fast();
488 int cpu_inw(CPUState
*env
, int addr
)
491 val
= ioport_read(1, addr
);
493 if (loglevel
& CPU_LOG_IOPORT
)
494 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
498 env
->last_io_time
= cpu_get_time_fast();
503 int cpu_inl(CPUState
*env
, int addr
)
506 val
= ioport_read(2, addr
);
508 if (loglevel
& CPU_LOG_IOPORT
)
509 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
513 env
->last_io_time
= cpu_get_time_fast();
518 /***********************************************************/
519 void hw_error(const char *fmt
, ...)
525 fprintf(stderr
, "qemu: hardware error: ");
526 vfprintf(stderr
, fmt
, ap
);
527 fprintf(stderr
, "\n");
528 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
529 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
531 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
533 cpu_dump_state(env
, stderr
, fprintf
, 0);
543 static QEMUBalloonEvent
*qemu_balloon_event
;
544 void *qemu_balloon_event_opaque
;
546 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
548 qemu_balloon_event
= func
;
549 qemu_balloon_event_opaque
= opaque
;
552 void qemu_balloon(ram_addr_t target
)
554 if (qemu_balloon_event
)
555 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
558 ram_addr_t
qemu_balloon_status(void)
560 if (qemu_balloon_event
)
561 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
565 /***********************************************************/
568 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
569 static void *qemu_put_kbd_event_opaque
;
570 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
571 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
573 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
575 qemu_put_kbd_event_opaque
= opaque
;
576 qemu_put_kbd_event
= func
;
579 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
580 void *opaque
, int absolute
,
583 QEMUPutMouseEntry
*s
, *cursor
;
585 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
589 s
->qemu_put_mouse_event
= func
;
590 s
->qemu_put_mouse_event_opaque
= opaque
;
591 s
->qemu_put_mouse_event_absolute
= absolute
;
592 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
595 if (!qemu_put_mouse_event_head
) {
596 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
600 cursor
= qemu_put_mouse_event_head
;
601 while (cursor
->next
!= NULL
)
602 cursor
= cursor
->next
;
605 qemu_put_mouse_event_current
= s
;
610 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
612 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
614 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
617 cursor
= qemu_put_mouse_event_head
;
618 while (cursor
!= NULL
&& cursor
!= entry
) {
620 cursor
= cursor
->next
;
623 if (cursor
== NULL
) // does not exist or list empty
625 else if (prev
== NULL
) { // entry is head
626 qemu_put_mouse_event_head
= cursor
->next
;
627 if (qemu_put_mouse_event_current
== entry
)
628 qemu_put_mouse_event_current
= cursor
->next
;
629 qemu_free(entry
->qemu_put_mouse_event_name
);
634 prev
->next
= entry
->next
;
636 if (qemu_put_mouse_event_current
== entry
)
637 qemu_put_mouse_event_current
= prev
;
639 qemu_free(entry
->qemu_put_mouse_event_name
);
643 void kbd_put_keycode(int keycode
)
645 if (qemu_put_kbd_event
) {
646 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
650 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
652 QEMUPutMouseEvent
*mouse_event
;
653 void *mouse_event_opaque
;
656 if (!qemu_put_mouse_event_current
) {
661 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
663 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
666 if (graphic_rotate
) {
667 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
670 width
= graphic_width
- 1;
671 mouse_event(mouse_event_opaque
,
672 width
- dy
, dx
, dz
, buttons_state
);
674 mouse_event(mouse_event_opaque
,
675 dx
, dy
, dz
, buttons_state
);
679 int kbd_mouse_is_absolute(void)
681 if (!qemu_put_mouse_event_current
)
684 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
687 void do_info_mice(void)
689 QEMUPutMouseEntry
*cursor
;
692 if (!qemu_put_mouse_event_head
) {
693 term_printf("No mouse devices connected\n");
697 term_printf("Mouse devices available:\n");
698 cursor
= qemu_put_mouse_event_head
;
699 while (cursor
!= NULL
) {
700 term_printf("%c Mouse #%d: %s\n",
701 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
702 index
, cursor
->qemu_put_mouse_event_name
);
704 cursor
= cursor
->next
;
708 void do_mouse_set(int index
)
710 QEMUPutMouseEntry
*cursor
;
713 if (!qemu_put_mouse_event_head
) {
714 term_printf("No mouse devices connected\n");
718 cursor
= qemu_put_mouse_event_head
;
719 while (cursor
!= NULL
&& index
!= i
) {
721 cursor
= cursor
->next
;
725 qemu_put_mouse_event_current
= cursor
;
727 term_printf("Mouse at given index not found\n");
730 /* compute with 96 bit intermediate result: (a*b)/c */
731 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
736 #ifdef WORDS_BIGENDIAN
746 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
747 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
750 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
754 /***********************************************************/
755 /* real time host monotonic timer */
757 #define QEMU_TIMER_BASE 1000000000LL
761 static int64_t clock_freq
;
763 static void init_get_clock(void)
767 ret
= QueryPerformanceFrequency(&freq
);
769 fprintf(stderr
, "Could not calibrate ticks\n");
772 clock_freq
= freq
.QuadPart
;
775 static int64_t get_clock(void)
778 QueryPerformanceCounter(&ti
);
779 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
784 static int use_rt_clock
;
786 static void init_get_clock(void)
789 #if defined(__linux__)
792 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
799 static int64_t get_clock(void)
801 #if defined(__linux__)
804 clock_gettime(CLOCK_MONOTONIC
, &ts
);
805 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
809 /* XXX: using gettimeofday leads to problems if the date
810 changes, so it should be avoided. */
812 gettimeofday(&tv
, NULL
);
813 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
818 /* Return the virtual CPU time, based on the instruction counter. */
819 static int64_t cpu_get_icount(void)
822 CPUState
*env
= cpu_single_env
;;
823 icount
= qemu_icount
;
826 fprintf(stderr
, "Bad clock read\n");
827 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
829 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
832 /***********************************************************/
833 /* guest cycle counter */
835 static int64_t cpu_ticks_prev
;
836 static int64_t cpu_ticks_offset
;
837 static int64_t cpu_clock_offset
;
838 static int cpu_ticks_enabled
;
840 /* return the host CPU cycle counter and handle stop/restart */
841 int64_t cpu_get_ticks(void)
844 return cpu_get_icount();
846 if (!cpu_ticks_enabled
) {
847 return cpu_ticks_offset
;
850 ticks
= cpu_get_real_ticks();
851 if (cpu_ticks_prev
> ticks
) {
852 /* Note: non increasing ticks may happen if the host uses
854 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
856 cpu_ticks_prev
= ticks
;
857 return ticks
+ cpu_ticks_offset
;
861 /* return the host CPU monotonic timer and handle stop/restart */
862 static int64_t cpu_get_clock(void)
865 if (!cpu_ticks_enabled
) {
866 return cpu_clock_offset
;
869 return ti
+ cpu_clock_offset
;
873 /* enable cpu_get_ticks() */
874 void cpu_enable_ticks(void)
876 if (!cpu_ticks_enabled
) {
877 cpu_ticks_offset
-= cpu_get_real_ticks();
878 cpu_clock_offset
-= get_clock();
879 cpu_ticks_enabled
= 1;
883 /* disable cpu_get_ticks() : the clock is stopped. You must not call
884 cpu_get_ticks() after that. */
885 void cpu_disable_ticks(void)
887 if (cpu_ticks_enabled
) {
888 cpu_ticks_offset
= cpu_get_ticks();
889 cpu_clock_offset
= cpu_get_clock();
890 cpu_ticks_enabled
= 0;
894 /***********************************************************/
897 #define QEMU_TIMER_REALTIME 0
898 #define QEMU_TIMER_VIRTUAL 1
902 /* XXX: add frequency */
910 struct QEMUTimer
*next
;
913 struct qemu_alarm_timer
{
917 int (*start
)(struct qemu_alarm_timer
*t
);
918 void (*stop
)(struct qemu_alarm_timer
*t
);
919 void (*rearm
)(struct qemu_alarm_timer
*t
);
923 #define ALARM_FLAG_DYNTICKS 0x1
924 #define ALARM_FLAG_EXPIRED 0x2
926 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
928 return t
->flags
& ALARM_FLAG_DYNTICKS
;
931 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
933 if (!alarm_has_dynticks(t
))
939 /* TODO: MIN_TIMER_REARM_US should be optimized */
940 #define MIN_TIMER_REARM_US 250
942 static struct qemu_alarm_timer
*alarm_timer
;
946 struct qemu_alarm_win32
{
950 } alarm_win32_data
= {0, NULL
, -1};
952 static int win32_start_timer(struct qemu_alarm_timer
*t
);
953 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
954 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
958 static int unix_start_timer(struct qemu_alarm_timer
*t
);
959 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
963 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
964 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
965 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
967 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
968 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
970 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
971 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
973 #endif /* __linux__ */
977 /* Correlation between real and virtual time is always going to be
978 fairly approximate, so ignore small variation.
979 When the guest is idle real and virtual time will be aligned in
981 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
983 static void icount_adjust(void)
988 static int64_t last_delta
;
989 /* If the VM is not running, then do nothing. */
993 cur_time
= cpu_get_clock();
994 cur_icount
= qemu_get_clock(vm_clock
);
995 delta
= cur_icount
- cur_time
;
996 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
998 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
999 && icount_time_shift
> 0) {
1000 /* The guest is getting too far ahead. Slow time down. */
1001 icount_time_shift
--;
1004 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1005 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1006 /* The guest is getting too far behind. Speed time up. */
1007 icount_time_shift
++;
1010 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1013 static void icount_adjust_rt(void * opaque
)
1015 qemu_mod_timer(icount_rt_timer
,
1016 qemu_get_clock(rt_clock
) + 1000);
1020 static void icount_adjust_vm(void * opaque
)
1022 qemu_mod_timer(icount_vm_timer
,
1023 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1027 static void init_icount_adjust(void)
1029 /* Have both realtime and virtual time triggers for speed adjustment.
1030 The realtime trigger catches emulated time passing too slowly,
1031 the virtual time trigger catches emulated time passing too fast.
1032 Realtime triggers occur even when idle, so use them less frequently
1033 than VM triggers. */
1034 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1035 qemu_mod_timer(icount_rt_timer
,
1036 qemu_get_clock(rt_clock
) + 1000);
1037 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1038 qemu_mod_timer(icount_vm_timer
,
1039 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1042 static struct qemu_alarm_timer alarm_timers
[] = {
1045 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1046 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1047 /* HPET - if available - is preferred */
1048 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1049 /* ...otherwise try RTC */
1050 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1052 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1054 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1055 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1056 {"win32", 0, win32_start_timer
,
1057 win32_stop_timer
, NULL
, &alarm_win32_data
},
1062 static void show_available_alarms(void)
1066 printf("Available alarm timers, in order of precedence:\n");
1067 for (i
= 0; alarm_timers
[i
].name
; i
++)
1068 printf("%s\n", alarm_timers
[i
].name
);
1071 static void configure_alarms(char const *opt
)
1075 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1078 struct qemu_alarm_timer tmp
;
1080 if (!strcmp(opt
, "?")) {
1081 show_available_alarms();
1087 /* Reorder the array */
1088 name
= strtok(arg
, ",");
1090 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1091 if (!strcmp(alarm_timers
[i
].name
, name
))
1096 fprintf(stderr
, "Unknown clock %s\n", name
);
1105 tmp
= alarm_timers
[i
];
1106 alarm_timers
[i
] = alarm_timers
[cur
];
1107 alarm_timers
[cur
] = tmp
;
1111 name
= strtok(NULL
, ",");
1117 /* Disable remaining timers */
1118 for (i
= cur
; i
< count
; i
++)
1119 alarm_timers
[i
].name
= NULL
;
1121 show_available_alarms();
1126 QEMUClock
*rt_clock
;
1127 QEMUClock
*vm_clock
;
1129 static QEMUTimer
*active_timers
[2];
1131 static QEMUClock
*qemu_new_clock(int type
)
1134 clock
= qemu_mallocz(sizeof(QEMUClock
));
1141 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1145 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1148 ts
->opaque
= opaque
;
1152 void qemu_free_timer(QEMUTimer
*ts
)
1157 /* stop a timer, but do not dealloc it */
1158 void qemu_del_timer(QEMUTimer
*ts
)
1162 /* NOTE: this code must be signal safe because
1163 qemu_timer_expired() can be called from a signal. */
1164 pt
= &active_timers
[ts
->clock
->type
];
1177 /* modify the current timer so that it will be fired when current_time
1178 >= expire_time. The corresponding callback will be called. */
1179 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1185 /* add the timer in the sorted list */
1186 /* NOTE: this code must be signal safe because
1187 qemu_timer_expired() can be called from a signal. */
1188 pt
= &active_timers
[ts
->clock
->type
];
1193 if (t
->expire_time
> expire_time
)
1197 ts
->expire_time
= expire_time
;
1201 /* Rearm if necessary */
1202 if (pt
== &active_timers
[ts
->clock
->type
]) {
1203 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1204 qemu_rearm_alarm_timer(alarm_timer
);
1206 /* Interrupt execution to force deadline recalculation. */
1207 if (use_icount
&& cpu_single_env
) {
1208 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1213 int qemu_timer_pending(QEMUTimer
*ts
)
1216 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1223 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1227 return (timer_head
->expire_time
<= current_time
);
1230 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1236 if (!ts
|| ts
->expire_time
> current_time
)
1238 /* remove timer from the list before calling the callback */
1239 *ptimer_head
= ts
->next
;
1242 /* run the callback (the timer list can be modified) */
1247 int64_t qemu_get_clock(QEMUClock
*clock
)
1249 switch(clock
->type
) {
1250 case QEMU_TIMER_REALTIME
:
1251 return get_clock() / 1000000;
1253 case QEMU_TIMER_VIRTUAL
:
1255 return cpu_get_icount();
1257 return cpu_get_clock();
1262 static void init_timers(void)
1265 ticks_per_sec
= QEMU_TIMER_BASE
;
1266 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1267 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1271 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1273 uint64_t expire_time
;
1275 if (qemu_timer_pending(ts
)) {
1276 expire_time
= ts
->expire_time
;
1280 qemu_put_be64(f
, expire_time
);
1283 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1285 uint64_t expire_time
;
1287 expire_time
= qemu_get_be64(f
);
1288 if (expire_time
!= -1) {
1289 qemu_mod_timer(ts
, expire_time
);
1295 static void timer_save(QEMUFile
*f
, void *opaque
)
1297 if (cpu_ticks_enabled
) {
1298 hw_error("cannot save state if virtual timers are running");
1300 qemu_put_be64(f
, cpu_ticks_offset
);
1301 qemu_put_be64(f
, ticks_per_sec
);
1302 qemu_put_be64(f
, cpu_clock_offset
);
1305 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1307 if (version_id
!= 1 && version_id
!= 2)
1309 if (cpu_ticks_enabled
) {
1312 cpu_ticks_offset
=qemu_get_be64(f
);
1313 ticks_per_sec
=qemu_get_be64(f
);
1314 if (version_id
== 2) {
1315 cpu_clock_offset
=qemu_get_be64(f
);
1321 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1322 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1324 static void host_alarm_handler(int host_signum
)
1328 #define DISP_FREQ 1000
1330 static int64_t delta_min
= INT64_MAX
;
1331 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1333 ti
= qemu_get_clock(vm_clock
);
1334 if (last_clock
!= 0) {
1335 delta
= ti
- last_clock
;
1336 if (delta
< delta_min
)
1338 if (delta
> delta_max
)
1341 if (++count
== DISP_FREQ
) {
1342 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1343 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1344 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1345 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1346 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1348 delta_min
= INT64_MAX
;
1357 alarm_has_dynticks(alarm_timer
) ||
1359 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1360 qemu_get_clock(vm_clock
))) ||
1361 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1362 qemu_get_clock(rt_clock
))) {
1364 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1365 SetEvent(data
->host_alarm
);
1367 CPUState
*env
= next_cpu
;
1369 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1372 /* stop the currently executing cpu because a timer occured */
1373 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1375 if (env
->kqemu_enabled
) {
1376 kqemu_cpu_interrupt(env
);
1384 static int64_t qemu_next_deadline(void)
1388 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1389 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1390 qemu_get_clock(vm_clock
);
1392 /* To avoid problems with overflow limit this to 2^32. */
1402 static uint64_t qemu_next_deadline_dyntick(void)
1410 delta
= (qemu_next_deadline() + 999) / 1000;
1412 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1413 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1414 qemu_get_clock(rt_clock
))*1000;
1415 if (rtdelta
< delta
)
1419 if (delta
< MIN_TIMER_REARM_US
)
1420 delta
= MIN_TIMER_REARM_US
;
1427 #if defined(__linux__)
1429 #define RTC_FREQ 1024
1431 static void enable_sigio_timer(int fd
)
1433 struct sigaction act
;
1436 sigfillset(&act
.sa_mask
);
1438 act
.sa_handler
= host_alarm_handler
;
1440 sigaction(SIGIO
, &act
, NULL
);
1441 fcntl(fd
, F_SETFL
, O_ASYNC
);
1442 fcntl(fd
, F_SETOWN
, getpid());
1445 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1447 struct hpet_info info
;
1450 fd
= open("/dev/hpet", O_RDONLY
);
1455 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1457 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1458 "error, but for better emulation accuracy type:\n"
1459 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1463 /* Check capabilities */
1464 r
= ioctl(fd
, HPET_INFO
, &info
);
1468 /* Enable periodic mode */
1469 r
= ioctl(fd
, HPET_EPI
, 0);
1470 if (info
.hi_flags
&& (r
< 0))
1473 /* Enable interrupt */
1474 r
= ioctl(fd
, HPET_IE_ON
, 0);
1478 enable_sigio_timer(fd
);
1479 t
->priv
= (void *)(long)fd
;
1487 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1489 int fd
= (long)t
->priv
;
1494 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1497 unsigned long current_rtc_freq
= 0;
1499 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1502 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1503 if (current_rtc_freq
!= RTC_FREQ
&&
1504 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1505 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1506 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1507 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1510 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1516 enable_sigio_timer(rtc_fd
);
1518 t
->priv
= (void *)(long)rtc_fd
;
1523 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1525 int rtc_fd
= (long)t
->priv
;
1530 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1534 struct sigaction act
;
1536 sigfillset(&act
.sa_mask
);
1538 act
.sa_handler
= host_alarm_handler
;
1540 sigaction(SIGALRM
, &act
, NULL
);
1542 ev
.sigev_value
.sival_int
= 0;
1543 ev
.sigev_notify
= SIGEV_SIGNAL
;
1544 ev
.sigev_signo
= SIGALRM
;
1546 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1547 perror("timer_create");
1549 /* disable dynticks */
1550 fprintf(stderr
, "Dynamic Ticks disabled\n");
1555 t
->priv
= (void *)host_timer
;
1560 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1562 timer_t host_timer
= (timer_t
)t
->priv
;
1564 timer_delete(host_timer
);
1567 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1569 timer_t host_timer
= (timer_t
)t
->priv
;
1570 struct itimerspec timeout
;
1571 int64_t nearest_delta_us
= INT64_MAX
;
1574 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1575 !active_timers
[QEMU_TIMER_VIRTUAL
])
1578 nearest_delta_us
= qemu_next_deadline_dyntick();
1580 /* check whether a timer is already running */
1581 if (timer_gettime(host_timer
, &timeout
)) {
1583 fprintf(stderr
, "Internal timer error: aborting\n");
1586 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1587 if (current_us
&& current_us
<= nearest_delta_us
)
1590 timeout
.it_interval
.tv_sec
= 0;
1591 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1592 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1593 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1594 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1596 fprintf(stderr
, "Internal timer error: aborting\n");
1601 #endif /* defined(__linux__) */
1603 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1605 struct sigaction act
;
1606 struct itimerval itv
;
1610 sigfillset(&act
.sa_mask
);
1612 act
.sa_handler
= host_alarm_handler
;
1614 sigaction(SIGALRM
, &act
, NULL
);
1616 itv
.it_interval
.tv_sec
= 0;
1617 /* for i386 kernel 2.6 to get 1 ms */
1618 itv
.it_interval
.tv_usec
= 999;
1619 itv
.it_value
.tv_sec
= 0;
1620 itv
.it_value
.tv_usec
= 10 * 1000;
1622 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1629 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1631 struct itimerval itv
;
1633 memset(&itv
, 0, sizeof(itv
));
1634 setitimer(ITIMER_REAL
, &itv
, NULL
);
1637 #endif /* !defined(_WIN32) */
1641 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1644 struct qemu_alarm_win32
*data
= t
->priv
;
1647 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1648 if (!data
->host_alarm
) {
1649 perror("Failed CreateEvent");
1653 memset(&tc
, 0, sizeof(tc
));
1654 timeGetDevCaps(&tc
, sizeof(tc
));
1656 if (data
->period
< tc
.wPeriodMin
)
1657 data
->period
= tc
.wPeriodMin
;
1659 timeBeginPeriod(data
->period
);
1661 flags
= TIME_CALLBACK_FUNCTION
;
1662 if (alarm_has_dynticks(t
))
1663 flags
|= TIME_ONESHOT
;
1665 flags
|= TIME_PERIODIC
;
1667 data
->timerId
= timeSetEvent(1, // interval (ms)
1668 data
->period
, // resolution
1669 host_alarm_handler
, // function
1670 (DWORD
)t
, // parameter
1673 if (!data
->timerId
) {
1674 perror("Failed to initialize win32 alarm timer");
1676 timeEndPeriod(data
->period
);
1677 CloseHandle(data
->host_alarm
);
1681 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1686 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1688 struct qemu_alarm_win32
*data
= t
->priv
;
1690 timeKillEvent(data
->timerId
);
1691 timeEndPeriod(data
->period
);
1693 CloseHandle(data
->host_alarm
);
1696 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1698 struct qemu_alarm_win32
*data
= t
->priv
;
1699 uint64_t nearest_delta_us
;
1701 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1702 !active_timers
[QEMU_TIMER_VIRTUAL
])
1705 nearest_delta_us
= qemu_next_deadline_dyntick();
1706 nearest_delta_us
/= 1000;
1708 timeKillEvent(data
->timerId
);
1710 data
->timerId
= timeSetEvent(1,
1714 TIME_ONESHOT
| TIME_PERIODIC
);
1716 if (!data
->timerId
) {
1717 perror("Failed to re-arm win32 alarm timer");
1719 timeEndPeriod(data
->period
);
1720 CloseHandle(data
->host_alarm
);
1727 static void init_timer_alarm(void)
1729 struct qemu_alarm_timer
*t
;
1732 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1733 t
= &alarm_timers
[i
];
1741 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1742 fprintf(stderr
, "Terminating\n");
1749 static void quit_timers(void)
1751 alarm_timer
->stop(alarm_timer
);
1755 /***********************************************************/
1756 /* host time/date access */
1757 void qemu_get_timedate(struct tm
*tm
, int offset
)
1764 if (rtc_date_offset
== -1) {
1768 ret
= localtime(&ti
);
1770 ti
-= rtc_date_offset
;
1774 memcpy(tm
, ret
, sizeof(struct tm
));
1777 int qemu_timedate_diff(struct tm
*tm
)
1781 if (rtc_date_offset
== -1)
1783 seconds
= mktimegm(tm
);
1785 seconds
= mktime(tm
);
1787 seconds
= mktimegm(tm
) + rtc_date_offset
;
1789 return seconds
- time(NULL
);
1792 /***********************************************************/
1793 /* character device */
1795 static void qemu_chr_event(CharDriverState
*s
, int event
)
1799 s
->chr_event(s
->handler_opaque
, event
);
1802 static void qemu_chr_reset_bh(void *opaque
)
1804 CharDriverState
*s
= opaque
;
1805 qemu_chr_event(s
, CHR_EVENT_RESET
);
1806 qemu_bh_delete(s
->bh
);
1810 void qemu_chr_reset(CharDriverState
*s
)
1812 if (s
->bh
== NULL
) {
1813 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1814 qemu_bh_schedule(s
->bh
);
1818 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1820 return s
->chr_write(s
, buf
, len
);
1823 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1827 return s
->chr_ioctl(s
, cmd
, arg
);
1830 int qemu_chr_can_read(CharDriverState
*s
)
1832 if (!s
->chr_can_read
)
1834 return s
->chr_can_read(s
->handler_opaque
);
1837 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1839 s
->chr_read(s
->handler_opaque
, buf
, len
);
1842 void qemu_chr_accept_input(CharDriverState
*s
)
1844 if (s
->chr_accept_input
)
1845 s
->chr_accept_input(s
);
1848 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1853 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1854 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1858 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1860 if (s
->chr_send_event
)
1861 s
->chr_send_event(s
, event
);
1864 void qemu_chr_add_handlers(CharDriverState
*s
,
1865 IOCanRWHandler
*fd_can_read
,
1866 IOReadHandler
*fd_read
,
1867 IOEventHandler
*fd_event
,
1870 s
->chr_can_read
= fd_can_read
;
1871 s
->chr_read
= fd_read
;
1872 s
->chr_event
= fd_event
;
1873 s
->handler_opaque
= opaque
;
1874 if (s
->chr_update_read_handler
)
1875 s
->chr_update_read_handler(s
);
1878 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1883 static CharDriverState
*qemu_chr_open_null(void)
1885 CharDriverState
*chr
;
1887 chr
= qemu_mallocz(sizeof(CharDriverState
));
1890 chr
->chr_write
= null_chr_write
;
1894 /* MUX driver for serial I/O splitting */
1895 static int term_timestamps
;
1896 static int64_t term_timestamps_start
;
1898 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1899 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1901 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1902 IOReadHandler
*chr_read
[MAX_MUX
];
1903 IOEventHandler
*chr_event
[MAX_MUX
];
1904 void *ext_opaque
[MAX_MUX
];
1905 CharDriverState
*drv
;
1906 unsigned char buffer
[MUX_BUFFER_SIZE
];
1910 int term_got_escape
;
1915 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1917 MuxDriver
*d
= chr
->opaque
;
1919 if (!term_timestamps
) {
1920 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1925 for(i
= 0; i
< len
; i
++) {
1926 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1927 if (buf
[i
] == '\n') {
1933 if (term_timestamps_start
== -1)
1934 term_timestamps_start
= ti
;
1935 ti
-= term_timestamps_start
;
1936 secs
= ti
/ 1000000000;
1937 snprintf(buf1
, sizeof(buf1
),
1938 "[%02d:%02d:%02d.%03d] ",
1942 (int)((ti
/ 1000000) % 1000));
1943 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1950 static char *mux_help
[] = {
1951 "% h print this help\n\r",
1952 "% x exit emulator\n\r",
1953 "% s save disk data back to file (if -snapshot)\n\r",
1954 "% t toggle console timestamps\n\r"
1955 "% b send break (magic sysrq)\n\r",
1956 "% c switch between console and monitor\n\r",
1961 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1962 static void mux_print_help(CharDriverState
*chr
)
1965 char ebuf
[15] = "Escape-Char";
1966 char cbuf
[50] = "\n\r";
1968 if (term_escape_char
> 0 && term_escape_char
< 26) {
1969 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1970 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1972 snprintf(cbuf
, sizeof(cbuf
),
1973 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1976 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1977 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1978 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1979 if (mux_help
[i
][j
] == '%')
1980 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1982 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1987 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1989 if (d
->term_got_escape
) {
1990 d
->term_got_escape
= 0;
1991 if (ch
== term_escape_char
)
1996 mux_print_help(chr
);
2000 char *term
= "QEMU: Terminated\n\r";
2001 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
2008 for (i
= 0; i
< nb_drives
; i
++) {
2009 bdrv_commit(drives_table
[i
].bdrv
);
2014 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2017 /* Switch to the next registered device */
2019 if (chr
->focus
>= d
->mux_cnt
)
2023 term_timestamps
= !term_timestamps
;
2024 term_timestamps_start
= -1;
2027 } else if (ch
== term_escape_char
) {
2028 d
->term_got_escape
= 1;
2036 static void mux_chr_accept_input(CharDriverState
*chr
)
2039 MuxDriver
*d
= chr
->opaque
;
2041 while (d
->prod
!= d
->cons
&&
2042 d
->chr_can_read
[m
] &&
2043 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
2044 d
->chr_read
[m
](d
->ext_opaque
[m
],
2045 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2049 static int mux_chr_can_read(void *opaque
)
2051 CharDriverState
*chr
= opaque
;
2052 MuxDriver
*d
= chr
->opaque
;
2054 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2056 if (d
->chr_can_read
[chr
->focus
])
2057 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2061 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2063 CharDriverState
*chr
= opaque
;
2064 MuxDriver
*d
= chr
->opaque
;
2068 mux_chr_accept_input (opaque
);
2070 for(i
= 0; i
< size
; i
++)
2071 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2072 if (d
->prod
== d
->cons
&&
2073 d
->chr_can_read
[m
] &&
2074 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2075 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2077 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2081 static void mux_chr_event(void *opaque
, int event
)
2083 CharDriverState
*chr
= opaque
;
2084 MuxDriver
*d
= chr
->opaque
;
2087 /* Send the event to all registered listeners */
2088 for (i
= 0; i
< d
->mux_cnt
; i
++)
2089 if (d
->chr_event
[i
])
2090 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2093 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2095 MuxDriver
*d
= chr
->opaque
;
2097 if (d
->mux_cnt
>= MAX_MUX
) {
2098 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2101 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2102 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2103 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2104 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2105 /* Fix up the real driver with mux routines */
2106 if (d
->mux_cnt
== 0) {
2107 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2108 mux_chr_event
, chr
);
2110 chr
->focus
= d
->mux_cnt
;
2114 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2116 CharDriverState
*chr
;
2119 chr
= qemu_mallocz(sizeof(CharDriverState
));
2122 d
= qemu_mallocz(sizeof(MuxDriver
));
2131 chr
->chr_write
= mux_chr_write
;
2132 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2133 chr
->chr_accept_input
= mux_chr_accept_input
;
2140 static void socket_cleanup(void)
2145 static int socket_init(void)
2150 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2152 err
= WSAGetLastError();
2153 fprintf(stderr
, "WSAStartup: %d\n", err
);
2156 atexit(socket_cleanup
);
2160 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2166 ret
= send(fd
, buf
, len
, 0);
2169 errno
= WSAGetLastError();
2170 if (errno
!= WSAEWOULDBLOCK
) {
2173 } else if (ret
== 0) {
2183 void socket_set_nonblock(int fd
)
2185 unsigned long opt
= 1;
2186 ioctlsocket(fd
, FIONBIO
, &opt
);
2191 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2197 ret
= write(fd
, buf
, len
);
2199 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2201 } else if (ret
== 0) {
2211 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2213 return unix_write(fd
, buf
, len1
);
2216 void socket_set_nonblock(int fd
)
2219 f
= fcntl(fd
, F_GETFL
);
2220 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2222 #endif /* !_WIN32 */
2231 #define STDIO_MAX_CLIENTS 1
2232 static int stdio_nb_clients
= 0;
2234 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2236 FDCharDriver
*s
= chr
->opaque
;
2237 return unix_write(s
->fd_out
, buf
, len
);
2240 static int fd_chr_read_poll(void *opaque
)
2242 CharDriverState
*chr
= opaque
;
2243 FDCharDriver
*s
= chr
->opaque
;
2245 s
->max_size
= qemu_chr_can_read(chr
);
2249 static void fd_chr_read(void *opaque
)
2251 CharDriverState
*chr
= opaque
;
2252 FDCharDriver
*s
= chr
->opaque
;
2257 if (len
> s
->max_size
)
2261 size
= read(s
->fd_in
, buf
, len
);
2263 /* FD has been closed. Remove it from the active list. */
2264 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2268 qemu_chr_read(chr
, buf
, size
);
2272 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2274 FDCharDriver
*s
= chr
->opaque
;
2276 if (s
->fd_in
>= 0) {
2277 if (nographic
&& s
->fd_in
== 0) {
2279 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2280 fd_chr_read
, NULL
, chr
);
2285 static void fd_chr_close(struct CharDriverState
*chr
)
2287 FDCharDriver
*s
= chr
->opaque
;
2289 if (s
->fd_in
>= 0) {
2290 if (nographic
&& s
->fd_in
== 0) {
2292 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2299 /* open a character device to a unix fd */
2300 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2302 CharDriverState
*chr
;
2305 chr
= qemu_mallocz(sizeof(CharDriverState
));
2308 s
= qemu_mallocz(sizeof(FDCharDriver
));
2316 chr
->chr_write
= fd_chr_write
;
2317 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2318 chr
->chr_close
= fd_chr_close
;
2320 qemu_chr_reset(chr
);
2325 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2329 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2332 return qemu_chr_open_fd(-1, fd_out
);
2335 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2338 char filename_in
[256], filename_out
[256];
2340 snprintf(filename_in
, 256, "%s.in", filename
);
2341 snprintf(filename_out
, 256, "%s.out", filename
);
2342 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2343 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2344 if (fd_in
< 0 || fd_out
< 0) {
2349 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2353 return qemu_chr_open_fd(fd_in
, fd_out
);
2357 /* for STDIO, we handle the case where several clients use it
2360 #define TERM_FIFO_MAX_SIZE 1
2362 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2363 static int term_fifo_size
;
2365 static int stdio_read_poll(void *opaque
)
2367 CharDriverState
*chr
= opaque
;
2369 /* try to flush the queue if needed */
2370 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2371 qemu_chr_read(chr
, term_fifo
, 1);
2374 /* see if we can absorb more chars */
2375 if (term_fifo_size
== 0)
2381 static void stdio_read(void *opaque
)
2385 CharDriverState
*chr
= opaque
;
2387 size
= read(0, buf
, 1);
2389 /* stdin has been closed. Remove it from the active list. */
2390 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2394 if (qemu_chr_can_read(chr
) > 0) {
2395 qemu_chr_read(chr
, buf
, 1);
2396 } else if (term_fifo_size
== 0) {
2397 term_fifo
[term_fifo_size
++] = buf
[0];
2402 /* init terminal so that we can grab keys */
2403 static struct termios oldtty
;
2404 static int old_fd0_flags
;
2405 static int term_atexit_done
;
2407 static void term_exit(void)
2409 tcsetattr (0, TCSANOW
, &oldtty
);
2410 fcntl(0, F_SETFL
, old_fd0_flags
);
2413 static void term_init(void)
2417 tcgetattr (0, &tty
);
2419 old_fd0_flags
= fcntl(0, F_GETFL
);
2421 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2422 |INLCR
|IGNCR
|ICRNL
|IXON
);
2423 tty
.c_oflag
|= OPOST
;
2424 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2425 /* if graphical mode, we allow Ctrl-C handling */
2427 tty
.c_lflag
&= ~ISIG
;
2428 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2431 tty
.c_cc
[VTIME
] = 0;
2433 tcsetattr (0, TCSANOW
, &tty
);
2435 if (!term_atexit_done
++)
2438 fcntl(0, F_SETFL
, O_NONBLOCK
);
2441 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2445 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2449 static CharDriverState
*qemu_chr_open_stdio(void)
2451 CharDriverState
*chr
;
2453 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2455 chr
= qemu_chr_open_fd(0, 1);
2456 chr
->chr_close
= qemu_chr_close_stdio
;
2457 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2465 /* Once Solaris has openpty(), this is going to be removed. */
2466 int openpty(int *amaster
, int *aslave
, char *name
,
2467 struct termios
*termp
, struct winsize
*winp
)
2470 int mfd
= -1, sfd
= -1;
2472 *amaster
= *aslave
= -1;
2474 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2478 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2481 if ((slave
= ptsname(mfd
)) == NULL
)
2484 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2487 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2488 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2496 ioctl(sfd
, TIOCSWINSZ
, winp
);
2507 void cfmakeraw (struct termios
*termios_p
)
2509 termios_p
->c_iflag
&=
2510 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2511 termios_p
->c_oflag
&= ~OPOST
;
2512 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2513 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2514 termios_p
->c_cflag
|= CS8
;
2516 termios_p
->c_cc
[VMIN
] = 0;
2517 termios_p
->c_cc
[VTIME
] = 0;
2521 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2522 || defined(__NetBSD__) || defined(__OpenBSD__)
2532 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2533 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2535 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2537 PtyCharDriver
*s
= chr
->opaque
;
2539 if (!s
->connected
) {
2540 /* guest sends data, check for (re-)connect */
2541 pty_chr_update_read_handler(chr
);
2544 return unix_write(s
->fd
, buf
, len
);
2547 static int pty_chr_read_poll(void *opaque
)
2549 CharDriverState
*chr
= opaque
;
2550 PtyCharDriver
*s
= chr
->opaque
;
2552 s
->read_bytes
= qemu_chr_can_read(chr
);
2553 return s
->read_bytes
;
2556 static void pty_chr_read(void *opaque
)
2558 CharDriverState
*chr
= opaque
;
2559 PtyCharDriver
*s
= chr
->opaque
;
2564 if (len
> s
->read_bytes
)
2565 len
= s
->read_bytes
;
2568 size
= read(s
->fd
, buf
, len
);
2569 if ((size
== -1 && errno
== EIO
) ||
2571 pty_chr_state(chr
, 0);
2575 pty_chr_state(chr
, 1);
2576 qemu_chr_read(chr
, buf
, size
);
2580 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2582 PtyCharDriver
*s
= chr
->opaque
;
2584 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2585 pty_chr_read
, NULL
, chr
);
2588 * Short timeout here: just need wait long enougth that qemu makes
2589 * it through the poll loop once. When reconnected we want a
2590 * short timeout so we notice it almost instantly. Otherwise
2591 * read() gives us -EIO instantly, making pty_chr_state() reset the
2592 * timeout to the normal (much longer) poll interval before the
2595 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2598 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2600 PtyCharDriver
*s
= chr
->opaque
;
2603 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2606 /* (re-)connect poll interval for idle guests: once per second.
2607 * We check more frequently in case the guests sends data to
2608 * the virtual device linked to our pty. */
2609 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2612 qemu_chr_reset(chr
);
2617 static void pty_chr_timer(void *opaque
)
2619 struct CharDriverState
*chr
= opaque
;
2620 PtyCharDriver
*s
= chr
->opaque
;
2625 /* If we arrive here without polling being cleared due
2626 * read returning -EIO, then we are (re-)connected */
2627 pty_chr_state(chr
, 1);
2632 pty_chr_update_read_handler(chr
);
2635 static void pty_chr_close(struct CharDriverState
*chr
)
2637 PtyCharDriver
*s
= chr
->opaque
;
2639 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2644 static CharDriverState
*qemu_chr_open_pty(void)
2646 CharDriverState
*chr
;
2650 #if defined(__OpenBSD__)
2651 char pty_name
[PATH_MAX
];
2652 #define q_ptsname(x) pty_name
2654 char *pty_name
= NULL
;
2655 #define q_ptsname(x) ptsname(x)
2658 chr
= qemu_mallocz(sizeof(CharDriverState
));
2661 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2667 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2671 /* Set raw attributes on the pty. */
2673 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2676 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2679 chr
->chr_write
= pty_chr_write
;
2680 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2681 chr
->chr_close
= pty_chr_close
;
2683 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2688 static void tty_serial_init(int fd
, int speed
,
2689 int parity
, int data_bits
, int stop_bits
)
2695 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2696 speed
, parity
, data_bits
, stop_bits
);
2698 tcgetattr (fd
, &tty
);
2701 if (speed
<= 50 * MARGIN
)
2703 else if (speed
<= 75 * MARGIN
)
2705 else if (speed
<= 300 * MARGIN
)
2707 else if (speed
<= 600 * MARGIN
)
2709 else if (speed
<= 1200 * MARGIN
)
2711 else if (speed
<= 2400 * MARGIN
)
2713 else if (speed
<= 4800 * MARGIN
)
2715 else if (speed
<= 9600 * MARGIN
)
2717 else if (speed
<= 19200 * MARGIN
)
2719 else if (speed
<= 38400 * MARGIN
)
2721 else if (speed
<= 57600 * MARGIN
)
2723 else if (speed
<= 115200 * MARGIN
)
2728 cfsetispeed(&tty
, spd
);
2729 cfsetospeed(&tty
, spd
);
2731 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2732 |INLCR
|IGNCR
|ICRNL
|IXON
);
2733 tty
.c_oflag
|= OPOST
;
2734 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2735 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2756 tty
.c_cflag
|= PARENB
;
2759 tty
.c_cflag
|= PARENB
| PARODD
;
2763 tty
.c_cflag
|= CSTOPB
;
2765 tcsetattr (fd
, TCSANOW
, &tty
);
2768 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2770 FDCharDriver
*s
= chr
->opaque
;
2773 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2775 QEMUSerialSetParams
*ssp
= arg
;
2776 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2777 ssp
->data_bits
, ssp
->stop_bits
);
2780 case CHR_IOCTL_SERIAL_SET_BREAK
:
2782 int enable
= *(int *)arg
;
2784 tcsendbreak(s
->fd_in
, 1);
2787 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2790 int *targ
= (int *)arg
;
2791 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2793 if (sarg
| TIOCM_CTS
)
2794 *targ
|= CHR_TIOCM_CTS
;
2795 if (sarg
| TIOCM_CAR
)
2796 *targ
|= CHR_TIOCM_CAR
;
2797 if (sarg
| TIOCM_DSR
)
2798 *targ
|= CHR_TIOCM_DSR
;
2799 if (sarg
| TIOCM_RI
)
2800 *targ
|= CHR_TIOCM_RI
;
2801 if (sarg
| TIOCM_DTR
)
2802 *targ
|= CHR_TIOCM_DTR
;
2803 if (sarg
| TIOCM_RTS
)
2804 *targ
|= CHR_TIOCM_RTS
;
2807 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2809 int sarg
= *(int *)arg
;
2811 if (sarg
| CHR_TIOCM_DTR
)
2813 if (sarg
| CHR_TIOCM_RTS
)
2815 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2824 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2826 CharDriverState
*chr
;
2829 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2830 tty_serial_init(fd
, 115200, 'N', 8, 1);
2831 chr
= qemu_chr_open_fd(fd
, fd
);
2836 chr
->chr_ioctl
= tty_serial_ioctl
;
2837 qemu_chr_reset(chr
);
2840 #else /* ! __linux__ && ! __sun__ */
2841 static CharDriverState
*qemu_chr_open_pty(void)
2845 #endif /* __linux__ || __sun__ */
2847 #if defined(__linux__)
2851 } ParallelCharDriver
;
2853 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2855 if (s
->mode
!= mode
) {
2857 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2864 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2866 ParallelCharDriver
*drv
= chr
->opaque
;
2871 case CHR_IOCTL_PP_READ_DATA
:
2872 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2874 *(uint8_t *)arg
= b
;
2876 case CHR_IOCTL_PP_WRITE_DATA
:
2877 b
= *(uint8_t *)arg
;
2878 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2881 case CHR_IOCTL_PP_READ_CONTROL
:
2882 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2884 /* Linux gives only the lowest bits, and no way to know data
2885 direction! For better compatibility set the fixed upper
2887 *(uint8_t *)arg
= b
| 0xc0;
2889 case CHR_IOCTL_PP_WRITE_CONTROL
:
2890 b
= *(uint8_t *)arg
;
2891 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2894 case CHR_IOCTL_PP_READ_STATUS
:
2895 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2897 *(uint8_t *)arg
= b
;
2899 case CHR_IOCTL_PP_DATA_DIR
:
2900 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2903 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2904 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2905 struct ParallelIOArg
*parg
= arg
;
2906 int n
= read(fd
, parg
->buffer
, parg
->count
);
2907 if (n
!= parg
->count
) {
2912 case CHR_IOCTL_PP_EPP_READ
:
2913 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2914 struct ParallelIOArg
*parg
= arg
;
2915 int n
= read(fd
, parg
->buffer
, parg
->count
);
2916 if (n
!= parg
->count
) {
2921 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2922 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2923 struct ParallelIOArg
*parg
= arg
;
2924 int n
= write(fd
, parg
->buffer
, parg
->count
);
2925 if (n
!= parg
->count
) {
2930 case CHR_IOCTL_PP_EPP_WRITE
:
2931 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2932 struct ParallelIOArg
*parg
= arg
;
2933 int n
= write(fd
, parg
->buffer
, parg
->count
);
2934 if (n
!= parg
->count
) {
2945 static void pp_close(CharDriverState
*chr
)
2947 ParallelCharDriver
*drv
= chr
->opaque
;
2950 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2951 ioctl(fd
, PPRELEASE
);
2956 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2958 CharDriverState
*chr
;
2959 ParallelCharDriver
*drv
;
2962 TFR(fd
= open(filename
, O_RDWR
));
2966 if (ioctl(fd
, PPCLAIM
) < 0) {
2971 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2977 drv
->mode
= IEEE1284_MODE_COMPAT
;
2979 chr
= qemu_mallocz(sizeof(CharDriverState
));
2985 chr
->chr_write
= null_chr_write
;
2986 chr
->chr_ioctl
= pp_ioctl
;
2987 chr
->chr_close
= pp_close
;
2990 qemu_chr_reset(chr
);
2994 #endif /* __linux__ */
3000 HANDLE hcom
, hrecv
, hsend
;
3001 OVERLAPPED orecv
, osend
;
3006 #define NSENDBUF 2048
3007 #define NRECVBUF 2048
3008 #define MAXCONNECT 1
3009 #define NTIMEOUT 5000
3011 static int win_chr_poll(void *opaque
);
3012 static int win_chr_pipe_poll(void *opaque
);
3014 static void win_chr_close(CharDriverState
*chr
)
3016 WinCharState
*s
= chr
->opaque
;
3019 CloseHandle(s
->hsend
);
3023 CloseHandle(s
->hrecv
);
3027 CloseHandle(s
->hcom
);
3031 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
3033 qemu_del_polling_cb(win_chr_poll
, chr
);
3036 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
3038 WinCharState
*s
= chr
->opaque
;
3040 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
3045 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3047 fprintf(stderr
, "Failed CreateEvent\n");
3050 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3052 fprintf(stderr
, "Failed CreateEvent\n");
3056 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
3057 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3058 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3059 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3064 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3065 fprintf(stderr
, "Failed SetupComm\n");
3069 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3070 size
= sizeof(COMMCONFIG
);
3071 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3072 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3073 CommConfigDialog(filename
, NULL
, &comcfg
);
3075 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3076 fprintf(stderr
, "Failed SetCommState\n");
3080 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3081 fprintf(stderr
, "Failed SetCommMask\n");
3085 cto
.ReadIntervalTimeout
= MAXDWORD
;
3086 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3087 fprintf(stderr
, "Failed SetCommTimeouts\n");
3091 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3092 fprintf(stderr
, "Failed ClearCommError\n");
3095 qemu_add_polling_cb(win_chr_poll
, chr
);
3103 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3105 WinCharState
*s
= chr
->opaque
;
3106 DWORD len
, ret
, size
, err
;
3109 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3110 s
->osend
.hEvent
= s
->hsend
;
3113 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3115 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3117 err
= GetLastError();
3118 if (err
== ERROR_IO_PENDING
) {
3119 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3137 static int win_chr_read_poll(CharDriverState
*chr
)
3139 WinCharState
*s
= chr
->opaque
;
3141 s
->max_size
= qemu_chr_can_read(chr
);
3145 static void win_chr_readfile(CharDriverState
*chr
)
3147 WinCharState
*s
= chr
->opaque
;
3152 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3153 s
->orecv
.hEvent
= s
->hrecv
;
3154 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3156 err
= GetLastError();
3157 if (err
== ERROR_IO_PENDING
) {
3158 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3163 qemu_chr_read(chr
, buf
, size
);
3167 static void win_chr_read(CharDriverState
*chr
)
3169 WinCharState
*s
= chr
->opaque
;
3171 if (s
->len
> s
->max_size
)
3172 s
->len
= s
->max_size
;
3176 win_chr_readfile(chr
);
3179 static int win_chr_poll(void *opaque
)
3181 CharDriverState
*chr
= opaque
;
3182 WinCharState
*s
= chr
->opaque
;
3186 ClearCommError(s
->hcom
, &comerr
, &status
);
3187 if (status
.cbInQue
> 0) {
3188 s
->len
= status
.cbInQue
;
3189 win_chr_read_poll(chr
);
3196 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3198 CharDriverState
*chr
;
3201 chr
= qemu_mallocz(sizeof(CharDriverState
));
3204 s
= qemu_mallocz(sizeof(WinCharState
));
3210 chr
->chr_write
= win_chr_write
;
3211 chr
->chr_close
= win_chr_close
;
3213 if (win_chr_init(chr
, filename
) < 0) {
3218 qemu_chr_reset(chr
);
3222 static int win_chr_pipe_poll(void *opaque
)
3224 CharDriverState
*chr
= opaque
;
3225 WinCharState
*s
= chr
->opaque
;
3228 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3231 win_chr_read_poll(chr
);
3238 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3240 WinCharState
*s
= chr
->opaque
;
3248 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3250 fprintf(stderr
, "Failed CreateEvent\n");
3253 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3255 fprintf(stderr
, "Failed CreateEvent\n");
3259 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3260 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3261 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3263 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3264 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3265 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3270 ZeroMemory(&ov
, sizeof(ov
));
3271 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3272 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3274 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3278 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3280 fprintf(stderr
, "Failed GetOverlappedResult\n");
3282 CloseHandle(ov
.hEvent
);
3289 CloseHandle(ov
.hEvent
);
3292 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3301 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3303 CharDriverState
*chr
;
3306 chr
= qemu_mallocz(sizeof(CharDriverState
));
3309 s
= qemu_mallocz(sizeof(WinCharState
));
3315 chr
->chr_write
= win_chr_write
;
3316 chr
->chr_close
= win_chr_close
;
3318 if (win_chr_pipe_init(chr
, filename
) < 0) {
3323 qemu_chr_reset(chr
);
3327 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3329 CharDriverState
*chr
;
3332 chr
= qemu_mallocz(sizeof(CharDriverState
));
3335 s
= qemu_mallocz(sizeof(WinCharState
));
3342 chr
->chr_write
= win_chr_write
;
3343 qemu_chr_reset(chr
);
3347 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3349 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3352 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3356 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3357 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3358 if (fd_out
== INVALID_HANDLE_VALUE
)
3361 return qemu_chr_open_win_file(fd_out
);
3363 #endif /* !_WIN32 */
3365 /***********************************************************/
3366 /* UDP Net console */
3370 struct sockaddr_in daddr
;
3377 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3379 NetCharDriver
*s
= chr
->opaque
;
3381 return sendto(s
->fd
, buf
, len
, 0,
3382 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3385 static int udp_chr_read_poll(void *opaque
)
3387 CharDriverState
*chr
= opaque
;
3388 NetCharDriver
*s
= chr
->opaque
;
3390 s
->max_size
= qemu_chr_can_read(chr
);
3392 /* If there were any stray characters in the queue process them
3395 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3396 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3398 s
->max_size
= qemu_chr_can_read(chr
);
3403 static void udp_chr_read(void *opaque
)
3405 CharDriverState
*chr
= opaque
;
3406 NetCharDriver
*s
= chr
->opaque
;
3408 if (s
->max_size
== 0)
3410 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3411 s
->bufptr
= s
->bufcnt
;
3416 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3417 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3419 s
->max_size
= qemu_chr_can_read(chr
);
3423 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3425 NetCharDriver
*s
= chr
->opaque
;
3428 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3429 udp_chr_read
, NULL
, chr
);
3434 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3436 int parse_host_src_port(struct sockaddr_in
*haddr
,
3437 struct sockaddr_in
*saddr
,
3440 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3442 CharDriverState
*chr
= NULL
;
3443 NetCharDriver
*s
= NULL
;
3445 struct sockaddr_in saddr
;
3447 chr
= qemu_mallocz(sizeof(CharDriverState
));
3450 s
= qemu_mallocz(sizeof(NetCharDriver
));
3454 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3456 perror("socket(PF_INET, SOCK_DGRAM)");
3460 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3461 printf("Could not parse: %s\n", def
);
3465 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3475 chr
->chr_write
= udp_chr_write
;
3476 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3489 /***********************************************************/
3490 /* TCP Net console */
3501 static void tcp_chr_accept(void *opaque
);
3503 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3505 TCPCharDriver
*s
= chr
->opaque
;
3507 return send_all(s
->fd
, buf
, len
);
3509 /* XXX: indicate an error ? */
3514 static int tcp_chr_read_poll(void *opaque
)
3516 CharDriverState
*chr
= opaque
;
3517 TCPCharDriver
*s
= chr
->opaque
;
3520 s
->max_size
= qemu_chr_can_read(chr
);
3525 #define IAC_BREAK 243
3526 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3528 uint8_t *buf
, int *size
)
3530 /* Handle any telnet client's basic IAC options to satisfy char by
3531 * char mode with no echo. All IAC options will be removed from
3532 * the buf and the do_telnetopt variable will be used to track the
3533 * state of the width of the IAC information.
3535 * IAC commands come in sets of 3 bytes with the exception of the
3536 * "IAC BREAK" command and the double IAC.
3542 for (i
= 0; i
< *size
; i
++) {
3543 if (s
->do_telnetopt
> 1) {
3544 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3545 /* Double IAC means send an IAC */
3549 s
->do_telnetopt
= 1;
3551 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3552 /* Handle IAC break commands by sending a serial break */
3553 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3558 if (s
->do_telnetopt
>= 4) {
3559 s
->do_telnetopt
= 1;
3562 if ((unsigned char)buf
[i
] == IAC
) {
3563 s
->do_telnetopt
= 2;
3574 static void tcp_chr_read(void *opaque
)
3576 CharDriverState
*chr
= opaque
;
3577 TCPCharDriver
*s
= chr
->opaque
;
3581 if (!s
->connected
|| s
->max_size
<= 0)
3584 if (len
> s
->max_size
)
3586 size
= recv(s
->fd
, buf
, len
, 0);
3588 /* connection closed */
3590 if (s
->listen_fd
>= 0) {
3591 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3593 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3596 } else if (size
> 0) {
3597 if (s
->do_telnetopt
)
3598 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3600 qemu_chr_read(chr
, buf
, size
);
3604 static void tcp_chr_connect(void *opaque
)
3606 CharDriverState
*chr
= opaque
;
3607 TCPCharDriver
*s
= chr
->opaque
;
3610 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3611 tcp_chr_read
, NULL
, chr
);
3612 qemu_chr_reset(chr
);
3615 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3616 static void tcp_chr_telnet_init(int fd
)
3619 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3620 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3621 send(fd
, (char *)buf
, 3, 0);
3622 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3623 send(fd
, (char *)buf
, 3, 0);
3624 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3625 send(fd
, (char *)buf
, 3, 0);
3626 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3627 send(fd
, (char *)buf
, 3, 0);
3630 static void socket_set_nodelay(int fd
)
3633 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3636 static void tcp_chr_accept(void *opaque
)
3638 CharDriverState
*chr
= opaque
;
3639 TCPCharDriver
*s
= chr
->opaque
;
3640 struct sockaddr_in saddr
;
3642 struct sockaddr_un uaddr
;
3644 struct sockaddr
*addr
;
3651 len
= sizeof(uaddr
);
3652 addr
= (struct sockaddr
*)&uaddr
;
3656 len
= sizeof(saddr
);
3657 addr
= (struct sockaddr
*)&saddr
;
3659 fd
= accept(s
->listen_fd
, addr
, &len
);
3660 if (fd
< 0 && errno
!= EINTR
) {
3662 } else if (fd
>= 0) {
3663 if (s
->do_telnetopt
)
3664 tcp_chr_telnet_init(fd
);
3668 socket_set_nonblock(fd
);
3670 socket_set_nodelay(fd
);
3672 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3673 tcp_chr_connect(chr
);
3676 static void tcp_chr_close(CharDriverState
*chr
)
3678 TCPCharDriver
*s
= chr
->opaque
;
3681 if (s
->listen_fd
>= 0)
3682 closesocket(s
->listen_fd
);
3686 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3690 CharDriverState
*chr
= NULL
;
3691 TCPCharDriver
*s
= NULL
;
3692 int fd
= -1, ret
, err
, val
;
3694 int is_waitconnect
= 1;
3697 struct sockaddr_in saddr
;
3699 struct sockaddr_un uaddr
;
3701 struct sockaddr
*addr
;
3706 addr
= (struct sockaddr
*)&uaddr
;
3707 addrlen
= sizeof(uaddr
);
3708 if (parse_unix_path(&uaddr
, host_str
) < 0)
3713 addr
= (struct sockaddr
*)&saddr
;
3714 addrlen
= sizeof(saddr
);
3715 if (parse_host_port(&saddr
, host_str
) < 0)
3720 while((ptr
= strchr(ptr
,','))) {
3722 if (!strncmp(ptr
,"server",6)) {
3724 } else if (!strncmp(ptr
,"nowait",6)) {
3726 } else if (!strncmp(ptr
,"nodelay",6)) {
3729 printf("Unknown option: %s\n", ptr
);
3736 chr
= qemu_mallocz(sizeof(CharDriverState
));
3739 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3745 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3748 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3753 if (!is_waitconnect
)
3754 socket_set_nonblock(fd
);
3759 s
->is_unix
= is_unix
;
3760 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3763 chr
->chr_write
= tcp_chr_write
;
3764 chr
->chr_close
= tcp_chr_close
;
3767 /* allow fast reuse */
3771 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3777 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3780 ret
= bind(fd
, addr
, addrlen
);
3784 ret
= listen(fd
, 0);
3789 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3791 s
->do_telnetopt
= 1;
3794 ret
= connect(fd
, addr
, addrlen
);
3796 err
= socket_error();
3797 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3798 } else if (err
== EINPROGRESS
) {
3801 } else if (err
== WSAEALREADY
) {
3813 socket_set_nodelay(fd
);
3815 tcp_chr_connect(chr
);
3817 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3820 if (is_listen
&& is_waitconnect
) {
3821 printf("QEMU waiting for connection on: %s\n", host_str
);
3822 tcp_chr_accept(chr
);
3823 socket_set_nonblock(s
->listen_fd
);
3835 CharDriverState
*qemu_chr_open(const char *filename
)
3839 if (!strcmp(filename
, "vc")) {
3840 return text_console_init(&display_state
, 0);
3841 } else if (strstart(filename
, "vc:", &p
)) {
3842 return text_console_init(&display_state
, p
);
3843 } else if (!strcmp(filename
, "null")) {
3844 return qemu_chr_open_null();
3846 if (strstart(filename
, "tcp:", &p
)) {
3847 return qemu_chr_open_tcp(p
, 0, 0);
3849 if (strstart(filename
, "telnet:", &p
)) {
3850 return qemu_chr_open_tcp(p
, 1, 0);
3852 if (strstart(filename
, "udp:", &p
)) {
3853 return qemu_chr_open_udp(p
);
3855 if (strstart(filename
, "mon:", &p
)) {
3856 CharDriverState
*drv
= qemu_chr_open(p
);
3858 drv
= qemu_chr_open_mux(drv
);
3859 monitor_init(drv
, !nographic
);
3862 printf("Unable to open driver: %s\n", p
);
3866 if (strstart(filename
, "unix:", &p
)) {
3867 return qemu_chr_open_tcp(p
, 0, 1);
3868 } else if (strstart(filename
, "file:", &p
)) {
3869 return qemu_chr_open_file_out(p
);
3870 } else if (strstart(filename
, "pipe:", &p
)) {
3871 return qemu_chr_open_pipe(p
);
3872 } else if (!strcmp(filename
, "pty")) {
3873 return qemu_chr_open_pty();
3874 } else if (!strcmp(filename
, "stdio")) {
3875 return qemu_chr_open_stdio();
3877 #if defined(__linux__)
3878 if (strstart(filename
, "/dev/parport", NULL
)) {
3879 return qemu_chr_open_pp(filename
);
3882 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3883 || defined(__NetBSD__) || defined(__OpenBSD__)
3884 if (strstart(filename
, "/dev/", NULL
)) {
3885 return qemu_chr_open_tty(filename
);
3889 if (strstart(filename
, "COM", NULL
)) {
3890 return qemu_chr_open_win(filename
);
3892 if (strstart(filename
, "pipe:", &p
)) {
3893 return qemu_chr_open_win_pipe(p
);
3895 if (strstart(filename
, "con:", NULL
)) {
3896 return qemu_chr_open_win_con(filename
);
3898 if (strstart(filename
, "file:", &p
)) {
3899 return qemu_chr_open_win_file_out(p
);
3902 #ifdef CONFIG_BRLAPI
3903 if (!strcmp(filename
, "braille")) {
3904 return chr_baum_init();
3912 void qemu_chr_close(CharDriverState
*chr
)
3915 chr
->chr_close(chr
);
3919 /***********************************************************/
3920 /* network device redirectors */
3922 __attribute__ (( unused
))
3923 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3927 for(i
=0;i
<size
;i
+=16) {
3931 fprintf(f
, "%08x ", i
);
3934 fprintf(f
, " %02x", buf
[i
+j
]);
3939 for(j
=0;j
<len
;j
++) {
3941 if (c
< ' ' || c
> '~')
3943 fprintf(f
, "%c", c
);
3949 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3956 offset
= strtol(p
, &last_char
, 0);
3957 if (0 == errno
&& '\0' == *last_char
&&
3958 offset
>= 0 && offset
<= 0xFFFFFF) {
3959 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3960 macaddr
[4] = (offset
& 0xFF00) >> 8;
3961 macaddr
[5] = offset
& 0xFF;
3964 for(i
= 0; i
< 6; i
++) {
3965 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3970 if (*p
!= ':' && *p
!= '-')
3981 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3986 p1
= strchr(p
, sep
);
3992 if (len
> buf_size
- 1)
3994 memcpy(buf
, p
, len
);
4001 int parse_host_src_port(struct sockaddr_in
*haddr
,
4002 struct sockaddr_in
*saddr
,
4003 const char *input_str
)
4005 char *str
= strdup(input_str
);
4006 char *host_str
= str
;
4011 * Chop off any extra arguments at the end of the string which
4012 * would start with a comma, then fill in the src port information
4013 * if it was provided else use the "any address" and "any port".
4015 if ((ptr
= strchr(str
,',')))
4018 if ((src_str
= strchr(input_str
,'@'))) {
4023 if (parse_host_port(haddr
, host_str
) < 0)
4026 if (!src_str
|| *src_str
== '\0')
4029 if (parse_host_port(saddr
, src_str
) < 0)
4040 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
4048 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4050 saddr
->sin_family
= AF_INET
;
4051 if (buf
[0] == '\0') {
4052 saddr
->sin_addr
.s_addr
= 0;
4054 if (isdigit(buf
[0])) {
4055 if (!inet_aton(buf
, &saddr
->sin_addr
))
4058 if ((he
= gethostbyname(buf
)) == NULL
)
4060 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4063 port
= strtol(p
, (char **)&r
, 0);
4066 saddr
->sin_port
= htons(port
);
4071 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4076 len
= MIN(108, strlen(str
));
4077 p
= strchr(str
, ',');
4079 len
= MIN(len
, p
- str
);
4081 memset(uaddr
, 0, sizeof(*uaddr
));
4083 uaddr
->sun_family
= AF_UNIX
;
4084 memcpy(uaddr
->sun_path
, str
, len
);
4090 /* find or alloc a new VLAN */
4091 VLANState
*qemu_find_vlan(int id
)
4093 VLANState
**pvlan
, *vlan
;
4094 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4098 vlan
= qemu_mallocz(sizeof(VLANState
));
4103 pvlan
= &first_vlan
;
4104 while (*pvlan
!= NULL
)
4105 pvlan
= &(*pvlan
)->next
;
4110 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4111 IOReadHandler
*fd_read
,
4112 IOCanRWHandler
*fd_can_read
,
4115 VLANClientState
*vc
, **pvc
;
4116 vc
= qemu_mallocz(sizeof(VLANClientState
));
4119 vc
->fd_read
= fd_read
;
4120 vc
->fd_can_read
= fd_can_read
;
4121 vc
->opaque
= opaque
;
4125 pvc
= &vlan
->first_client
;
4126 while (*pvc
!= NULL
)
4127 pvc
= &(*pvc
)->next
;
4132 void qemu_del_vlan_client(VLANClientState
*vc
)
4134 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4136 while (*pvc
!= NULL
)
4142 pvc
= &(*pvc
)->next
;
4145 int qemu_can_send_packet(VLANClientState
*vc1
)
4147 VLANState
*vlan
= vc1
->vlan
;
4148 VLANClientState
*vc
;
4150 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4152 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4159 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4161 VLANState
*vlan
= vc1
->vlan
;
4162 VLANClientState
*vc
;
4166 printf("vlan %d send:\n", vlan
->id
);
4167 hex_dump(stdout
, buf
, size
);
4169 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4171 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
4172 vc
->fd_read(vc
->opaque
, buf
, size
);
4181 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
4188 for (i
= 0; i
< iovcnt
; i
++) {
4191 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
4192 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
4196 vc
->fd_read(vc
->opaque
, buffer
, offset
);
4201 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
4204 VLANState
*vlan
= vc1
->vlan
;
4205 VLANClientState
*vc
;
4206 ssize_t max_len
= 0;
4208 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4215 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
4216 else if (vc
->fd_read
)
4217 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
4219 max_len
= MAX(max_len
, len
);
4225 #if defined(CONFIG_SLIRP)
4227 /* slirp network adapter */
4229 static int slirp_inited
;
4230 static VLANClientState
*slirp_vc
;
4232 int slirp_can_output(void)
4234 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4237 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4240 printf("slirp output:\n");
4241 hex_dump(stdout
, pkt
, pkt_len
);
4245 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4248 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4251 printf("slirp input:\n");
4252 hex_dump(stdout
, buf
, size
);
4254 slirp_input(buf
, size
);
4257 static int net_slirp_init(VLANState
*vlan
)
4259 if (!slirp_inited
) {
4263 slirp_vc
= qemu_new_vlan_client(vlan
,
4264 slirp_receive
, NULL
, NULL
);
4265 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4269 static void net_slirp_redir(const char *redir_str
)
4274 struct in_addr guest_addr
;
4275 int host_port
, guest_port
;
4277 if (!slirp_inited
) {
4283 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4285 if (!strcmp(buf
, "tcp")) {
4287 } else if (!strcmp(buf
, "udp")) {
4293 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4295 host_port
= strtol(buf
, &r
, 0);
4299 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4301 if (buf
[0] == '\0') {
4302 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4304 if (!inet_aton(buf
, &guest_addr
))
4307 guest_port
= strtol(p
, &r
, 0);
4311 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4312 fprintf(stderr
, "qemu: could not set up redirection\n");
4317 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4325 static void erase_dir(char *dir_name
)
4329 char filename
[1024];
4331 /* erase all the files in the directory */
4332 if ((d
= opendir(dir_name
)) != 0) {
4337 if (strcmp(de
->d_name
, ".") != 0 &&
4338 strcmp(de
->d_name
, "..") != 0) {
4339 snprintf(filename
, sizeof(filename
), "%s/%s",
4340 smb_dir
, de
->d_name
);
4341 if (unlink(filename
) != 0) /* is it a directory? */
4342 erase_dir(filename
);
4350 /* automatic user mode samba server configuration */
4351 static void smb_exit(void)
4356 /* automatic user mode samba server configuration */
4357 static void net_slirp_smb(const char *exported_dir
)
4359 char smb_conf
[1024];
4360 char smb_cmdline
[1024];
4363 if (!slirp_inited
) {
4368 /* XXX: better tmp dir construction */
4369 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4370 if (mkdir(smb_dir
, 0700) < 0) {
4371 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4374 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4376 f
= fopen(smb_conf
, "w");
4378 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4385 "socket address=127.0.0.1\n"
4386 "pid directory=%s\n"
4387 "lock directory=%s\n"
4388 "log file=%s/log.smbd\n"
4389 "smb passwd file=%s/smbpasswd\n"
4390 "security = share\n"
4405 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4406 SMBD_COMMAND
, smb_conf
);
4408 slirp_add_exec(0, smb_cmdline
, 4, 139);
4411 #endif /* !defined(_WIN32) */
4412 void do_info_slirp(void)
4417 #endif /* CONFIG_SLIRP */
4421 int tap_has_vnet_hdr(void *opaque
)
4426 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4430 #else /* !defined(_WIN32) */
4432 #ifndef IFF_VNET_HDR
4433 #define TAP_BUFSIZE 4096
4435 #include <linux/virtio_net.h>
4437 #define ETH_DATA_LEN 1500
4438 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4439 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4440 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4443 typedef struct TAPState
{
4444 VLANClientState
*vc
;
4446 char down_script
[1024];
4447 char buf
[TAP_BUFSIZE
];
4449 unsigned int has_vnet_hdr
: 1;
4450 unsigned int using_vnet_hdr
: 1;
4453 static ssize_t
tap_writev(void *opaque
, const struct iovec
*iov
,
4456 TAPState
*s
= opaque
;
4460 len
= writev(s
->fd
, iov
, iovcnt
);
4461 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4466 static ssize_t
tap_receive_iov(void *opaque
, const struct iovec
*iov
,
4470 TAPState
*s
= opaque
;
4472 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4473 struct iovec
*iov_copy
;
4474 struct virtio_net_hdr hdr
= { 0, };
4476 iov_copy
= alloca(sizeof(struct iovec
) * (iovcnt
+ 1));
4478 iov_copy
[0].iov_base
= &hdr
;
4479 iov_copy
[0].iov_len
= sizeof(hdr
);
4481 memcpy(&iov_copy
[1], iov
, sizeof(struct iovec
) * iovcnt
);
4483 return tap_writev(opaque
, iov_copy
, iovcnt
+ 1);
4487 return tap_writev(opaque
, iov
, iovcnt
);
4490 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4492 struct iovec iov
[2];
4496 TAPState
*s
= opaque
;
4497 struct virtio_net_hdr hdr
= { 0, };
4499 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4500 iov
[i
].iov_base
= &hdr
;
4501 iov
[i
].iov_len
= sizeof(hdr
);
4506 iov
[i
].iov_base
= (char *) buf
;
4507 iov
[i
].iov_len
= size
;
4510 tap_writev(opaque
, iov
, i
);
4513 static int tap_can_send(void *opaque
)
4515 TAPState
*s
= opaque
;
4516 VLANClientState
*vc
;
4517 int can_receive
= 0;
4519 /* Check to see if any of our clients can receive a packet */
4520 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4521 /* Skip ourselves */
4525 if (!vc
->fd_can_read
) {
4526 /* no fd_can_read handler, they always can receive */
4529 can_receive
= vc
->fd_can_read(vc
->opaque
);
4531 /* Once someone can receive, we try to send a packet */
4539 static int tap_send_packet(TAPState
*s
)
4541 uint8_t *buf
= s
->buf
;
4545 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4546 buf
+= sizeof(struct virtio_net_hdr
);
4547 size
-= sizeof(struct virtio_net_hdr
);
4551 return qemu_send_packet(s
->vc
, buf
, size
);
4554 static void tap_send(void *opaque
)
4556 TAPState
*s
= opaque
;
4558 /* First try to send any buffered packet */
4562 /* If noone can receive the packet, buffer it */
4563 err
= tap_send_packet(s
);
4568 /* Read packets until we hit EAGAIN */
4573 sbuf
.maxlen
= sizeof(s
->buf
);
4575 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4578 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4582 if (s
->size
== -1 && errno
== EINTR
)
4588 /* If noone can receive the packet, buffer it */
4589 err
= tap_send_packet(s
);
4593 } while (s
->size
> 0);
4596 int tap_has_vnet_hdr(void *opaque
)
4598 VLANClientState
*vc
= opaque
;
4599 TAPState
*s
= vc
->opaque
;
4601 return s
? s
->has_vnet_hdr
: 0;
4604 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4606 VLANClientState
*vc
= opaque
;
4607 TAPState
*s
= vc
->opaque
;
4609 if (!s
|| !s
->has_vnet_hdr
)
4612 s
->using_vnet_hdr
= using_vnet_hdr
!= 0;
4615 static int tap_probe_vnet_hdr(int fd
)
4617 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4620 if (ioctl(fd
, TUNGETIFF
, &ifr
) != 0) {
4621 fprintf(stderr
, "TUNGETIFF ioctl() failed: %s\n", strerror(errno
));
4625 return ifr
.ifr_flags
& IFF_VNET_HDR
;
4631 #ifdef TUNSETOFFLOAD
4632 static void tap_set_offload(VLANClientState
*vc
, int csum
, int tso4
, int tso6
,
4635 TAPState
*s
= vc
->opaque
;
4636 unsigned int offload
= 0;
4639 offload
|= TUN_F_CSUM
;
4641 offload
|= TUN_F_TSO4
;
4643 offload
|= TUN_F_TSO6
;
4644 if ((tso4
|| tso6
) && ecn
)
4645 offload
|= TUN_F_TSO_ECN
;
4648 if (ioctl(s
->fd
, TUNSETOFFLOAD
, offload
) != 0)
4649 fprintf(stderr
, "TUNSETOFFLOAD ioctl() failed: %s\n",
4652 #endif /* TUNSETOFFLOAD */
4656 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
, int vnet_hdr
)
4660 s
= qemu_mallocz(sizeof(TAPState
));
4664 s
->has_vnet_hdr
= vnet_hdr
!= 0;
4665 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4666 s
->vc
->fd_readv
= tap_receive_iov
;
4667 #ifdef TUNSETOFFLOAD
4668 s
->vc
->set_offload
= tap_set_offload
;
4670 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4671 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4675 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4676 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4682 TFR(fd
= open("/dev/tap", O_RDWR
));
4684 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4689 dev
= devname(s
.st_rdev
, S_IFCHR
);
4690 pstrcpy(ifname
, ifname_size
, dev
);
4692 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4695 #elif defined(__sun__)
4696 #define TUNNEWPPA (('T'<<16) | 0x0001)
4698 * Allocate TAP device, returns opened fd.
4699 * Stores dev name in the first arg(must be large enough).
4701 int tap_alloc(char *dev
, size_t dev_size
)
4703 int tap_fd
, if_fd
, ppa
= -1;
4704 static int ip_fd
= 0;
4707 static int arp_fd
= 0;
4708 int ip_muxid
, arp_muxid
;
4709 struct strioctl strioc_if
, strioc_ppa
;
4710 int link_type
= I_PLINK
;;
4712 char actual_name
[32] = "";
4714 memset(&ifr
, 0x0, sizeof(ifr
));
4718 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4722 /* Check if IP device was opened */
4726 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4728 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4732 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4734 syslog(LOG_ERR
, "Can't open /dev/tap");
4738 /* Assign a new PPA and get its unit number. */
4739 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4740 strioc_ppa
.ic_timout
= 0;
4741 strioc_ppa
.ic_len
= sizeof(ppa
);
4742 strioc_ppa
.ic_dp
= (char *)&ppa
;
4743 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4744 syslog (LOG_ERR
, "Can't assign new interface");
4746 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4748 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4751 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4752 syslog(LOG_ERR
, "Can't push IP module");
4756 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4757 syslog(LOG_ERR
, "Can't get flags\n");
4759 snprintf (actual_name
, 32, "tap%d", ppa
);
4760 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4763 /* Assign ppa according to the unit number returned by tun device */
4765 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4766 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4767 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4768 syslog (LOG_ERR
, "Can't get flags\n");
4769 /* Push arp module to if_fd */
4770 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4771 syslog (LOG_ERR
, "Can't push ARP module (2)");
4773 /* Push arp module to ip_fd */
4774 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4775 syslog (LOG_ERR
, "I_POP failed\n");
4776 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4777 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4779 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4781 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4783 /* Set ifname to arp */
4784 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4785 strioc_if
.ic_timout
= 0;
4786 strioc_if
.ic_len
= sizeof(ifr
);
4787 strioc_if
.ic_dp
= (char *)&ifr
;
4788 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4789 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4792 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4793 syslog(LOG_ERR
, "Can't link TAP device to IP");
4797 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4798 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4802 memset(&ifr
, 0x0, sizeof(ifr
));
4803 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4804 ifr
.lifr_ip_muxid
= ip_muxid
;
4805 ifr
.lifr_arp_muxid
= arp_muxid
;
4807 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4809 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4810 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4811 syslog (LOG_ERR
, "Can't set multiplexor id");
4814 snprintf(dev
, dev_size
, "tap%d", ppa
);
4818 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4822 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4823 fprintf(stderr
, "Cannot allocate TAP device\n");
4826 pstrcpy(ifname
, ifname_size
, dev
);
4827 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4831 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4836 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4838 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4841 memset(&ifr
, 0, sizeof(ifr
));
4842 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4844 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4846 unsigned int features
;
4848 if (ioctl(fd
, TUNGETFEATURES
, &features
) == 0 &&
4849 features
& IFF_VNET_HDR
) {
4851 ifr
.ifr_flags
|= IFF_VNET_HDR
;
4856 if (ifname
[0] != '\0')
4857 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4859 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4860 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4862 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4866 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4867 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4872 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4878 /* try to launch network script */
4882 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4883 for (i
= 0; i
< open_max
; i
++)
4884 if (i
!= STDIN_FILENO
&&
4885 i
!= STDOUT_FILENO
&&
4886 i
!= STDERR_FILENO
&&
4891 *parg
++ = (char *)setup_script
;
4892 *parg
++ = (char *)ifname
;
4894 execv(setup_script
, args
);
4897 while (waitpid(pid
, &status
, 0) != pid
);
4898 if (!WIFEXITED(status
) ||
4899 WEXITSTATUS(status
) != 0) {
4900 fprintf(stderr
, "%s: could not launch network script\n",
4908 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4909 const char *setup_script
, const char *down_script
)
4916 if (ifname1
!= NULL
)
4917 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4921 TFR(fd
= tap_open(ifname
, sizeof(ifname
), &vnet_hdr
));
4925 if (!setup_script
|| !strcmp(setup_script
, "no"))
4927 if (setup_script
[0] != '\0') {
4928 if (launch_script(setup_script
, ifname
, fd
))
4931 s
= net_tap_fd_init(vlan
, fd
, vnet_hdr
);
4935 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4936 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4937 if (down_script
&& strcmp(down_script
, "no"))
4938 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4942 #endif /* !_WIN32 */
4944 #if defined(CONFIG_VDE)
4945 typedef struct VDEState
{
4946 VLANClientState
*vc
;
4950 static void vde_to_qemu(void *opaque
)
4952 VDEState
*s
= opaque
;
4956 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4958 qemu_send_packet(s
->vc
, buf
, size
);
4962 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4964 VDEState
*s
= opaque
;
4967 ret
= vde_send(s
->vde
, buf
, size
, 0);
4968 if (ret
< 0 && errno
== EINTR
) {
4975 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4976 const char *group
, int mode
)
4979 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4980 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4982 struct vde_open_args args
= {
4984 .group
= init_group
,
4988 s
= qemu_mallocz(sizeof(VDEState
));
4991 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4996 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4997 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4998 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4999 sock
, vde_datafd(s
->vde
));
5004 /* network connection */
5005 typedef struct NetSocketState
{
5006 VLANClientState
*vc
;
5008 int state
; /* 0 = getting length, 1 = getting data */
5012 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
5015 typedef struct NetSocketListenState
{
5018 } NetSocketListenState
;
5020 /* XXX: we consider we can send the whole packet without blocking */
5021 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
5023 NetSocketState
*s
= opaque
;
5027 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
5028 send_all(s
->fd
, buf
, size
);
5031 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
5033 NetSocketState
*s
= opaque
;
5034 sendto(s
->fd
, buf
, size
, 0,
5035 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
5038 static void net_socket_send(void *opaque
)
5040 NetSocketState
*s
= opaque
;
5045 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
5047 err
= socket_error();
5048 if (err
!= EWOULDBLOCK
)
5050 } else if (size
== 0) {
5051 /* end of connection */
5053 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5059 /* reassemble a packet from the network */
5065 memcpy(s
->buf
+ s
->index
, buf
, l
);
5069 if (s
->index
== 4) {
5071 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
5077 l
= s
->packet_len
- s
->index
;
5080 memcpy(s
->buf
+ s
->index
, buf
, l
);
5084 if (s
->index
>= s
->packet_len
) {
5085 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
5094 static void net_socket_send_dgram(void *opaque
)
5096 NetSocketState
*s
= opaque
;
5099 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
5103 /* end of connection */
5104 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5107 qemu_send_packet(s
->vc
, s
->buf
, size
);
5110 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
5115 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
5116 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5117 inet_ntoa(mcastaddr
->sin_addr
),
5118 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
5122 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
5124 perror("socket(PF_INET, SOCK_DGRAM)");
5129 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
5130 (const char *)&val
, sizeof(val
));
5132 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5136 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
5142 /* Add host to multicast group */
5143 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
5144 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
5146 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
5147 (const char *)&imr
, sizeof(struct ip_mreq
));
5149 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5153 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5155 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
5156 (const char *)&val
, sizeof(val
));
5158 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5162 socket_set_nonblock(fd
);
5170 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
5173 struct sockaddr_in saddr
;
5175 socklen_t saddr_len
;
5178 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5179 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5180 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5184 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
5186 if (saddr
.sin_addr
.s_addr
==0) {
5187 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5191 /* clone dgram socket */
5192 newfd
= net_socket_mcast_create(&saddr
);
5194 /* error already reported by net_socket_mcast_create() */
5198 /* clone newfd to fd, close newfd */
5203 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5204 fd
, strerror(errno
));
5209 s
= qemu_mallocz(sizeof(NetSocketState
));
5214 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
5215 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
5217 /* mcast: save bound address as dst */
5218 if (is_connected
) s
->dgram_dst
=saddr
;
5220 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5221 "socket: fd=%d (%s mcast=%s:%d)",
5222 fd
, is_connected
? "cloned" : "",
5223 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5227 static void net_socket_connect(void *opaque
)
5229 NetSocketState
*s
= opaque
;
5230 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5233 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5237 s
= qemu_mallocz(sizeof(NetSocketState
));
5241 s
->vc
= qemu_new_vlan_client(vlan
,
5242 net_socket_receive
, NULL
, s
);
5243 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5244 "socket: fd=%d", fd
);
5246 net_socket_connect(s
);
5248 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5253 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5256 int so_type
=-1, optlen
=sizeof(so_type
);
5258 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5259 (socklen_t
*)&optlen
)< 0) {
5260 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5265 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5267 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5269 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5270 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5271 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5276 static void net_socket_accept(void *opaque
)
5278 NetSocketListenState
*s
= opaque
;
5280 struct sockaddr_in saddr
;
5285 len
= sizeof(saddr
);
5286 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5287 if (fd
< 0 && errno
!= EINTR
) {
5289 } else if (fd
>= 0) {
5293 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5297 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5298 "socket: connection from %s:%d",
5299 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5303 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5305 NetSocketListenState
*s
;
5307 struct sockaddr_in saddr
;
5309 if (parse_host_port(&saddr
, host_str
) < 0)
5312 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5316 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5321 socket_set_nonblock(fd
);
5323 /* allow fast reuse */
5325 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5327 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5332 ret
= listen(fd
, 0);
5339 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5343 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5346 int fd
, connected
, ret
, err
;
5347 struct sockaddr_in saddr
;
5349 if (parse_host_port(&saddr
, host_str
) < 0)
5352 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5357 socket_set_nonblock(fd
);
5361 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5363 err
= socket_error();
5364 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5365 } else if (err
== EINPROGRESS
) {
5368 } else if (err
== WSAEALREADY
) {
5381 s
= net_socket_fd_init(vlan
, fd
, connected
);
5384 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5385 "socket: connect to %s:%d",
5386 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5390 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5394 struct sockaddr_in saddr
;
5396 if (parse_host_port(&saddr
, host_str
) < 0)
5400 fd
= net_socket_mcast_create(&saddr
);
5404 s
= net_socket_fd_init(vlan
, fd
, 0);
5408 s
->dgram_dst
= saddr
;
5410 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5411 "socket: mcast=%s:%d",
5412 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5417 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5422 while (*p
!= '\0' && *p
!= '=') {
5423 if (q
&& (q
- buf
) < buf_size
- 1)
5433 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5438 while (*p
!= '\0') {
5440 if (*(p
+ 1) != ',')
5444 if (q
&& (q
- buf
) < buf_size
- 1)
5454 int get_param_value(char *buf
, int buf_size
,
5455 const char *tag
, const char *str
)
5462 p
= get_opt_name(option
, sizeof(option
), p
);
5466 if (!strcmp(tag
, option
)) {
5467 (void)get_opt_value(buf
, buf_size
, p
);
5470 p
= get_opt_value(NULL
, 0, p
);
5479 int check_params(char *buf
, int buf_size
,
5480 char **params
, const char *str
)
5487 p
= get_opt_name(buf
, buf_size
, p
);
5491 for(i
= 0; params
[i
] != NULL
; i
++)
5492 if (!strcmp(params
[i
], buf
))
5494 if (params
[i
] == NULL
)
5496 p
= get_opt_value(NULL
, 0, p
);
5504 static int nic_get_free_idx(void)
5508 for (index
= 0; index
< MAX_NICS
; index
++)
5509 if (!nd_table
[index
].used
)
5514 int net_client_init(const char *device
, const char *p
)
5521 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5522 vlan_id
= strtol(buf
, NULL
, 0);
5524 vlan
= qemu_find_vlan(vlan_id
);
5526 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5529 if (!strcmp(device
, "nic")) {
5532 int idx
= nic_get_free_idx();
5534 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5535 fprintf(stderr
, "Too Many NICs\n");
5538 nd
= &nd_table
[idx
];
5539 macaddr
= nd
->macaddr
;
5545 macaddr
[5] = 0x56 + idx
;
5547 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5548 if (parse_macaddr(macaddr
, buf
) < 0) {
5549 fprintf(stderr
, "invalid syntax for ethernet address\n");
5553 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5554 nd
->model
= strdup(buf
);
5559 vlan
->nb_guest_devs
++;
5562 if (!strcmp(device
, "none")) {
5563 /* does nothing. It is needed to signal that no network cards
5568 if (!strcmp(device
, "user")) {
5569 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5570 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5572 vlan
->nb_host_devs
++;
5573 ret
= net_slirp_init(vlan
);
5577 if (!strcmp(device
, "tap")) {
5579 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5580 fprintf(stderr
, "tap: no interface name\n");
5583 vlan
->nb_host_devs
++;
5584 ret
= tap_win32_init(vlan
, ifname
);
5587 if (!strcmp(device
, "tap")) {
5589 char setup_script
[1024], down_script
[1024];
5591 vlan
->nb_host_devs
++;
5592 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5593 fd
= strtol(buf
, NULL
, 0);
5594 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5596 if (net_tap_fd_init(vlan
, fd
, tap_probe_vnet_hdr(fd
)))
5599 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5602 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5603 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5605 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5606 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5608 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5612 if (!strcmp(device
, "socket")) {
5613 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5615 fd
= strtol(buf
, NULL
, 0);
5617 if (net_socket_fd_init(vlan
, fd
, 1))
5619 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5620 ret
= net_socket_listen_init(vlan
, buf
);
5621 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5622 ret
= net_socket_connect_init(vlan
, buf
);
5623 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5624 ret
= net_socket_mcast_init(vlan
, buf
);
5626 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5629 vlan
->nb_host_devs
++;
5632 if (!strcmp(device
, "vde")) {
5633 char vde_sock
[1024], vde_group
[512];
5634 int vde_port
, vde_mode
;
5635 vlan
->nb_host_devs
++;
5636 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5639 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5640 vde_port
= strtol(buf
, NULL
, 10);
5644 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5645 vde_group
[0] = '\0';
5647 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5648 vde_mode
= strtol(buf
, NULL
, 8);
5652 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5656 fprintf(stderr
, "Unknown network device: %s\n", device
);
5660 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5666 void net_client_uninit(NICInfo
*nd
)
5668 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5671 free((void *)nd
->model
);
5674 static int net_client_parse(const char *str
)
5682 while (*p
!= '\0' && *p
!= ',') {
5683 if ((q
- device
) < sizeof(device
) - 1)
5691 return net_client_init(device
, p
);
5694 void do_info_network(void)
5697 VLANClientState
*vc
;
5699 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5700 term_printf("VLAN %d devices:\n", vlan
->id
);
5701 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5702 term_printf(" %s\n", vc
->info_str
);
5706 #define HD_ALIAS "index=%d,media=disk"
5708 #define CDROM_ALIAS "index=1,media=cdrom"
5710 #define CDROM_ALIAS "index=2,media=cdrom"
5712 #define FD_ALIAS "index=%d,if=floppy"
5713 #define PFLASH_ALIAS "if=pflash"
5714 #define MTD_ALIAS "if=mtd"
5715 #define SD_ALIAS "index=0,if=sd"
5717 static int drive_opt_get_free_idx(void)
5721 for (index
= 0; index
< MAX_DRIVES
; index
++)
5722 if (!drives_opt
[index
].used
) {
5723 drives_opt
[index
].used
= 1;
5730 static int drive_get_free_idx(void)
5734 for (index
= 0; index
< MAX_DRIVES
; index
++)
5735 if (!drives_table
[index
].used
) {
5736 drives_table
[index
].used
= 1;
5743 int drive_add(const char *file
, const char *fmt
, ...)
5746 int index
= drive_opt_get_free_idx();
5748 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5749 fprintf(stderr
, "qemu: too many drives\n");
5753 drives_opt
[index
].file
= file
;
5755 vsnprintf(drives_opt
[index
].opt
,
5756 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5763 void drive_remove(int index
)
5765 drives_opt
[index
].used
= 0;
5769 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5773 /* seek interface, bus and unit */
5775 for (index
= 0; index
< MAX_DRIVES
; index
++)
5776 if (drives_table
[index
].type
== type
&&
5777 drives_table
[index
].bus
== bus
&&
5778 drives_table
[index
].unit
== unit
&&
5779 drives_table
[index
].used
)
5785 int drive_get_max_bus(BlockInterfaceType type
)
5791 for (index
= 0; index
< nb_drives
; index
++) {
5792 if(drives_table
[index
].type
== type
&&
5793 drives_table
[index
].bus
> max_bus
)
5794 max_bus
= drives_table
[index
].bus
;
5799 static void bdrv_format_print(void *opaque
, const char *name
)
5801 fprintf(stderr
, " %s", name
);
5804 void drive_uninit(BlockDriverState
*bdrv
)
5808 for (i
= 0; i
< MAX_DRIVES
; i
++)
5809 if (drives_table
[i
].bdrv
== bdrv
) {
5810 drives_table
[i
].bdrv
= NULL
;
5811 drives_table
[i
].used
= 0;
5812 drive_remove(drives_table
[i
].drive_opt_idx
);
5818 int drive_init(struct drive_opt
*arg
, int snapshot
,
5819 QEMUMachine
*machine
)
5824 const char *mediastr
= "";
5825 BlockInterfaceType type
;
5826 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5827 int bus_id
, unit_id
;
5828 int cyls
, heads
, secs
, translation
;
5829 BlockDriverState
*bdrv
;
5830 BlockDriver
*drv
= NULL
;
5835 int drives_table_idx
;
5836 char *str
= arg
->opt
;
5837 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5838 "secs", "trans", "media", "snapshot", "file",
5839 "cache", "format", "boot", NULL
};
5841 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5842 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5848 cyls
= heads
= secs
= 0;
5851 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5855 if (!strcmp(machine
->name
, "realview") ||
5856 !strcmp(machine
->name
, "SS-5") ||
5857 !strcmp(machine
->name
, "SS-10") ||
5858 !strcmp(machine
->name
, "SS-600MP") ||
5859 !strcmp(machine
->name
, "versatilepb") ||
5860 !strcmp(machine
->name
, "versatileab")) {
5862 max_devs
= MAX_SCSI_DEVS
;
5863 pstrcpy(devname
, sizeof(devname
), "scsi");
5866 max_devs
= MAX_IDE_DEVS
;
5867 pstrcpy(devname
, sizeof(devname
), "ide");
5871 /* extract parameters */
5873 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5874 bus_id
= strtol(buf
, NULL
, 0);
5876 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5881 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5882 unit_id
= strtol(buf
, NULL
, 0);
5884 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5889 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5890 pstrcpy(devname
, sizeof(devname
), buf
);
5891 if (!strcmp(buf
, "ide")) {
5893 max_devs
= MAX_IDE_DEVS
;
5894 } else if (!strcmp(buf
, "scsi")) {
5896 max_devs
= MAX_SCSI_DEVS
;
5897 } else if (!strcmp(buf
, "floppy")) {
5900 } else if (!strcmp(buf
, "pflash")) {
5903 } else if (!strcmp(buf
, "mtd")) {
5906 } else if (!strcmp(buf
, "sd")) {
5909 } else if (!strcmp(buf
, "virtio")) {
5913 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5918 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5919 index
= strtol(buf
, NULL
, 0);
5921 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5926 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5927 cyls
= strtol(buf
, NULL
, 0);
5930 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5931 heads
= strtol(buf
, NULL
, 0);
5934 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5935 secs
= strtol(buf
, NULL
, 0);
5938 if (cyls
|| heads
|| secs
) {
5939 if (cyls
< 1 || cyls
> 16383) {
5940 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5943 if (heads
< 1 || heads
> 16) {
5944 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5947 if (secs
< 1 || secs
> 63) {
5948 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5953 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5956 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5960 if (!strcmp(buf
, "none"))
5961 translation
= BIOS_ATA_TRANSLATION_NONE
;
5962 else if (!strcmp(buf
, "lba"))
5963 translation
= BIOS_ATA_TRANSLATION_LBA
;
5964 else if (!strcmp(buf
, "auto"))
5965 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5967 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5972 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5973 if (!strcmp(buf
, "disk")) {
5975 } else if (!strcmp(buf
, "cdrom")) {
5976 if (cyls
|| secs
|| heads
) {
5978 "qemu: '%s' invalid physical CHS format\n", str
);
5981 media
= MEDIA_CDROM
;
5983 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5988 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5989 if (!strcmp(buf
, "on"))
5991 else if (!strcmp(buf
, "off"))
5994 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5999 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
6000 if (!strcmp(buf
, "off"))
6002 else if (!strcmp(buf
, "on"))
6005 fprintf(stderr
, "qemu: invalid cache option\n");
6010 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
6011 if (strcmp(buf
, "?") == 0) {
6012 fprintf(stderr
, "qemu: Supported formats:");
6013 bdrv_iterate_format(bdrv_format_print
, NULL
);
6014 fprintf(stderr
, "\n");
6017 drv
= bdrv_find_format(buf
);
6019 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
6024 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
6025 if (!strcmp(buf
, "on")) {
6026 if (extboot_drive
!= -1) {
6027 fprintf(stderr
, "qemu: two bootable drives specified\n");
6030 extboot_drive
= nb_drives
;
6031 } else if (strcmp(buf
, "off")) {
6032 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
6037 if (arg
->file
== NULL
)
6038 get_param_value(file
, sizeof(file
), "file", str
);
6040 pstrcpy(file
, sizeof(file
), arg
->file
);
6042 /* compute bus and unit according index */
6045 if (bus_id
!= 0 || unit_id
!= -1) {
6047 "qemu: '%s' index cannot be used with bus and unit\n", str
);
6055 unit_id
= index
% max_devs
;
6056 bus_id
= index
/ max_devs
;
6060 /* if user doesn't specify a unit_id,
6061 * try to find the first free
6064 if (unit_id
== -1) {
6066 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
6068 if (max_devs
&& unit_id
>= max_devs
) {
6069 unit_id
-= max_devs
;
6077 if (max_devs
&& unit_id
>= max_devs
) {
6078 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
6079 str
, unit_id
, max_devs
- 1);
6084 * ignore multiple definitions
6087 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
6092 if (type
== IF_IDE
|| type
== IF_SCSI
)
6093 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
6095 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
6096 devname
, bus_id
, mediastr
, unit_id
);
6098 snprintf(buf
, sizeof(buf
), "%s%s%i",
6099 devname
, mediastr
, unit_id
);
6100 bdrv
= bdrv_new(buf
);
6101 drives_table_idx
= drive_get_free_idx();
6102 drives_table
[drives_table_idx
].bdrv
= bdrv
;
6103 drives_table
[drives_table_idx
].type
= type
;
6104 drives_table
[drives_table_idx
].bus
= bus_id
;
6105 drives_table
[drives_table_idx
].unit
= unit_id
;
6106 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
6115 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
6116 bdrv_set_translation_hint(bdrv
, translation
);
6120 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
6125 /* FIXME: This isn't really a floppy, but it's a reasonable
6128 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
6139 bdrv_flags
|= BDRV_O_SNAPSHOT
;
6141 bdrv_flags
|= BDRV_O_DIRECT
;
6142 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
6143 fprintf(stderr
, "qemu: could not open disk image %s\n",
6147 return drives_table_idx
;
6150 /***********************************************************/
6153 static USBPort
*used_usb_ports
;
6154 static USBPort
*free_usb_ports
;
6156 /* ??? Maybe change this to register a hub to keep track of the topology. */
6157 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
6158 usb_attachfn attach
)
6160 port
->opaque
= opaque
;
6161 port
->index
= index
;
6162 port
->attach
= attach
;
6163 port
->next
= free_usb_ports
;
6164 free_usb_ports
= port
;
6167 int usb_device_add_dev(USBDevice
*dev
)
6171 /* Find a USB port to add the device to. */
6172 port
= free_usb_ports
;
6176 /* Create a new hub and chain it on. */
6177 free_usb_ports
= NULL
;
6178 port
->next
= used_usb_ports
;
6179 used_usb_ports
= port
;
6181 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
6182 usb_attach(port
, hub
);
6183 port
= free_usb_ports
;
6186 free_usb_ports
= port
->next
;
6187 port
->next
= used_usb_ports
;
6188 used_usb_ports
= port
;
6189 usb_attach(port
, dev
);
6193 static int usb_device_add(const char *devname
)
6199 if (!free_usb_ports
)
6202 if (strstart(devname
, "host:", &p
)) {
6203 dev
= usb_host_device_open(p
);
6204 } else if (!strcmp(devname
, "mouse")) {
6205 dev
= usb_mouse_init();
6206 } else if (!strcmp(devname
, "tablet")) {
6207 dev
= usb_tablet_init();
6208 } else if (!strcmp(devname
, "keyboard")) {
6209 dev
= usb_keyboard_init();
6210 } else if (strstart(devname
, "disk:", &p
)) {
6211 dev
= usb_msd_init(p
);
6212 } else if (!strcmp(devname
, "wacom-tablet")) {
6213 dev
= usb_wacom_init();
6214 } else if (strstart(devname
, "serial:", &p
)) {
6215 dev
= usb_serial_init(p
);
6216 #ifdef CONFIG_BRLAPI
6217 } else if (!strcmp(devname
, "braille")) {
6218 dev
= usb_baum_init();
6220 } else if (strstart(devname
, "net:", &p
)) {
6223 if (net_client_init("nic", p
) < 0)
6225 nd_table
[nic
].model
= "usb";
6226 dev
= usb_net_init(&nd_table
[nic
]);
6233 return usb_device_add_dev(dev
);
6236 int usb_device_del_addr(int bus_num
, int addr
)
6242 if (!used_usb_ports
)
6248 lastp
= &used_usb_ports
;
6249 port
= used_usb_ports
;
6250 while (port
&& port
->dev
->addr
!= addr
) {
6251 lastp
= &port
->next
;
6259 *lastp
= port
->next
;
6260 usb_attach(port
, NULL
);
6261 dev
->handle_destroy(dev
);
6262 port
->next
= free_usb_ports
;
6263 free_usb_ports
= port
;
6267 static int usb_device_del(const char *devname
)
6272 if (!used_usb_ports
)
6275 p
= strchr(devname
, '.');
6278 bus_num
= strtoul(devname
, NULL
, 0);
6279 addr
= strtoul(p
+ 1, NULL
, 0);
6281 return usb_device_del_addr(bus_num
, addr
);
6284 void do_usb_add(const char *devname
)
6286 usb_device_add(devname
);
6289 void do_usb_del(const char *devname
)
6291 usb_device_del(devname
);
6298 const char *speed_str
;
6301 term_printf("USB support not enabled\n");
6305 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6309 switch(dev
->speed
) {
6313 case USB_SPEED_FULL
:
6316 case USB_SPEED_HIGH
:
6323 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6324 0, dev
->addr
, speed_str
, dev
->devname
);
6328 /***********************************************************/
6329 /* PCMCIA/Cardbus */
6331 static struct pcmcia_socket_entry_s
{
6332 struct pcmcia_socket_s
*socket
;
6333 struct pcmcia_socket_entry_s
*next
;
6334 } *pcmcia_sockets
= 0;
6336 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6338 struct pcmcia_socket_entry_s
*entry
;
6340 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6341 entry
->socket
= socket
;
6342 entry
->next
= pcmcia_sockets
;
6343 pcmcia_sockets
= entry
;
6346 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6348 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6350 ptr
= &pcmcia_sockets
;
6351 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6352 if (entry
->socket
== socket
) {
6358 void pcmcia_info(void)
6360 struct pcmcia_socket_entry_s
*iter
;
6361 if (!pcmcia_sockets
)
6362 term_printf("No PCMCIA sockets\n");
6364 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6365 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6366 iter
->socket
->attached
? iter
->socket
->card_string
:
6370 /***********************************************************/
6373 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6377 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6381 static void dumb_refresh(DisplayState
*ds
)
6383 #if defined(CONFIG_SDL)
6388 static void dumb_display_init(DisplayState
*ds
)
6393 ds
->dpy_update
= dumb_update
;
6394 ds
->dpy_resize
= dumb_resize
;
6395 ds
->dpy_refresh
= dumb_refresh
;
6396 ds
->gui_timer_interval
= 500;
6400 /***********************************************************/
6403 #define MAX_IO_HANDLERS 64
6405 typedef struct IOHandlerRecord
{
6407 IOCanRWHandler
*fd_read_poll
;
6409 IOHandler
*fd_write
;
6412 /* temporary data */
6414 struct IOHandlerRecord
*next
;
6417 static IOHandlerRecord
*first_io_handler
;
6419 /* XXX: fd_read_poll should be suppressed, but an API change is
6420 necessary in the character devices to suppress fd_can_read(). */
6421 int qemu_set_fd_handler2(int fd
,
6422 IOCanRWHandler
*fd_read_poll
,
6424 IOHandler
*fd_write
,
6427 IOHandlerRecord
**pioh
, *ioh
;
6429 if (!fd_read
&& !fd_write
) {
6430 pioh
= &first_io_handler
;
6435 if (ioh
->fd
== fd
) {
6442 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6446 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6449 ioh
->next
= first_io_handler
;
6450 first_io_handler
= ioh
;
6453 ioh
->fd_read_poll
= fd_read_poll
;
6454 ioh
->fd_read
= fd_read
;
6455 ioh
->fd_write
= fd_write
;
6456 ioh
->opaque
= opaque
;
6463 int qemu_set_fd_handler(int fd
,
6465 IOHandler
*fd_write
,
6468 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6471 /***********************************************************/
6472 /* Polling handling */
6474 typedef struct PollingEntry
{
6477 struct PollingEntry
*next
;
6480 static PollingEntry
*first_polling_entry
;
6482 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6484 PollingEntry
**ppe
, *pe
;
6485 pe
= qemu_mallocz(sizeof(PollingEntry
));
6489 pe
->opaque
= opaque
;
6490 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6495 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6497 PollingEntry
**ppe
, *pe
;
6498 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6500 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6509 /***********************************************************/
6510 /* Wait objects support */
6511 typedef struct WaitObjects
{
6513 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6514 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6515 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6518 static WaitObjects wait_objects
= {0};
6520 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6522 WaitObjects
*w
= &wait_objects
;
6524 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6526 w
->events
[w
->num
] = handle
;
6527 w
->func
[w
->num
] = func
;
6528 w
->opaque
[w
->num
] = opaque
;
6533 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6536 WaitObjects
*w
= &wait_objects
;
6539 for (i
= 0; i
< w
->num
; i
++) {
6540 if (w
->events
[i
] == handle
)
6543 w
->events
[i
] = w
->events
[i
+ 1];
6544 w
->func
[i
] = w
->func
[i
+ 1];
6545 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6553 #define SELF_ANNOUNCE_ROUNDS 5
6554 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6555 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6556 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6558 static int announce_self_create(uint8_t *buf
,
6561 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6562 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6564 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6566 memset(buf
, 0xff, 6); /* h_dst */
6567 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6568 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6569 memcpy(buf
+ 14, &magic
, 4); /* magic */
6571 return 18; /* len */
6574 static void qemu_announce_self(void)
6578 VLANClientState
*vc
;
6581 for (i
= 0; i
< nb_nics
; i
++) {
6582 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6583 vlan
= nd_table
[i
].vlan
;
6584 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6585 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6586 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6587 vc
->fd_read(vc
->opaque
, buf
, len
);
6592 /***********************************************************/
6593 /* savevm/loadvm support */
6595 #define IO_BUF_SIZE 32768
6598 QEMUFilePutBufferFunc
*put_buffer
;
6599 QEMUFileGetBufferFunc
*get_buffer
;
6600 QEMUFileCloseFunc
*close
;
6603 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6606 int buf_size
; /* 0 when writing */
6607 uint8_t buf
[IO_BUF_SIZE
];
6610 typedef struct QEMUFileFD
6615 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6617 QEMUFileFD
*s
= opaque
;
6622 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6624 if (errno
== EINTR
|| errno
== EAGAIN
)
6631 QEMUFile
*qemu_fopen_fd(int fd
)
6633 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6635 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6638 typedef struct QEMUFileUnix
6643 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6645 QEMUFileUnix
*s
= opaque
;
6646 fseek(s
->outfile
, pos
, SEEK_SET
);
6647 fwrite(buf
, 1, size
, s
->outfile
);
6650 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6652 QEMUFileUnix
*s
= opaque
;
6653 fseek(s
->outfile
, pos
, SEEK_SET
);
6654 return fread(buf
, 1, size
, s
->outfile
);
6657 static void file_close(void *opaque
)
6659 QEMUFileUnix
*s
= opaque
;
6664 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6668 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6672 s
->outfile
= fopen(filename
, mode
);
6676 if (!strcmp(mode
, "wb"))
6677 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6678 else if (!strcmp(mode
, "rb"))
6679 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6688 typedef struct QEMUFileBdrv
6690 BlockDriverState
*bs
;
6691 int64_t base_offset
;
6694 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6696 QEMUFileBdrv
*s
= opaque
;
6697 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6700 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6702 QEMUFileBdrv
*s
= opaque
;
6703 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6706 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6710 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6715 s
->base_offset
= offset
;
6718 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6720 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6723 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6724 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6728 f
= qemu_mallocz(sizeof(QEMUFile
));
6733 f
->put_buffer
= put_buffer
;
6734 f
->get_buffer
= get_buffer
;
6740 void qemu_fflush(QEMUFile
*f
)
6745 if (f
->buf_index
> 0) {
6746 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6747 f
->buf_offset
+= f
->buf_index
;
6752 static void qemu_fill_buffer(QEMUFile
*f
)
6759 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6765 f
->buf_offset
+= len
;
6768 void qemu_fclose(QEMUFile
*f
)
6772 f
->close(f
->opaque
);
6776 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6780 l
= IO_BUF_SIZE
- f
->buf_index
;
6783 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6787 if (f
->buf_index
>= IO_BUF_SIZE
)
6792 void qemu_put_byte(QEMUFile
*f
, int v
)
6794 f
->buf
[f
->buf_index
++] = v
;
6795 if (f
->buf_index
>= IO_BUF_SIZE
)
6799 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6805 l
= f
->buf_size
- f
->buf_index
;
6807 qemu_fill_buffer(f
);
6808 l
= f
->buf_size
- f
->buf_index
;
6814 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6819 return size1
- size
;
6822 int qemu_get_byte(QEMUFile
*f
)
6824 if (f
->buf_index
>= f
->buf_size
) {
6825 qemu_fill_buffer(f
);
6826 if (f
->buf_index
>= f
->buf_size
)
6829 return f
->buf
[f
->buf_index
++];
6832 int64_t qemu_ftell(QEMUFile
*f
)
6834 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6837 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6839 if (whence
== SEEK_SET
) {
6841 } else if (whence
== SEEK_CUR
) {
6842 pos
+= qemu_ftell(f
);
6844 /* SEEK_END not supported */
6847 if (f
->put_buffer
) {
6849 f
->buf_offset
= pos
;
6851 f
->buf_offset
= pos
;
6858 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6860 qemu_put_byte(f
, v
>> 8);
6861 qemu_put_byte(f
, v
);
6864 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6866 qemu_put_byte(f
, v
>> 24);
6867 qemu_put_byte(f
, v
>> 16);
6868 qemu_put_byte(f
, v
>> 8);
6869 qemu_put_byte(f
, v
);
6872 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6874 qemu_put_be32(f
, v
>> 32);
6875 qemu_put_be32(f
, v
);
6878 unsigned int qemu_get_be16(QEMUFile
*f
)
6881 v
= qemu_get_byte(f
) << 8;
6882 v
|= qemu_get_byte(f
);
6886 unsigned int qemu_get_be32(QEMUFile
*f
)
6889 v
= qemu_get_byte(f
) << 24;
6890 v
|= qemu_get_byte(f
) << 16;
6891 v
|= qemu_get_byte(f
) << 8;
6892 v
|= qemu_get_byte(f
);
6896 uint64_t qemu_get_be64(QEMUFile
*f
)
6899 v
= (uint64_t)qemu_get_be32(f
) << 32;
6900 v
|= qemu_get_be32(f
);
6904 typedef struct SaveStateEntry
{
6908 SaveStateHandler
*save_state
;
6909 LoadStateHandler
*load_state
;
6911 struct SaveStateEntry
*next
;
6914 static SaveStateEntry
*first_se
;
6916 /* TODO: Individual devices generally have very little idea about the rest
6917 of the system, so instance_id should be removed/replaced.
6918 Meanwhile pass -1 as instance_id if you do not already have a clearly
6919 distinguishing id for all instances of your device class. */
6920 int register_savevm(const char *idstr
,
6923 SaveStateHandler
*save_state
,
6924 LoadStateHandler
*load_state
,
6927 SaveStateEntry
*se
, **pse
;
6929 se
= qemu_malloc(sizeof(SaveStateEntry
));
6932 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6933 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6934 se
->version_id
= version_id
;
6935 se
->save_state
= save_state
;
6936 se
->load_state
= load_state
;
6937 se
->opaque
= opaque
;
6940 /* add at the end of list */
6942 while (*pse
!= NULL
) {
6943 if (instance_id
== -1
6944 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6945 && se
->instance_id
<= (*pse
)->instance_id
)
6946 se
->instance_id
= (*pse
)->instance_id
+ 1;
6947 pse
= &(*pse
)->next
;
6953 #define QEMU_VM_FILE_MAGIC 0x5145564d
6954 #define QEMU_VM_FILE_VERSION 0x00000002
6956 static int qemu_savevm_state(QEMUFile
*f
)
6960 int64_t cur_pos
, len_pos
, total_len_pos
;
6962 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6963 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6964 total_len_pos
= qemu_ftell(f
);
6965 qemu_put_be64(f
, 0); /* total size */
6967 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6968 if (se
->save_state
== NULL
)
6969 /* this one has a loader only, for backwards compatibility */
6973 len
= strlen(se
->idstr
);
6974 qemu_put_byte(f
, len
);
6975 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6977 qemu_put_be32(f
, se
->instance_id
);
6978 qemu_put_be32(f
, se
->version_id
);
6980 /* record size: filled later */
6981 len_pos
= qemu_ftell(f
);
6982 qemu_put_be32(f
, 0);
6983 se
->save_state(f
, se
->opaque
);
6985 /* fill record size */
6986 cur_pos
= qemu_ftell(f
);
6987 len
= cur_pos
- len_pos
- 4;
6988 qemu_fseek(f
, len_pos
, SEEK_SET
);
6989 qemu_put_be32(f
, len
);
6990 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6992 cur_pos
= qemu_ftell(f
);
6993 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6994 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6995 qemu_fseek(f
, cur_pos
, SEEK_SET
);
7001 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
7005 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
7006 if (!strcmp(se
->idstr
, idstr
) &&
7007 instance_id
== se
->instance_id
)
7013 static int qemu_loadvm_state(QEMUFile
*f
)
7016 int len
, ret
, instance_id
, record_len
, version_id
;
7017 int64_t total_len
, end_pos
, cur_pos
;
7021 v
= qemu_get_be32(f
);
7022 if (v
!= QEMU_VM_FILE_MAGIC
)
7024 v
= qemu_get_be32(f
);
7025 if (v
!= QEMU_VM_FILE_VERSION
) {
7030 total_len
= qemu_get_be64(f
);
7031 end_pos
= total_len
+ qemu_ftell(f
);
7033 if (qemu_ftell(f
) >= end_pos
)
7035 len
= qemu_get_byte(f
);
7036 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
7038 instance_id
= qemu_get_be32(f
);
7039 version_id
= qemu_get_be32(f
);
7040 record_len
= qemu_get_be32(f
);
7042 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7043 idstr
, instance_id
, version_id
, record_len
);
7045 cur_pos
= qemu_ftell(f
);
7046 se
= find_se(idstr
, instance_id
);
7048 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7049 instance_id
, idstr
);
7051 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7053 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7054 instance_id
, idstr
);
7058 /* always seek to exact end of record */
7059 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
7066 int qemu_live_savevm_state(QEMUFile
*f
)
7071 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
7072 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
7074 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
7075 len
= strlen(se
->idstr
);
7077 qemu_put_byte(f
, len
);
7078 qemu_put_buffer(f
, se
->idstr
, len
);
7079 qemu_put_be32(f
, se
->instance_id
);
7080 qemu_put_be32(f
, se
->version_id
);
7082 se
->save_state(f
, se
->opaque
);
7085 qemu_put_byte(f
, 0);
7091 int qemu_live_loadvm_state(QEMUFile
*f
)
7094 int len
, ret
, instance_id
, version_id
;
7098 v
= qemu_get_be32(f
);
7099 if (v
!= QEMU_VM_FILE_MAGIC
)
7101 v
= qemu_get_be32(f
);
7102 if (v
!= QEMU_VM_FILE_VERSION
) {
7109 len
= qemu_get_byte(f
);
7112 qemu_get_buffer(f
, idstr
, len
);
7114 instance_id
= qemu_get_be32(f
);
7115 version_id
= qemu_get_be32(f
);
7116 se
= find_se(idstr
, instance_id
);
7118 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7119 instance_id
, idstr
);
7121 if (version_id
> se
->version_id
) { /* src version > dst version */
7122 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7123 idstr
, version_id
, se
->version_id
);
7127 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7129 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7130 instance_id
, idstr
);
7137 qemu_announce_self();
7143 /* device can contain snapshots */
7144 static int bdrv_can_snapshot(BlockDriverState
*bs
)
7147 !bdrv_is_removable(bs
) &&
7148 !bdrv_is_read_only(bs
));
7151 /* device must be snapshots in order to have a reliable snapshot */
7152 static int bdrv_has_snapshot(BlockDriverState
*bs
)
7155 !bdrv_is_removable(bs
) &&
7156 !bdrv_is_read_only(bs
));
7159 static BlockDriverState
*get_bs_snapshots(void)
7161 BlockDriverState
*bs
;
7165 return bs_snapshots
;
7166 for(i
= 0; i
<= nb_drives
; i
++) {
7167 bs
= drives_table
[i
].bdrv
;
7168 if (bdrv_can_snapshot(bs
))
7177 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
7180 QEMUSnapshotInfo
*sn_tab
, *sn
;
7184 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7187 for(i
= 0; i
< nb_sns
; i
++) {
7189 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
7199 void do_savevm(const char *name
)
7201 BlockDriverState
*bs
, *bs1
;
7202 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
7203 int must_delete
, ret
, i
;
7204 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7206 int saved_vm_running
;
7213 bs
= get_bs_snapshots();
7215 term_printf("No block device can accept snapshots\n");
7219 /* ??? Should this occur after vm_stop? */
7222 saved_vm_running
= vm_running
;
7227 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
7232 memset(sn
, 0, sizeof(*sn
));
7234 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
7235 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
7238 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
7241 /* fill auxiliary fields */
7244 sn
->date_sec
= tb
.time
;
7245 sn
->date_nsec
= tb
.millitm
* 1000000;
7247 gettimeofday(&tv
, NULL
);
7248 sn
->date_sec
= tv
.tv_sec
;
7249 sn
->date_nsec
= tv
.tv_usec
* 1000;
7251 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7253 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7254 term_printf("Device %s does not support VM state snapshots\n",
7255 bdrv_get_device_name(bs
));
7259 /* save the VM state */
7260 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7262 term_printf("Could not open VM state file\n");
7265 ret
= qemu_savevm_state(f
);
7266 sn
->vm_state_size
= qemu_ftell(f
);
7269 term_printf("Error %d while writing VM\n", ret
);
7273 /* create the snapshots */
7275 for(i
= 0; i
< nb_drives
; i
++) {
7276 bs1
= drives_table
[i
].bdrv
;
7277 if (bdrv_has_snapshot(bs1
)) {
7279 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7281 term_printf("Error while deleting snapshot on '%s'\n",
7282 bdrv_get_device_name(bs1
));
7285 ret
= bdrv_snapshot_create(bs1
, sn
);
7287 term_printf("Error while creating snapshot on '%s'\n",
7288 bdrv_get_device_name(bs1
));
7294 if (saved_vm_running
)
7298 void do_loadvm(const char *name
)
7300 BlockDriverState
*bs
, *bs1
;
7301 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7304 int saved_vm_running
;
7306 bs
= get_bs_snapshots();
7308 term_printf("No block device supports snapshots\n");
7312 /* Flush all IO requests so they don't interfere with the new state. */
7315 saved_vm_running
= vm_running
;
7318 for(i
= 0; i
<= nb_drives
; i
++) {
7319 bs1
= drives_table
[i
].bdrv
;
7320 if (bdrv_has_snapshot(bs1
)) {
7321 ret
= bdrv_snapshot_goto(bs1
, name
);
7324 term_printf("Warning: ");
7327 term_printf("Snapshots not supported on device '%s'\n",
7328 bdrv_get_device_name(bs1
));
7331 term_printf("Could not find snapshot '%s' on device '%s'\n",
7332 name
, bdrv_get_device_name(bs1
));
7335 term_printf("Error %d while activating snapshot on '%s'\n",
7336 ret
, bdrv_get_device_name(bs1
));
7339 /* fatal on snapshot block device */
7346 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7347 term_printf("Device %s does not support VM state snapshots\n",
7348 bdrv_get_device_name(bs
));
7352 /* restore the VM state */
7353 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7355 term_printf("Could not open VM state file\n");
7358 ret
= qemu_loadvm_state(f
);
7361 term_printf("Error %d while loading VM state\n", ret
);
7364 if (saved_vm_running
)
7368 void do_delvm(const char *name
)
7370 BlockDriverState
*bs
, *bs1
;
7373 bs
= get_bs_snapshots();
7375 term_printf("No block device supports snapshots\n");
7379 for(i
= 0; i
<= nb_drives
; i
++) {
7380 bs1
= drives_table
[i
].bdrv
;
7381 if (bdrv_has_snapshot(bs1
)) {
7382 ret
= bdrv_snapshot_delete(bs1
, name
);
7384 if (ret
== -ENOTSUP
)
7385 term_printf("Snapshots not supported on device '%s'\n",
7386 bdrv_get_device_name(bs1
));
7388 term_printf("Error %d while deleting snapshot on '%s'\n",
7389 ret
, bdrv_get_device_name(bs1
));
7395 void do_info_snapshots(void)
7397 BlockDriverState
*bs
, *bs1
;
7398 QEMUSnapshotInfo
*sn_tab
, *sn
;
7402 bs
= get_bs_snapshots();
7404 term_printf("No available block device supports snapshots\n");
7407 term_printf("Snapshot devices:");
7408 for(i
= 0; i
<= nb_drives
; i
++) {
7409 bs1
= drives_table
[i
].bdrv
;
7410 if (bdrv_has_snapshot(bs1
)) {
7412 term_printf(" %s", bdrv_get_device_name(bs1
));
7417 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7419 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7422 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7423 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7424 for(i
= 0; i
< nb_sns
; i
++) {
7426 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7431 /***********************************************************/
7432 /* ram save/restore */
7434 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7438 v
= qemu_get_byte(f
);
7441 if (qemu_get_buffer(f
, buf
, len
) != len
)
7445 v
= qemu_get_byte(f
);
7446 memset(buf
, v
, len
);
7454 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7459 if (qemu_get_be32(f
) != phys_ram_size
)
7461 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7462 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7464 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7471 #define BDRV_HASH_BLOCK_SIZE 1024
7472 #define IOBUF_SIZE 4096
7473 #define RAM_CBLOCK_MAGIC 0xfabe
7475 typedef struct RamCompressState
{
7478 uint8_t buf
[IOBUF_SIZE
];
7481 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7484 memset(s
, 0, sizeof(*s
));
7486 ret
= deflateInit2(&s
->zstream
, 1,
7488 9, Z_DEFAULT_STRATEGY
);
7491 s
->zstream
.avail_out
= IOBUF_SIZE
;
7492 s
->zstream
.next_out
= s
->buf
;
7496 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7498 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7499 qemu_put_be16(s
->f
, len
);
7500 qemu_put_buffer(s
->f
, buf
, len
);
7503 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7507 s
->zstream
.avail_in
= len
;
7508 s
->zstream
.next_in
= (uint8_t *)buf
;
7509 while (s
->zstream
.avail_in
> 0) {
7510 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7513 if (s
->zstream
.avail_out
== 0) {
7514 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7515 s
->zstream
.avail_out
= IOBUF_SIZE
;
7516 s
->zstream
.next_out
= s
->buf
;
7522 static void ram_compress_close(RamCompressState
*s
)
7526 /* compress last bytes */
7528 ret
= deflate(&s
->zstream
, Z_FINISH
);
7529 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7530 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7532 ram_put_cblock(s
, s
->buf
, len
);
7534 s
->zstream
.avail_out
= IOBUF_SIZE
;
7535 s
->zstream
.next_out
= s
->buf
;
7536 if (ret
== Z_STREAM_END
)
7543 deflateEnd(&s
->zstream
);
7546 typedef struct RamDecompressState
{
7549 uint8_t buf
[IOBUF_SIZE
];
7550 } RamDecompressState
;
7552 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7555 memset(s
, 0, sizeof(*s
));
7557 ret
= inflateInit(&s
->zstream
);
7563 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7567 s
->zstream
.avail_out
= len
;
7568 s
->zstream
.next_out
= buf
;
7569 while (s
->zstream
.avail_out
> 0) {
7570 if (s
->zstream
.avail_in
== 0) {
7571 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7573 clen
= qemu_get_be16(s
->f
);
7574 if (clen
> IOBUF_SIZE
)
7576 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7577 s
->zstream
.avail_in
= clen
;
7578 s
->zstream
.next_in
= s
->buf
;
7580 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7581 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7588 static void ram_decompress_close(RamDecompressState
*s
)
7590 inflateEnd(&s
->zstream
);
7593 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7597 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7598 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7600 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7601 qemu_put_be32(f
, addr
);
7602 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7605 qemu_put_be32(f
, 1);
7608 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7611 RamCompressState s1
, *s
= &s1
;
7614 qemu_put_be32(f
, phys_ram_size
);
7615 if (ram_compress_open(s
, f
) < 0)
7617 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7618 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7621 if (tight_savevm_enabled
) {
7625 /* find if the memory block is available on a virtual
7628 for(j
= 0; j
< nb_drives
; j
++) {
7629 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7631 BDRV_HASH_BLOCK_SIZE
);
7632 if (sector_num
>= 0)
7636 goto normal_compress
;
7639 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7640 ram_compress_buf(s
, buf
, 10);
7646 ram_compress_buf(s
, buf
, 1);
7647 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7650 ram_compress_close(s
);
7653 static void ram_save(QEMUFile
*f
, void *opaque
)
7655 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7657 qemu_put_byte(f
, in_migration
);
7660 ram_save_live(f
, opaque
);
7662 ram_save_static(f
, opaque
);
7665 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7670 addr
= qemu_get_be32(f
);
7674 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7680 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7682 RamDecompressState s1
, *s
= &s1
;
7686 if (qemu_get_be32(f
) != phys_ram_size
)
7688 if (ram_decompress_open(s
, f
) < 0)
7690 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7691 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7693 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7694 fprintf(stderr
, "Error while reading ram block header\n");
7698 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7699 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7708 ram_decompress_buf(s
, buf
+ 1, 9);
7710 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7711 if (bs_index
>= nb_drives
) {
7712 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7715 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7717 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7718 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7719 bs_index
, sector_num
);
7726 printf("Error block header\n");
7730 ram_decompress_close(s
);
7734 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7738 switch (version_id
) {
7740 ret
= ram_load_v1(f
, opaque
);
7743 if (qemu_get_byte(f
)) {
7744 ret
= ram_load_live(f
, opaque
);
7748 ret
= ram_load_static(f
, opaque
);
7758 /***********************************************************/
7759 /* bottom halves (can be seen as timers which expire ASAP) */
7768 static QEMUBH
*first_bh
= NULL
;
7770 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7773 bh
= qemu_mallocz(sizeof(QEMUBH
));
7777 bh
->opaque
= opaque
;
7781 int qemu_bh_poll(void)
7800 void qemu_bh_schedule(QEMUBH
*bh
)
7802 CPUState
*env
= cpu_single_env
;
7806 bh
->next
= first_bh
;
7809 /* stop the currently executing CPU to execute the BH ASAP */
7811 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7816 void qemu_bh_cancel(QEMUBH
*bh
)
7819 if (bh
->scheduled
) {
7822 pbh
= &(*pbh
)->next
;
7828 void qemu_bh_delete(QEMUBH
*bh
)
7834 /***********************************************************/
7835 /* machine registration */
7837 QEMUMachine
*first_machine
= NULL
;
7838 QEMUMachine
*current_machine
= NULL
;
7840 int qemu_register_machine(QEMUMachine
*m
)
7843 pm
= &first_machine
;
7851 static QEMUMachine
*find_machine(const char *name
)
7855 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7856 if (!strcmp(m
->name
, name
))
7862 /***********************************************************/
7863 /* main execution loop */
7865 static void gui_update(void *opaque
)
7867 DisplayState
*ds
= opaque
;
7868 ds
->dpy_refresh(ds
);
7869 qemu_mod_timer(ds
->gui_timer
,
7870 (ds
->gui_timer_interval
?
7871 ds
->gui_timer_interval
:
7872 GUI_REFRESH_INTERVAL
)
7873 + qemu_get_clock(rt_clock
));
7876 struct vm_change_state_entry
{
7877 VMChangeStateHandler
*cb
;
7879 LIST_ENTRY (vm_change_state_entry
) entries
;
7882 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7884 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7887 VMChangeStateEntry
*e
;
7889 e
= qemu_mallocz(sizeof (*e
));
7895 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7899 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7901 LIST_REMOVE (e
, entries
);
7905 static void vm_state_notify(int running
)
7907 VMChangeStateEntry
*e
;
7909 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7910 e
->cb(e
->opaque
, running
);
7914 /* XXX: support several handlers */
7915 static VMStopHandler
*vm_stop_cb
;
7916 static void *vm_stop_opaque
;
7918 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7921 vm_stop_opaque
= opaque
;
7925 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7936 qemu_rearm_alarm_timer(alarm_timer
);
7940 void vm_stop(int reason
)
7943 cpu_disable_ticks();
7947 vm_stop_cb(vm_stop_opaque
, reason
);
7954 /* reset/shutdown handler */
7956 typedef struct QEMUResetEntry
{
7957 QEMUResetHandler
*func
;
7959 struct QEMUResetEntry
*next
;
7962 static QEMUResetEntry
*first_reset_entry
;
7963 static int reset_requested
;
7964 static int shutdown_requested
;
7965 static int powerdown_requested
;
7967 int qemu_shutdown_requested(void)
7969 int r
= shutdown_requested
;
7970 shutdown_requested
= 0;
7974 int qemu_reset_requested(void)
7976 int r
= reset_requested
;
7977 reset_requested
= 0;
7981 int qemu_powerdown_requested(void)
7983 int r
= powerdown_requested
;
7984 powerdown_requested
= 0;
7988 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7990 QEMUResetEntry
**pre
, *re
;
7992 pre
= &first_reset_entry
;
7993 while (*pre
!= NULL
)
7994 pre
= &(*pre
)->next
;
7995 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7997 re
->opaque
= opaque
;
8002 void qemu_system_reset(void)
8006 /* reset all devices */
8007 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
8008 re
->func(re
->opaque
);
8012 void qemu_system_reset_request(void)
8015 shutdown_requested
= 1;
8017 reset_requested
= 1;
8020 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8024 void qemu_system_shutdown_request(void)
8026 shutdown_requested
= 1;
8028 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8031 void qemu_system_powerdown_request(void)
8033 powerdown_requested
= 1;
8035 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8038 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
8043 /* KVM holds a mutex while QEMU code is running, we need hooks to
8044 release the mutex whenever QEMU code sleeps. */
8048 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
8055 void main_loop_wait(int timeout
)
8057 IOHandlerRecord
*ioh
;
8058 fd_set rfds
, wfds
, xfds
;
8067 /* XXX: need to suppress polling by better using win32 events */
8069 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
8070 ret
|= pe
->func(pe
->opaque
);
8075 WaitObjects
*w
= &wait_objects
;
8077 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
8078 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
8079 if (w
->func
[ret
- WAIT_OBJECT_0
])
8080 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
8082 /* Check for additional signaled events */
8083 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
8085 /* Check if event is signaled */
8086 ret2
= WaitForSingleObject(w
->events
[i
], 0);
8087 if(ret2
== WAIT_OBJECT_0
) {
8089 w
->func
[i
](w
->opaque
[i
]);
8090 } else if (ret2
== WAIT_TIMEOUT
) {
8092 err
= GetLastError();
8093 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
8096 } else if (ret
== WAIT_TIMEOUT
) {
8098 err
= GetLastError();
8099 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
8103 /* poll any events */
8104 /* XXX: separate device handlers from system ones */
8109 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8113 (!ioh
->fd_read_poll
||
8114 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
8115 FD_SET(ioh
->fd
, &rfds
);
8119 if (ioh
->fd_write
) {
8120 FD_SET(ioh
->fd
, &wfds
);
8130 tv
.tv_sec
= timeout
/ 1000;
8131 tv
.tv_usec
= (timeout
% 1000) * 1000;
8133 #if defined(CONFIG_SLIRP)
8135 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
8138 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
8140 IOHandlerRecord
**pioh
;
8142 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8143 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
8144 ioh
->fd_read(ioh
->opaque
);
8145 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
8146 FD_CLR(ioh
->fd
, &rfds
);
8148 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
8149 ioh
->fd_write(ioh
->opaque
);
8153 /* remove deleted IO handlers */
8154 pioh
= &first_io_handler
;
8164 #if defined(CONFIG_SLIRP)
8171 slirp_select_poll(&rfds
, &wfds
, &xfds
);
8176 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
8177 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
8178 qemu_get_clock(vm_clock
));
8179 /* run dma transfers, if any */
8183 /* real time timers */
8184 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
8185 qemu_get_clock(rt_clock
));
8187 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
8188 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
8189 qemu_rearm_alarm_timer(alarm_timer
);
8192 /* Check bottom-halves last in case any of the earlier events triggered
8198 static int main_loop(void)
8201 #ifdef CONFIG_PROFILER
8207 if (kvm_enabled()) {
8209 cpu_disable_ticks();
8213 cur_cpu
= first_cpu
;
8214 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
8221 #ifdef CONFIG_PROFILER
8222 ti
= profile_getclock();
8227 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
8228 env
->icount_decr
.u16
.low
= 0;
8229 env
->icount_extra
= 0;
8230 count
= qemu_next_deadline();
8231 count
= (count
+ (1 << icount_time_shift
) - 1)
8232 >> icount_time_shift
;
8233 qemu_icount
+= count
;
8234 decr
= (count
> 0xffff) ? 0xffff : count
;
8236 env
->icount_decr
.u16
.low
= decr
;
8237 env
->icount_extra
= count
;
8239 ret
= cpu_exec(env
);
8240 #ifdef CONFIG_PROFILER
8241 qemu_time
+= profile_getclock() - ti
;
8244 /* Fold pending instructions back into the
8245 instruction counter, and clear the interrupt flag. */
8246 qemu_icount
-= (env
->icount_decr
.u16
.low
8247 + env
->icount_extra
);
8248 env
->icount_decr
.u32
= 0;
8249 env
->icount_extra
= 0;
8251 next_cpu
= env
->next_cpu
?: first_cpu
;
8252 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8253 ret
= EXCP_INTERRUPT
;
8257 if (ret
== EXCP_HLT
) {
8258 /* Give the next CPU a chance to run. */
8262 if (ret
!= EXCP_HALTED
)
8264 /* all CPUs are halted ? */
8270 if (shutdown_requested
) {
8271 ret
= EXCP_INTERRUPT
;
8279 if (reset_requested
) {
8280 reset_requested
= 0;
8281 qemu_system_reset();
8283 kvm_load_registers(env
);
8284 ret
= EXCP_INTERRUPT
;
8286 if (powerdown_requested
) {
8287 powerdown_requested
= 0;
8288 qemu_system_powerdown();
8289 ret
= EXCP_INTERRUPT
;
8291 if (unlikely(ret
== EXCP_DEBUG
)) {
8292 vm_stop(EXCP_DEBUG
);
8294 /* If all cpus are halted then wait until the next IRQ */
8295 /* XXX: use timeout computed from timers */
8296 if (ret
== EXCP_HALTED
) {
8300 /* Advance virtual time to the next event. */
8301 if (use_icount
== 1) {
8302 /* When not using an adaptive execution frequency
8303 we tend to get badly out of sync with real time,
8304 so just delay for a reasonable amount of time. */
8307 delta
= cpu_get_icount() - cpu_get_clock();
8310 /* If virtual time is ahead of real time then just
8312 timeout
= (delta
/ 1000000) + 1;
8314 /* Wait for either IO to occur or the next
8316 add
= qemu_next_deadline();
8317 /* We advance the timer before checking for IO.
8318 Limit the amount we advance so that early IO
8319 activity won't get the guest too far ahead. */
8323 add
= (add
+ (1 << icount_time_shift
) - 1)
8324 >> icount_time_shift
;
8326 timeout
= delta
/ 1000000;
8337 if (shutdown_requested
)
8341 #ifdef CONFIG_PROFILER
8342 ti
= profile_getclock();
8344 main_loop_wait(timeout
);
8345 #ifdef CONFIG_PROFILER
8346 dev_time
+= profile_getclock() - ti
;
8349 cpu_disable_ticks();
8353 static void help(int exitcode
)
8355 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8356 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8357 "usage: %s [options] [disk_image]\n"
8359 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8361 "Standard options:\n"
8362 "-M machine select emulated machine (-M ? for list)\n"
8363 "-cpu cpu select CPU (-cpu ? for list)\n"
8364 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8365 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8366 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8367 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8368 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8369 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8370 " [,cache=on|off][,format=f][,boot=on|off]\n"
8371 " use 'file' as a drive image\n"
8372 "-mtdblock file use 'file' as on-board Flash memory image\n"
8373 "-sd file use 'file' as SecureDigital card image\n"
8374 "-pflash file use 'file' as a parallel flash image\n"
8375 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8376 "-snapshot write to temporary files instead of disk image files\n"
8378 "-no-frame open SDL window without a frame and window decorations\n"
8379 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8380 "-no-quit disable SDL window close capability\n"
8383 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8385 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8386 "-smp n set the number of CPUs to 'n' [default=1]\n"
8387 "-nographic disable graphical output and redirect serial I/Os to console\n"
8388 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8390 "-k language use keyboard layout (for example \"fr\" for French)\n"
8393 "-audio-help print list of audio drivers and their options\n"
8394 "-soundhw c1,... enable audio support\n"
8395 " and only specified sound cards (comma separated list)\n"
8396 " use -soundhw ? to get the list of supported cards\n"
8397 " use -soundhw all to enable all of them\n"
8399 "-localtime set the real time clock to local time [default=utc]\n"
8400 "-full-screen start in full screen\n"
8402 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8404 "-usb enable the USB driver (will be the default soon)\n"
8405 "-usbdevice name add the host or guest USB device 'name'\n"
8406 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8407 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8409 "-name string set the name of the guest\n"
8411 "Network options:\n"
8412 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8413 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8415 "-net user[,vlan=n][,hostname=host]\n"
8416 " connect the user mode network stack to VLAN 'n' and send\n"
8417 " hostname 'host' to DHCP clients\n"
8420 "-net tap[,vlan=n],ifname=name\n"
8421 " connect the host TAP network interface to VLAN 'n'\n"
8423 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8424 " connect the host TAP network interface to VLAN 'n' and use the\n"
8425 " network scripts 'file' (default=%s)\n"
8426 " and 'dfile' (default=%s);\n"
8427 " use '[down]script=no' to disable script execution;\n"
8428 " use 'fd=h' to connect to an already opened TAP interface\n"
8430 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8431 " connect the vlan 'n' to another VLAN using a socket connection\n"
8432 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8433 " connect the vlan 'n' to multicast maddr and port\n"
8435 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8436 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8437 " on host and listening for incoming connections on 'socketpath'.\n"
8438 " Use group 'groupname' and mode 'octalmode' to change default\n"
8439 " ownership and permissions for communication port.\n"
8441 "-net none use it alone to have zero network devices; if no -net option\n"
8442 " is provided, the default is '-net nic -net user'\n"
8445 "-tftp dir allow tftp access to files in dir [-net user]\n"
8446 "-bootp file advertise file in BOOTP replies\n"
8448 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8450 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8451 " redirect TCP or UDP connections from host to guest [-net user]\n"
8454 "Linux boot specific:\n"
8455 "-kernel bzImage use 'bzImage' as kernel image\n"
8456 "-append cmdline use 'cmdline' as kernel command line\n"
8457 "-initrd file use 'file' as initial ram disk\n"
8459 "Debug/Expert options:\n"
8460 "-monitor dev redirect the monitor to char device 'dev'\n"
8461 "-serial dev redirect the serial port to char device 'dev'\n"
8462 "-parallel dev redirect the parallel port to char device 'dev'\n"
8463 "-pidfile file Write PID to 'file'\n"
8464 "-S freeze CPU at startup (use 'c' to start execution)\n"
8465 "-s wait gdb connection to port\n"
8466 "-p port set gdb connection port [default=%s]\n"
8467 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8468 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8469 " translation (t=none or lba) (usually qemu can guess them)\n"
8470 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8472 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8473 "-no-kqemu disable KQEMU kernel module usage\n"
8476 #ifndef NO_CPU_EMULATION
8477 "-no-kvm disable KVM hardware virtualization\n"
8479 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8480 "-no-kvm-pit disable KVM kernel mode PIT\n"
8483 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8484 " (default is CL-GD5446 PCI VGA)\n"
8485 "-no-acpi disable ACPI\n"
8487 #ifdef CONFIG_CURSES
8488 "-curses use a curses/ncurses interface instead of SDL\n"
8490 "-no-reboot exit instead of rebooting\n"
8491 "-no-shutdown stop before shutdown\n"
8492 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8493 "-vnc display start a VNC server on display\n"
8495 "-daemonize daemonize QEMU after initializing\n"
8497 "-tdf inject timer interrupts that got lost\n"
8498 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8499 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8500 "-option-rom rom load a file, rom, into the option ROM space\n"
8502 "-prom-env variable=value set OpenBIOS nvram variables\n"
8504 "-clock force the use of the given methods for timer alarm.\n"
8505 " To see what timers are available use -clock ?\n"
8506 "-startdate select initial date of the clock\n"
8507 "-icount [N|auto]\n"
8508 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8510 "During emulation, the following keys are useful:\n"
8511 "ctrl-alt-f toggle full screen\n"
8512 "ctrl-alt-n switch to virtual console 'n'\n"
8513 "ctrl-alt toggle mouse and keyboard grab\n"
8515 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8520 DEFAULT_NETWORK_SCRIPT
,
8521 DEFAULT_NETWORK_DOWN_SCRIPT
,
8523 DEFAULT_GDBSTUB_PORT
,
8528 #define HAS_ARG 0x0001
8543 QEMU_OPTION_mtdblock
,
8547 QEMU_OPTION_snapshot
,
8549 QEMU_OPTION_no_fd_bootchk
,
8552 QEMU_OPTION_nographic
,
8553 QEMU_OPTION_portrait
,
8555 QEMU_OPTION_audio_help
,
8556 QEMU_OPTION_soundhw
,
8577 QEMU_OPTION_localtime
,
8578 QEMU_OPTION_cirrusvga
,
8581 QEMU_OPTION_std_vga
,
8583 QEMU_OPTION_monitor
,
8585 QEMU_OPTION_parallel
,
8587 QEMU_OPTION_full_screen
,
8588 QEMU_OPTION_no_frame
,
8589 QEMU_OPTION_alt_grab
,
8590 QEMU_OPTION_no_quit
,
8591 QEMU_OPTION_pidfile
,
8592 QEMU_OPTION_no_kqemu
,
8593 QEMU_OPTION_kernel_kqemu
,
8594 QEMU_OPTION_win2k_hack
,
8596 QEMU_OPTION_usbdevice
,
8599 QEMU_OPTION_no_acpi
,
8602 QEMU_OPTION_no_kvm_irqchip
,
8603 QEMU_OPTION_no_kvm_pit
,
8604 QEMU_OPTION_no_reboot
,
8605 QEMU_OPTION_no_shutdown
,
8606 QEMU_OPTION_show_cursor
,
8607 QEMU_OPTION_daemonize
,
8608 QEMU_OPTION_option_rom
,
8609 QEMU_OPTION_semihosting
,
8610 QEMU_OPTION_cpu_vendor
,
8612 QEMU_OPTION_prom_env
,
8613 QEMU_OPTION_old_param
,
8615 QEMU_OPTION_startdate
,
8616 QEMU_OPTION_tb_size
,
8618 QEMU_OPTION_incoming
,
8620 QEMU_OPTION_kvm_shadow_memory
,
8621 QEMU_OPTION_mempath
,
8624 typedef struct QEMUOption
{
8630 const QEMUOption qemu_options
[] = {
8631 { "h", 0, QEMU_OPTION_h
},
8632 { "help", 0, QEMU_OPTION_h
},
8634 { "M", HAS_ARG
, QEMU_OPTION_M
},
8635 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8636 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8637 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8638 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8639 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8640 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8641 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8642 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8643 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8644 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8645 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8646 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8647 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8648 { "snapshot", 0, QEMU_OPTION_snapshot
},
8650 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8652 { "m", HAS_ARG
, QEMU_OPTION_m
},
8653 { "nographic", 0, QEMU_OPTION_nographic
},
8654 { "portrait", 0, QEMU_OPTION_portrait
},
8655 { "k", HAS_ARG
, QEMU_OPTION_k
},
8657 { "audio-help", 0, QEMU_OPTION_audio_help
},
8658 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8661 { "net", HAS_ARG
, QEMU_OPTION_net
},
8663 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8664 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8666 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8668 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8671 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8672 { "append", HAS_ARG
, QEMU_OPTION_append
},
8673 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8675 { "S", 0, QEMU_OPTION_S
},
8676 { "s", 0, QEMU_OPTION_s
},
8677 { "p", HAS_ARG
, QEMU_OPTION_p
},
8678 { "d", HAS_ARG
, QEMU_OPTION_d
},
8679 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8680 { "L", HAS_ARG
, QEMU_OPTION_L
},
8681 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8683 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8684 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8687 #ifndef NO_CPU_EMULATION
8688 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8690 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8691 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8693 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8694 { "g", 1, QEMU_OPTION_g
},
8696 { "localtime", 0, QEMU_OPTION_localtime
},
8697 { "std-vga", 0, QEMU_OPTION_std_vga
},
8698 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8699 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8700 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8701 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8702 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8703 { "incoming", 1, QEMU_OPTION_incoming
},
8704 { "full-screen", 0, QEMU_OPTION_full_screen
},
8706 { "no-frame", 0, QEMU_OPTION_no_frame
},
8707 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8708 { "no-quit", 0, QEMU_OPTION_no_quit
},
8710 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8711 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8712 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8713 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8714 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8715 #ifdef CONFIG_CURSES
8716 { "curses", 0, QEMU_OPTION_curses
},
8719 /* temporary options */
8720 { "usb", 0, QEMU_OPTION_usb
},
8721 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8722 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8723 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8724 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8725 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8726 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8727 { "daemonize", 0, QEMU_OPTION_daemonize
},
8728 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8729 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8730 { "semihosting", 0, QEMU_OPTION_semihosting
},
8732 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8733 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8734 { "name", HAS_ARG
, QEMU_OPTION_name
},
8735 #if defined(TARGET_SPARC)
8736 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8738 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8739 #if defined(TARGET_ARM)
8740 { "old-param", 0, QEMU_OPTION_old_param
},
8742 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8743 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8744 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8745 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8746 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8750 /* password input */
8752 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8757 if (!bdrv_is_encrypted(bs
))
8760 term_printf("%s is encrypted.\n", name
);
8761 for(i
= 0; i
< 3; i
++) {
8762 monitor_readline("Password: ", 1, password
, sizeof(password
));
8763 if (bdrv_set_key(bs
, password
) == 0)
8765 term_printf("invalid password\n");
8770 static BlockDriverState
*get_bdrv(int index
)
8772 if (index
> nb_drives
)
8774 return drives_table
[index
].bdrv
;
8777 static void read_passwords(void)
8779 BlockDriverState
*bs
;
8782 for(i
= 0; i
< 6; i
++) {
8785 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8790 struct soundhw soundhw
[] = {
8791 #ifdef HAS_AUDIO_CHOICE
8792 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8798 { .init_isa
= pcspk_audio_init
}
8803 "Creative Sound Blaster 16",
8806 { .init_isa
= SB16_init
}
8809 #ifdef CONFIG_CS4231A
8815 { .init_isa
= cs4231a_init
}
8823 "Yamaha YMF262 (OPL3)",
8825 "Yamaha YM3812 (OPL2)",
8829 { .init_isa
= Adlib_init
}
8836 "Gravis Ultrasound GF1",
8839 { .init_isa
= GUS_init
}
8846 "Intel 82801AA AC97 Audio",
8849 { .init_pci
= ac97_init
}
8855 "ENSONIQ AudioPCI ES1370",
8858 { .init_pci
= es1370_init
}
8862 { NULL
, NULL
, 0, 0, { NULL
} }
8865 static void select_soundhw (const char *optarg
)
8869 if (*optarg
== '?') {
8872 printf ("Valid sound card names (comma separated):\n");
8873 for (c
= soundhw
; c
->name
; ++c
) {
8874 printf ("%-11s %s\n", c
->name
, c
->descr
);
8876 printf ("\n-soundhw all will enable all of the above\n");
8877 exit (*optarg
!= '?');
8885 if (!strcmp (optarg
, "all")) {
8886 for (c
= soundhw
; c
->name
; ++c
) {
8894 e
= strchr (p
, ',');
8895 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8897 for (c
= soundhw
; c
->name
; ++c
) {
8898 if (!strncmp (c
->name
, p
, l
)) {
8907 "Unknown sound card name (too big to show)\n");
8910 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8915 p
+= l
+ (e
!= NULL
);
8919 goto show_valid_cards
;
8925 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8927 exit(STATUS_CONTROL_C_EXIT
);
8932 #define MAX_NET_CLIENTS 32
8934 static int saved_argc
;
8935 static char **saved_argv
;
8937 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8941 *opt_daemonize
= daemonize
;
8942 *opt_incoming
= incoming
;
8946 static int gethugepagesize(void)
8950 char *needle
= "Hugepagesize:";
8952 unsigned long hugepagesize
;
8954 fd
= open("/proc/meminfo", O_RDONLY
);
8960 ret
= read(fd
, buf
, sizeof(buf
));
8966 size
= strstr(buf
, needle
);
8969 size
+= strlen(needle
);
8970 hugepagesize
= strtol(size
, NULL
, 0);
8971 return hugepagesize
;
8974 void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
8980 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8983 hpagesize
= gethugepagesize() * 1024;
8987 fd
= mkstemp(filename
);
8996 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8999 * ftruncate is not supported by hugetlbfs in older
9000 * hosts, so don't bother checking for errors.
9001 * If anything goes wrong with it under other filesystems,
9004 ftruncate(fd
, memory
);
9006 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
9007 if (area
== MAP_FAILED
) {
9017 void *qemu_alloc_physram(unsigned long memory
)
9020 unsigned long map_len
= memory
;
9024 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
9027 area
= qemu_vmalloc(memory
);
9029 if (kvm_setup_guest_memory(area
, map_len
))
9037 static void termsig_handler(int signal
)
9039 qemu_system_shutdown_request();
9042 void termsig_setup(void)
9044 struct sigaction act
;
9046 memset(&act
, 0, sizeof(act
));
9047 act
.sa_handler
= termsig_handler
;
9048 sigaction(SIGINT
, &act
, NULL
);
9049 sigaction(SIGHUP
, &act
, NULL
);
9050 sigaction(SIGTERM
, &act
, NULL
);
9055 int main(int argc
, char **argv
)
9057 #ifdef CONFIG_GDBSTUB
9059 const char *gdbstub_port
;
9061 uint32_t boot_devices_bitmap
= 0;
9063 int snapshot
, linux_boot
, net_boot
;
9064 const char *initrd_filename
;
9065 const char *kernel_filename
, *kernel_cmdline
;
9066 const char *boot_devices
= "";
9067 DisplayState
*ds
= &display_state
;
9068 int cyls
, heads
, secs
, translation
;
9069 const char *net_clients
[MAX_NET_CLIENTS
];
9073 const char *r
, *optarg
;
9074 CharDriverState
*monitor_hd
;
9075 const char *monitor_device
;
9076 const char *serial_devices
[MAX_SERIAL_PORTS
];
9077 int serial_device_index
;
9078 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
9079 int parallel_device_index
;
9080 const char *loadvm
= NULL
;
9081 QEMUMachine
*machine
;
9082 const char *cpu_model
;
9083 const char *usb_devices
[MAX_USB_CMDLINE
];
9084 int usb_devices_index
;
9087 const char *pid_file
= NULL
;
9093 LIST_INIT (&vm_change_state_head
);
9096 struct sigaction act
;
9097 sigfillset(&act
.sa_mask
);
9099 act
.sa_handler
= SIG_IGN
;
9100 sigaction(SIGPIPE
, &act
, NULL
);
9103 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
9104 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9105 QEMU to run on a single CPU */
9110 h
= GetCurrentProcess();
9111 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
9112 for(i
= 0; i
< 32; i
++) {
9113 if (mask
& (1 << i
))
9118 SetProcessAffinityMask(h
, mask
);
9124 register_machines();
9125 machine
= first_machine
;
9127 initrd_filename
= NULL
;
9129 vga_ram_size
= VGA_RAM_SIZE
;
9130 #ifdef CONFIG_GDBSTUB
9132 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
9137 kernel_filename
= NULL
;
9138 kernel_cmdline
= "";
9139 cyls
= heads
= secs
= 0;
9140 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9141 monitor_device
= "vc";
9143 serial_devices
[0] = "vc:80Cx24C";
9144 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
9145 serial_devices
[i
] = NULL
;
9146 serial_device_index
= 0;
9148 parallel_devices
[0] = "vc:640x480";
9149 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
9150 parallel_devices
[i
] = NULL
;
9151 parallel_device_index
= 0;
9153 usb_devices_index
= 0;
9170 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
9172 const QEMUOption
*popt
;
9175 /* Treat --foo the same as -foo. */
9178 popt
= qemu_options
;
9181 fprintf(stderr
, "%s: invalid option -- '%s'\n",
9185 if (!strcmp(popt
->name
, r
+ 1))
9189 if (popt
->flags
& HAS_ARG
) {
9190 if (optind
>= argc
) {
9191 fprintf(stderr
, "%s: option '%s' requires an argument\n",
9195 optarg
= argv
[optind
++];
9200 switch(popt
->index
) {
9202 machine
= find_machine(optarg
);
9205 printf("Supported machines are:\n");
9206 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
9207 printf("%-10s %s%s\n",
9209 m
== first_machine
? " (default)" : "");
9211 exit(*optarg
!= '?');
9214 case QEMU_OPTION_cpu
:
9215 /* hw initialization will check this */
9216 if (*optarg
== '?') {
9217 /* XXX: implement xxx_cpu_list for targets that still miss it */
9218 #if defined(cpu_list)
9219 cpu_list(stdout
, &fprintf
);
9226 case QEMU_OPTION_initrd
:
9227 initrd_filename
= optarg
;
9229 case QEMU_OPTION_hda
:
9231 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
9233 hda_index
= drive_add(optarg
, HD_ALIAS
9234 ",cyls=%d,heads=%d,secs=%d%s",
9235 0, cyls
, heads
, secs
,
9236 translation
== BIOS_ATA_TRANSLATION_LBA
?
9238 translation
== BIOS_ATA_TRANSLATION_NONE
?
9239 ",trans=none" : "");
9241 case QEMU_OPTION_hdb
:
9242 case QEMU_OPTION_hdc
:
9243 case QEMU_OPTION_hdd
:
9244 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
9246 case QEMU_OPTION_drive
:
9247 drive_add(NULL
, "%s", optarg
);
9249 case QEMU_OPTION_mtdblock
:
9250 drive_add(optarg
, MTD_ALIAS
);
9252 case QEMU_OPTION_sd
:
9253 drive_add(optarg
, SD_ALIAS
);
9255 case QEMU_OPTION_pflash
:
9256 drive_add(optarg
, PFLASH_ALIAS
);
9258 case QEMU_OPTION_snapshot
:
9261 case QEMU_OPTION_hdachs
:
9265 cyls
= strtol(p
, (char **)&p
, 0);
9266 if (cyls
< 1 || cyls
> 16383)
9271 heads
= strtol(p
, (char **)&p
, 0);
9272 if (heads
< 1 || heads
> 16)
9277 secs
= strtol(p
, (char **)&p
, 0);
9278 if (secs
< 1 || secs
> 63)
9282 if (!strcmp(p
, "none"))
9283 translation
= BIOS_ATA_TRANSLATION_NONE
;
9284 else if (!strcmp(p
, "lba"))
9285 translation
= BIOS_ATA_TRANSLATION_LBA
;
9286 else if (!strcmp(p
, "auto"))
9287 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9290 } else if (*p
!= '\0') {
9292 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9295 if (hda_index
!= -1)
9296 snprintf(drives_opt
[hda_index
].opt
,
9297 sizeof(drives_opt
[hda_index
].opt
),
9298 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9299 0, cyls
, heads
, secs
,
9300 translation
== BIOS_ATA_TRANSLATION_LBA
?
9302 translation
== BIOS_ATA_TRANSLATION_NONE
?
9303 ",trans=none" : "");
9306 case QEMU_OPTION_nographic
:
9309 #ifdef CONFIG_CURSES
9310 case QEMU_OPTION_curses
:
9314 case QEMU_OPTION_portrait
:
9317 case QEMU_OPTION_kernel
:
9318 kernel_filename
= optarg
;
9320 case QEMU_OPTION_append
:
9321 kernel_cmdline
= optarg
;
9323 case QEMU_OPTION_cdrom
:
9324 drive_add(optarg
, CDROM_ALIAS
);
9326 case QEMU_OPTION_boot
:
9327 boot_devices
= optarg
;
9328 /* We just do some generic consistency checks */
9330 /* Could easily be extended to 64 devices if needed */
9333 boot_devices_bitmap
= 0;
9334 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9335 /* Allowed boot devices are:
9336 * a b : floppy disk drives
9337 * c ... f : IDE disk drives
9338 * g ... m : machine implementation dependant drives
9339 * n ... p : network devices
9340 * It's up to each machine implementation to check
9341 * if the given boot devices match the actual hardware
9342 * implementation and firmware features.
9344 if (*p
< 'a' || *p
> 'q') {
9345 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9348 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9350 "Boot device '%c' was given twice\n",*p
);
9353 boot_devices_bitmap
|= 1 << (*p
- 'a');
9357 case QEMU_OPTION_fda
:
9358 case QEMU_OPTION_fdb
:
9359 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9362 case QEMU_OPTION_no_fd_bootchk
:
9366 case QEMU_OPTION_net
:
9367 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9368 fprintf(stderr
, "qemu: too many network clients\n");
9371 net_clients
[nb_net_clients
] = optarg
;
9375 case QEMU_OPTION_tftp
:
9376 tftp_prefix
= optarg
;
9378 case QEMU_OPTION_bootp
:
9379 bootp_filename
= optarg
;
9382 case QEMU_OPTION_smb
:
9383 net_slirp_smb(optarg
);
9386 case QEMU_OPTION_redir
:
9387 net_slirp_redir(optarg
);
9391 case QEMU_OPTION_audio_help
:
9395 case QEMU_OPTION_soundhw
:
9396 select_soundhw (optarg
);
9402 case QEMU_OPTION_m
: {
9406 value
= strtoul(optarg
, &ptr
, 10);
9408 case 0: case 'M': case 'm':
9415 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9419 /* On 32-bit hosts, QEMU is limited by virtual address space */
9420 if (value
> (2047 << 20)
9422 && HOST_LONG_BITS
== 32
9425 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9428 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9429 fprintf(stderr
, "qemu: ram size too large\n");
9440 mask
= cpu_str_to_log_mask(optarg
);
9442 printf("Log items (comma separated):\n");
9443 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9444 printf("%-10s %s\n", item
->name
, item
->help
);
9451 #ifdef CONFIG_GDBSTUB
9456 gdbstub_port
= optarg
;
9462 case QEMU_OPTION_bios
:
9469 keyboard_layout
= optarg
;
9471 case QEMU_OPTION_localtime
:
9474 case QEMU_OPTION_cirrusvga
:
9475 cirrus_vga_enabled
= 1;
9478 case QEMU_OPTION_vmsvga
:
9479 cirrus_vga_enabled
= 0;
9482 case QEMU_OPTION_std_vga
:
9483 cirrus_vga_enabled
= 0;
9491 w
= strtol(p
, (char **)&p
, 10);
9494 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9500 h
= strtol(p
, (char **)&p
, 10);
9505 depth
= strtol(p
, (char **)&p
, 10);
9506 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9507 depth
!= 24 && depth
!= 32)
9509 } else if (*p
== '\0') {
9510 depth
= graphic_depth
;
9517 graphic_depth
= depth
;
9520 case QEMU_OPTION_echr
:
9523 term_escape_char
= strtol(optarg
, &r
, 0);
9525 printf("Bad argument to echr\n");
9528 case QEMU_OPTION_monitor
:
9529 monitor_device
= optarg
;
9531 case QEMU_OPTION_serial
:
9532 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9533 fprintf(stderr
, "qemu: too many serial ports\n");
9536 serial_devices
[serial_device_index
] = optarg
;
9537 serial_device_index
++;
9539 case QEMU_OPTION_parallel
:
9540 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9541 fprintf(stderr
, "qemu: too many parallel ports\n");
9544 parallel_devices
[parallel_device_index
] = optarg
;
9545 parallel_device_index
++;
9547 case QEMU_OPTION_loadvm
:
9550 case QEMU_OPTION_incoming
:
9553 case QEMU_OPTION_full_screen
:
9557 case QEMU_OPTION_no_frame
:
9560 case QEMU_OPTION_alt_grab
:
9563 case QEMU_OPTION_no_quit
:
9567 case QEMU_OPTION_pidfile
:
9571 case QEMU_OPTION_win2k_hack
:
9572 win2k_install_hack
= 1;
9576 case QEMU_OPTION_no_kqemu
:
9579 case QEMU_OPTION_kernel_kqemu
:
9584 case QEMU_OPTION_no_kvm
:
9587 case QEMU_OPTION_no_kvm_irqchip
: {
9588 extern int kvm_irqchip
, kvm_pit
;
9593 case QEMU_OPTION_no_kvm_pit
: {
9599 case QEMU_OPTION_usb
:
9602 case QEMU_OPTION_usbdevice
:
9604 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9605 fprintf(stderr
, "Too many USB devices\n");
9608 usb_devices
[usb_devices_index
] = optarg
;
9609 usb_devices_index
++;
9611 case QEMU_OPTION_smp
:
9612 smp_cpus
= atoi(optarg
);
9613 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9614 fprintf(stderr
, "Invalid number of CPUs\n");
9618 case QEMU_OPTION_vnc
:
9619 vnc_display
= optarg
;
9621 case QEMU_OPTION_no_acpi
:
9624 case QEMU_OPTION_no_reboot
:
9627 case QEMU_OPTION_no_shutdown
:
9630 case QEMU_OPTION_show_cursor
:
9633 case QEMU_OPTION_daemonize
:
9636 case QEMU_OPTION_option_rom
:
9637 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9638 fprintf(stderr
, "Too many option ROMs\n");
9641 option_rom
[nb_option_roms
] = optarg
;
9644 case QEMU_OPTION_semihosting
:
9645 semihosting_enabled
= 1;
9647 case QEMU_OPTION_tdf
:
9650 case QEMU_OPTION_kvm_shadow_memory
:
9651 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9653 case QEMU_OPTION_mempath
:
9656 case QEMU_OPTION_name
:
9660 case QEMU_OPTION_prom_env
:
9661 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9662 fprintf(stderr
, "Too many prom variables\n");
9665 prom_envs
[nb_prom_envs
] = optarg
;
9669 case QEMU_OPTION_cpu_vendor
:
9670 cpu_vendor_string
= optarg
;
9673 case QEMU_OPTION_old_param
:
9677 case QEMU_OPTION_clock
:
9678 configure_alarms(optarg
);
9680 case QEMU_OPTION_startdate
:
9683 time_t rtc_start_date
;
9684 if (!strcmp(optarg
, "now")) {
9685 rtc_date_offset
= -1;
9687 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9695 } else if (sscanf(optarg
, "%d-%d-%d",
9698 &tm
.tm_mday
) == 3) {
9707 rtc_start_date
= mktimegm(&tm
);
9708 if (rtc_start_date
== -1) {
9710 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9711 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9714 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9718 case QEMU_OPTION_tb_size
:
9719 tb_size
= strtol(optarg
, NULL
, 0);
9723 case QEMU_OPTION_icount
:
9725 if (strcmp(optarg
, "auto") == 0) {
9726 icount_time_shift
= -1;
9728 icount_time_shift
= strtol(optarg
, NULL
, 0);
9736 if (serial_device_index
== 0)
9737 serial_devices
[0] = "stdio";
9738 if (parallel_device_index
== 0)
9739 parallel_devices
[0] = "null";
9740 if (strncmp(monitor_device
, "vc", 2) == 0)
9741 monitor_device
= "stdio";
9748 if (pipe(fds
) == -1)
9759 len
= read(fds
[0], &status
, 1);
9760 if (len
== -1 && (errno
== EINTR
))
9765 else if (status
== 1) {
9766 fprintf(stderr
, "Could not acquire pidfile\n");
9783 signal(SIGTSTP
, SIG_IGN
);
9784 signal(SIGTTOU
, SIG_IGN
);
9785 signal(SIGTTIN
, SIG_IGN
);
9790 if (kvm_enabled()) {
9791 if (kvm_qemu_init() < 0) {
9792 extern int kvm_allowed
;
9793 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9794 #ifdef NO_CPU_EMULATION
9795 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9803 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9806 write(fds
[1], &status
, 1);
9808 fprintf(stderr
, "Could not acquire pid file\n");
9816 linux_boot
= (kernel_filename
!= NULL
);
9817 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9819 if (!linux_boot
&& net_boot
== 0 &&
9820 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9823 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9824 fprintf(stderr
, "-append only allowed with -kernel option\n");
9828 if (!linux_boot
&& initrd_filename
!= NULL
) {
9829 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9833 /* boot to floppy or the default cd if no hard disk defined yet */
9834 if (!boot_devices
[0]) {
9835 boot_devices
= "cad";
9837 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9842 if (use_icount
&& icount_time_shift
< 0) {
9844 /* 125MIPS seems a reasonable initial guess at the guest speed.
9845 It will be corrected fairly quickly anyway. */
9846 icount_time_shift
= 3;
9847 init_icount_adjust();
9854 /* init network clients */
9855 if (nb_net_clients
== 0) {
9856 /* if no clients, we use a default config */
9857 net_clients
[0] = "nic";
9858 net_clients
[1] = "user";
9862 for(i
= 0;i
< nb_net_clients
; i
++) {
9863 if (net_client_parse(net_clients
[i
]) < 0)
9866 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9867 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9869 if (vlan
->nb_guest_devs
== 0)
9870 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9871 if (vlan
->nb_host_devs
== 0)
9873 "Warning: vlan %d is not connected to host network\n",
9878 /* XXX: this should be moved in the PC machine instantiation code */
9879 if (net_boot
!= 0) {
9881 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9882 const char *model
= nd_table
[i
].model
;
9884 if (net_boot
& (1 << i
)) {
9887 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9888 if (get_image_size(buf
) > 0) {
9889 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9890 fprintf(stderr
, "Too many option ROMs\n");
9893 option_rom
[nb_option_roms
] = strdup(buf
);
9900 fprintf(stderr
, "No valid PXE rom found for network device\n");
9906 /* init the memory */
9907 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9909 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9911 if (ram_size
< phys_ram_size
) {
9912 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9913 machine
->name
, (unsigned long long) phys_ram_size
);
9917 phys_ram_size
= ram_size
;
9919 ram_size
= phys_ram_size
;
9922 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9924 phys_ram_size
+= ram_size
;
9927 /* Initialize kvm */
9928 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9929 #define KVM_EXTRA_PAGES 3
9931 #define KVM_EXTRA_PAGES 0
9933 if (kvm_enabled()) {
9934 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9935 if (kvm_qemu_create_context() < 0) {
9936 fprintf(stderr
, "Could not create KVM context\n");
9941 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9942 if (!phys_ram_base
) {
9943 fprintf(stderr
, "Could not allocate physical memory\n");
9947 /* init the dynamic translator */
9948 cpu_exec_init_all(tb_size
* 1024 * 1024);
9952 /* we always create the cdrom drive, even if no disk is there */
9954 if (nb_drives_opt
< MAX_DRIVES
)
9955 drive_add(NULL
, CDROM_ALIAS
);
9957 /* we always create at least one floppy */
9959 if (nb_drives_opt
< MAX_DRIVES
)
9960 drive_add(NULL
, FD_ALIAS
, 0);
9962 /* we always create one sd slot, even if no card is in it */
9964 if (nb_drives_opt
< MAX_DRIVES
)
9965 drive_add(NULL
, SD_ALIAS
);
9967 /* open the virtual block devices
9968 * note that migration with device
9969 * hot add/remove is broken.
9971 for(i
= 0; i
< nb_drives_opt
; i
++)
9972 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9975 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9976 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9979 memset(&display_state
, 0, sizeof(display_state
));
9982 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9985 /* nearly nothing to do */
9986 dumb_display_init(ds
);
9987 } else if (vnc_display
!= NULL
) {
9988 vnc_display_init(ds
);
9989 if (vnc_display_open(ds
, vnc_display
) < 0)
9992 #if defined(CONFIG_CURSES)
9994 curses_display_init(ds
, full_screen
);
9998 #if defined(CONFIG_SDL)
9999 sdl_display_init(ds
, full_screen
, no_frame
);
10000 #elif defined(CONFIG_COCOA)
10001 cocoa_display_init(ds
, full_screen
);
10003 dumb_display_init(ds
);
10008 /* must be after terminal init, SDL library changes signal handlers */
10012 /* Maintain compatibility with multiple stdio monitors */
10013 if (!strcmp(monitor_device
,"stdio")) {
10014 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10015 const char *devname
= serial_devices
[i
];
10016 if (devname
&& !strcmp(devname
,"mon:stdio")) {
10017 monitor_device
= NULL
;
10019 } else if (devname
&& !strcmp(devname
,"stdio")) {
10020 monitor_device
= NULL
;
10021 serial_devices
[i
] = "mon:stdio";
10026 if (monitor_device
) {
10027 monitor_hd
= qemu_chr_open(monitor_device
);
10029 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
10032 monitor_init(monitor_hd
, !nographic
);
10035 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10036 const char *devname
= serial_devices
[i
];
10037 if (devname
&& strcmp(devname
, "none")) {
10038 serial_hds
[i
] = qemu_chr_open(devname
);
10039 if (!serial_hds
[i
]) {
10040 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
10044 if (strstart(devname
, "vc", 0))
10045 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
10049 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
10050 const char *devname
= parallel_devices
[i
];
10051 if (devname
&& strcmp(devname
, "none")) {
10052 parallel_hds
[i
] = qemu_chr_open(devname
);
10053 if (!parallel_hds
[i
]) {
10054 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
10058 if (strstart(devname
, "vc", 0))
10059 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
10066 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
10067 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
10069 current_machine
= machine
;
10071 /* init USB devices */
10073 for(i
= 0; i
< usb_devices_index
; i
++) {
10074 if (usb_device_add(usb_devices
[i
]) < 0) {
10075 fprintf(stderr
, "Warning: could not add USB device %s\n",
10081 if (display_state
.dpy_refresh
) {
10082 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
10083 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
10086 #ifdef CONFIG_GDBSTUB
10088 /* XXX: use standard host:port notation and modify options
10090 if (gdbserver_start(gdbstub_port
) < 0) {
10091 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
10104 rc
= migrate_incoming(incoming
);
10106 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
10112 /* XXX: simplify init */
10120 uint8_t status
= 0;
10125 len
= write(fds
[1], &status
, 1);
10126 if (len
== -1 && (errno
== EINTR
))
10133 TFR(fd
= open("/dev/null", O_RDWR
));
10147 #if !defined(_WIN32)
10148 /* close network clients */
10149 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
10150 VLANClientState
*vc
;
10152 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
10153 if (vc
->fd_read
== tap_receive
) {
10155 TAPState
*s
= vc
->opaque
;
10157 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
10159 launch_script(s
->down_script
, ifname
, s
->fd
);
10161 #if defined(CONFIG_VDE)
10162 if (vc
->fd_read
== vde_from_qemu
) {
10163 VDEState
*s
= vc
->opaque
;