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>
108 #include "qemu_socket.h"
110 #if defined(CONFIG_SLIRP)
111 #include "libslirp.h"
114 #if defined(__OpenBSD__)
118 #if defined(CONFIG_VDE)
119 #include <libvdeplug.h>
124 #include <sys/timeb.h>
125 #include <mmsystem.h>
126 #define getopt_long_only getopt_long
127 #define memalign(align, size) malloc(size)
134 #endif /* CONFIG_SDL */
138 #define main qemu_main
139 #endif /* CONFIG_COCOA */
143 #include "exec-all.h"
145 #include "qemu-kvm.h"
147 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
148 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
150 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
152 #define SMBD_COMMAND "/usr/sbin/smbd"
155 //#define DEBUG_UNUSED_IOPORT
156 //#define DEBUG_IOPORT
159 #define DEFAULT_RAM_SIZE 144
161 #define DEFAULT_RAM_SIZE 128
164 /* Max number of USB devices that can be specified on the commandline. */
165 #define MAX_USB_CMDLINE 8
167 /* XXX: use a two level table to limit memory usage */
168 #define MAX_IOPORTS 65536
170 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
171 const char *bios_name
= NULL
;
172 void *ioport_opaque
[MAX_IOPORTS
];
173 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
174 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
175 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
176 to store the VM snapshots */
177 DriveInfo drives_table
[MAX_DRIVES
+1];
179 int extboot_drive
= -1;
180 /* point to the block driver where the snapshots are managed */
181 BlockDriverState
*bs_snapshots
;
183 static DisplayState display_state
;
186 const char* keyboard_layout
= NULL
;
187 int64_t ticks_per_sec
;
189 int pit_min_timer_count
= 0;
191 NICInfo nd_table
[MAX_NICS
];
193 static int rtc_utc
= 1;
194 static int rtc_date_offset
= -1; /* -1 means no change */
195 int cirrus_vga_enabled
= 1;
196 int vmsvga_enabled
= 0;
198 int graphic_width
= 1024;
199 int graphic_height
= 768;
200 int graphic_depth
= 8;
202 int graphic_width
= 800;
203 int graphic_height
= 600;
204 int graphic_depth
= 15;
209 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
210 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
212 int win2k_install_hack
= 0;
215 static VLANState
*first_vlan
;
217 const char *vnc_display
;
218 #if defined(TARGET_SPARC)
220 #elif defined(TARGET_I386)
222 #elif defined(TARGET_IA64)
227 int acpi_enabled
= 1;
232 int graphic_rotate
= 0;
234 const char *incoming
;
235 const char *option_rom
[MAX_OPTION_ROMS
];
237 int semihosting_enabled
= 0;
239 int time_drift_fix
= 0;
240 unsigned int kvm_shadow_memory
= 0;
241 const char *mem_path
= NULL
;
243 const char *cpu_vendor_string
;
247 const char *qemu_name
;
250 unsigned int nb_prom_envs
= 0;
251 const char *prom_envs
[MAX_PROM_ENVS
];
254 struct drive_opt drives_opt
[MAX_DRIVES
];
256 static CPUState
*cur_cpu
;
257 static CPUState
*next_cpu
;
258 static int event_pending
= 1;
259 /* Conversion factor from emulated instructions to virtual clock ticks. */
260 static int icount_time_shift
;
261 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
262 #define MAX_ICOUNT_SHIFT 10
263 /* Compensate for varying guest execution speed. */
264 static int64_t qemu_icount_bias
;
265 QEMUTimer
*icount_rt_timer
;
266 QEMUTimer
*icount_vm_timer
;
268 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
270 /* KVM runs the main loop in a separate thread. If we update one of the lists
271 * that are polled before or after select(), we need to make sure to break out
272 * of the select() to ensure the new item is serviced.
274 static void main_loop_break(void)
277 qemu_kvm_notify_work();
280 /***********************************************************/
281 /* x86 ISA bus support */
283 target_phys_addr_t isa_mem_base
= 0;
286 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
287 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
289 static uint32_t ioport_read(int index
, uint32_t address
)
291 static IOPortReadFunc
*default_func
[3] = {
292 default_ioport_readb
,
293 default_ioport_readw
,
296 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
298 func
= default_func
[index
];
299 return func(ioport_opaque
[address
], address
);
302 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
304 static IOPortWriteFunc
*default_func
[3] = {
305 default_ioport_writeb
,
306 default_ioport_writew
,
307 default_ioport_writel
309 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
311 func
= default_func
[index
];
312 func(ioport_opaque
[address
], address
, data
);
315 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
317 #ifdef DEBUG_UNUSED_IOPORT
318 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
323 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
325 #ifdef DEBUG_UNUSED_IOPORT
326 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
330 /* default is to make two byte accesses */
331 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
334 data
= ioport_read(0, address
);
335 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
336 data
|= ioport_read(0, address
) << 8;
340 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
342 ioport_write(0, address
, data
& 0xff);
343 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
344 ioport_write(0, address
, (data
>> 8) & 0xff);
347 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
349 #ifdef DEBUG_UNUSED_IOPORT
350 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
355 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
357 #ifdef DEBUG_UNUSED_IOPORT
358 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
362 /* size is the word size in byte */
363 int register_ioport_read(int start
, int length
, int size
,
364 IOPortReadFunc
*func
, void *opaque
)
370 } else if (size
== 2) {
372 } else if (size
== 4) {
375 hw_error("register_ioport_read: invalid size");
378 for(i
= start
; i
< start
+ length
; i
+= size
) {
379 ioport_read_table
[bsize
][i
] = func
;
380 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
381 hw_error("register_ioport_read: invalid opaque");
382 ioport_opaque
[i
] = opaque
;
387 /* size is the word size in byte */
388 int register_ioport_write(int start
, int length
, int size
,
389 IOPortWriteFunc
*func
, void *opaque
)
395 } else if (size
== 2) {
397 } else if (size
== 4) {
400 hw_error("register_ioport_write: invalid size");
403 for(i
= start
; i
< start
+ length
; i
+= size
) {
404 ioport_write_table
[bsize
][i
] = func
;
405 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
406 hw_error("register_ioport_write: invalid opaque");
407 ioport_opaque
[i
] = opaque
;
412 void isa_unassign_ioport(int start
, int length
)
416 for(i
= start
; i
< start
+ length
; i
++) {
417 ioport_read_table
[0][i
] = default_ioport_readb
;
418 ioport_read_table
[1][i
] = default_ioport_readw
;
419 ioport_read_table
[2][i
] = default_ioport_readl
;
421 ioport_write_table
[0][i
] = default_ioport_writeb
;
422 ioport_write_table
[1][i
] = default_ioport_writew
;
423 ioport_write_table
[2][i
] = default_ioport_writel
;
425 ioport_opaque
[i
] = NULL
;
429 /***********************************************************/
431 void cpu_outb(CPUState
*env
, int addr
, int val
)
434 if (loglevel
& CPU_LOG_IOPORT
)
435 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
437 ioport_write(0, addr
, val
);
440 env
->last_io_time
= cpu_get_time_fast();
444 void cpu_outw(CPUState
*env
, int addr
, int val
)
447 if (loglevel
& CPU_LOG_IOPORT
)
448 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
450 ioport_write(1, addr
, val
);
453 env
->last_io_time
= cpu_get_time_fast();
457 void cpu_outl(CPUState
*env
, int addr
, int val
)
460 if (loglevel
& CPU_LOG_IOPORT
)
461 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
463 ioport_write(2, addr
, val
);
466 env
->last_io_time
= cpu_get_time_fast();
470 int cpu_inb(CPUState
*env
, int addr
)
473 val
= ioport_read(0, addr
);
475 if (loglevel
& CPU_LOG_IOPORT
)
476 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
480 env
->last_io_time
= cpu_get_time_fast();
485 int cpu_inw(CPUState
*env
, int addr
)
488 val
= ioport_read(1, addr
);
490 if (loglevel
& CPU_LOG_IOPORT
)
491 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
495 env
->last_io_time
= cpu_get_time_fast();
500 int cpu_inl(CPUState
*env
, int addr
)
503 val
= ioport_read(2, addr
);
505 if (loglevel
& CPU_LOG_IOPORT
)
506 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
510 env
->last_io_time
= cpu_get_time_fast();
515 /***********************************************************/
516 void hw_error(const char *fmt
, ...)
522 fprintf(stderr
, "qemu: hardware error: ");
523 vfprintf(stderr
, fmt
, ap
);
524 fprintf(stderr
, "\n");
525 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
526 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
528 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
530 cpu_dump_state(env
, stderr
, fprintf
, 0);
540 static QEMUBalloonEvent
*qemu_balloon_event
;
541 void *qemu_balloon_event_opaque
;
543 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
545 qemu_balloon_event
= func
;
546 qemu_balloon_event_opaque
= opaque
;
549 void qemu_balloon(ram_addr_t target
)
551 if (qemu_balloon_event
)
552 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
555 ram_addr_t
qemu_balloon_status(void)
557 if (qemu_balloon_event
)
558 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
562 /***********************************************************/
565 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
566 static void *qemu_put_kbd_event_opaque
;
567 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
568 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
570 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
572 qemu_put_kbd_event_opaque
= opaque
;
573 qemu_put_kbd_event
= func
;
576 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
577 void *opaque
, int absolute
,
580 QEMUPutMouseEntry
*s
, *cursor
;
582 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
586 s
->qemu_put_mouse_event
= func
;
587 s
->qemu_put_mouse_event_opaque
= opaque
;
588 s
->qemu_put_mouse_event_absolute
= absolute
;
589 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
592 if (!qemu_put_mouse_event_head
) {
593 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
597 cursor
= qemu_put_mouse_event_head
;
598 while (cursor
->next
!= NULL
)
599 cursor
= cursor
->next
;
602 qemu_put_mouse_event_current
= s
;
607 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
609 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
611 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
614 cursor
= qemu_put_mouse_event_head
;
615 while (cursor
!= NULL
&& cursor
!= entry
) {
617 cursor
= cursor
->next
;
620 if (cursor
== NULL
) // does not exist or list empty
622 else if (prev
== NULL
) { // entry is head
623 qemu_put_mouse_event_head
= cursor
->next
;
624 if (qemu_put_mouse_event_current
== entry
)
625 qemu_put_mouse_event_current
= cursor
->next
;
626 qemu_free(entry
->qemu_put_mouse_event_name
);
631 prev
->next
= entry
->next
;
633 if (qemu_put_mouse_event_current
== entry
)
634 qemu_put_mouse_event_current
= prev
;
636 qemu_free(entry
->qemu_put_mouse_event_name
);
640 void kbd_put_keycode(int keycode
)
642 if (qemu_put_kbd_event
) {
643 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
647 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
649 QEMUPutMouseEvent
*mouse_event
;
650 void *mouse_event_opaque
;
653 if (!qemu_put_mouse_event_current
) {
658 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
660 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
663 if (graphic_rotate
) {
664 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
667 width
= graphic_width
- 1;
668 mouse_event(mouse_event_opaque
,
669 width
- dy
, dx
, dz
, buttons_state
);
671 mouse_event(mouse_event_opaque
,
672 dx
, dy
, dz
, buttons_state
);
676 int kbd_mouse_is_absolute(void)
678 if (!qemu_put_mouse_event_current
)
681 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
684 void do_info_mice(void)
686 QEMUPutMouseEntry
*cursor
;
689 if (!qemu_put_mouse_event_head
) {
690 term_printf("No mouse devices connected\n");
694 term_printf("Mouse devices available:\n");
695 cursor
= qemu_put_mouse_event_head
;
696 while (cursor
!= NULL
) {
697 term_printf("%c Mouse #%d: %s\n",
698 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
699 index
, cursor
->qemu_put_mouse_event_name
);
701 cursor
= cursor
->next
;
705 void do_mouse_set(int index
)
707 QEMUPutMouseEntry
*cursor
;
710 if (!qemu_put_mouse_event_head
) {
711 term_printf("No mouse devices connected\n");
715 cursor
= qemu_put_mouse_event_head
;
716 while (cursor
!= NULL
&& index
!= i
) {
718 cursor
= cursor
->next
;
722 qemu_put_mouse_event_current
= cursor
;
724 term_printf("Mouse at given index not found\n");
727 /* compute with 96 bit intermediate result: (a*b)/c */
728 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
733 #ifdef WORDS_BIGENDIAN
743 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
744 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
747 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
751 /***********************************************************/
752 /* real time host monotonic timer */
754 #define QEMU_TIMER_BASE 1000000000LL
758 static int64_t clock_freq
;
760 static void init_get_clock(void)
764 ret
= QueryPerformanceFrequency(&freq
);
766 fprintf(stderr
, "Could not calibrate ticks\n");
769 clock_freq
= freq
.QuadPart
;
772 static int64_t get_clock(void)
775 QueryPerformanceCounter(&ti
);
776 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
781 static int use_rt_clock
;
783 static void init_get_clock(void)
786 #if defined(__linux__)
789 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
796 static int64_t get_clock(void)
798 #if defined(__linux__)
801 clock_gettime(CLOCK_MONOTONIC
, &ts
);
802 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
806 /* XXX: using gettimeofday leads to problems if the date
807 changes, so it should be avoided. */
809 gettimeofday(&tv
, NULL
);
810 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
815 /* Return the virtual CPU time, based on the instruction counter. */
816 static int64_t cpu_get_icount(void)
819 CPUState
*env
= cpu_single_env
;;
820 icount
= qemu_icount
;
823 fprintf(stderr
, "Bad clock read\n");
824 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
826 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
829 /***********************************************************/
830 /* guest cycle counter */
832 static int64_t cpu_ticks_prev
;
833 static int64_t cpu_ticks_offset
;
834 static int64_t cpu_clock_offset
;
835 static int cpu_ticks_enabled
;
837 /* return the host CPU cycle counter and handle stop/restart */
838 int64_t cpu_get_ticks(void)
841 return cpu_get_icount();
843 if (!cpu_ticks_enabled
) {
844 return cpu_ticks_offset
;
847 ticks
= cpu_get_real_ticks();
848 if (cpu_ticks_prev
> ticks
) {
849 /* Note: non increasing ticks may happen if the host uses
851 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
853 cpu_ticks_prev
= ticks
;
854 return ticks
+ cpu_ticks_offset
;
858 /* return the host CPU monotonic timer and handle stop/restart */
859 static int64_t cpu_get_clock(void)
862 if (!cpu_ticks_enabled
) {
863 return cpu_clock_offset
;
866 return ti
+ cpu_clock_offset
;
870 /* enable cpu_get_ticks() */
871 void cpu_enable_ticks(void)
873 if (!cpu_ticks_enabled
) {
874 cpu_ticks_offset
-= cpu_get_real_ticks();
875 cpu_clock_offset
-= get_clock();
876 cpu_ticks_enabled
= 1;
880 /* disable cpu_get_ticks() : the clock is stopped. You must not call
881 cpu_get_ticks() after that. */
882 void cpu_disable_ticks(void)
884 if (cpu_ticks_enabled
) {
885 cpu_ticks_offset
= cpu_get_ticks();
886 cpu_clock_offset
= cpu_get_clock();
887 cpu_ticks_enabled
= 0;
891 /***********************************************************/
894 #define QEMU_TIMER_REALTIME 0
895 #define QEMU_TIMER_VIRTUAL 1
899 /* XXX: add frequency */
907 struct QEMUTimer
*next
;
910 struct qemu_alarm_timer
{
914 int (*start
)(struct qemu_alarm_timer
*t
);
915 void (*stop
)(struct qemu_alarm_timer
*t
);
916 void (*rearm
)(struct qemu_alarm_timer
*t
);
920 #define ALARM_FLAG_DYNTICKS 0x1
921 #define ALARM_FLAG_EXPIRED 0x2
923 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
925 return t
->flags
& ALARM_FLAG_DYNTICKS
;
928 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
930 if (!alarm_has_dynticks(t
))
936 /* TODO: MIN_TIMER_REARM_US should be optimized */
937 #define MIN_TIMER_REARM_US 250
939 static struct qemu_alarm_timer
*alarm_timer
;
943 struct qemu_alarm_win32
{
947 } alarm_win32_data
= {0, NULL
, -1};
949 static int win32_start_timer(struct qemu_alarm_timer
*t
);
950 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
951 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
955 static int unix_start_timer(struct qemu_alarm_timer
*t
);
956 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
960 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
961 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
962 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
964 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
965 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
967 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
968 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
970 #endif /* __linux__ */
974 /* Correlation between real and virtual time is always going to be
975 fairly approximate, so ignore small variation.
976 When the guest is idle real and virtual time will be aligned in
978 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
980 static void icount_adjust(void)
985 static int64_t last_delta
;
986 /* If the VM is not running, then do nothing. */
990 cur_time
= cpu_get_clock();
991 cur_icount
= qemu_get_clock(vm_clock
);
992 delta
= cur_icount
- cur_time
;
993 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
995 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
996 && icount_time_shift
> 0) {
997 /* The guest is getting too far ahead. Slow time down. */
1001 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1002 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1003 /* The guest is getting too far behind. Speed time up. */
1004 icount_time_shift
++;
1007 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1010 static void icount_adjust_rt(void * opaque
)
1012 qemu_mod_timer(icount_rt_timer
,
1013 qemu_get_clock(rt_clock
) + 1000);
1017 static void icount_adjust_vm(void * opaque
)
1019 qemu_mod_timer(icount_vm_timer
,
1020 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1024 static void init_icount_adjust(void)
1026 /* Have both realtime and virtual time triggers for speed adjustment.
1027 The realtime trigger catches emulated time passing too slowly,
1028 the virtual time trigger catches emulated time passing too fast.
1029 Realtime triggers occur even when idle, so use them less frequently
1030 than VM triggers. */
1031 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1032 qemu_mod_timer(icount_rt_timer
,
1033 qemu_get_clock(rt_clock
) + 1000);
1034 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1035 qemu_mod_timer(icount_vm_timer
,
1036 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1039 static struct qemu_alarm_timer alarm_timers
[] = {
1042 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1043 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1044 /* HPET - if available - is preferred */
1045 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1046 /* ...otherwise try RTC */
1047 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1049 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1051 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1052 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1053 {"win32", 0, win32_start_timer
,
1054 win32_stop_timer
, NULL
, &alarm_win32_data
},
1059 static void show_available_alarms(void)
1063 printf("Available alarm timers, in order of precedence:\n");
1064 for (i
= 0; alarm_timers
[i
].name
; i
++)
1065 printf("%s\n", alarm_timers
[i
].name
);
1068 static void configure_alarms(char const *opt
)
1072 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1075 struct qemu_alarm_timer tmp
;
1077 if (!strcmp(opt
, "?")) {
1078 show_available_alarms();
1084 /* Reorder the array */
1085 name
= strtok(arg
, ",");
1087 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1088 if (!strcmp(alarm_timers
[i
].name
, name
))
1093 fprintf(stderr
, "Unknown clock %s\n", name
);
1102 tmp
= alarm_timers
[i
];
1103 alarm_timers
[i
] = alarm_timers
[cur
];
1104 alarm_timers
[cur
] = tmp
;
1108 name
= strtok(NULL
, ",");
1114 /* Disable remaining timers */
1115 for (i
= cur
; i
< count
; i
++)
1116 alarm_timers
[i
].name
= NULL
;
1118 show_available_alarms();
1123 QEMUClock
*rt_clock
;
1124 QEMUClock
*vm_clock
;
1126 static QEMUTimer
*active_timers
[2];
1128 static QEMUClock
*qemu_new_clock(int type
)
1131 clock
= qemu_mallocz(sizeof(QEMUClock
));
1138 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1142 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1145 ts
->opaque
= opaque
;
1149 void qemu_free_timer(QEMUTimer
*ts
)
1154 /* stop a timer, but do not dealloc it */
1155 void qemu_del_timer(QEMUTimer
*ts
)
1159 /* NOTE: this code must be signal safe because
1160 qemu_timer_expired() can be called from a signal. */
1161 pt
= &active_timers
[ts
->clock
->type
];
1174 /* modify the current timer so that it will be fired when current_time
1175 >= expire_time. The corresponding callback will be called. */
1176 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1182 /* add the timer in the sorted list */
1183 /* NOTE: this code must be signal safe because
1184 qemu_timer_expired() can be called from a signal. */
1185 pt
= &active_timers
[ts
->clock
->type
];
1190 if (t
->expire_time
> expire_time
)
1194 ts
->expire_time
= expire_time
;
1198 /* Rearm if necessary */
1199 if (pt
== &active_timers
[ts
->clock
->type
]) {
1200 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1201 qemu_rearm_alarm_timer(alarm_timer
);
1203 /* Interrupt execution to force deadline recalculation. */
1204 if (use_icount
&& cpu_single_env
) {
1205 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1210 int qemu_timer_pending(QEMUTimer
*ts
)
1213 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1220 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1224 return (timer_head
->expire_time
<= current_time
);
1227 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1233 if (!ts
|| ts
->expire_time
> current_time
)
1235 /* remove timer from the list before calling the callback */
1236 *ptimer_head
= ts
->next
;
1239 /* run the callback (the timer list can be modified) */
1244 int64_t qemu_get_clock(QEMUClock
*clock
)
1246 switch(clock
->type
) {
1247 case QEMU_TIMER_REALTIME
:
1248 return get_clock() / 1000000;
1250 case QEMU_TIMER_VIRTUAL
:
1252 return cpu_get_icount();
1254 return cpu_get_clock();
1259 static void init_timers(void)
1262 ticks_per_sec
= QEMU_TIMER_BASE
;
1263 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1264 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1268 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1270 uint64_t expire_time
;
1272 if (qemu_timer_pending(ts
)) {
1273 expire_time
= ts
->expire_time
;
1277 qemu_put_be64(f
, expire_time
);
1280 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1282 uint64_t expire_time
;
1284 expire_time
= qemu_get_be64(f
);
1285 if (expire_time
!= -1) {
1286 qemu_mod_timer(ts
, expire_time
);
1292 static void timer_save(QEMUFile
*f
, void *opaque
)
1294 if (cpu_ticks_enabled
) {
1295 hw_error("cannot save state if virtual timers are running");
1297 qemu_put_be64(f
, cpu_ticks_offset
);
1298 qemu_put_be64(f
, ticks_per_sec
);
1299 qemu_put_be64(f
, cpu_clock_offset
);
1302 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1304 if (version_id
!= 1 && version_id
!= 2)
1306 if (cpu_ticks_enabled
) {
1309 cpu_ticks_offset
=qemu_get_be64(f
);
1310 ticks_per_sec
=qemu_get_be64(f
);
1311 if (version_id
== 2) {
1312 cpu_clock_offset
=qemu_get_be64(f
);
1318 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1319 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1321 static void host_alarm_handler(int host_signum
)
1325 #define DISP_FREQ 1000
1327 static int64_t delta_min
= INT64_MAX
;
1328 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1330 ti
= qemu_get_clock(vm_clock
);
1331 if (last_clock
!= 0) {
1332 delta
= ti
- last_clock
;
1333 if (delta
< delta_min
)
1335 if (delta
> delta_max
)
1338 if (++count
== DISP_FREQ
) {
1339 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1340 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1341 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1342 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1343 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1345 delta_min
= INT64_MAX
;
1354 alarm_has_dynticks(alarm_timer
) ||
1356 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1357 qemu_get_clock(vm_clock
))) ||
1358 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1359 qemu_get_clock(rt_clock
))) {
1361 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1362 SetEvent(data
->host_alarm
);
1364 CPUState
*env
= next_cpu
;
1366 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1369 /* stop the currently executing cpu because a timer occured */
1370 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1372 if (env
->kqemu_enabled
) {
1373 kqemu_cpu_interrupt(env
);
1381 static int64_t qemu_next_deadline(void)
1385 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1386 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1387 qemu_get_clock(vm_clock
);
1389 /* To avoid problems with overflow limit this to 2^32. */
1399 #if defined(__linux__) || defined(_WIN32)
1400 static uint64_t qemu_next_deadline_dyntick(void)
1408 delta
= (qemu_next_deadline() + 999) / 1000;
1410 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1411 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1412 qemu_get_clock(rt_clock
))*1000;
1413 if (rtdelta
< delta
)
1417 if (delta
< MIN_TIMER_REARM_US
)
1418 delta
= MIN_TIMER_REARM_US
;
1426 #if defined(__linux__)
1428 #define RTC_FREQ 1024
1430 static void enable_sigio_timer(int fd
)
1432 struct sigaction act
;
1435 sigfillset(&act
.sa_mask
);
1437 act
.sa_handler
= host_alarm_handler
;
1439 sigaction(SIGIO
, &act
, NULL
);
1440 fcntl(fd
, F_SETFL
, O_ASYNC
);
1441 fcntl(fd
, F_SETOWN
, getpid());
1444 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1446 struct hpet_info info
;
1449 fd
= open("/dev/hpet", O_RDONLY
);
1454 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1456 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1457 "error, but for better emulation accuracy type:\n"
1458 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1462 /* Check capabilities */
1463 r
= ioctl(fd
, HPET_INFO
, &info
);
1467 /* Enable periodic mode */
1468 r
= ioctl(fd
, HPET_EPI
, 0);
1469 if (info
.hi_flags
&& (r
< 0))
1472 /* Enable interrupt */
1473 r
= ioctl(fd
, HPET_IE_ON
, 0);
1477 enable_sigio_timer(fd
);
1478 t
->priv
= (void *)(long)fd
;
1486 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1488 int fd
= (long)t
->priv
;
1493 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1496 unsigned long current_rtc_freq
= 0;
1498 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1501 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1502 if (current_rtc_freq
!= RTC_FREQ
&&
1503 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1504 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1505 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1506 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1509 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1515 enable_sigio_timer(rtc_fd
);
1517 t
->priv
= (void *)(long)rtc_fd
;
1522 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1524 int rtc_fd
= (long)t
->priv
;
1529 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1533 struct sigaction act
;
1535 sigfillset(&act
.sa_mask
);
1537 act
.sa_handler
= host_alarm_handler
;
1539 sigaction(SIGALRM
, &act
, NULL
);
1541 ev
.sigev_value
.sival_int
= 0;
1542 ev
.sigev_notify
= SIGEV_SIGNAL
;
1543 ev
.sigev_signo
= SIGALRM
;
1545 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1546 perror("timer_create");
1548 /* disable dynticks */
1549 fprintf(stderr
, "Dynamic Ticks disabled\n");
1554 t
->priv
= (void *)host_timer
;
1559 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1561 timer_t host_timer
= (timer_t
)t
->priv
;
1563 timer_delete(host_timer
);
1566 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1568 timer_t host_timer
= (timer_t
)t
->priv
;
1569 struct itimerspec timeout
;
1570 int64_t nearest_delta_us
= INT64_MAX
;
1573 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1574 !active_timers
[QEMU_TIMER_VIRTUAL
])
1577 nearest_delta_us
= qemu_next_deadline_dyntick();
1579 /* check whether a timer is already running */
1580 if (timer_gettime(host_timer
, &timeout
)) {
1582 fprintf(stderr
, "Internal timer error: aborting\n");
1585 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1586 if (current_us
&& current_us
<= nearest_delta_us
)
1589 timeout
.it_interval
.tv_sec
= 0;
1590 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1591 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1592 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1593 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1595 fprintf(stderr
, "Internal timer error: aborting\n");
1600 #endif /* defined(__linux__) */
1602 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1604 struct sigaction act
;
1605 struct itimerval itv
;
1609 sigfillset(&act
.sa_mask
);
1611 act
.sa_handler
= host_alarm_handler
;
1613 sigaction(SIGALRM
, &act
, NULL
);
1615 itv
.it_interval
.tv_sec
= 0;
1616 /* for i386 kernel 2.6 to get 1 ms */
1617 itv
.it_interval
.tv_usec
= 999;
1618 itv
.it_value
.tv_sec
= 0;
1619 itv
.it_value
.tv_usec
= 10 * 1000;
1621 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1628 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1630 struct itimerval itv
;
1632 memset(&itv
, 0, sizeof(itv
));
1633 setitimer(ITIMER_REAL
, &itv
, NULL
);
1636 #endif /* !defined(_WIN32) */
1640 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1643 struct qemu_alarm_win32
*data
= t
->priv
;
1646 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1647 if (!data
->host_alarm
) {
1648 perror("Failed CreateEvent");
1652 memset(&tc
, 0, sizeof(tc
));
1653 timeGetDevCaps(&tc
, sizeof(tc
));
1655 if (data
->period
< tc
.wPeriodMin
)
1656 data
->period
= tc
.wPeriodMin
;
1658 timeBeginPeriod(data
->period
);
1660 flags
= TIME_CALLBACK_FUNCTION
;
1661 if (alarm_has_dynticks(t
))
1662 flags
|= TIME_ONESHOT
;
1664 flags
|= TIME_PERIODIC
;
1666 data
->timerId
= timeSetEvent(1, // interval (ms)
1667 data
->period
, // resolution
1668 host_alarm_handler
, // function
1669 (DWORD
)t
, // parameter
1672 if (!data
->timerId
) {
1673 perror("Failed to initialize win32 alarm timer");
1675 timeEndPeriod(data
->period
);
1676 CloseHandle(data
->host_alarm
);
1680 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1685 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1687 struct qemu_alarm_win32
*data
= t
->priv
;
1689 timeKillEvent(data
->timerId
);
1690 timeEndPeriod(data
->period
);
1692 CloseHandle(data
->host_alarm
);
1695 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1697 struct qemu_alarm_win32
*data
= t
->priv
;
1698 uint64_t nearest_delta_us
;
1700 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1701 !active_timers
[QEMU_TIMER_VIRTUAL
])
1704 nearest_delta_us
= qemu_next_deadline_dyntick();
1705 nearest_delta_us
/= 1000;
1707 timeKillEvent(data
->timerId
);
1709 data
->timerId
= timeSetEvent(1,
1713 TIME_ONESHOT
| TIME_PERIODIC
);
1715 if (!data
->timerId
) {
1716 perror("Failed to re-arm win32 alarm timer");
1718 timeEndPeriod(data
->period
);
1719 CloseHandle(data
->host_alarm
);
1726 static void init_timer_alarm(void)
1728 struct qemu_alarm_timer
*t
;
1731 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1732 t
= &alarm_timers
[i
];
1740 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1741 fprintf(stderr
, "Terminating\n");
1748 static void quit_timers(void)
1750 alarm_timer
->stop(alarm_timer
);
1754 /***********************************************************/
1755 /* host time/date access */
1756 void qemu_get_timedate(struct tm
*tm
, int offset
)
1763 if (rtc_date_offset
== -1) {
1767 ret
= localtime(&ti
);
1769 ti
-= rtc_date_offset
;
1773 memcpy(tm
, ret
, sizeof(struct tm
));
1776 int qemu_timedate_diff(struct tm
*tm
)
1780 if (rtc_date_offset
== -1)
1782 seconds
= mktimegm(tm
);
1784 seconds
= mktime(tm
);
1786 seconds
= mktimegm(tm
) + rtc_date_offset
;
1788 return seconds
- time(NULL
);
1791 /***********************************************************/
1792 /* character device */
1794 static void qemu_chr_event(CharDriverState
*s
, int event
)
1798 s
->chr_event(s
->handler_opaque
, event
);
1801 static void qemu_chr_reset_bh(void *opaque
)
1803 CharDriverState
*s
= opaque
;
1804 qemu_chr_event(s
, CHR_EVENT_RESET
);
1805 qemu_bh_delete(s
->bh
);
1809 void qemu_chr_reset(CharDriverState
*s
)
1811 if (s
->bh
== NULL
) {
1812 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1813 qemu_bh_schedule(s
->bh
);
1817 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1819 return s
->chr_write(s
, buf
, len
);
1822 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1826 return s
->chr_ioctl(s
, cmd
, arg
);
1829 int qemu_chr_can_read(CharDriverState
*s
)
1831 if (!s
->chr_can_read
)
1833 return s
->chr_can_read(s
->handler_opaque
);
1836 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1838 s
->chr_read(s
->handler_opaque
, buf
, len
);
1841 void qemu_chr_accept_input(CharDriverState
*s
)
1843 if (s
->chr_accept_input
)
1844 s
->chr_accept_input(s
);
1847 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1852 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1853 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1857 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1859 if (s
->chr_send_event
)
1860 s
->chr_send_event(s
, event
);
1863 void qemu_chr_add_handlers(CharDriverState
*s
,
1864 IOCanRWHandler
*fd_can_read
,
1865 IOReadHandler
*fd_read
,
1866 IOEventHandler
*fd_event
,
1869 s
->chr_can_read
= fd_can_read
;
1870 s
->chr_read
= fd_read
;
1871 s
->chr_event
= fd_event
;
1872 s
->handler_opaque
= opaque
;
1873 if (s
->chr_update_read_handler
)
1874 s
->chr_update_read_handler(s
);
1877 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1882 static CharDriverState
*qemu_chr_open_null(void)
1884 CharDriverState
*chr
;
1886 chr
= qemu_mallocz(sizeof(CharDriverState
));
1889 chr
->chr_write
= null_chr_write
;
1893 /* MUX driver for serial I/O splitting */
1894 static int term_timestamps
;
1895 static int64_t term_timestamps_start
;
1897 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1898 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1900 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1901 IOReadHandler
*chr_read
[MAX_MUX
];
1902 IOEventHandler
*chr_event
[MAX_MUX
];
1903 void *ext_opaque
[MAX_MUX
];
1904 CharDriverState
*drv
;
1905 unsigned char buffer
[MUX_BUFFER_SIZE
];
1909 int term_got_escape
;
1914 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1916 MuxDriver
*d
= chr
->opaque
;
1918 if (!term_timestamps
) {
1919 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1924 for(i
= 0; i
< len
; i
++) {
1925 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1926 if (buf
[i
] == '\n') {
1932 if (term_timestamps_start
== -1)
1933 term_timestamps_start
= ti
;
1934 ti
-= term_timestamps_start
;
1935 secs
= ti
/ 1000000000;
1936 snprintf(buf1
, sizeof(buf1
),
1937 "[%02d:%02d:%02d.%03d] ",
1941 (int)((ti
/ 1000000) % 1000));
1942 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1949 static const char * const mux_help
[] = {
1950 "% h print this help\n\r",
1951 "% x exit emulator\n\r",
1952 "% s save disk data back to file (if -snapshot)\n\r",
1953 "% t toggle console timestamps\n\r"
1954 "% b send break (magic sysrq)\n\r",
1955 "% c switch between console and monitor\n\r",
1960 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1961 static void mux_print_help(CharDriverState
*chr
)
1964 char ebuf
[15] = "Escape-Char";
1965 char cbuf
[50] = "\n\r";
1967 if (term_escape_char
> 0 && term_escape_char
< 26) {
1968 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1969 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1971 snprintf(cbuf
, sizeof(cbuf
),
1972 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1975 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1976 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1977 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1978 if (mux_help
[i
][j
] == '%')
1979 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1981 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1986 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1988 if (d
->term_got_escape
) {
1989 d
->term_got_escape
= 0;
1990 if (ch
== term_escape_char
)
1995 mux_print_help(chr
);
1999 const char *term
= "QEMU: Terminated\n\r";
2000 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
2007 for (i
= 0; i
< nb_drives
; i
++) {
2008 bdrv_commit(drives_table
[i
].bdrv
);
2013 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2016 /* Switch to the next registered device */
2018 if (chr
->focus
>= d
->mux_cnt
)
2022 term_timestamps
= !term_timestamps
;
2023 term_timestamps_start
= -1;
2026 } else if (ch
== term_escape_char
) {
2027 d
->term_got_escape
= 1;
2035 static void mux_chr_accept_input(CharDriverState
*chr
)
2038 MuxDriver
*d
= chr
->opaque
;
2040 while (d
->prod
!= d
->cons
&&
2041 d
->chr_can_read
[m
] &&
2042 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
2043 d
->chr_read
[m
](d
->ext_opaque
[m
],
2044 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2048 static int mux_chr_can_read(void *opaque
)
2050 CharDriverState
*chr
= opaque
;
2051 MuxDriver
*d
= chr
->opaque
;
2053 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2055 if (d
->chr_can_read
[chr
->focus
])
2056 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2060 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2062 CharDriverState
*chr
= opaque
;
2063 MuxDriver
*d
= chr
->opaque
;
2067 mux_chr_accept_input (opaque
);
2069 for(i
= 0; i
< size
; i
++)
2070 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2071 if (d
->prod
== d
->cons
&&
2072 d
->chr_can_read
[m
] &&
2073 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2074 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2076 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2080 static void mux_chr_event(void *opaque
, int event
)
2082 CharDriverState
*chr
= opaque
;
2083 MuxDriver
*d
= chr
->opaque
;
2086 /* Send the event to all registered listeners */
2087 for (i
= 0; i
< d
->mux_cnt
; i
++)
2088 if (d
->chr_event
[i
])
2089 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2092 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2094 MuxDriver
*d
= chr
->opaque
;
2096 if (d
->mux_cnt
>= MAX_MUX
) {
2097 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2100 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2101 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2102 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2103 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2104 /* Fix up the real driver with mux routines */
2105 if (d
->mux_cnt
== 0) {
2106 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2107 mux_chr_event
, chr
);
2109 chr
->focus
= d
->mux_cnt
;
2113 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2115 CharDriverState
*chr
;
2118 chr
= qemu_mallocz(sizeof(CharDriverState
));
2121 d
= qemu_mallocz(sizeof(MuxDriver
));
2130 chr
->chr_write
= mux_chr_write
;
2131 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2132 chr
->chr_accept_input
= mux_chr_accept_input
;
2139 static void socket_cleanup(void)
2144 static int socket_init(void)
2149 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2151 err
= WSAGetLastError();
2152 fprintf(stderr
, "WSAStartup: %d\n", err
);
2155 atexit(socket_cleanup
);
2159 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2165 ret
= send(fd
, buf
, len
, 0);
2168 errno
= WSAGetLastError();
2169 if (errno
!= WSAEWOULDBLOCK
) {
2172 } else if (ret
== 0) {
2184 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2190 ret
= write(fd
, buf
, len
);
2192 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2194 } else if (ret
== 0) {
2204 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2206 return unix_write(fd
, buf
, len1
);
2208 #endif /* !_WIN32 */
2217 #define STDIO_MAX_CLIENTS 1
2218 static int stdio_nb_clients
= 0;
2220 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2222 FDCharDriver
*s
= chr
->opaque
;
2223 return unix_write(s
->fd_out
, buf
, len
);
2226 static int fd_chr_read_poll(void *opaque
)
2228 CharDriverState
*chr
= opaque
;
2229 FDCharDriver
*s
= chr
->opaque
;
2231 s
->max_size
= qemu_chr_can_read(chr
);
2235 static void fd_chr_read(void *opaque
)
2237 CharDriverState
*chr
= opaque
;
2238 FDCharDriver
*s
= chr
->opaque
;
2243 if (len
> s
->max_size
)
2247 size
= read(s
->fd_in
, buf
, len
);
2249 /* FD has been closed. Remove it from the active list. */
2250 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2254 qemu_chr_read(chr
, buf
, size
);
2258 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2260 FDCharDriver
*s
= chr
->opaque
;
2262 if (s
->fd_in
>= 0) {
2263 if (nographic
&& s
->fd_in
== 0) {
2265 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2266 fd_chr_read
, NULL
, chr
);
2271 static void fd_chr_close(struct CharDriverState
*chr
)
2273 FDCharDriver
*s
= chr
->opaque
;
2275 if (s
->fd_in
>= 0) {
2276 if (nographic
&& s
->fd_in
== 0) {
2278 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2285 /* open a character device to a unix fd */
2286 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2288 CharDriverState
*chr
;
2291 chr
= qemu_mallocz(sizeof(CharDriverState
));
2294 s
= qemu_mallocz(sizeof(FDCharDriver
));
2302 chr
->chr_write
= fd_chr_write
;
2303 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2304 chr
->chr_close
= fd_chr_close
;
2306 qemu_chr_reset(chr
);
2311 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2315 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2318 return qemu_chr_open_fd(-1, fd_out
);
2321 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2324 char filename_in
[256], filename_out
[256];
2326 snprintf(filename_in
, 256, "%s.in", filename
);
2327 snprintf(filename_out
, 256, "%s.out", filename
);
2328 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2329 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2330 if (fd_in
< 0 || fd_out
< 0) {
2335 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2339 return qemu_chr_open_fd(fd_in
, fd_out
);
2343 /* for STDIO, we handle the case where several clients use it
2346 #define TERM_FIFO_MAX_SIZE 1
2348 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2349 static int term_fifo_size
;
2351 static int stdio_read_poll(void *opaque
)
2353 CharDriverState
*chr
= opaque
;
2355 /* try to flush the queue if needed */
2356 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2357 qemu_chr_read(chr
, term_fifo
, 1);
2360 /* see if we can absorb more chars */
2361 if (term_fifo_size
== 0)
2367 static void stdio_read(void *opaque
)
2371 CharDriverState
*chr
= opaque
;
2373 size
= read(0, buf
, 1);
2375 /* stdin has been closed. Remove it from the active list. */
2376 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2380 if (qemu_chr_can_read(chr
) > 0) {
2381 qemu_chr_read(chr
, buf
, 1);
2382 } else if (term_fifo_size
== 0) {
2383 term_fifo
[term_fifo_size
++] = buf
[0];
2388 /* init terminal so that we can grab keys */
2389 static struct termios oldtty
;
2390 static int old_fd0_flags
;
2391 static int term_atexit_done
;
2393 static void term_exit(void)
2395 tcsetattr (0, TCSANOW
, &oldtty
);
2396 fcntl(0, F_SETFL
, old_fd0_flags
);
2399 static void term_init(void)
2403 tcgetattr (0, &tty
);
2405 old_fd0_flags
= fcntl(0, F_GETFL
);
2407 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2408 |INLCR
|IGNCR
|ICRNL
|IXON
);
2409 tty
.c_oflag
|= OPOST
;
2410 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2411 /* if graphical mode, we allow Ctrl-C handling */
2413 tty
.c_lflag
&= ~ISIG
;
2414 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2417 tty
.c_cc
[VTIME
] = 0;
2419 tcsetattr (0, TCSANOW
, &tty
);
2421 if (!term_atexit_done
++)
2424 fcntl(0, F_SETFL
, O_NONBLOCK
);
2427 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2431 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2435 static CharDriverState
*qemu_chr_open_stdio(void)
2437 CharDriverState
*chr
;
2439 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2441 chr
= qemu_chr_open_fd(0, 1);
2442 chr
->chr_close
= qemu_chr_close_stdio
;
2443 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2451 /* Once Solaris has openpty(), this is going to be removed. */
2452 int openpty(int *amaster
, int *aslave
, char *name
,
2453 struct termios
*termp
, struct winsize
*winp
)
2456 int mfd
= -1, sfd
= -1;
2458 *amaster
= *aslave
= -1;
2460 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2464 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2467 if ((slave
= ptsname(mfd
)) == NULL
)
2470 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2473 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2474 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2482 ioctl(sfd
, TIOCSWINSZ
, winp
);
2493 void cfmakeraw (struct termios
*termios_p
)
2495 termios_p
->c_iflag
&=
2496 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2497 termios_p
->c_oflag
&= ~OPOST
;
2498 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2499 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2500 termios_p
->c_cflag
|= CS8
;
2502 termios_p
->c_cc
[VMIN
] = 0;
2503 termios_p
->c_cc
[VTIME
] = 0;
2507 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2508 || defined(__NetBSD__) || defined(__OpenBSD__)
2518 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2519 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2521 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2523 PtyCharDriver
*s
= chr
->opaque
;
2525 if (!s
->connected
) {
2526 /* guest sends data, check for (re-)connect */
2527 pty_chr_update_read_handler(chr
);
2530 return unix_write(s
->fd
, buf
, len
);
2533 static int pty_chr_read_poll(void *opaque
)
2535 CharDriverState
*chr
= opaque
;
2536 PtyCharDriver
*s
= chr
->opaque
;
2538 s
->read_bytes
= qemu_chr_can_read(chr
);
2539 return s
->read_bytes
;
2542 static void pty_chr_read(void *opaque
)
2544 CharDriverState
*chr
= opaque
;
2545 PtyCharDriver
*s
= chr
->opaque
;
2550 if (len
> s
->read_bytes
)
2551 len
= s
->read_bytes
;
2554 size
= read(s
->fd
, buf
, len
);
2555 if ((size
== -1 && errno
== EIO
) ||
2557 pty_chr_state(chr
, 0);
2561 pty_chr_state(chr
, 1);
2562 qemu_chr_read(chr
, buf
, size
);
2566 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2568 PtyCharDriver
*s
= chr
->opaque
;
2570 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2571 pty_chr_read
, NULL
, chr
);
2574 * Short timeout here: just need wait long enougth that qemu makes
2575 * it through the poll loop once. When reconnected we want a
2576 * short timeout so we notice it almost instantly. Otherwise
2577 * read() gives us -EIO instantly, making pty_chr_state() reset the
2578 * timeout to the normal (much longer) poll interval before the
2581 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2584 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2586 PtyCharDriver
*s
= chr
->opaque
;
2589 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2592 /* (re-)connect poll interval for idle guests: once per second.
2593 * We check more frequently in case the guests sends data to
2594 * the virtual device linked to our pty. */
2595 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2598 qemu_chr_reset(chr
);
2603 static void pty_chr_timer(void *opaque
)
2605 struct CharDriverState
*chr
= opaque
;
2606 PtyCharDriver
*s
= chr
->opaque
;
2611 /* If we arrive here without polling being cleared due
2612 * read returning -EIO, then we are (re-)connected */
2613 pty_chr_state(chr
, 1);
2618 pty_chr_update_read_handler(chr
);
2621 static void pty_chr_close(struct CharDriverState
*chr
)
2623 PtyCharDriver
*s
= chr
->opaque
;
2625 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2630 static CharDriverState
*qemu_chr_open_pty(void)
2632 CharDriverState
*chr
;
2636 #if defined(__OpenBSD__)
2637 char pty_name
[PATH_MAX
];
2638 #define q_ptsname(x) pty_name
2640 char *pty_name
= NULL
;
2641 #define q_ptsname(x) ptsname(x)
2644 chr
= qemu_mallocz(sizeof(CharDriverState
));
2647 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2653 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2657 /* Set raw attributes on the pty. */
2659 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2662 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2665 chr
->chr_write
= pty_chr_write
;
2666 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2667 chr
->chr_close
= pty_chr_close
;
2669 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2674 static void tty_serial_init(int fd
, int speed
,
2675 int parity
, int data_bits
, int stop_bits
)
2681 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2682 speed
, parity
, data_bits
, stop_bits
);
2684 tcgetattr (fd
, &tty
);
2687 if (speed
<= 50 * MARGIN
)
2689 else if (speed
<= 75 * MARGIN
)
2691 else if (speed
<= 300 * MARGIN
)
2693 else if (speed
<= 600 * MARGIN
)
2695 else if (speed
<= 1200 * MARGIN
)
2697 else if (speed
<= 2400 * MARGIN
)
2699 else if (speed
<= 4800 * MARGIN
)
2701 else if (speed
<= 9600 * MARGIN
)
2703 else if (speed
<= 19200 * MARGIN
)
2705 else if (speed
<= 38400 * MARGIN
)
2707 else if (speed
<= 57600 * MARGIN
)
2709 else if (speed
<= 115200 * MARGIN
)
2714 cfsetispeed(&tty
, spd
);
2715 cfsetospeed(&tty
, spd
);
2717 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2718 |INLCR
|IGNCR
|ICRNL
|IXON
);
2719 tty
.c_oflag
|= OPOST
;
2720 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2721 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2742 tty
.c_cflag
|= PARENB
;
2745 tty
.c_cflag
|= PARENB
| PARODD
;
2749 tty
.c_cflag
|= CSTOPB
;
2751 tcsetattr (fd
, TCSANOW
, &tty
);
2754 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2756 FDCharDriver
*s
= chr
->opaque
;
2759 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2761 QEMUSerialSetParams
*ssp
= arg
;
2762 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2763 ssp
->data_bits
, ssp
->stop_bits
);
2766 case CHR_IOCTL_SERIAL_SET_BREAK
:
2768 int enable
= *(int *)arg
;
2770 tcsendbreak(s
->fd_in
, 1);
2773 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2776 int *targ
= (int *)arg
;
2777 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2779 if (sarg
| TIOCM_CTS
)
2780 *targ
|= CHR_TIOCM_CTS
;
2781 if (sarg
| TIOCM_CAR
)
2782 *targ
|= CHR_TIOCM_CAR
;
2783 if (sarg
| TIOCM_DSR
)
2784 *targ
|= CHR_TIOCM_DSR
;
2785 if (sarg
| TIOCM_RI
)
2786 *targ
|= CHR_TIOCM_RI
;
2787 if (sarg
| TIOCM_DTR
)
2788 *targ
|= CHR_TIOCM_DTR
;
2789 if (sarg
| TIOCM_RTS
)
2790 *targ
|= CHR_TIOCM_RTS
;
2793 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2795 int sarg
= *(int *)arg
;
2797 if (sarg
| CHR_TIOCM_DTR
)
2799 if (sarg
| CHR_TIOCM_RTS
)
2801 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2810 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2812 CharDriverState
*chr
;
2815 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2816 tty_serial_init(fd
, 115200, 'N', 8, 1);
2817 chr
= qemu_chr_open_fd(fd
, fd
);
2822 chr
->chr_ioctl
= tty_serial_ioctl
;
2823 qemu_chr_reset(chr
);
2826 #else /* ! __linux__ && ! __sun__ */
2827 static CharDriverState
*qemu_chr_open_pty(void)
2831 #endif /* __linux__ || __sun__ */
2833 #if defined(__linux__)
2837 } ParallelCharDriver
;
2839 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2841 if (s
->mode
!= mode
) {
2843 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2850 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2852 ParallelCharDriver
*drv
= chr
->opaque
;
2857 case CHR_IOCTL_PP_READ_DATA
:
2858 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2860 *(uint8_t *)arg
= b
;
2862 case CHR_IOCTL_PP_WRITE_DATA
:
2863 b
= *(uint8_t *)arg
;
2864 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2867 case CHR_IOCTL_PP_READ_CONTROL
:
2868 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2870 /* Linux gives only the lowest bits, and no way to know data
2871 direction! For better compatibility set the fixed upper
2873 *(uint8_t *)arg
= b
| 0xc0;
2875 case CHR_IOCTL_PP_WRITE_CONTROL
:
2876 b
= *(uint8_t *)arg
;
2877 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2880 case CHR_IOCTL_PP_READ_STATUS
:
2881 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2883 *(uint8_t *)arg
= b
;
2885 case CHR_IOCTL_PP_DATA_DIR
:
2886 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2889 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2890 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2891 struct ParallelIOArg
*parg
= arg
;
2892 int n
= read(fd
, parg
->buffer
, parg
->count
);
2893 if (n
!= parg
->count
) {
2898 case CHR_IOCTL_PP_EPP_READ
:
2899 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2900 struct ParallelIOArg
*parg
= arg
;
2901 int n
= read(fd
, parg
->buffer
, parg
->count
);
2902 if (n
!= parg
->count
) {
2907 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2908 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2909 struct ParallelIOArg
*parg
= arg
;
2910 int n
= write(fd
, parg
->buffer
, parg
->count
);
2911 if (n
!= parg
->count
) {
2916 case CHR_IOCTL_PP_EPP_WRITE
:
2917 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2918 struct ParallelIOArg
*parg
= arg
;
2919 int n
= write(fd
, parg
->buffer
, parg
->count
);
2920 if (n
!= parg
->count
) {
2931 static void pp_close(CharDriverState
*chr
)
2933 ParallelCharDriver
*drv
= chr
->opaque
;
2936 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2937 ioctl(fd
, PPRELEASE
);
2942 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2944 CharDriverState
*chr
;
2945 ParallelCharDriver
*drv
;
2948 TFR(fd
= open(filename
, O_RDWR
));
2952 if (ioctl(fd
, PPCLAIM
) < 0) {
2957 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2963 drv
->mode
= IEEE1284_MODE_COMPAT
;
2965 chr
= qemu_mallocz(sizeof(CharDriverState
));
2971 chr
->chr_write
= null_chr_write
;
2972 chr
->chr_ioctl
= pp_ioctl
;
2973 chr
->chr_close
= pp_close
;
2976 qemu_chr_reset(chr
);
2980 #endif /* __linux__ */
2986 HANDLE hcom
, hrecv
, hsend
;
2987 OVERLAPPED orecv
, osend
;
2992 #define NSENDBUF 2048
2993 #define NRECVBUF 2048
2994 #define MAXCONNECT 1
2995 #define NTIMEOUT 5000
2997 static int win_chr_poll(void *opaque
);
2998 static int win_chr_pipe_poll(void *opaque
);
3000 static void win_chr_close(CharDriverState
*chr
)
3002 WinCharState
*s
= chr
->opaque
;
3005 CloseHandle(s
->hsend
);
3009 CloseHandle(s
->hrecv
);
3013 CloseHandle(s
->hcom
);
3017 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
3019 qemu_del_polling_cb(win_chr_poll
, chr
);
3022 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
3024 WinCharState
*s
= chr
->opaque
;
3026 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
3031 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3033 fprintf(stderr
, "Failed CreateEvent\n");
3036 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3038 fprintf(stderr
, "Failed CreateEvent\n");
3042 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
3043 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3044 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3045 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3050 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3051 fprintf(stderr
, "Failed SetupComm\n");
3055 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3056 size
= sizeof(COMMCONFIG
);
3057 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3058 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3059 CommConfigDialog(filename
, NULL
, &comcfg
);
3061 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3062 fprintf(stderr
, "Failed SetCommState\n");
3066 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3067 fprintf(stderr
, "Failed SetCommMask\n");
3071 cto
.ReadIntervalTimeout
= MAXDWORD
;
3072 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3073 fprintf(stderr
, "Failed SetCommTimeouts\n");
3077 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3078 fprintf(stderr
, "Failed ClearCommError\n");
3081 qemu_add_polling_cb(win_chr_poll
, chr
);
3089 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3091 WinCharState
*s
= chr
->opaque
;
3092 DWORD len
, ret
, size
, err
;
3095 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3096 s
->osend
.hEvent
= s
->hsend
;
3099 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3101 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3103 err
= GetLastError();
3104 if (err
== ERROR_IO_PENDING
) {
3105 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3123 static int win_chr_read_poll(CharDriverState
*chr
)
3125 WinCharState
*s
= chr
->opaque
;
3127 s
->max_size
= qemu_chr_can_read(chr
);
3131 static void win_chr_readfile(CharDriverState
*chr
)
3133 WinCharState
*s
= chr
->opaque
;
3138 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3139 s
->orecv
.hEvent
= s
->hrecv
;
3140 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3142 err
= GetLastError();
3143 if (err
== ERROR_IO_PENDING
) {
3144 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3149 qemu_chr_read(chr
, buf
, size
);
3153 static void win_chr_read(CharDriverState
*chr
)
3155 WinCharState
*s
= chr
->opaque
;
3157 if (s
->len
> s
->max_size
)
3158 s
->len
= s
->max_size
;
3162 win_chr_readfile(chr
);
3165 static int win_chr_poll(void *opaque
)
3167 CharDriverState
*chr
= opaque
;
3168 WinCharState
*s
= chr
->opaque
;
3172 ClearCommError(s
->hcom
, &comerr
, &status
);
3173 if (status
.cbInQue
> 0) {
3174 s
->len
= status
.cbInQue
;
3175 win_chr_read_poll(chr
);
3182 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3184 CharDriverState
*chr
;
3187 chr
= qemu_mallocz(sizeof(CharDriverState
));
3190 s
= qemu_mallocz(sizeof(WinCharState
));
3196 chr
->chr_write
= win_chr_write
;
3197 chr
->chr_close
= win_chr_close
;
3199 if (win_chr_init(chr
, filename
) < 0) {
3204 qemu_chr_reset(chr
);
3208 static int win_chr_pipe_poll(void *opaque
)
3210 CharDriverState
*chr
= opaque
;
3211 WinCharState
*s
= chr
->opaque
;
3214 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3217 win_chr_read_poll(chr
);
3224 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3226 WinCharState
*s
= chr
->opaque
;
3234 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3236 fprintf(stderr
, "Failed CreateEvent\n");
3239 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3241 fprintf(stderr
, "Failed CreateEvent\n");
3245 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3246 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3247 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3249 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3250 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3251 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3256 ZeroMemory(&ov
, sizeof(ov
));
3257 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3258 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3260 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3264 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3266 fprintf(stderr
, "Failed GetOverlappedResult\n");
3268 CloseHandle(ov
.hEvent
);
3275 CloseHandle(ov
.hEvent
);
3278 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3287 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3289 CharDriverState
*chr
;
3292 chr
= qemu_mallocz(sizeof(CharDriverState
));
3295 s
= qemu_mallocz(sizeof(WinCharState
));
3301 chr
->chr_write
= win_chr_write
;
3302 chr
->chr_close
= win_chr_close
;
3304 if (win_chr_pipe_init(chr
, filename
) < 0) {
3309 qemu_chr_reset(chr
);
3313 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3315 CharDriverState
*chr
;
3318 chr
= qemu_mallocz(sizeof(CharDriverState
));
3321 s
= qemu_mallocz(sizeof(WinCharState
));
3328 chr
->chr_write
= win_chr_write
;
3329 qemu_chr_reset(chr
);
3333 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3335 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3338 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3342 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3343 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3344 if (fd_out
== INVALID_HANDLE_VALUE
)
3347 return qemu_chr_open_win_file(fd_out
);
3349 #endif /* !_WIN32 */
3351 /***********************************************************/
3352 /* UDP Net console */
3356 struct sockaddr_in daddr
;
3363 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3365 NetCharDriver
*s
= chr
->opaque
;
3367 return sendto(s
->fd
, buf
, len
, 0,
3368 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3371 static int udp_chr_read_poll(void *opaque
)
3373 CharDriverState
*chr
= opaque
;
3374 NetCharDriver
*s
= chr
->opaque
;
3376 s
->max_size
= qemu_chr_can_read(chr
);
3378 /* If there were any stray characters in the queue process them
3381 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3382 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3384 s
->max_size
= qemu_chr_can_read(chr
);
3389 static void udp_chr_read(void *opaque
)
3391 CharDriverState
*chr
= opaque
;
3392 NetCharDriver
*s
= chr
->opaque
;
3394 if (s
->max_size
== 0)
3396 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3397 s
->bufptr
= s
->bufcnt
;
3402 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3403 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3405 s
->max_size
= qemu_chr_can_read(chr
);
3409 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3411 NetCharDriver
*s
= chr
->opaque
;
3414 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3415 udp_chr_read
, NULL
, chr
);
3420 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3422 int parse_host_src_port(struct sockaddr_in
*haddr
,
3423 struct sockaddr_in
*saddr
,
3426 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3428 CharDriverState
*chr
= NULL
;
3429 NetCharDriver
*s
= NULL
;
3431 struct sockaddr_in saddr
;
3433 chr
= qemu_mallocz(sizeof(CharDriverState
));
3436 s
= qemu_mallocz(sizeof(NetCharDriver
));
3440 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3442 perror("socket(PF_INET, SOCK_DGRAM)");
3446 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3447 printf("Could not parse: %s\n", def
);
3451 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3461 chr
->chr_write
= udp_chr_write
;
3462 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3475 /***********************************************************/
3476 /* TCP Net console */
3487 static void tcp_chr_accept(void *opaque
);
3489 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3491 TCPCharDriver
*s
= chr
->opaque
;
3493 return send_all(s
->fd
, buf
, len
);
3495 /* XXX: indicate an error ? */
3500 static int tcp_chr_read_poll(void *opaque
)
3502 CharDriverState
*chr
= opaque
;
3503 TCPCharDriver
*s
= chr
->opaque
;
3506 s
->max_size
= qemu_chr_can_read(chr
);
3511 #define IAC_BREAK 243
3512 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3514 uint8_t *buf
, int *size
)
3516 /* Handle any telnet client's basic IAC options to satisfy char by
3517 * char mode with no echo. All IAC options will be removed from
3518 * the buf and the do_telnetopt variable will be used to track the
3519 * state of the width of the IAC information.
3521 * IAC commands come in sets of 3 bytes with the exception of the
3522 * "IAC BREAK" command and the double IAC.
3528 for (i
= 0; i
< *size
; i
++) {
3529 if (s
->do_telnetopt
> 1) {
3530 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3531 /* Double IAC means send an IAC */
3535 s
->do_telnetopt
= 1;
3537 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3538 /* Handle IAC break commands by sending a serial break */
3539 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3544 if (s
->do_telnetopt
>= 4) {
3545 s
->do_telnetopt
= 1;
3548 if ((unsigned char)buf
[i
] == IAC
) {
3549 s
->do_telnetopt
= 2;
3560 static void tcp_chr_read(void *opaque
)
3562 CharDriverState
*chr
= opaque
;
3563 TCPCharDriver
*s
= chr
->opaque
;
3567 if (!s
->connected
|| s
->max_size
<= 0)
3570 if (len
> s
->max_size
)
3572 size
= recv(s
->fd
, buf
, len
, 0);
3574 /* connection closed */
3576 if (s
->listen_fd
>= 0) {
3577 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3579 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3582 } else if (size
> 0) {
3583 if (s
->do_telnetopt
)
3584 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3586 qemu_chr_read(chr
, buf
, size
);
3590 static void tcp_chr_connect(void *opaque
)
3592 CharDriverState
*chr
= opaque
;
3593 TCPCharDriver
*s
= chr
->opaque
;
3596 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3597 tcp_chr_read
, NULL
, chr
);
3598 qemu_chr_reset(chr
);
3601 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3602 static void tcp_chr_telnet_init(int fd
)
3605 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3606 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3607 send(fd
, (char *)buf
, 3, 0);
3608 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3609 send(fd
, (char *)buf
, 3, 0);
3610 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3611 send(fd
, (char *)buf
, 3, 0);
3612 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3613 send(fd
, (char *)buf
, 3, 0);
3616 static void socket_set_nodelay(int fd
)
3619 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3622 static void tcp_chr_accept(void *opaque
)
3624 CharDriverState
*chr
= opaque
;
3625 TCPCharDriver
*s
= chr
->opaque
;
3626 struct sockaddr_in saddr
;
3628 struct sockaddr_un uaddr
;
3630 struct sockaddr
*addr
;
3637 len
= sizeof(uaddr
);
3638 addr
= (struct sockaddr
*)&uaddr
;
3642 len
= sizeof(saddr
);
3643 addr
= (struct sockaddr
*)&saddr
;
3645 fd
= accept(s
->listen_fd
, addr
, &len
);
3646 if (fd
< 0 && errno
!= EINTR
) {
3648 } else if (fd
>= 0) {
3649 if (s
->do_telnetopt
)
3650 tcp_chr_telnet_init(fd
);
3654 socket_set_nonblock(fd
);
3656 socket_set_nodelay(fd
);
3658 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3659 tcp_chr_connect(chr
);
3662 static void tcp_chr_close(CharDriverState
*chr
)
3664 TCPCharDriver
*s
= chr
->opaque
;
3667 if (s
->listen_fd
>= 0)
3668 closesocket(s
->listen_fd
);
3672 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3676 CharDriverState
*chr
= NULL
;
3677 TCPCharDriver
*s
= NULL
;
3678 int fd
= -1, ret
, err
, val
;
3680 int is_waitconnect
= 1;
3683 struct sockaddr_in saddr
;
3685 struct sockaddr_un uaddr
;
3687 struct sockaddr
*addr
;
3692 addr
= (struct sockaddr
*)&uaddr
;
3693 addrlen
= sizeof(uaddr
);
3694 if (parse_unix_path(&uaddr
, host_str
) < 0)
3699 addr
= (struct sockaddr
*)&saddr
;
3700 addrlen
= sizeof(saddr
);
3701 if (parse_host_port(&saddr
, host_str
) < 0)
3706 while((ptr
= strchr(ptr
,','))) {
3708 if (!strncmp(ptr
,"server",6)) {
3710 } else if (!strncmp(ptr
,"nowait",6)) {
3712 } else if (!strncmp(ptr
,"nodelay",6)) {
3715 printf("Unknown option: %s\n", ptr
);
3722 chr
= qemu_mallocz(sizeof(CharDriverState
));
3725 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3731 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3734 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3739 if (!is_waitconnect
)
3740 socket_set_nonblock(fd
);
3745 s
->is_unix
= is_unix
;
3746 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3749 chr
->chr_write
= tcp_chr_write
;
3750 chr
->chr_close
= tcp_chr_close
;
3753 /* allow fast reuse */
3757 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3763 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3766 ret
= bind(fd
, addr
, addrlen
);
3770 ret
= listen(fd
, 0);
3775 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3777 s
->do_telnetopt
= 1;
3780 ret
= connect(fd
, addr
, addrlen
);
3782 err
= socket_error();
3783 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3784 } else if (err
== EINPROGRESS
) {
3787 } else if (err
== WSAEALREADY
) {
3799 socket_set_nodelay(fd
);
3801 tcp_chr_connect(chr
);
3803 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3806 if (is_listen
&& is_waitconnect
) {
3807 printf("QEMU waiting for connection on: %s\n", host_str
);
3808 tcp_chr_accept(chr
);
3809 socket_set_nonblock(s
->listen_fd
);
3821 CharDriverState
*qemu_chr_open(const char *filename
)
3825 if (!strcmp(filename
, "vc")) {
3826 return text_console_init(&display_state
, 0);
3827 } else if (strstart(filename
, "vc:", &p
)) {
3828 return text_console_init(&display_state
, p
);
3829 } else if (!strcmp(filename
, "null")) {
3830 return qemu_chr_open_null();
3832 if (strstart(filename
, "tcp:", &p
)) {
3833 return qemu_chr_open_tcp(p
, 0, 0);
3835 if (strstart(filename
, "telnet:", &p
)) {
3836 return qemu_chr_open_tcp(p
, 1, 0);
3838 if (strstart(filename
, "udp:", &p
)) {
3839 return qemu_chr_open_udp(p
);
3841 if (strstart(filename
, "mon:", &p
)) {
3842 CharDriverState
*drv
= qemu_chr_open(p
);
3844 drv
= qemu_chr_open_mux(drv
);
3845 monitor_init(drv
, !nographic
);
3848 printf("Unable to open driver: %s\n", p
);
3852 if (strstart(filename
, "unix:", &p
)) {
3853 return qemu_chr_open_tcp(p
, 0, 1);
3854 } else if (strstart(filename
, "file:", &p
)) {
3855 return qemu_chr_open_file_out(p
);
3856 } else if (strstart(filename
, "pipe:", &p
)) {
3857 return qemu_chr_open_pipe(p
);
3858 } else if (!strcmp(filename
, "pty")) {
3859 return qemu_chr_open_pty();
3860 } else if (!strcmp(filename
, "stdio")) {
3861 return qemu_chr_open_stdio();
3863 #if defined(__linux__)
3864 if (strstart(filename
, "/dev/parport", NULL
)) {
3865 return qemu_chr_open_pp(filename
);
3868 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3869 || defined(__NetBSD__) || defined(__OpenBSD__)
3870 if (strstart(filename
, "/dev/", NULL
)) {
3871 return qemu_chr_open_tty(filename
);
3875 if (strstart(filename
, "COM", NULL
)) {
3876 return qemu_chr_open_win(filename
);
3878 if (strstart(filename
, "pipe:", &p
)) {
3879 return qemu_chr_open_win_pipe(p
);
3881 if (strstart(filename
, "con:", NULL
)) {
3882 return qemu_chr_open_win_con(filename
);
3884 if (strstart(filename
, "file:", &p
)) {
3885 return qemu_chr_open_win_file_out(p
);
3888 #ifdef CONFIG_BRLAPI
3889 if (!strcmp(filename
, "braille")) {
3890 return chr_baum_init();
3898 void qemu_chr_close(CharDriverState
*chr
)
3901 chr
->chr_close(chr
);
3905 /***********************************************************/
3906 /* network device redirectors */
3908 __attribute__ (( unused
))
3909 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3913 for(i
=0;i
<size
;i
+=16) {
3917 fprintf(f
, "%08x ", i
);
3920 fprintf(f
, " %02x", buf
[i
+j
]);
3925 for(j
=0;j
<len
;j
++) {
3927 if (c
< ' ' || c
> '~')
3929 fprintf(f
, "%c", c
);
3935 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3942 offset
= strtol(p
, &last_char
, 0);
3943 if (0 == errno
&& '\0' == *last_char
&&
3944 offset
>= 0 && offset
<= 0xFFFFFF) {
3945 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3946 macaddr
[4] = (offset
& 0xFF00) >> 8;
3947 macaddr
[5] = offset
& 0xFF;
3950 for(i
= 0; i
< 6; i
++) {
3951 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3956 if (*p
!= ':' && *p
!= '-')
3967 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3972 p1
= strchr(p
, sep
);
3978 if (len
> buf_size
- 1)
3980 memcpy(buf
, p
, len
);
3987 int parse_host_src_port(struct sockaddr_in
*haddr
,
3988 struct sockaddr_in
*saddr
,
3989 const char *input_str
)
3991 char *str
= strdup(input_str
);
3992 char *host_str
= str
;
3994 const char *src_str2
;
3998 * Chop off any extra arguments at the end of the string which
3999 * would start with a comma, then fill in the src port information
4000 * if it was provided else use the "any address" and "any port".
4002 if ((ptr
= strchr(str
,',')))
4005 if ((src_str
= strchr(input_str
,'@'))) {
4010 if (parse_host_port(haddr
, host_str
) < 0)
4014 if (!src_str
|| *src_str
== '\0')
4017 if (parse_host_port(saddr
, src_str2
) < 0)
4028 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
4036 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4038 saddr
->sin_family
= AF_INET
;
4039 if (buf
[0] == '\0') {
4040 saddr
->sin_addr
.s_addr
= 0;
4042 if (isdigit(buf
[0])) {
4043 if (!inet_aton(buf
, &saddr
->sin_addr
))
4046 if ((he
= gethostbyname(buf
)) == NULL
)
4048 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4051 port
= strtol(p
, (char **)&r
, 0);
4054 saddr
->sin_port
= htons(port
);
4059 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4064 len
= MIN(108, strlen(str
));
4065 p
= strchr(str
, ',');
4067 len
= MIN(len
, p
- str
);
4069 memset(uaddr
, 0, sizeof(*uaddr
));
4071 uaddr
->sun_family
= AF_UNIX
;
4072 memcpy(uaddr
->sun_path
, str
, len
);
4078 /* find or alloc a new VLAN */
4079 VLANState
*qemu_find_vlan(int id
)
4081 VLANState
**pvlan
, *vlan
;
4082 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4086 vlan
= qemu_mallocz(sizeof(VLANState
));
4091 pvlan
= &first_vlan
;
4092 while (*pvlan
!= NULL
)
4093 pvlan
= &(*pvlan
)->next
;
4098 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4099 IOReadHandler
*fd_read
,
4100 IOCanRWHandler
*fd_can_read
,
4103 VLANClientState
*vc
, **pvc
;
4104 vc
= qemu_mallocz(sizeof(VLANClientState
));
4107 vc
->fd_read
= fd_read
;
4108 vc
->fd_can_read
= fd_can_read
;
4109 vc
->opaque
= opaque
;
4113 pvc
= &vlan
->first_client
;
4114 while (*pvc
!= NULL
)
4115 pvc
= &(*pvc
)->next
;
4120 void qemu_del_vlan_client(VLANClientState
*vc
)
4122 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4124 while (*pvc
!= NULL
)
4130 pvc
= &(*pvc
)->next
;
4133 int qemu_can_send_packet(VLANClientState
*vc1
)
4135 VLANState
*vlan
= vc1
->vlan
;
4136 VLANClientState
*vc
;
4138 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4140 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4147 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4149 VLANState
*vlan
= vc1
->vlan
;
4150 VLANClientState
*vc
;
4154 printf("vlan %d send:\n", vlan
->id
);
4155 hex_dump(stdout
, buf
, size
);
4157 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4159 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
4160 vc
->fd_read(vc
->opaque
, buf
, size
);
4169 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
4176 for (i
= 0; i
< iovcnt
; i
++) {
4179 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
4180 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
4184 vc
->fd_read(vc
->opaque
, buffer
, offset
);
4189 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
4192 VLANState
*vlan
= vc1
->vlan
;
4193 VLANClientState
*vc
;
4194 ssize_t max_len
= 0;
4196 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4203 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
4204 else if (vc
->fd_read
)
4205 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
4207 max_len
= MAX(max_len
, len
);
4213 #if defined(CONFIG_SLIRP)
4215 /* slirp network adapter */
4217 static int slirp_inited
;
4218 static VLANClientState
*slirp_vc
;
4220 int slirp_can_output(void)
4222 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4225 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4228 printf("slirp output:\n");
4229 hex_dump(stdout
, pkt
, pkt_len
);
4233 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4236 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4239 printf("slirp input:\n");
4240 hex_dump(stdout
, buf
, size
);
4242 slirp_input(buf
, size
);
4245 static int net_slirp_init(VLANState
*vlan
)
4247 if (!slirp_inited
) {
4251 slirp_vc
= qemu_new_vlan_client(vlan
,
4252 slirp_receive
, NULL
, NULL
);
4253 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4257 static void net_slirp_redir(const char *redir_str
)
4262 struct in_addr guest_addr
;
4263 int host_port
, guest_port
;
4265 if (!slirp_inited
) {
4271 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4273 if (!strcmp(buf
, "tcp")) {
4275 } else if (!strcmp(buf
, "udp")) {
4281 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4283 host_port
= strtol(buf
, &r
, 0);
4287 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4289 if (buf
[0] == '\0') {
4290 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4292 if (!inet_aton(buf
, &guest_addr
))
4295 guest_port
= strtol(p
, &r
, 0);
4299 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4300 fprintf(stderr
, "qemu: could not set up redirection\n");
4305 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4313 static void erase_dir(char *dir_name
)
4317 char filename
[1024];
4319 /* erase all the files in the directory */
4320 if ((d
= opendir(dir_name
)) != 0) {
4325 if (strcmp(de
->d_name
, ".") != 0 &&
4326 strcmp(de
->d_name
, "..") != 0) {
4327 snprintf(filename
, sizeof(filename
), "%s/%s",
4328 smb_dir
, de
->d_name
);
4329 if (unlink(filename
) != 0) /* is it a directory? */
4330 erase_dir(filename
);
4338 /* automatic user mode samba server configuration */
4339 static void smb_exit(void)
4344 /* automatic user mode samba server configuration */
4345 static void net_slirp_smb(const char *exported_dir
)
4347 char smb_conf
[1024];
4348 char smb_cmdline
[1024];
4351 if (!slirp_inited
) {
4356 /* XXX: better tmp dir construction */
4357 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4358 if (mkdir(smb_dir
, 0700) < 0) {
4359 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4362 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4364 f
= fopen(smb_conf
, "w");
4366 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4373 "socket address=127.0.0.1\n"
4374 "pid directory=%s\n"
4375 "lock directory=%s\n"
4376 "log file=%s/log.smbd\n"
4377 "smb passwd file=%s/smbpasswd\n"
4378 "security = share\n"
4393 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4394 SMBD_COMMAND
, smb_conf
);
4396 slirp_add_exec(0, smb_cmdline
, 4, 139);
4399 #endif /* !defined(_WIN32) */
4400 void do_info_slirp(void)
4405 #endif /* CONFIG_SLIRP */
4409 int tap_has_vnet_hdr(void *opaque
)
4414 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4418 #else /* !defined(_WIN32) */
4420 #ifndef IFF_VNET_HDR
4421 #define TAP_BUFSIZE 4096
4423 #include <linux/virtio_net.h>
4425 #define ETH_DATA_LEN 1500
4426 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4427 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4428 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4431 typedef struct TAPState
{
4432 VLANClientState
*vc
;
4434 char down_script
[1024];
4435 char buf
[TAP_BUFSIZE
];
4437 unsigned int has_vnet_hdr
: 1;
4438 unsigned int using_vnet_hdr
: 1;
4441 static ssize_t
tap_writev(void *opaque
, const struct iovec
*iov
,
4444 TAPState
*s
= opaque
;
4448 len
= writev(s
->fd
, iov
, iovcnt
);
4449 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4454 static ssize_t
tap_receive_iov(void *opaque
, const struct iovec
*iov
,
4458 TAPState
*s
= opaque
;
4460 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4461 struct iovec
*iov_copy
;
4462 struct virtio_net_hdr hdr
= { 0, };
4464 iov_copy
= alloca(sizeof(struct iovec
) * (iovcnt
+ 1));
4466 iov_copy
[0].iov_base
= &hdr
;
4467 iov_copy
[0].iov_len
= sizeof(hdr
);
4469 memcpy(&iov_copy
[1], iov
, sizeof(struct iovec
) * iovcnt
);
4471 return tap_writev(opaque
, iov_copy
, iovcnt
+ 1);
4475 return tap_writev(opaque
, iov
, iovcnt
);
4478 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4480 struct iovec iov
[2];
4484 TAPState
*s
= opaque
;
4485 struct virtio_net_hdr hdr
= { 0, };
4487 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4488 iov
[i
].iov_base
= &hdr
;
4489 iov
[i
].iov_len
= sizeof(hdr
);
4494 iov
[i
].iov_base
= (char *) buf
;
4495 iov
[i
].iov_len
= size
;
4498 tap_writev(opaque
, iov
, i
);
4501 static int tap_can_send(void *opaque
)
4503 TAPState
*s
= opaque
;
4504 VLANClientState
*vc
;
4505 int can_receive
= 0;
4507 /* Check to see if any of our clients can receive a packet */
4508 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4509 /* Skip ourselves */
4513 if (!vc
->fd_can_read
) {
4514 /* no fd_can_read handler, they always can receive */
4517 can_receive
= vc
->fd_can_read(vc
->opaque
);
4519 /* Once someone can receive, we try to send a packet */
4527 static int tap_send_packet(TAPState
*s
)
4529 uint8_t *buf
= s
->buf
;
4533 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4534 buf
+= sizeof(struct virtio_net_hdr
);
4535 size
-= sizeof(struct virtio_net_hdr
);
4539 return qemu_send_packet(s
->vc
, buf
, size
);
4542 static void tap_send(void *opaque
)
4544 TAPState
*s
= opaque
;
4546 /* First try to send any buffered packet */
4550 /* If noone can receive the packet, buffer it */
4551 err
= tap_send_packet(s
);
4556 /* Read packets until we hit EAGAIN */
4561 sbuf
.maxlen
= sizeof(s
->buf
);
4563 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4566 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4570 if (s
->size
== -1 && errno
== EINTR
)
4576 /* If noone can receive the packet, buffer it */
4577 err
= tap_send_packet(s
);
4581 } while (s
->size
> 0);
4584 int tap_has_vnet_hdr(void *opaque
)
4586 VLANClientState
*vc
= opaque
;
4587 TAPState
*s
= vc
->opaque
;
4589 return s
? s
->has_vnet_hdr
: 0;
4592 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4594 VLANClientState
*vc
= opaque
;
4595 TAPState
*s
= vc
->opaque
;
4597 if (!s
|| !s
->has_vnet_hdr
)
4600 s
->using_vnet_hdr
= using_vnet_hdr
!= 0;
4603 static int tap_probe_vnet_hdr(int fd
)
4605 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4608 if (ioctl(fd
, TUNGETIFF
, &ifr
) != 0) {
4609 fprintf(stderr
, "TUNGETIFF ioctl() failed: %s\n", strerror(errno
));
4613 return ifr
.ifr_flags
& IFF_VNET_HDR
;
4619 #ifdef TUNSETOFFLOAD
4620 static void tap_set_offload(VLANClientState
*vc
, int csum
, int tso4
, int tso6
,
4623 TAPState
*s
= vc
->opaque
;
4624 unsigned int offload
= 0;
4627 offload
|= TUN_F_CSUM
;
4629 offload
|= TUN_F_TSO4
;
4631 offload
|= TUN_F_TSO6
;
4632 if ((tso4
|| tso6
) && ecn
)
4633 offload
|= TUN_F_TSO_ECN
;
4636 if (ioctl(s
->fd
, TUNSETOFFLOAD
, offload
) != 0)
4637 fprintf(stderr
, "TUNSETOFFLOAD ioctl() failed: %s\n",
4640 #endif /* TUNSETOFFLOAD */
4644 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
, int vnet_hdr
)
4648 s
= qemu_mallocz(sizeof(TAPState
));
4652 s
->has_vnet_hdr
= vnet_hdr
!= 0;
4653 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4654 s
->vc
->fd_readv
= tap_receive_iov
;
4655 #ifdef TUNSETOFFLOAD
4656 s
->vc
->set_offload
= tap_set_offload
;
4658 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4659 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4663 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4664 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4670 TFR(fd
= open("/dev/tap", O_RDWR
));
4672 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4677 dev
= devname(s
.st_rdev
, S_IFCHR
);
4678 pstrcpy(ifname
, ifname_size
, dev
);
4680 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4683 #elif defined(__sun__)
4684 #define TUNNEWPPA (('T'<<16) | 0x0001)
4686 * Allocate TAP device, returns opened fd.
4687 * Stores dev name in the first arg(must be large enough).
4689 int tap_alloc(char *dev
, size_t dev_size
)
4691 int tap_fd
, if_fd
, ppa
= -1;
4692 static int ip_fd
= 0;
4695 static int arp_fd
= 0;
4696 int ip_muxid
, arp_muxid
;
4697 struct strioctl strioc_if
, strioc_ppa
;
4698 int link_type
= I_PLINK
;;
4700 char actual_name
[32] = "";
4702 memset(&ifr
, 0x0, sizeof(ifr
));
4706 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4710 /* Check if IP device was opened */
4714 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4716 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4720 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4722 syslog(LOG_ERR
, "Can't open /dev/tap");
4726 /* Assign a new PPA and get its unit number. */
4727 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4728 strioc_ppa
.ic_timout
= 0;
4729 strioc_ppa
.ic_len
= sizeof(ppa
);
4730 strioc_ppa
.ic_dp
= (char *)&ppa
;
4731 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4732 syslog (LOG_ERR
, "Can't assign new interface");
4734 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4736 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4739 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4740 syslog(LOG_ERR
, "Can't push IP module");
4744 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4745 syslog(LOG_ERR
, "Can't get flags\n");
4747 snprintf (actual_name
, 32, "tap%d", ppa
);
4748 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4751 /* Assign ppa according to the unit number returned by tun device */
4753 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4754 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4755 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4756 syslog (LOG_ERR
, "Can't get flags\n");
4757 /* Push arp module to if_fd */
4758 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4759 syslog (LOG_ERR
, "Can't push ARP module (2)");
4761 /* Push arp module to ip_fd */
4762 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4763 syslog (LOG_ERR
, "I_POP failed\n");
4764 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4765 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4767 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4769 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4771 /* Set ifname to arp */
4772 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4773 strioc_if
.ic_timout
= 0;
4774 strioc_if
.ic_len
= sizeof(ifr
);
4775 strioc_if
.ic_dp
= (char *)&ifr
;
4776 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4777 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4780 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4781 syslog(LOG_ERR
, "Can't link TAP device to IP");
4785 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4786 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4790 memset(&ifr
, 0x0, sizeof(ifr
));
4791 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4792 ifr
.lifr_ip_muxid
= ip_muxid
;
4793 ifr
.lifr_arp_muxid
= arp_muxid
;
4795 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4797 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4798 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4799 syslog (LOG_ERR
, "Can't set multiplexor id");
4802 snprintf(dev
, dev_size
, "tap%d", ppa
);
4806 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4810 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4811 fprintf(stderr
, "Cannot allocate TAP device\n");
4814 pstrcpy(ifname
, ifname_size
, dev
);
4815 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4819 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4824 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4826 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4829 memset(&ifr
, 0, sizeof(ifr
));
4830 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4832 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4834 unsigned int features
;
4836 if (ioctl(fd
, TUNGETFEATURES
, &features
) == 0 &&
4837 features
& IFF_VNET_HDR
) {
4839 ifr
.ifr_flags
|= IFF_VNET_HDR
;
4844 if (ifname
[0] != '\0')
4845 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4847 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4848 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4850 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4854 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4855 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4860 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4866 /* try to launch network script */
4870 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4871 for (i
= 0; i
< open_max
; i
++)
4872 if (i
!= STDIN_FILENO
&&
4873 i
!= STDOUT_FILENO
&&
4874 i
!= STDERR_FILENO
&&
4879 *parg
++ = (char *)setup_script
;
4880 *parg
++ = (char *)ifname
;
4882 execv(setup_script
, args
);
4885 while (waitpid(pid
, &status
, 0) != pid
);
4886 if (!WIFEXITED(status
) ||
4887 WEXITSTATUS(status
) != 0) {
4888 fprintf(stderr
, "%s: could not launch network script\n",
4896 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4897 const char *setup_script
, const char *down_script
)
4904 if (ifname1
!= NULL
)
4905 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4909 TFR(fd
= tap_open(ifname
, sizeof(ifname
), &vnet_hdr
));
4913 if (!setup_script
|| !strcmp(setup_script
, "no"))
4915 if (setup_script
[0] != '\0') {
4916 if (launch_script(setup_script
, ifname
, fd
))
4919 s
= net_tap_fd_init(vlan
, fd
, vnet_hdr
);
4923 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4924 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4925 if (down_script
&& strcmp(down_script
, "no"))
4926 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4930 #endif /* !_WIN32 */
4932 #if defined(CONFIG_VDE)
4933 typedef struct VDEState
{
4934 VLANClientState
*vc
;
4938 static void vde_to_qemu(void *opaque
)
4940 VDEState
*s
= opaque
;
4944 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4946 qemu_send_packet(s
->vc
, buf
, size
);
4950 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4952 VDEState
*s
= opaque
;
4955 ret
= vde_send(s
->vde
, buf
, size
, 0);
4956 if (ret
< 0 && errno
== EINTR
) {
4963 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4964 const char *group
, int mode
)
4967 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4968 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4970 struct vde_open_args args
= {
4972 .group
= init_group
,
4976 s
= qemu_mallocz(sizeof(VDEState
));
4979 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4984 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4985 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4986 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4987 sock
, vde_datafd(s
->vde
));
4992 /* network connection */
4993 typedef struct NetSocketState
{
4994 VLANClientState
*vc
;
4996 int state
; /* 0 = getting length, 1 = getting data */
5000 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
5003 typedef struct NetSocketListenState
{
5006 } NetSocketListenState
;
5008 /* XXX: we consider we can send the whole packet without blocking */
5009 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
5011 NetSocketState
*s
= opaque
;
5015 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
5016 send_all(s
->fd
, buf
, size
);
5019 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
5021 NetSocketState
*s
= opaque
;
5022 sendto(s
->fd
, buf
, size
, 0,
5023 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
5026 static void net_socket_send(void *opaque
)
5028 NetSocketState
*s
= opaque
;
5033 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
5035 err
= socket_error();
5036 if (err
!= EWOULDBLOCK
)
5038 } else if (size
== 0) {
5039 /* end of connection */
5041 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5047 /* reassemble a packet from the network */
5053 memcpy(s
->buf
+ s
->index
, buf
, l
);
5057 if (s
->index
== 4) {
5059 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
5065 l
= s
->packet_len
- s
->index
;
5068 memcpy(s
->buf
+ s
->index
, buf
, l
);
5072 if (s
->index
>= s
->packet_len
) {
5073 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
5082 static void net_socket_send_dgram(void *opaque
)
5084 NetSocketState
*s
= opaque
;
5087 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
5091 /* end of connection */
5092 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5095 qemu_send_packet(s
->vc
, s
->buf
, size
);
5098 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
5103 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
5104 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5105 inet_ntoa(mcastaddr
->sin_addr
),
5106 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
5110 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
5112 perror("socket(PF_INET, SOCK_DGRAM)");
5117 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
5118 (const char *)&val
, sizeof(val
));
5120 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5124 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
5130 /* Add host to multicast group */
5131 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
5132 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
5134 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
5135 (const char *)&imr
, sizeof(struct ip_mreq
));
5137 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5141 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5143 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
5144 (const char *)&val
, sizeof(val
));
5146 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5150 socket_set_nonblock(fd
);
5158 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
5161 struct sockaddr_in saddr
;
5163 socklen_t saddr_len
;
5166 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5167 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5168 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5172 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
5174 if (saddr
.sin_addr
.s_addr
==0) {
5175 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5179 /* clone dgram socket */
5180 newfd
= net_socket_mcast_create(&saddr
);
5182 /* error already reported by net_socket_mcast_create() */
5186 /* clone newfd to fd, close newfd */
5191 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5192 fd
, strerror(errno
));
5197 s
= qemu_mallocz(sizeof(NetSocketState
));
5202 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
5203 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
5205 /* mcast: save bound address as dst */
5206 if (is_connected
) s
->dgram_dst
=saddr
;
5208 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5209 "socket: fd=%d (%s mcast=%s:%d)",
5210 fd
, is_connected
? "cloned" : "",
5211 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5215 static void net_socket_connect(void *opaque
)
5217 NetSocketState
*s
= opaque
;
5218 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5221 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5225 s
= qemu_mallocz(sizeof(NetSocketState
));
5229 s
->vc
= qemu_new_vlan_client(vlan
,
5230 net_socket_receive
, NULL
, s
);
5231 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5232 "socket: fd=%d", fd
);
5234 net_socket_connect(s
);
5236 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5241 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5244 int so_type
=-1, optlen
=sizeof(so_type
);
5246 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5247 (socklen_t
*)&optlen
)< 0) {
5248 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5253 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5255 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5257 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5258 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5259 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5264 static void net_socket_accept(void *opaque
)
5266 NetSocketListenState
*s
= opaque
;
5268 struct sockaddr_in saddr
;
5273 len
= sizeof(saddr
);
5274 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5275 if (fd
< 0 && errno
!= EINTR
) {
5277 } else if (fd
>= 0) {
5281 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5285 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5286 "socket: connection from %s:%d",
5287 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5291 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5293 NetSocketListenState
*s
;
5295 struct sockaddr_in saddr
;
5297 if (parse_host_port(&saddr
, host_str
) < 0)
5300 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5304 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5309 socket_set_nonblock(fd
);
5311 /* allow fast reuse */
5313 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5315 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5320 ret
= listen(fd
, 0);
5327 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5331 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5334 int fd
, connected
, ret
, err
;
5335 struct sockaddr_in saddr
;
5337 if (parse_host_port(&saddr
, host_str
) < 0)
5340 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5345 socket_set_nonblock(fd
);
5349 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5351 err
= socket_error();
5352 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5353 } else if (err
== EINPROGRESS
) {
5356 } else if (err
== WSAEALREADY
) {
5369 s
= net_socket_fd_init(vlan
, fd
, connected
);
5372 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5373 "socket: connect to %s:%d",
5374 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5378 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5382 struct sockaddr_in saddr
;
5384 if (parse_host_port(&saddr
, host_str
) < 0)
5388 fd
= net_socket_mcast_create(&saddr
);
5392 s
= net_socket_fd_init(vlan
, fd
, 0);
5396 s
->dgram_dst
= saddr
;
5398 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5399 "socket: mcast=%s:%d",
5400 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5405 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5410 while (*p
!= '\0' && *p
!= '=') {
5411 if (q
&& (q
- buf
) < buf_size
- 1)
5421 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5426 while (*p
!= '\0') {
5428 if (*(p
+ 1) != ',')
5432 if (q
&& (q
- buf
) < buf_size
- 1)
5442 int get_param_value(char *buf
, int buf_size
,
5443 const char *tag
, const char *str
)
5450 p
= get_opt_name(option
, sizeof(option
), p
);
5454 if (!strcmp(tag
, option
)) {
5455 (void)get_opt_value(buf
, buf_size
, p
);
5458 p
= get_opt_value(NULL
, 0, p
);
5467 int check_params(char *buf
, int buf_size
,
5468 const char * const *params
, const char *str
)
5475 p
= get_opt_name(buf
, buf_size
, p
);
5479 for(i
= 0; params
[i
] != NULL
; i
++)
5480 if (!strcmp(params
[i
], buf
))
5482 if (params
[i
] == NULL
)
5484 p
= get_opt_value(NULL
, 0, p
);
5492 static int nic_get_free_idx(void)
5496 for (index
= 0; index
< MAX_NICS
; index
++)
5497 if (!nd_table
[index
].used
)
5502 int net_client_init(const char *device
, const char *p
)
5509 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5510 vlan_id
= strtol(buf
, NULL
, 0);
5512 vlan
= qemu_find_vlan(vlan_id
);
5514 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5517 if (!strcmp(device
, "nic")) {
5520 int idx
= nic_get_free_idx();
5522 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5523 fprintf(stderr
, "Too Many NICs\n");
5526 nd
= &nd_table
[idx
];
5527 macaddr
= nd
->macaddr
;
5533 macaddr
[5] = 0x56 + idx
;
5535 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5536 if (parse_macaddr(macaddr
, buf
) < 0) {
5537 fprintf(stderr
, "invalid syntax for ethernet address\n");
5541 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5542 nd
->model
= strdup(buf
);
5547 vlan
->nb_guest_devs
++;
5550 if (!strcmp(device
, "none")) {
5551 /* does nothing. It is needed to signal that no network cards
5556 if (!strcmp(device
, "user")) {
5557 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5558 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5560 vlan
->nb_host_devs
++;
5561 ret
= net_slirp_init(vlan
);
5565 if (!strcmp(device
, "tap")) {
5567 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5568 fprintf(stderr
, "tap: no interface name\n");
5571 vlan
->nb_host_devs
++;
5572 ret
= tap_win32_init(vlan
, ifname
);
5575 if (!strcmp(device
, "tap")) {
5577 char setup_script
[1024], down_script
[1024];
5579 vlan
->nb_host_devs
++;
5580 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5581 fd
= strtol(buf
, NULL
, 0);
5582 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5584 if (net_tap_fd_init(vlan
, fd
, tap_probe_vnet_hdr(fd
)))
5587 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5590 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5591 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5593 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5594 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5596 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5600 if (!strcmp(device
, "socket")) {
5601 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5603 fd
= strtol(buf
, NULL
, 0);
5605 if (net_socket_fd_init(vlan
, fd
, 1))
5607 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5608 ret
= net_socket_listen_init(vlan
, buf
);
5609 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5610 ret
= net_socket_connect_init(vlan
, buf
);
5611 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5612 ret
= net_socket_mcast_init(vlan
, buf
);
5614 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5617 vlan
->nb_host_devs
++;
5620 if (!strcmp(device
, "vde")) {
5621 char vde_sock
[1024], vde_group
[512];
5622 int vde_port
, vde_mode
;
5623 vlan
->nb_host_devs
++;
5624 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5627 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5628 vde_port
= strtol(buf
, NULL
, 10);
5632 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5633 vde_group
[0] = '\0';
5635 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5636 vde_mode
= strtol(buf
, NULL
, 8);
5640 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5644 fprintf(stderr
, "Unknown network device: %s\n", device
);
5648 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5654 void net_client_uninit(NICInfo
*nd
)
5656 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5659 free((void *)nd
->model
);
5662 static int net_client_parse(const char *str
)
5670 while (*p
!= '\0' && *p
!= ',') {
5671 if ((q
- device
) < sizeof(device
) - 1)
5679 return net_client_init(device
, p
);
5682 void do_info_network(void)
5685 VLANClientState
*vc
;
5687 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5688 term_printf("VLAN %d devices:\n", vlan
->id
);
5689 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5690 term_printf(" %s\n", vc
->info_str
);
5694 #define HD_ALIAS "index=%d,media=disk"
5696 #define CDROM_ALIAS "index=1,media=cdrom"
5698 #define CDROM_ALIAS "index=2,media=cdrom"
5700 #define FD_ALIAS "index=%d,if=floppy"
5701 #define PFLASH_ALIAS "if=pflash"
5702 #define MTD_ALIAS "if=mtd"
5703 #define SD_ALIAS "index=0,if=sd"
5705 static int drive_opt_get_free_idx(void)
5709 for (index
= 0; index
< MAX_DRIVES
; index
++)
5710 if (!drives_opt
[index
].used
) {
5711 drives_opt
[index
].used
= 1;
5718 static int drive_get_free_idx(void)
5722 for (index
= 0; index
< MAX_DRIVES
; index
++)
5723 if (!drives_table
[index
].used
) {
5724 drives_table
[index
].used
= 1;
5731 int drive_add(const char *file
, const char *fmt
, ...)
5734 int index
= drive_opt_get_free_idx();
5736 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5737 fprintf(stderr
, "qemu: too many drives\n");
5741 drives_opt
[index
].file
= file
;
5743 vsnprintf(drives_opt
[index
].opt
,
5744 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5751 void drive_remove(int index
)
5753 drives_opt
[index
].used
= 0;
5757 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5761 /* seek interface, bus and unit */
5763 for (index
= 0; index
< MAX_DRIVES
; index
++)
5764 if (drives_table
[index
].type
== type
&&
5765 drives_table
[index
].bus
== bus
&&
5766 drives_table
[index
].unit
== unit
&&
5767 drives_table
[index
].used
)
5773 int drive_get_max_bus(BlockInterfaceType type
)
5779 for (index
= 0; index
< nb_drives
; index
++) {
5780 if(drives_table
[index
].type
== type
&&
5781 drives_table
[index
].bus
> max_bus
)
5782 max_bus
= drives_table
[index
].bus
;
5787 static void bdrv_format_print(void *opaque
, const char *name
)
5789 fprintf(stderr
, " %s", name
);
5792 void drive_uninit(BlockDriverState
*bdrv
)
5796 for (i
= 0; i
< MAX_DRIVES
; i
++)
5797 if (drives_table
[i
].bdrv
== bdrv
) {
5798 drives_table
[i
].bdrv
= NULL
;
5799 drives_table
[i
].used
= 0;
5800 drive_remove(drives_table
[i
].drive_opt_idx
);
5806 int drive_init(struct drive_opt
*arg
, int snapshot
,
5807 QEMUMachine
*machine
)
5812 const char *mediastr
= "";
5813 BlockInterfaceType type
;
5814 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5815 int bus_id
, unit_id
;
5816 int cyls
, heads
, secs
, translation
;
5817 BlockDriverState
*bdrv
;
5818 BlockDriver
*drv
= NULL
;
5823 int drives_table_idx
;
5824 char *str
= arg
->opt
;
5825 static const char * const params
[] = { "bus", "unit", "if", "index",
5826 "cyls", "heads", "secs", "trans",
5827 "media", "snapshot", "file",
5828 "cache", "format", "boot", NULL
};
5830 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5831 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5837 cyls
= heads
= secs
= 0;
5840 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5844 if (!strcmp(machine
->name
, "realview") ||
5845 !strcmp(machine
->name
, "SS-5") ||
5846 !strcmp(machine
->name
, "SS-10") ||
5847 !strcmp(machine
->name
, "SS-600MP") ||
5848 !strcmp(machine
->name
, "versatilepb") ||
5849 !strcmp(machine
->name
, "versatileab")) {
5851 max_devs
= MAX_SCSI_DEVS
;
5852 pstrcpy(devname
, sizeof(devname
), "scsi");
5855 max_devs
= MAX_IDE_DEVS
;
5856 pstrcpy(devname
, sizeof(devname
), "ide");
5860 /* extract parameters */
5862 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5863 bus_id
= strtol(buf
, NULL
, 0);
5865 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5870 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5871 unit_id
= strtol(buf
, NULL
, 0);
5873 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5878 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5879 pstrcpy(devname
, sizeof(devname
), buf
);
5880 if (!strcmp(buf
, "ide")) {
5882 max_devs
= MAX_IDE_DEVS
;
5883 } else if (!strcmp(buf
, "scsi")) {
5885 max_devs
= MAX_SCSI_DEVS
;
5886 } else if (!strcmp(buf
, "floppy")) {
5889 } else if (!strcmp(buf
, "pflash")) {
5892 } else if (!strcmp(buf
, "mtd")) {
5895 } else if (!strcmp(buf
, "sd")) {
5898 } else if (!strcmp(buf
, "virtio")) {
5902 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5907 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5908 index
= strtol(buf
, NULL
, 0);
5910 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5915 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5916 cyls
= strtol(buf
, NULL
, 0);
5919 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5920 heads
= strtol(buf
, NULL
, 0);
5923 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5924 secs
= strtol(buf
, NULL
, 0);
5927 if (cyls
|| heads
|| secs
) {
5928 if (cyls
< 1 || cyls
> 16383) {
5929 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5932 if (heads
< 1 || heads
> 16) {
5933 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5936 if (secs
< 1 || secs
> 63) {
5937 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5942 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5945 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5949 if (!strcmp(buf
, "none"))
5950 translation
= BIOS_ATA_TRANSLATION_NONE
;
5951 else if (!strcmp(buf
, "lba"))
5952 translation
= BIOS_ATA_TRANSLATION_LBA
;
5953 else if (!strcmp(buf
, "auto"))
5954 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5956 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5961 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5962 if (!strcmp(buf
, "disk")) {
5964 } else if (!strcmp(buf
, "cdrom")) {
5965 if (cyls
|| secs
|| heads
) {
5967 "qemu: '%s' invalid physical CHS format\n", str
);
5970 media
= MEDIA_CDROM
;
5972 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5977 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5978 if (!strcmp(buf
, "on"))
5980 else if (!strcmp(buf
, "off"))
5983 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5988 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5989 if (!strcmp(buf
, "off"))
5991 else if (!strcmp(buf
, "on"))
5994 fprintf(stderr
, "qemu: invalid cache option\n");
5999 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
6000 if (strcmp(buf
, "?") == 0) {
6001 fprintf(stderr
, "qemu: Supported formats:");
6002 bdrv_iterate_format(bdrv_format_print
, NULL
);
6003 fprintf(stderr
, "\n");
6006 drv
= bdrv_find_format(buf
);
6008 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
6013 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
6014 if (!strcmp(buf
, "on")) {
6015 if (extboot_drive
!= -1) {
6016 fprintf(stderr
, "qemu: two bootable drives specified\n");
6019 extboot_drive
= nb_drives
;
6020 } else if (strcmp(buf
, "off")) {
6021 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
6026 if (arg
->file
== NULL
)
6027 get_param_value(file
, sizeof(file
), "file", str
);
6029 pstrcpy(file
, sizeof(file
), arg
->file
);
6031 /* compute bus and unit according index */
6034 if (bus_id
!= 0 || unit_id
!= -1) {
6036 "qemu: '%s' index cannot be used with bus and unit\n", str
);
6044 unit_id
= index
% max_devs
;
6045 bus_id
= index
/ max_devs
;
6049 /* if user doesn't specify a unit_id,
6050 * try to find the first free
6053 if (unit_id
== -1) {
6055 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
6057 if (max_devs
&& unit_id
>= max_devs
) {
6058 unit_id
-= max_devs
;
6066 if (max_devs
&& unit_id
>= max_devs
) {
6067 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
6068 str
, unit_id
, max_devs
- 1);
6073 * ignore multiple definitions
6076 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
6081 if (type
== IF_IDE
|| type
== IF_SCSI
)
6082 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
6084 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
6085 devname
, bus_id
, mediastr
, unit_id
);
6087 snprintf(buf
, sizeof(buf
), "%s%s%i",
6088 devname
, mediastr
, unit_id
);
6089 bdrv
= bdrv_new(buf
);
6090 drives_table_idx
= drive_get_free_idx();
6091 drives_table
[drives_table_idx
].bdrv
= bdrv
;
6092 drives_table
[drives_table_idx
].type
= type
;
6093 drives_table
[drives_table_idx
].bus
= bus_id
;
6094 drives_table
[drives_table_idx
].unit
= unit_id
;
6095 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
6104 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
6105 bdrv_set_translation_hint(bdrv
, translation
);
6109 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
6114 /* FIXME: This isn't really a floppy, but it's a reasonable
6117 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
6128 bdrv_flags
|= BDRV_O_SNAPSHOT
;
6130 bdrv_flags
|= BDRV_O_DIRECT
;
6131 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
6132 fprintf(stderr
, "qemu: could not open disk image %s\n",
6136 return drives_table_idx
;
6139 /***********************************************************/
6142 static USBPort
*used_usb_ports
;
6143 static USBPort
*free_usb_ports
;
6145 /* ??? Maybe change this to register a hub to keep track of the topology. */
6146 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
6147 usb_attachfn attach
)
6149 port
->opaque
= opaque
;
6150 port
->index
= index
;
6151 port
->attach
= attach
;
6152 port
->next
= free_usb_ports
;
6153 free_usb_ports
= port
;
6156 int usb_device_add_dev(USBDevice
*dev
)
6160 /* Find a USB port to add the device to. */
6161 port
= free_usb_ports
;
6165 /* Create a new hub and chain it on. */
6166 free_usb_ports
= NULL
;
6167 port
->next
= used_usb_ports
;
6168 used_usb_ports
= port
;
6170 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
6171 usb_attach(port
, hub
);
6172 port
= free_usb_ports
;
6175 free_usb_ports
= port
->next
;
6176 port
->next
= used_usb_ports
;
6177 used_usb_ports
= port
;
6178 usb_attach(port
, dev
);
6182 static int usb_device_add(const char *devname
)
6187 if (!free_usb_ports
)
6190 if (strstart(devname
, "host:", &p
)) {
6191 dev
= usb_host_device_open(p
);
6192 } else if (!strcmp(devname
, "mouse")) {
6193 dev
= usb_mouse_init();
6194 } else if (!strcmp(devname
, "tablet")) {
6195 dev
= usb_tablet_init();
6196 } else if (!strcmp(devname
, "keyboard")) {
6197 dev
= usb_keyboard_init();
6198 } else if (strstart(devname
, "disk:", &p
)) {
6199 dev
= usb_msd_init(p
);
6200 } else if (!strcmp(devname
, "wacom-tablet")) {
6201 dev
= usb_wacom_init();
6202 } else if (strstart(devname
, "serial:", &p
)) {
6203 dev
= usb_serial_init(p
);
6204 #ifdef CONFIG_BRLAPI
6205 } else if (!strcmp(devname
, "braille")) {
6206 dev
= usb_baum_init();
6208 } else if (strstart(devname
, "net:", &p
)) {
6211 if (net_client_init("nic", p
) < 0)
6213 nd_table
[nic
].model
= "usb";
6214 dev
= usb_net_init(&nd_table
[nic
]);
6221 return usb_device_add_dev(dev
);
6224 int usb_device_del_addr(int bus_num
, int addr
)
6230 if (!used_usb_ports
)
6236 lastp
= &used_usb_ports
;
6237 port
= used_usb_ports
;
6238 while (port
&& port
->dev
->addr
!= addr
) {
6239 lastp
= &port
->next
;
6247 *lastp
= port
->next
;
6248 usb_attach(port
, NULL
);
6249 dev
->handle_destroy(dev
);
6250 port
->next
= free_usb_ports
;
6251 free_usb_ports
= port
;
6255 static int usb_device_del(const char *devname
)
6260 if (strstart(devname
, "host:", &p
))
6261 return usb_host_device_close(p
);
6263 if (!used_usb_ports
)
6266 p
= strchr(devname
, '.');
6269 bus_num
= strtoul(devname
, NULL
, 0);
6270 addr
= strtoul(p
+ 1, NULL
, 0);
6272 return usb_device_del_addr(bus_num
, addr
);
6275 void do_usb_add(const char *devname
)
6277 usb_device_add(devname
);
6280 void do_usb_del(const char *devname
)
6282 usb_device_del(devname
);
6289 const char *speed_str
;
6292 term_printf("USB support not enabled\n");
6296 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6300 switch(dev
->speed
) {
6304 case USB_SPEED_FULL
:
6307 case USB_SPEED_HIGH
:
6314 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6315 0, dev
->addr
, speed_str
, dev
->devname
);
6319 /***********************************************************/
6320 /* PCMCIA/Cardbus */
6322 static struct pcmcia_socket_entry_s
{
6323 struct pcmcia_socket_s
*socket
;
6324 struct pcmcia_socket_entry_s
*next
;
6325 } *pcmcia_sockets
= 0;
6327 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6329 struct pcmcia_socket_entry_s
*entry
;
6331 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6332 entry
->socket
= socket
;
6333 entry
->next
= pcmcia_sockets
;
6334 pcmcia_sockets
= entry
;
6337 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6339 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6341 ptr
= &pcmcia_sockets
;
6342 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6343 if (entry
->socket
== socket
) {
6349 void pcmcia_info(void)
6351 struct pcmcia_socket_entry_s
*iter
;
6352 if (!pcmcia_sockets
)
6353 term_printf("No PCMCIA sockets\n");
6355 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6356 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6357 iter
->socket
->attached
? iter
->socket
->card_string
:
6361 /***********************************************************/
6364 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6368 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6372 static void dumb_refresh(DisplayState
*ds
)
6374 #if defined(CONFIG_SDL)
6379 static void dumb_display_init(DisplayState
*ds
)
6384 ds
->dpy_update
= dumb_update
;
6385 ds
->dpy_resize
= dumb_resize
;
6386 ds
->dpy_refresh
= dumb_refresh
;
6387 ds
->gui_timer_interval
= 500;
6391 /***********************************************************/
6394 #define MAX_IO_HANDLERS 64
6396 typedef struct IOHandlerRecord
{
6398 IOCanRWHandler
*fd_read_poll
;
6400 IOHandler
*fd_write
;
6403 /* temporary data */
6405 struct IOHandlerRecord
*next
;
6408 static IOHandlerRecord
*first_io_handler
;
6410 /* XXX: fd_read_poll should be suppressed, but an API change is
6411 necessary in the character devices to suppress fd_can_read(). */
6412 int qemu_set_fd_handler2(int fd
,
6413 IOCanRWHandler
*fd_read_poll
,
6415 IOHandler
*fd_write
,
6418 IOHandlerRecord
**pioh
, *ioh
;
6420 if (!fd_read
&& !fd_write
) {
6421 pioh
= &first_io_handler
;
6426 if (ioh
->fd
== fd
) {
6433 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6437 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6440 ioh
->next
= first_io_handler
;
6441 first_io_handler
= ioh
;
6444 ioh
->fd_read_poll
= fd_read_poll
;
6445 ioh
->fd_read
= fd_read
;
6446 ioh
->fd_write
= fd_write
;
6447 ioh
->opaque
= opaque
;
6454 int qemu_set_fd_handler(int fd
,
6456 IOHandler
*fd_write
,
6459 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6462 /***********************************************************/
6463 /* Polling handling */
6465 typedef struct PollingEntry
{
6468 struct PollingEntry
*next
;
6471 static PollingEntry
*first_polling_entry
;
6473 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6475 PollingEntry
**ppe
, *pe
;
6476 pe
= qemu_mallocz(sizeof(PollingEntry
));
6480 pe
->opaque
= opaque
;
6481 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6486 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6488 PollingEntry
**ppe
, *pe
;
6489 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6491 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6500 /***********************************************************/
6501 /* Wait objects support */
6502 typedef struct WaitObjects
{
6504 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6505 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6506 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6509 static WaitObjects wait_objects
= {0};
6511 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6513 WaitObjects
*w
= &wait_objects
;
6515 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6517 w
->events
[w
->num
] = handle
;
6518 w
->func
[w
->num
] = func
;
6519 w
->opaque
[w
->num
] = opaque
;
6524 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6527 WaitObjects
*w
= &wait_objects
;
6530 for (i
= 0; i
< w
->num
; i
++) {
6531 if (w
->events
[i
] == handle
)
6534 w
->events
[i
] = w
->events
[i
+ 1];
6535 w
->func
[i
] = w
->func
[i
+ 1];
6536 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6544 #define SELF_ANNOUNCE_ROUNDS 5
6545 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6546 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6547 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6549 static int announce_self_create(uint8_t *buf
,
6552 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6553 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6555 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6557 memset(buf
, 0xff, 6); /* h_dst */
6558 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6559 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6560 memcpy(buf
+ 14, &magic
, 4); /* magic */
6562 return 18; /* len */
6565 static void qemu_announce_self(void)
6569 VLANClientState
*vc
;
6572 for (i
= 0; i
< nb_nics
; i
++) {
6573 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6574 vlan
= nd_table
[i
].vlan
;
6575 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6576 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6577 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6578 vc
->fd_read(vc
->opaque
, buf
, len
);
6583 /***********************************************************/
6584 /* savevm/loadvm support */
6586 #define IO_BUF_SIZE 32768
6589 QEMUFilePutBufferFunc
*put_buffer
;
6590 QEMUFileGetBufferFunc
*get_buffer
;
6591 QEMUFileCloseFunc
*close
;
6594 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6597 int buf_size
; /* 0 when writing */
6598 uint8_t buf
[IO_BUF_SIZE
];
6601 typedef struct QEMUFileFD
6606 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6608 QEMUFileFD
*s
= opaque
;
6613 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6615 if (errno
== EINTR
|| errno
== EAGAIN
)
6622 QEMUFile
*qemu_fopen_fd(int fd
)
6624 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6626 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6629 typedef struct QEMUFileUnix
6634 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6636 QEMUFileUnix
*s
= opaque
;
6637 fseek(s
->outfile
, pos
, SEEK_SET
);
6638 fwrite(buf
, 1, size
, s
->outfile
);
6641 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6643 QEMUFileUnix
*s
= opaque
;
6644 fseek(s
->outfile
, pos
, SEEK_SET
);
6645 return fread(buf
, 1, size
, s
->outfile
);
6648 static void file_close(void *opaque
)
6650 QEMUFileUnix
*s
= opaque
;
6655 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6659 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6663 s
->outfile
= fopen(filename
, mode
);
6667 if (!strcmp(mode
, "wb"))
6668 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6669 else if (!strcmp(mode
, "rb"))
6670 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6679 typedef struct QEMUFileBdrv
6681 BlockDriverState
*bs
;
6682 int64_t base_offset
;
6685 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6687 QEMUFileBdrv
*s
= opaque
;
6688 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6691 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6693 QEMUFileBdrv
*s
= opaque
;
6694 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6697 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6701 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6706 s
->base_offset
= offset
;
6709 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6711 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6714 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6715 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6719 f
= qemu_mallocz(sizeof(QEMUFile
));
6724 f
->put_buffer
= put_buffer
;
6725 f
->get_buffer
= get_buffer
;
6731 void qemu_fflush(QEMUFile
*f
)
6736 if (f
->buf_index
> 0) {
6737 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6738 f
->buf_offset
+= f
->buf_index
;
6743 static void qemu_fill_buffer(QEMUFile
*f
)
6750 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6756 f
->buf_offset
+= len
;
6759 void qemu_fclose(QEMUFile
*f
)
6763 f
->close(f
->opaque
);
6767 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6771 l
= IO_BUF_SIZE
- f
->buf_index
;
6774 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6778 if (f
->buf_index
>= IO_BUF_SIZE
)
6783 void qemu_put_byte(QEMUFile
*f
, int v
)
6785 f
->buf
[f
->buf_index
++] = v
;
6786 if (f
->buf_index
>= IO_BUF_SIZE
)
6790 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6796 l
= f
->buf_size
- f
->buf_index
;
6798 qemu_fill_buffer(f
);
6799 l
= f
->buf_size
- f
->buf_index
;
6805 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6810 return size1
- size
;
6813 int qemu_get_byte(QEMUFile
*f
)
6815 if (f
->buf_index
>= f
->buf_size
) {
6816 qemu_fill_buffer(f
);
6817 if (f
->buf_index
>= f
->buf_size
)
6820 return f
->buf
[f
->buf_index
++];
6823 int64_t qemu_ftell(QEMUFile
*f
)
6825 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6828 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6830 if (whence
== SEEK_SET
) {
6832 } else if (whence
== SEEK_CUR
) {
6833 pos
+= qemu_ftell(f
);
6835 /* SEEK_END not supported */
6838 if (f
->put_buffer
) {
6840 f
->buf_offset
= pos
;
6842 f
->buf_offset
= pos
;
6849 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6851 qemu_put_byte(f
, v
>> 8);
6852 qemu_put_byte(f
, v
);
6855 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6857 qemu_put_byte(f
, v
>> 24);
6858 qemu_put_byte(f
, v
>> 16);
6859 qemu_put_byte(f
, v
>> 8);
6860 qemu_put_byte(f
, v
);
6863 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6865 qemu_put_be32(f
, v
>> 32);
6866 qemu_put_be32(f
, v
);
6869 unsigned int qemu_get_be16(QEMUFile
*f
)
6872 v
= qemu_get_byte(f
) << 8;
6873 v
|= qemu_get_byte(f
);
6877 unsigned int qemu_get_be32(QEMUFile
*f
)
6880 v
= qemu_get_byte(f
) << 24;
6881 v
|= qemu_get_byte(f
) << 16;
6882 v
|= qemu_get_byte(f
) << 8;
6883 v
|= qemu_get_byte(f
);
6887 uint64_t qemu_get_be64(QEMUFile
*f
)
6890 v
= (uint64_t)qemu_get_be32(f
) << 32;
6891 v
|= qemu_get_be32(f
);
6895 typedef struct SaveStateEntry
{
6899 SaveStateHandler
*save_state
;
6900 LoadStateHandler
*load_state
;
6902 struct SaveStateEntry
*next
;
6905 static SaveStateEntry
*first_se
;
6907 /* TODO: Individual devices generally have very little idea about the rest
6908 of the system, so instance_id should be removed/replaced.
6909 Meanwhile pass -1 as instance_id if you do not already have a clearly
6910 distinguishing id for all instances of your device class. */
6911 int register_savevm(const char *idstr
,
6914 SaveStateHandler
*save_state
,
6915 LoadStateHandler
*load_state
,
6918 SaveStateEntry
*se
, **pse
;
6920 se
= qemu_malloc(sizeof(SaveStateEntry
));
6923 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6924 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6925 se
->version_id
= version_id
;
6926 se
->save_state
= save_state
;
6927 se
->load_state
= load_state
;
6928 se
->opaque
= opaque
;
6931 /* add at the end of list */
6933 while (*pse
!= NULL
) {
6934 if (instance_id
== -1
6935 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6936 && se
->instance_id
<= (*pse
)->instance_id
)
6937 se
->instance_id
= (*pse
)->instance_id
+ 1;
6938 pse
= &(*pse
)->next
;
6944 #define QEMU_VM_FILE_MAGIC 0x5145564d
6945 #define QEMU_VM_FILE_VERSION 0x00000002
6947 static int qemu_savevm_state(QEMUFile
*f
)
6951 int64_t cur_pos
, len_pos
, total_len_pos
;
6953 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6954 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6955 total_len_pos
= qemu_ftell(f
);
6956 qemu_put_be64(f
, 0); /* total size */
6958 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6959 if (se
->save_state
== NULL
)
6960 /* this one has a loader only, for backwards compatibility */
6964 len
= strlen(se
->idstr
);
6965 qemu_put_byte(f
, len
);
6966 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6968 qemu_put_be32(f
, se
->instance_id
);
6969 qemu_put_be32(f
, se
->version_id
);
6971 /* record size: filled later */
6972 len_pos
= qemu_ftell(f
);
6973 qemu_put_be32(f
, 0);
6974 se
->save_state(f
, se
->opaque
);
6976 /* fill record size */
6977 cur_pos
= qemu_ftell(f
);
6978 len
= cur_pos
- len_pos
- 4;
6979 qemu_fseek(f
, len_pos
, SEEK_SET
);
6980 qemu_put_be32(f
, len
);
6981 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6983 cur_pos
= qemu_ftell(f
);
6984 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6985 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6986 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6992 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6996 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6997 if (!strcmp(se
->idstr
, idstr
) &&
6998 instance_id
== se
->instance_id
)
7004 static int qemu_loadvm_state(QEMUFile
*f
)
7007 int len
, ret
, instance_id
, record_len
, version_id
;
7008 int64_t total_len
, end_pos
, cur_pos
;
7012 v
= qemu_get_be32(f
);
7013 if (v
!= QEMU_VM_FILE_MAGIC
)
7015 v
= qemu_get_be32(f
);
7016 if (v
!= QEMU_VM_FILE_VERSION
) {
7021 total_len
= qemu_get_be64(f
);
7022 end_pos
= total_len
+ qemu_ftell(f
);
7024 if (qemu_ftell(f
) >= end_pos
)
7026 len
= qemu_get_byte(f
);
7027 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
7029 instance_id
= qemu_get_be32(f
);
7030 version_id
= qemu_get_be32(f
);
7031 record_len
= qemu_get_be32(f
);
7033 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7034 idstr
, instance_id
, version_id
, record_len
);
7036 cur_pos
= qemu_ftell(f
);
7037 se
= find_se(idstr
, instance_id
);
7039 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7040 instance_id
, idstr
);
7042 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7044 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7045 instance_id
, idstr
);
7049 /* always seek to exact end of record */
7050 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
7057 int qemu_live_savevm_state(QEMUFile
*f
)
7062 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
7063 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
7065 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
7066 len
= strlen(se
->idstr
);
7068 qemu_put_byte(f
, len
);
7069 qemu_put_buffer(f
, se
->idstr
, len
);
7070 qemu_put_be32(f
, se
->instance_id
);
7071 qemu_put_be32(f
, se
->version_id
);
7073 se
->save_state(f
, se
->opaque
);
7076 qemu_put_byte(f
, 0);
7082 int qemu_live_loadvm_state(QEMUFile
*f
)
7085 int len
, ret
, instance_id
, version_id
;
7089 v
= qemu_get_be32(f
);
7090 if (v
!= QEMU_VM_FILE_MAGIC
)
7092 v
= qemu_get_be32(f
);
7093 if (v
!= QEMU_VM_FILE_VERSION
) {
7100 len
= qemu_get_byte(f
);
7103 qemu_get_buffer(f
, idstr
, len
);
7105 instance_id
= qemu_get_be32(f
);
7106 version_id
= qemu_get_be32(f
);
7107 se
= find_se(idstr
, instance_id
);
7109 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7110 instance_id
, idstr
);
7112 if (version_id
> se
->version_id
) { /* src version > dst version */
7113 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7114 idstr
, version_id
, se
->version_id
);
7118 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7120 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7121 instance_id
, idstr
);
7128 qemu_announce_self();
7134 /* device can contain snapshots */
7135 static int bdrv_can_snapshot(BlockDriverState
*bs
)
7138 !bdrv_is_removable(bs
) &&
7139 !bdrv_is_read_only(bs
));
7142 /* device must be snapshots in order to have a reliable snapshot */
7143 static int bdrv_has_snapshot(BlockDriverState
*bs
)
7146 !bdrv_is_removable(bs
) &&
7147 !bdrv_is_read_only(bs
));
7150 static BlockDriverState
*get_bs_snapshots(void)
7152 BlockDriverState
*bs
;
7156 return bs_snapshots
;
7157 for(i
= 0; i
<= nb_drives
; i
++) {
7158 bs
= drives_table
[i
].bdrv
;
7159 if (bdrv_can_snapshot(bs
))
7168 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
7171 QEMUSnapshotInfo
*sn_tab
, *sn
;
7175 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7178 for(i
= 0; i
< nb_sns
; i
++) {
7180 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
7190 void do_savevm(const char *name
)
7192 BlockDriverState
*bs
, *bs1
;
7193 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
7194 int must_delete
, ret
, i
;
7195 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7197 int saved_vm_running
;
7204 bs
= get_bs_snapshots();
7206 term_printf("No block device can accept snapshots\n");
7210 /* ??? Should this occur after vm_stop? */
7213 saved_vm_running
= vm_running
;
7218 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
7223 memset(sn
, 0, sizeof(*sn
));
7225 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
7226 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
7229 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
7232 /* fill auxiliary fields */
7235 sn
->date_sec
= tb
.time
;
7236 sn
->date_nsec
= tb
.millitm
* 1000000;
7238 gettimeofday(&tv
, NULL
);
7239 sn
->date_sec
= tv
.tv_sec
;
7240 sn
->date_nsec
= tv
.tv_usec
* 1000;
7242 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7244 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7245 term_printf("Device %s does not support VM state snapshots\n",
7246 bdrv_get_device_name(bs
));
7250 /* save the VM state */
7251 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7253 term_printf("Could not open VM state file\n");
7256 ret
= qemu_savevm_state(f
);
7257 sn
->vm_state_size
= qemu_ftell(f
);
7260 term_printf("Error %d while writing VM\n", ret
);
7264 /* create the snapshots */
7266 for(i
= 0; i
< nb_drives
; i
++) {
7267 bs1
= drives_table
[i
].bdrv
;
7268 if (bdrv_has_snapshot(bs1
)) {
7270 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7272 term_printf("Error while deleting snapshot on '%s'\n",
7273 bdrv_get_device_name(bs1
));
7276 ret
= bdrv_snapshot_create(bs1
, sn
);
7278 term_printf("Error while creating snapshot on '%s'\n",
7279 bdrv_get_device_name(bs1
));
7285 if (saved_vm_running
)
7289 void do_loadvm(const char *name
)
7291 BlockDriverState
*bs
, *bs1
;
7292 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7295 int saved_vm_running
;
7297 bs
= get_bs_snapshots();
7299 term_printf("No block device supports snapshots\n");
7303 /* Flush all IO requests so they don't interfere with the new state. */
7306 saved_vm_running
= vm_running
;
7309 for(i
= 0; i
<= nb_drives
; i
++) {
7310 bs1
= drives_table
[i
].bdrv
;
7311 if (bdrv_has_snapshot(bs1
)) {
7312 ret
= bdrv_snapshot_goto(bs1
, name
);
7315 term_printf("Warning: ");
7318 term_printf("Snapshots not supported on device '%s'\n",
7319 bdrv_get_device_name(bs1
));
7322 term_printf("Could not find snapshot '%s' on device '%s'\n",
7323 name
, bdrv_get_device_name(bs1
));
7326 term_printf("Error %d while activating snapshot on '%s'\n",
7327 ret
, bdrv_get_device_name(bs1
));
7330 /* fatal on snapshot block device */
7337 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7338 term_printf("Device %s does not support VM state snapshots\n",
7339 bdrv_get_device_name(bs
));
7343 /* restore the VM state */
7344 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7346 term_printf("Could not open VM state file\n");
7349 ret
= qemu_loadvm_state(f
);
7352 term_printf("Error %d while loading VM state\n", ret
);
7355 if (saved_vm_running
)
7359 void do_delvm(const char *name
)
7361 BlockDriverState
*bs
, *bs1
;
7364 bs
= get_bs_snapshots();
7366 term_printf("No block device supports snapshots\n");
7370 for(i
= 0; i
<= nb_drives
; i
++) {
7371 bs1
= drives_table
[i
].bdrv
;
7372 if (bdrv_has_snapshot(bs1
)) {
7373 ret
= bdrv_snapshot_delete(bs1
, name
);
7375 if (ret
== -ENOTSUP
)
7376 term_printf("Snapshots not supported on device '%s'\n",
7377 bdrv_get_device_name(bs1
));
7379 term_printf("Error %d while deleting snapshot on '%s'\n",
7380 ret
, bdrv_get_device_name(bs1
));
7386 void do_info_snapshots(void)
7388 BlockDriverState
*bs
, *bs1
;
7389 QEMUSnapshotInfo
*sn_tab
, *sn
;
7393 bs
= get_bs_snapshots();
7395 term_printf("No available block device supports snapshots\n");
7398 term_printf("Snapshot devices:");
7399 for(i
= 0; i
<= nb_drives
; i
++) {
7400 bs1
= drives_table
[i
].bdrv
;
7401 if (bdrv_has_snapshot(bs1
)) {
7403 term_printf(" %s", bdrv_get_device_name(bs1
));
7408 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7410 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7413 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7414 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7415 for(i
= 0; i
< nb_sns
; i
++) {
7417 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7422 /***********************************************************/
7423 /* ram save/restore */
7425 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7429 v
= qemu_get_byte(f
);
7432 if (qemu_get_buffer(f
, buf
, len
) != len
)
7436 v
= qemu_get_byte(f
);
7437 memset(buf
, v
, len
);
7445 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7450 if (qemu_get_be32(f
) != phys_ram_size
)
7452 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7453 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7455 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7462 #define BDRV_HASH_BLOCK_SIZE 1024
7463 #define IOBUF_SIZE 4096
7464 #define RAM_CBLOCK_MAGIC 0xfabe
7466 typedef struct RamCompressState
{
7469 uint8_t buf
[IOBUF_SIZE
];
7472 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7475 memset(s
, 0, sizeof(*s
));
7477 ret
= deflateInit2(&s
->zstream
, 1,
7479 9, Z_DEFAULT_STRATEGY
);
7482 s
->zstream
.avail_out
= IOBUF_SIZE
;
7483 s
->zstream
.next_out
= s
->buf
;
7487 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7489 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7490 qemu_put_be16(s
->f
, len
);
7491 qemu_put_buffer(s
->f
, buf
, len
);
7494 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7498 s
->zstream
.avail_in
= len
;
7499 s
->zstream
.next_in
= (uint8_t *)buf
;
7500 while (s
->zstream
.avail_in
> 0) {
7501 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7504 if (s
->zstream
.avail_out
== 0) {
7505 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7506 s
->zstream
.avail_out
= IOBUF_SIZE
;
7507 s
->zstream
.next_out
= s
->buf
;
7513 static void ram_compress_close(RamCompressState
*s
)
7517 /* compress last bytes */
7519 ret
= deflate(&s
->zstream
, Z_FINISH
);
7520 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7521 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7523 ram_put_cblock(s
, s
->buf
, len
);
7525 s
->zstream
.avail_out
= IOBUF_SIZE
;
7526 s
->zstream
.next_out
= s
->buf
;
7527 if (ret
== Z_STREAM_END
)
7534 deflateEnd(&s
->zstream
);
7537 typedef struct RamDecompressState
{
7540 uint8_t buf
[IOBUF_SIZE
];
7541 } RamDecompressState
;
7543 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7546 memset(s
, 0, sizeof(*s
));
7548 ret
= inflateInit(&s
->zstream
);
7554 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7558 s
->zstream
.avail_out
= len
;
7559 s
->zstream
.next_out
= buf
;
7560 while (s
->zstream
.avail_out
> 0) {
7561 if (s
->zstream
.avail_in
== 0) {
7562 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7564 clen
= qemu_get_be16(s
->f
);
7565 if (clen
> IOBUF_SIZE
)
7567 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7568 s
->zstream
.avail_in
= clen
;
7569 s
->zstream
.next_in
= s
->buf
;
7571 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7572 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7579 static void ram_decompress_close(RamDecompressState
*s
)
7581 inflateEnd(&s
->zstream
);
7584 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7588 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7589 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7591 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7592 qemu_put_be32(f
, addr
);
7593 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7596 qemu_put_be32(f
, 1);
7599 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7602 RamCompressState s1
, *s
= &s1
;
7605 qemu_put_be32(f
, phys_ram_size
);
7606 if (ram_compress_open(s
, f
) < 0)
7608 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7609 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7612 if (tight_savevm_enabled
) {
7616 /* find if the memory block is available on a virtual
7619 for(j
= 0; j
< nb_drives
; j
++) {
7620 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7622 BDRV_HASH_BLOCK_SIZE
);
7623 if (sector_num
>= 0)
7627 goto normal_compress
;
7630 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7631 ram_compress_buf(s
, buf
, 10);
7637 ram_compress_buf(s
, buf
, 1);
7638 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7641 ram_compress_close(s
);
7644 static void ram_save(QEMUFile
*f
, void *opaque
)
7646 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7648 qemu_put_byte(f
, in_migration
);
7651 ram_save_live(f
, opaque
);
7653 ram_save_static(f
, opaque
);
7656 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7661 addr
= qemu_get_be32(f
);
7665 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7671 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7673 RamDecompressState s1
, *s
= &s1
;
7677 if (qemu_get_be32(f
) != phys_ram_size
)
7679 if (ram_decompress_open(s
, f
) < 0)
7681 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7682 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7684 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7685 fprintf(stderr
, "Error while reading ram block header\n");
7689 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7690 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7699 ram_decompress_buf(s
, buf
+ 1, 9);
7701 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7702 if (bs_index
>= nb_drives
) {
7703 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7706 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7708 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7709 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7710 bs_index
, sector_num
);
7717 printf("Error block header\n");
7721 ram_decompress_close(s
);
7725 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7729 switch (version_id
) {
7731 ret
= ram_load_v1(f
, opaque
);
7734 if (qemu_get_byte(f
)) {
7735 ret
= ram_load_live(f
, opaque
);
7739 ret
= ram_load_static(f
, opaque
);
7749 /***********************************************************/
7750 /* bottom halves (can be seen as timers which expire ASAP) */
7759 static QEMUBH
*first_bh
= NULL
;
7761 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7764 bh
= qemu_mallocz(sizeof(QEMUBH
));
7768 bh
->opaque
= opaque
;
7772 int qemu_bh_poll(void)
7791 void qemu_bh_schedule(QEMUBH
*bh
)
7793 CPUState
*env
= cpu_single_env
;
7797 bh
->next
= first_bh
;
7800 /* stop the currently executing CPU to execute the BH ASAP */
7802 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7807 void qemu_bh_cancel(QEMUBH
*bh
)
7810 if (bh
->scheduled
) {
7813 pbh
= &(*pbh
)->next
;
7819 void qemu_bh_delete(QEMUBH
*bh
)
7825 /***********************************************************/
7826 /* machine registration */
7828 QEMUMachine
*first_machine
= NULL
;
7829 QEMUMachine
*current_machine
= NULL
;
7831 int qemu_register_machine(QEMUMachine
*m
)
7834 pm
= &first_machine
;
7842 static QEMUMachine
*find_machine(const char *name
)
7846 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7847 if (!strcmp(m
->name
, name
))
7853 /***********************************************************/
7854 /* main execution loop */
7856 static void gui_update(void *opaque
)
7858 DisplayState
*ds
= opaque
;
7859 ds
->dpy_refresh(ds
);
7860 qemu_mod_timer(ds
->gui_timer
,
7861 (ds
->gui_timer_interval
?
7862 ds
->gui_timer_interval
:
7863 GUI_REFRESH_INTERVAL
)
7864 + qemu_get_clock(rt_clock
));
7867 struct vm_change_state_entry
{
7868 VMChangeStateHandler
*cb
;
7870 LIST_ENTRY (vm_change_state_entry
) entries
;
7873 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7875 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7878 VMChangeStateEntry
*e
;
7880 e
= qemu_mallocz(sizeof (*e
));
7886 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7890 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7892 LIST_REMOVE (e
, entries
);
7896 static void vm_state_notify(int running
)
7898 VMChangeStateEntry
*e
;
7900 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7901 e
->cb(e
->opaque
, running
);
7905 /* XXX: support several handlers */
7906 static VMStopHandler
*vm_stop_cb
;
7907 static void *vm_stop_opaque
;
7909 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7912 vm_stop_opaque
= opaque
;
7916 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7927 qemu_rearm_alarm_timer(alarm_timer
);
7931 void vm_stop(int reason
)
7934 cpu_disable_ticks();
7938 vm_stop_cb(vm_stop_opaque
, reason
);
7945 /* reset/shutdown handler */
7947 typedef struct QEMUResetEntry
{
7948 QEMUResetHandler
*func
;
7950 struct QEMUResetEntry
*next
;
7953 static QEMUResetEntry
*first_reset_entry
;
7954 static int reset_requested
;
7955 static int shutdown_requested
;
7956 static int powerdown_requested
;
7958 int qemu_shutdown_requested(void)
7960 int r
= shutdown_requested
;
7961 shutdown_requested
= 0;
7965 int qemu_reset_requested(void)
7967 int r
= reset_requested
;
7968 reset_requested
= 0;
7972 int qemu_powerdown_requested(void)
7974 int r
= powerdown_requested
;
7975 powerdown_requested
= 0;
7979 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7981 QEMUResetEntry
**pre
, *re
;
7983 pre
= &first_reset_entry
;
7984 while (*pre
!= NULL
)
7985 pre
= &(*pre
)->next
;
7986 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7988 re
->opaque
= opaque
;
7993 void qemu_system_reset(void)
7997 /* reset all devices */
7998 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7999 re
->func(re
->opaque
);
8003 void qemu_system_reset_request(void)
8006 shutdown_requested
= 1;
8008 reset_requested
= 1;
8011 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8015 void qemu_system_shutdown_request(void)
8017 shutdown_requested
= 1;
8019 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8022 void qemu_system_powerdown_request(void)
8024 powerdown_requested
= 1;
8026 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8029 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
8034 /* KVM holds a mutex while QEMU code is running, we need hooks to
8035 release the mutex whenever QEMU code sleeps. */
8039 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
8046 void main_loop_wait(int timeout
)
8048 IOHandlerRecord
*ioh
;
8049 fd_set rfds
, wfds
, xfds
;
8058 /* XXX: need to suppress polling by better using win32 events */
8060 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
8061 ret
|= pe
->func(pe
->opaque
);
8066 WaitObjects
*w
= &wait_objects
;
8068 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
8069 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
8070 if (w
->func
[ret
- WAIT_OBJECT_0
])
8071 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
8073 /* Check for additional signaled events */
8074 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
8076 /* Check if event is signaled */
8077 ret2
= WaitForSingleObject(w
->events
[i
], 0);
8078 if(ret2
== WAIT_OBJECT_0
) {
8080 w
->func
[i
](w
->opaque
[i
]);
8081 } else if (ret2
== WAIT_TIMEOUT
) {
8083 err
= GetLastError();
8084 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
8087 } else if (ret
== WAIT_TIMEOUT
) {
8089 err
= GetLastError();
8090 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
8094 /* poll any events */
8095 /* XXX: separate device handlers from system ones */
8100 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8104 (!ioh
->fd_read_poll
||
8105 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
8106 FD_SET(ioh
->fd
, &rfds
);
8110 if (ioh
->fd_write
) {
8111 FD_SET(ioh
->fd
, &wfds
);
8121 tv
.tv_sec
= timeout
/ 1000;
8122 tv
.tv_usec
= (timeout
% 1000) * 1000;
8124 #if defined(CONFIG_SLIRP)
8126 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
8129 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
8131 IOHandlerRecord
**pioh
;
8133 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8134 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
8135 ioh
->fd_read(ioh
->opaque
);
8136 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
8137 FD_CLR(ioh
->fd
, &rfds
);
8139 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
8140 ioh
->fd_write(ioh
->opaque
);
8144 /* remove deleted IO handlers */
8145 pioh
= &first_io_handler
;
8155 #if defined(CONFIG_SLIRP)
8162 slirp_select_poll(&rfds
, &wfds
, &xfds
);
8167 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
8168 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
8169 qemu_get_clock(vm_clock
));
8170 /* run dma transfers, if any */
8174 /* real time timers */
8175 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
8176 qemu_get_clock(rt_clock
));
8178 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
8179 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
8180 qemu_rearm_alarm_timer(alarm_timer
);
8183 /* Check bottom-halves last in case any of the earlier events triggered
8189 static int main_loop(void)
8192 #ifdef CONFIG_PROFILER
8198 if (kvm_enabled()) {
8200 cpu_disable_ticks();
8204 cur_cpu
= first_cpu
;
8205 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
8212 #ifdef CONFIG_PROFILER
8213 ti
= profile_getclock();
8218 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
8219 env
->icount_decr
.u16
.low
= 0;
8220 env
->icount_extra
= 0;
8221 count
= qemu_next_deadline();
8222 count
= (count
+ (1 << icount_time_shift
) - 1)
8223 >> icount_time_shift
;
8224 qemu_icount
+= count
;
8225 decr
= (count
> 0xffff) ? 0xffff : count
;
8227 env
->icount_decr
.u16
.low
= decr
;
8228 env
->icount_extra
= count
;
8230 ret
= cpu_exec(env
);
8231 #ifdef CONFIG_PROFILER
8232 qemu_time
+= profile_getclock() - ti
;
8235 /* Fold pending instructions back into the
8236 instruction counter, and clear the interrupt flag. */
8237 qemu_icount
-= (env
->icount_decr
.u16
.low
8238 + env
->icount_extra
);
8239 env
->icount_decr
.u32
= 0;
8240 env
->icount_extra
= 0;
8242 next_cpu
= env
->next_cpu
?: first_cpu
;
8243 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8244 ret
= EXCP_INTERRUPT
;
8248 if (ret
== EXCP_HLT
) {
8249 /* Give the next CPU a chance to run. */
8253 if (ret
!= EXCP_HALTED
)
8255 /* all CPUs are halted ? */
8261 if (shutdown_requested
) {
8262 ret
= EXCP_INTERRUPT
;
8270 if (reset_requested
) {
8271 reset_requested
= 0;
8272 qemu_system_reset();
8274 kvm_load_registers(env
);
8275 ret
= EXCP_INTERRUPT
;
8277 if (powerdown_requested
) {
8278 powerdown_requested
= 0;
8279 qemu_system_powerdown();
8280 ret
= EXCP_INTERRUPT
;
8282 if (unlikely(ret
== EXCP_DEBUG
)) {
8283 vm_stop(EXCP_DEBUG
);
8285 /* If all cpus are halted then wait until the next IRQ */
8286 /* XXX: use timeout computed from timers */
8287 if (ret
== EXCP_HALTED
) {
8291 /* Advance virtual time to the next event. */
8292 if (use_icount
== 1) {
8293 /* When not using an adaptive execution frequency
8294 we tend to get badly out of sync with real time,
8295 so just delay for a reasonable amount of time. */
8298 delta
= cpu_get_icount() - cpu_get_clock();
8301 /* If virtual time is ahead of real time then just
8303 timeout
= (delta
/ 1000000) + 1;
8305 /* Wait for either IO to occur or the next
8307 add
= qemu_next_deadline();
8308 /* We advance the timer before checking for IO.
8309 Limit the amount we advance so that early IO
8310 activity won't get the guest too far ahead. */
8314 add
= (add
+ (1 << icount_time_shift
) - 1)
8315 >> icount_time_shift
;
8317 timeout
= delta
/ 1000000;
8328 if (shutdown_requested
)
8332 #ifdef CONFIG_PROFILER
8333 ti
= profile_getclock();
8335 main_loop_wait(timeout
);
8336 #ifdef CONFIG_PROFILER
8337 dev_time
+= profile_getclock() - ti
;
8340 cpu_disable_ticks();
8344 static void help(int exitcode
)
8346 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8347 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8348 "usage: %s [options] [disk_image]\n"
8350 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8352 "Standard options:\n"
8353 "-M machine select emulated machine (-M ? for list)\n"
8354 "-cpu cpu select CPU (-cpu ? for list)\n"
8355 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8356 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8357 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8358 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8359 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8360 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8361 " [,cache=on|off][,format=f][,boot=on|off]\n"
8362 " use 'file' as a drive image\n"
8363 "-mtdblock file use 'file' as on-board Flash memory image\n"
8364 "-sd file use 'file' as SecureDigital card image\n"
8365 "-pflash file use 'file' as a parallel flash image\n"
8366 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8367 "-snapshot write to temporary files instead of disk image files\n"
8369 "-no-frame open SDL window without a frame and window decorations\n"
8370 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8371 "-no-quit disable SDL window close capability\n"
8374 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8376 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8377 "-smp n set the number of CPUs to 'n' [default=1]\n"
8378 "-nographic disable graphical output and redirect serial I/Os to console\n"
8379 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8381 "-k language use keyboard layout (for example \"fr\" for French)\n"
8384 "-audio-help print list of audio drivers and their options\n"
8385 "-soundhw c1,... enable audio support\n"
8386 " and only specified sound cards (comma separated list)\n"
8387 " use -soundhw ? to get the list of supported cards\n"
8388 " use -soundhw all to enable all of them\n"
8390 "-localtime set the real time clock to local time [default=utc]\n"
8391 "-full-screen start in full screen\n"
8393 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8395 "-usb enable the USB driver (will be the default soon)\n"
8396 "-usbdevice name add the host or guest USB device 'name'\n"
8397 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8398 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8400 "-name string set the name of the guest\n"
8402 "Network options:\n"
8403 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8404 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8406 "-net user[,vlan=n][,hostname=host]\n"
8407 " connect the user mode network stack to VLAN 'n' and send\n"
8408 " hostname 'host' to DHCP clients\n"
8411 "-net tap[,vlan=n],ifname=name\n"
8412 " connect the host TAP network interface to VLAN 'n'\n"
8414 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8415 " connect the host TAP network interface to VLAN 'n' and use the\n"
8416 " network scripts 'file' (default=%s)\n"
8417 " and 'dfile' (default=%s);\n"
8418 " use '[down]script=no' to disable script execution;\n"
8419 " use 'fd=h' to connect to an already opened TAP interface\n"
8421 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8422 " connect the vlan 'n' to another VLAN using a socket connection\n"
8423 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8424 " connect the vlan 'n' to multicast maddr and port\n"
8426 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8427 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8428 " on host and listening for incoming connections on 'socketpath'.\n"
8429 " Use group 'groupname' and mode 'octalmode' to change default\n"
8430 " ownership and permissions for communication port.\n"
8432 "-net none use it alone to have zero network devices; if no -net option\n"
8433 " is provided, the default is '-net nic -net user'\n"
8436 "-tftp dir allow tftp access to files in dir [-net user]\n"
8437 "-bootp file advertise file in BOOTP replies\n"
8439 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8441 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8442 " redirect TCP or UDP connections from host to guest [-net user]\n"
8445 "Linux boot specific:\n"
8446 "-kernel bzImage use 'bzImage' as kernel image\n"
8447 "-append cmdline use 'cmdline' as kernel command line\n"
8448 "-initrd file use 'file' as initial ram disk\n"
8450 "Debug/Expert options:\n"
8451 "-monitor dev redirect the monitor to char device 'dev'\n"
8452 "-serial dev redirect the serial port to char device 'dev'\n"
8453 "-parallel dev redirect the parallel port to char device 'dev'\n"
8454 "-pidfile file Write PID to 'file'\n"
8455 "-S freeze CPU at startup (use 'c' to start execution)\n"
8456 "-s wait gdb connection to port\n"
8457 "-p port set gdb connection port [default=%s]\n"
8458 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8459 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8460 " translation (t=none or lba) (usually qemu can guess them)\n"
8461 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8463 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8464 "-no-kqemu disable KQEMU kernel module usage\n"
8467 #ifndef NO_CPU_EMULATION
8468 "-no-kvm disable KVM hardware virtualization\n"
8470 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8471 "-no-kvm-pit disable KVM kernel mode PIT\n"
8474 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8475 " (default is CL-GD5446 PCI VGA)\n"
8476 "-no-acpi disable ACPI\n"
8478 #ifdef CONFIG_CURSES
8479 "-curses use a curses/ncurses interface instead of SDL\n"
8481 "-no-reboot exit instead of rebooting\n"
8482 "-no-shutdown stop before shutdown\n"
8483 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8484 "-vnc display start a VNC server on display\n"
8486 "-daemonize daemonize QEMU after initializing\n"
8488 "-tdf inject timer interrupts that got lost\n"
8489 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8490 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8491 "-option-rom rom load a file, rom, into the option ROM space\n"
8493 "-prom-env variable=value set OpenBIOS nvram variables\n"
8495 "-clock force the use of the given methods for timer alarm.\n"
8496 " To see what timers are available use -clock ?\n"
8497 "-startdate select initial date of the clock\n"
8498 "-icount [N|auto]\n"
8499 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8501 "During emulation, the following keys are useful:\n"
8502 "ctrl-alt-f toggle full screen\n"
8503 "ctrl-alt-n switch to virtual console 'n'\n"
8504 "ctrl-alt toggle mouse and keyboard grab\n"
8506 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8511 DEFAULT_NETWORK_SCRIPT
,
8512 DEFAULT_NETWORK_DOWN_SCRIPT
,
8514 DEFAULT_GDBSTUB_PORT
,
8519 #define HAS_ARG 0x0001
8534 QEMU_OPTION_mtdblock
,
8538 QEMU_OPTION_snapshot
,
8540 QEMU_OPTION_no_fd_bootchk
,
8543 QEMU_OPTION_nographic
,
8544 QEMU_OPTION_portrait
,
8546 QEMU_OPTION_audio_help
,
8547 QEMU_OPTION_soundhw
,
8568 QEMU_OPTION_localtime
,
8569 QEMU_OPTION_cirrusvga
,
8572 QEMU_OPTION_std_vga
,
8574 QEMU_OPTION_monitor
,
8576 QEMU_OPTION_parallel
,
8578 QEMU_OPTION_full_screen
,
8579 QEMU_OPTION_no_frame
,
8580 QEMU_OPTION_alt_grab
,
8581 QEMU_OPTION_no_quit
,
8582 QEMU_OPTION_pidfile
,
8583 QEMU_OPTION_no_kqemu
,
8584 QEMU_OPTION_kernel_kqemu
,
8585 QEMU_OPTION_win2k_hack
,
8587 QEMU_OPTION_usbdevice
,
8590 QEMU_OPTION_no_acpi
,
8593 QEMU_OPTION_no_kvm_irqchip
,
8594 QEMU_OPTION_no_kvm_pit
,
8595 QEMU_OPTION_no_reboot
,
8596 QEMU_OPTION_no_shutdown
,
8597 QEMU_OPTION_show_cursor
,
8598 QEMU_OPTION_daemonize
,
8599 QEMU_OPTION_option_rom
,
8600 QEMU_OPTION_semihosting
,
8601 QEMU_OPTION_cpu_vendor
,
8603 QEMU_OPTION_prom_env
,
8604 QEMU_OPTION_old_param
,
8606 QEMU_OPTION_startdate
,
8607 QEMU_OPTION_tb_size
,
8609 QEMU_OPTION_incoming
,
8611 QEMU_OPTION_kvm_shadow_memory
,
8612 QEMU_OPTION_mempath
,
8615 typedef struct QEMUOption
{
8621 const QEMUOption qemu_options
[] = {
8622 { "h", 0, QEMU_OPTION_h
},
8623 { "help", 0, QEMU_OPTION_h
},
8625 { "M", HAS_ARG
, QEMU_OPTION_M
},
8626 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8627 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8628 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8629 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8630 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8631 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8632 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8633 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8634 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8635 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8636 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8637 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8638 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8639 { "snapshot", 0, QEMU_OPTION_snapshot
},
8641 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8643 { "m", HAS_ARG
, QEMU_OPTION_m
},
8644 { "nographic", 0, QEMU_OPTION_nographic
},
8645 { "portrait", 0, QEMU_OPTION_portrait
},
8646 { "k", HAS_ARG
, QEMU_OPTION_k
},
8648 { "audio-help", 0, QEMU_OPTION_audio_help
},
8649 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8652 { "net", HAS_ARG
, QEMU_OPTION_net
},
8654 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8655 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8657 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8659 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8662 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8663 { "append", HAS_ARG
, QEMU_OPTION_append
},
8664 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8666 { "S", 0, QEMU_OPTION_S
},
8667 { "s", 0, QEMU_OPTION_s
},
8668 { "p", HAS_ARG
, QEMU_OPTION_p
},
8669 { "d", HAS_ARG
, QEMU_OPTION_d
},
8670 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8671 { "L", HAS_ARG
, QEMU_OPTION_L
},
8672 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8674 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8675 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8678 #ifndef NO_CPU_EMULATION
8679 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8681 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8682 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8684 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8685 { "g", 1, QEMU_OPTION_g
},
8687 { "localtime", 0, QEMU_OPTION_localtime
},
8688 { "std-vga", 0, QEMU_OPTION_std_vga
},
8689 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8690 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8691 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8692 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8693 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8694 { "incoming", 1, QEMU_OPTION_incoming
},
8695 { "full-screen", 0, QEMU_OPTION_full_screen
},
8697 { "no-frame", 0, QEMU_OPTION_no_frame
},
8698 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8699 { "no-quit", 0, QEMU_OPTION_no_quit
},
8701 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8702 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8703 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8704 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8705 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8706 #ifdef CONFIG_CURSES
8707 { "curses", 0, QEMU_OPTION_curses
},
8710 /* temporary options */
8711 { "usb", 0, QEMU_OPTION_usb
},
8712 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8713 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8714 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8715 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8716 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8717 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8718 { "daemonize", 0, QEMU_OPTION_daemonize
},
8719 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8720 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8721 { "semihosting", 0, QEMU_OPTION_semihosting
},
8723 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8724 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8725 { "name", HAS_ARG
, QEMU_OPTION_name
},
8726 #if defined(TARGET_SPARC)
8727 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8729 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8730 #if defined(TARGET_ARM)
8731 { "old-param", 0, QEMU_OPTION_old_param
},
8733 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8734 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8735 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8736 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8737 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8741 /* password input */
8743 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8748 if (!bdrv_is_encrypted(bs
))
8751 term_printf("%s is encrypted.\n", name
);
8752 for(i
= 0; i
< 3; i
++) {
8753 monitor_readline("Password: ", 1, password
, sizeof(password
));
8754 if (bdrv_set_key(bs
, password
) == 0)
8756 term_printf("invalid password\n");
8761 static BlockDriverState
*get_bdrv(int index
)
8763 if (index
> nb_drives
)
8765 return drives_table
[index
].bdrv
;
8768 static void read_passwords(void)
8770 BlockDriverState
*bs
;
8773 for(i
= 0; i
< 6; i
++) {
8776 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8781 struct soundhw soundhw
[] = {
8782 #ifdef HAS_AUDIO_CHOICE
8783 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8789 { .init_isa
= pcspk_audio_init
}
8794 "Creative Sound Blaster 16",
8797 { .init_isa
= SB16_init
}
8800 #ifdef CONFIG_CS4231A
8806 { .init_isa
= cs4231a_init
}
8814 "Yamaha YMF262 (OPL3)",
8816 "Yamaha YM3812 (OPL2)",
8820 { .init_isa
= Adlib_init
}
8827 "Gravis Ultrasound GF1",
8830 { .init_isa
= GUS_init
}
8837 "Intel 82801AA AC97 Audio",
8840 { .init_pci
= ac97_init
}
8846 "ENSONIQ AudioPCI ES1370",
8849 { .init_pci
= es1370_init
}
8853 { NULL
, NULL
, 0, 0, { NULL
} }
8856 static void select_soundhw (const char *optarg
)
8860 if (*optarg
== '?') {
8863 printf ("Valid sound card names (comma separated):\n");
8864 for (c
= soundhw
; c
->name
; ++c
) {
8865 printf ("%-11s %s\n", c
->name
, c
->descr
);
8867 printf ("\n-soundhw all will enable all of the above\n");
8868 exit (*optarg
!= '?');
8876 if (!strcmp (optarg
, "all")) {
8877 for (c
= soundhw
; c
->name
; ++c
) {
8885 e
= strchr (p
, ',');
8886 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8888 for (c
= soundhw
; c
->name
; ++c
) {
8889 if (!strncmp (c
->name
, p
, l
)) {
8898 "Unknown sound card name (too big to show)\n");
8901 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8906 p
+= l
+ (e
!= NULL
);
8910 goto show_valid_cards
;
8916 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8918 exit(STATUS_CONTROL_C_EXIT
);
8923 #define MAX_NET_CLIENTS 32
8925 static int saved_argc
;
8926 static char **saved_argv
;
8928 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8932 *opt_daemonize
= daemonize
;
8933 *opt_incoming
= incoming
;
8937 static int gethugepagesize(void)
8941 char *needle
= "Hugepagesize:";
8943 unsigned long hugepagesize
;
8945 fd
= open("/proc/meminfo", O_RDONLY
);
8951 ret
= read(fd
, buf
, sizeof(buf
));
8957 size
= strstr(buf
, needle
);
8960 size
+= strlen(needle
);
8961 hugepagesize
= strtol(size
, NULL
, 0);
8962 return hugepagesize
;
8965 void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
8971 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8974 hpagesize
= gethugepagesize() * 1024;
8978 fd
= mkstemp(filename
);
8987 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8990 * ftruncate is not supported by hugetlbfs in older
8991 * hosts, so don't bother checking for errors.
8992 * If anything goes wrong with it under other filesystems,
8995 ftruncate(fd
, memory
);
8997 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8998 if (area
== MAP_FAILED
) {
9008 void *qemu_alloc_physram(unsigned long memory
)
9011 unsigned long map_len
= memory
;
9015 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
9018 area
= qemu_vmalloc(memory
);
9020 if (kvm_setup_guest_memory(area
, map_len
))
9028 static void termsig_handler(int signal
)
9030 qemu_system_shutdown_request();
9033 static void termsig_setup(void)
9035 struct sigaction act
;
9037 memset(&act
, 0, sizeof(act
));
9038 act
.sa_handler
= termsig_handler
;
9039 sigaction(SIGINT
, &act
, NULL
);
9040 sigaction(SIGHUP
, &act
, NULL
);
9041 sigaction(SIGTERM
, &act
, NULL
);
9046 int main(int argc
, char **argv
)
9048 #ifdef CONFIG_GDBSTUB
9050 const char *gdbstub_port
;
9052 uint32_t boot_devices_bitmap
= 0;
9054 int snapshot
, linux_boot
, net_boot
;
9055 const char *initrd_filename
;
9056 const char *kernel_filename
, *kernel_cmdline
;
9057 const char *boot_devices
= "";
9058 DisplayState
*ds
= &display_state
;
9059 int cyls
, heads
, secs
, translation
;
9060 const char *net_clients
[MAX_NET_CLIENTS
];
9064 const char *r
, *optarg
;
9065 CharDriverState
*monitor_hd
;
9066 const char *monitor_device
;
9067 const char *serial_devices
[MAX_SERIAL_PORTS
];
9068 int serial_device_index
;
9069 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
9070 int parallel_device_index
;
9071 const char *loadvm
= NULL
;
9072 QEMUMachine
*machine
;
9073 const char *cpu_model
;
9074 const char *usb_devices
[MAX_USB_CMDLINE
];
9075 int usb_devices_index
;
9078 const char *pid_file
= NULL
;
9084 LIST_INIT (&vm_change_state_head
);
9087 struct sigaction act
;
9088 sigfillset(&act
.sa_mask
);
9090 act
.sa_handler
= SIG_IGN
;
9091 sigaction(SIGPIPE
, &act
, NULL
);
9094 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
9095 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9096 QEMU to run on a single CPU */
9101 h
= GetCurrentProcess();
9102 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
9103 for(i
= 0; i
< 32; i
++) {
9104 if (mask
& (1 << i
))
9109 SetProcessAffinityMask(h
, mask
);
9115 register_machines();
9116 machine
= first_machine
;
9118 initrd_filename
= NULL
;
9120 vga_ram_size
= VGA_RAM_SIZE
;
9121 #ifdef CONFIG_GDBSTUB
9123 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
9128 kernel_filename
= NULL
;
9129 kernel_cmdline
= "";
9130 cyls
= heads
= secs
= 0;
9131 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9132 monitor_device
= "vc";
9134 serial_devices
[0] = "vc:80Cx24C";
9135 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
9136 serial_devices
[i
] = NULL
;
9137 serial_device_index
= 0;
9139 parallel_devices
[0] = "vc:640x480";
9140 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
9141 parallel_devices
[i
] = NULL
;
9142 parallel_device_index
= 0;
9144 usb_devices_index
= 0;
9161 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
9163 const QEMUOption
*popt
;
9166 /* Treat --foo the same as -foo. */
9169 popt
= qemu_options
;
9172 fprintf(stderr
, "%s: invalid option -- '%s'\n",
9176 if (!strcmp(popt
->name
, r
+ 1))
9180 if (popt
->flags
& HAS_ARG
) {
9181 if (optind
>= argc
) {
9182 fprintf(stderr
, "%s: option '%s' requires an argument\n",
9186 optarg
= argv
[optind
++];
9191 switch(popt
->index
) {
9193 machine
= find_machine(optarg
);
9196 printf("Supported machines are:\n");
9197 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
9198 printf("%-10s %s%s\n",
9200 m
== first_machine
? " (default)" : "");
9202 exit(*optarg
!= '?');
9205 case QEMU_OPTION_cpu
:
9206 /* hw initialization will check this */
9207 if (*optarg
== '?') {
9208 /* XXX: implement xxx_cpu_list for targets that still miss it */
9209 #if defined(cpu_list)
9210 cpu_list(stdout
, &fprintf
);
9217 case QEMU_OPTION_initrd
:
9218 initrd_filename
= optarg
;
9220 case QEMU_OPTION_hda
:
9222 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
9224 hda_index
= drive_add(optarg
, HD_ALIAS
9225 ",cyls=%d,heads=%d,secs=%d%s",
9226 0, cyls
, heads
, secs
,
9227 translation
== BIOS_ATA_TRANSLATION_LBA
?
9229 translation
== BIOS_ATA_TRANSLATION_NONE
?
9230 ",trans=none" : "");
9232 case QEMU_OPTION_hdb
:
9233 case QEMU_OPTION_hdc
:
9234 case QEMU_OPTION_hdd
:
9235 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
9237 case QEMU_OPTION_drive
:
9238 drive_add(NULL
, "%s", optarg
);
9240 case QEMU_OPTION_mtdblock
:
9241 drive_add(optarg
, MTD_ALIAS
);
9243 case QEMU_OPTION_sd
:
9244 drive_add(optarg
, SD_ALIAS
);
9246 case QEMU_OPTION_pflash
:
9247 drive_add(optarg
, PFLASH_ALIAS
);
9249 case QEMU_OPTION_snapshot
:
9252 case QEMU_OPTION_hdachs
:
9256 cyls
= strtol(p
, (char **)&p
, 0);
9257 if (cyls
< 1 || cyls
> 16383)
9262 heads
= strtol(p
, (char **)&p
, 0);
9263 if (heads
< 1 || heads
> 16)
9268 secs
= strtol(p
, (char **)&p
, 0);
9269 if (secs
< 1 || secs
> 63)
9273 if (!strcmp(p
, "none"))
9274 translation
= BIOS_ATA_TRANSLATION_NONE
;
9275 else if (!strcmp(p
, "lba"))
9276 translation
= BIOS_ATA_TRANSLATION_LBA
;
9277 else if (!strcmp(p
, "auto"))
9278 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9281 } else if (*p
!= '\0') {
9283 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9286 if (hda_index
!= -1)
9287 snprintf(drives_opt
[hda_index
].opt
,
9288 sizeof(drives_opt
[hda_index
].opt
),
9289 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9290 0, cyls
, heads
, secs
,
9291 translation
== BIOS_ATA_TRANSLATION_LBA
?
9293 translation
== BIOS_ATA_TRANSLATION_NONE
?
9294 ",trans=none" : "");
9297 case QEMU_OPTION_nographic
:
9300 #ifdef CONFIG_CURSES
9301 case QEMU_OPTION_curses
:
9305 case QEMU_OPTION_portrait
:
9308 case QEMU_OPTION_kernel
:
9309 kernel_filename
= optarg
;
9311 case QEMU_OPTION_append
:
9312 kernel_cmdline
= optarg
;
9314 case QEMU_OPTION_cdrom
:
9315 drive_add(optarg
, CDROM_ALIAS
);
9317 case QEMU_OPTION_boot
:
9318 boot_devices
= optarg
;
9319 /* We just do some generic consistency checks */
9321 /* Could easily be extended to 64 devices if needed */
9324 boot_devices_bitmap
= 0;
9325 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9326 /* Allowed boot devices are:
9327 * a b : floppy disk drives
9328 * c ... f : IDE disk drives
9329 * g ... m : machine implementation dependant drives
9330 * n ... p : network devices
9331 * It's up to each machine implementation to check
9332 * if the given boot devices match the actual hardware
9333 * implementation and firmware features.
9335 if (*p
< 'a' || *p
> 'q') {
9336 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9339 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9341 "Boot device '%c' was given twice\n",*p
);
9344 boot_devices_bitmap
|= 1 << (*p
- 'a');
9348 case QEMU_OPTION_fda
:
9349 case QEMU_OPTION_fdb
:
9350 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9353 case QEMU_OPTION_no_fd_bootchk
:
9357 case QEMU_OPTION_net
:
9358 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9359 fprintf(stderr
, "qemu: too many network clients\n");
9362 net_clients
[nb_net_clients
] = optarg
;
9366 case QEMU_OPTION_tftp
:
9367 tftp_prefix
= optarg
;
9369 case QEMU_OPTION_bootp
:
9370 bootp_filename
= optarg
;
9373 case QEMU_OPTION_smb
:
9374 net_slirp_smb(optarg
);
9377 case QEMU_OPTION_redir
:
9378 net_slirp_redir(optarg
);
9382 case QEMU_OPTION_audio_help
:
9386 case QEMU_OPTION_soundhw
:
9387 select_soundhw (optarg
);
9393 case QEMU_OPTION_m
: {
9397 value
= strtoul(optarg
, &ptr
, 10);
9399 case 0: case 'M': case 'm':
9406 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9410 /* On 32-bit hosts, QEMU is limited by virtual address space */
9411 if (value
> (2047 << 20)
9413 && HOST_LONG_BITS
== 32
9416 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9419 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9420 fprintf(stderr
, "qemu: ram size too large\n");
9431 mask
= cpu_str_to_log_mask(optarg
);
9433 printf("Log items (comma separated):\n");
9434 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9435 printf("%-10s %s\n", item
->name
, item
->help
);
9442 #ifdef CONFIG_GDBSTUB
9447 gdbstub_port
= optarg
;
9453 case QEMU_OPTION_bios
:
9460 keyboard_layout
= optarg
;
9462 case QEMU_OPTION_localtime
:
9465 case QEMU_OPTION_cirrusvga
:
9466 cirrus_vga_enabled
= 1;
9469 case QEMU_OPTION_vmsvga
:
9470 cirrus_vga_enabled
= 0;
9473 case QEMU_OPTION_std_vga
:
9474 cirrus_vga_enabled
= 0;
9482 w
= strtol(p
, (char **)&p
, 10);
9485 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9491 h
= strtol(p
, (char **)&p
, 10);
9496 depth
= strtol(p
, (char **)&p
, 10);
9497 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9498 depth
!= 24 && depth
!= 32)
9500 } else if (*p
== '\0') {
9501 depth
= graphic_depth
;
9508 graphic_depth
= depth
;
9511 case QEMU_OPTION_echr
:
9514 term_escape_char
= strtol(optarg
, &r
, 0);
9516 printf("Bad argument to echr\n");
9519 case QEMU_OPTION_monitor
:
9520 monitor_device
= optarg
;
9522 case QEMU_OPTION_serial
:
9523 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9524 fprintf(stderr
, "qemu: too many serial ports\n");
9527 serial_devices
[serial_device_index
] = optarg
;
9528 serial_device_index
++;
9530 case QEMU_OPTION_parallel
:
9531 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9532 fprintf(stderr
, "qemu: too many parallel ports\n");
9535 parallel_devices
[parallel_device_index
] = optarg
;
9536 parallel_device_index
++;
9538 case QEMU_OPTION_loadvm
:
9541 case QEMU_OPTION_incoming
:
9544 case QEMU_OPTION_full_screen
:
9548 case QEMU_OPTION_no_frame
:
9551 case QEMU_OPTION_alt_grab
:
9554 case QEMU_OPTION_no_quit
:
9558 case QEMU_OPTION_pidfile
:
9562 case QEMU_OPTION_win2k_hack
:
9563 win2k_install_hack
= 1;
9567 case QEMU_OPTION_no_kqemu
:
9570 case QEMU_OPTION_kernel_kqemu
:
9575 case QEMU_OPTION_no_kvm
:
9578 case QEMU_OPTION_no_kvm_irqchip
: {
9579 extern int kvm_irqchip
, kvm_pit
;
9584 case QEMU_OPTION_no_kvm_pit
: {
9590 case QEMU_OPTION_usb
:
9593 case QEMU_OPTION_usbdevice
:
9595 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9596 fprintf(stderr
, "Too many USB devices\n");
9599 usb_devices
[usb_devices_index
] = optarg
;
9600 usb_devices_index
++;
9602 case QEMU_OPTION_smp
:
9603 smp_cpus
= atoi(optarg
);
9604 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9605 fprintf(stderr
, "Invalid number of CPUs\n");
9609 case QEMU_OPTION_vnc
:
9610 vnc_display
= optarg
;
9612 case QEMU_OPTION_no_acpi
:
9615 case QEMU_OPTION_no_reboot
:
9618 case QEMU_OPTION_no_shutdown
:
9621 case QEMU_OPTION_show_cursor
:
9624 case QEMU_OPTION_daemonize
:
9627 case QEMU_OPTION_option_rom
:
9628 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9629 fprintf(stderr
, "Too many option ROMs\n");
9632 option_rom
[nb_option_roms
] = optarg
;
9635 case QEMU_OPTION_semihosting
:
9636 semihosting_enabled
= 1;
9638 case QEMU_OPTION_tdf
:
9641 case QEMU_OPTION_kvm_shadow_memory
:
9642 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9644 case QEMU_OPTION_mempath
:
9647 case QEMU_OPTION_name
:
9651 case QEMU_OPTION_prom_env
:
9652 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9653 fprintf(stderr
, "Too many prom variables\n");
9656 prom_envs
[nb_prom_envs
] = optarg
;
9660 case QEMU_OPTION_cpu_vendor
:
9661 cpu_vendor_string
= optarg
;
9664 case QEMU_OPTION_old_param
:
9668 case QEMU_OPTION_clock
:
9669 configure_alarms(optarg
);
9671 case QEMU_OPTION_startdate
:
9674 time_t rtc_start_date
;
9675 if (!strcmp(optarg
, "now")) {
9676 rtc_date_offset
= -1;
9678 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9686 } else if (sscanf(optarg
, "%d-%d-%d",
9689 &tm
.tm_mday
) == 3) {
9698 rtc_start_date
= mktimegm(&tm
);
9699 if (rtc_start_date
== -1) {
9701 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9702 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9705 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9709 case QEMU_OPTION_tb_size
:
9710 tb_size
= strtol(optarg
, NULL
, 0);
9714 case QEMU_OPTION_icount
:
9716 if (strcmp(optarg
, "auto") == 0) {
9717 icount_time_shift
= -1;
9719 icount_time_shift
= strtol(optarg
, NULL
, 0);
9727 if (serial_device_index
== 0)
9728 serial_devices
[0] = "stdio";
9729 if (parallel_device_index
== 0)
9730 parallel_devices
[0] = "null";
9731 if (strncmp(monitor_device
, "vc", 2) == 0)
9732 monitor_device
= "stdio";
9739 if (pipe(fds
) == -1)
9750 len
= read(fds
[0], &status
, 1);
9751 if (len
== -1 && (errno
== EINTR
))
9756 else if (status
== 1) {
9757 fprintf(stderr
, "Could not acquire pidfile\n");
9774 signal(SIGTSTP
, SIG_IGN
);
9775 signal(SIGTTOU
, SIG_IGN
);
9776 signal(SIGTTIN
, SIG_IGN
);
9781 if (kvm_enabled()) {
9782 if (kvm_qemu_init() < 0) {
9783 extern int kvm_allowed
;
9784 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9785 #ifdef NO_CPU_EMULATION
9786 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9794 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9797 write(fds
[1], &status
, 1);
9799 fprintf(stderr
, "Could not acquire pid file\n");
9807 linux_boot
= (kernel_filename
!= NULL
);
9808 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9810 if (!linux_boot
&& net_boot
== 0 &&
9811 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9814 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9815 fprintf(stderr
, "-append only allowed with -kernel option\n");
9819 if (!linux_boot
&& initrd_filename
!= NULL
) {
9820 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9824 /* boot to floppy or the default cd if no hard disk defined yet */
9825 if (!boot_devices
[0]) {
9826 boot_devices
= "cad";
9828 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9833 if (use_icount
&& icount_time_shift
< 0) {
9835 /* 125MIPS seems a reasonable initial guess at the guest speed.
9836 It will be corrected fairly quickly anyway. */
9837 icount_time_shift
= 3;
9838 init_icount_adjust();
9845 /* init network clients */
9846 if (nb_net_clients
== 0) {
9847 /* if no clients, we use a default config */
9848 net_clients
[nb_net_clients
++] = "nic";
9850 net_clients
[nb_net_clients
++] = "user";
9854 for(i
= 0;i
< nb_net_clients
; i
++) {
9855 if (net_client_parse(net_clients
[i
]) < 0)
9858 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9859 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9861 if (vlan
->nb_guest_devs
== 0)
9862 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9863 if (vlan
->nb_host_devs
== 0)
9865 "Warning: vlan %d is not connected to host network\n",
9870 /* XXX: this should be moved in the PC machine instantiation code */
9871 if (net_boot
!= 0) {
9873 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9874 const char *model
= nd_table
[i
].model
;
9876 if (net_boot
& (1 << i
)) {
9879 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9880 if (get_image_size(buf
) > 0) {
9881 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9882 fprintf(stderr
, "Too many option ROMs\n");
9885 option_rom
[nb_option_roms
] = strdup(buf
);
9892 fprintf(stderr
, "No valid PXE rom found for network device\n");
9898 /* init the memory */
9899 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9901 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9903 if (ram_size
< phys_ram_size
) {
9904 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9905 machine
->name
, (unsigned long long) phys_ram_size
);
9909 phys_ram_size
= ram_size
;
9911 ram_size
= phys_ram_size
;
9914 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9916 phys_ram_size
+= ram_size
;
9919 /* Initialize kvm */
9920 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9921 #define KVM_EXTRA_PAGES 3
9923 #define KVM_EXTRA_PAGES 0
9925 if (kvm_enabled()) {
9926 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9927 if (kvm_qemu_create_context() < 0) {
9928 fprintf(stderr
, "Could not create KVM context\n");
9933 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9934 if (!phys_ram_base
) {
9935 fprintf(stderr
, "Could not allocate physical memory\n");
9939 /* init the dynamic translator */
9940 cpu_exec_init_all(tb_size
* 1024 * 1024);
9944 /* we always create the cdrom drive, even if no disk is there */
9946 if (nb_drives_opt
< MAX_DRIVES
)
9947 drive_add(NULL
, CDROM_ALIAS
);
9949 /* we always create at least one floppy */
9951 if (nb_drives_opt
< MAX_DRIVES
)
9952 drive_add(NULL
, FD_ALIAS
, 0);
9954 /* we always create one sd slot, even if no card is in it */
9956 if (nb_drives_opt
< MAX_DRIVES
)
9957 drive_add(NULL
, SD_ALIAS
);
9959 /* open the virtual block devices
9960 * note that migration with device
9961 * hot add/remove is broken.
9963 for(i
= 0; i
< nb_drives_opt
; i
++)
9964 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9967 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9968 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9971 memset(&display_state
, 0, sizeof(display_state
));
9974 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9977 /* nearly nothing to do */
9978 dumb_display_init(ds
);
9979 } else if (vnc_display
!= NULL
) {
9980 vnc_display_init(ds
);
9981 if (vnc_display_open(ds
, vnc_display
) < 0)
9984 #if defined(CONFIG_CURSES)
9986 curses_display_init(ds
, full_screen
);
9990 #if defined(CONFIG_SDL)
9991 sdl_display_init(ds
, full_screen
, no_frame
);
9992 #elif defined(CONFIG_COCOA)
9993 cocoa_display_init(ds
, full_screen
);
9995 dumb_display_init(ds
);
10000 /* must be after terminal init, SDL library changes signal handlers */
10004 /* Maintain compatibility with multiple stdio monitors */
10005 if (!strcmp(monitor_device
,"stdio")) {
10006 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10007 const char *devname
= serial_devices
[i
];
10008 if (devname
&& !strcmp(devname
,"mon:stdio")) {
10009 monitor_device
= NULL
;
10011 } else if (devname
&& !strcmp(devname
,"stdio")) {
10012 monitor_device
= NULL
;
10013 serial_devices
[i
] = "mon:stdio";
10018 if (monitor_device
) {
10019 monitor_hd
= qemu_chr_open(monitor_device
);
10021 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
10024 monitor_init(monitor_hd
, !nographic
);
10027 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10028 const char *devname
= serial_devices
[i
];
10029 if (devname
&& strcmp(devname
, "none")) {
10030 serial_hds
[i
] = qemu_chr_open(devname
);
10031 if (!serial_hds
[i
]) {
10032 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
10036 if (strstart(devname
, "vc", 0))
10037 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
10041 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
10042 const char *devname
= parallel_devices
[i
];
10043 if (devname
&& strcmp(devname
, "none")) {
10044 parallel_hds
[i
] = qemu_chr_open(devname
);
10045 if (!parallel_hds
[i
]) {
10046 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
10050 if (strstart(devname
, "vc", 0))
10051 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
10058 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
10059 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
10061 current_machine
= machine
;
10063 /* init USB devices */
10065 for(i
= 0; i
< usb_devices_index
; i
++) {
10066 if (usb_device_add(usb_devices
[i
]) < 0) {
10067 fprintf(stderr
, "Warning: could not add USB device %s\n",
10073 if (display_state
.dpy_refresh
) {
10074 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
10075 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
10078 #ifdef CONFIG_GDBSTUB
10080 /* XXX: use standard host:port notation and modify options
10082 if (gdbserver_start(gdbstub_port
) < 0) {
10083 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
10096 rc
= migrate_incoming(incoming
);
10098 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
10104 /* XXX: simplify init */
10112 uint8_t status
= 0;
10117 len
= write(fds
[1], &status
, 1);
10118 if (len
== -1 && (errno
== EINTR
))
10125 TFR(fd
= open("/dev/null", O_RDWR
));
10139 #if !defined(_WIN32)
10140 /* close network clients */
10141 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
10142 VLANClientState
*vc
;
10144 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
10145 if (vc
->fd_read
== tap_receive
) {
10147 TAPState
*s
= vc
->opaque
;
10149 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
10151 launch_script(s
->down_script
, ifname
, s
->fd
);
10153 #if defined(CONFIG_VDE)
10154 if (vc
->fd_read
== vde_from_qemu
) {
10155 VDEState
*s
= vc
->opaque
;