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 uint8_t qemu_uuid
[16];
270 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
272 /* KVM runs the main loop in a separate thread. If we update one of the lists
273 * that are polled before or after select(), we need to make sure to break out
274 * of the select() to ensure the new item is serviced.
276 static void main_loop_break(void)
279 qemu_kvm_notify_work();
282 /***********************************************************/
283 /* x86 ISA bus support */
285 target_phys_addr_t isa_mem_base
= 0;
288 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
289 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
291 static uint32_t ioport_read(int index
, uint32_t address
)
293 static IOPortReadFunc
*default_func
[3] = {
294 default_ioport_readb
,
295 default_ioport_readw
,
298 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
300 func
= default_func
[index
];
301 return func(ioport_opaque
[address
], address
);
304 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
306 static IOPortWriteFunc
*default_func
[3] = {
307 default_ioport_writeb
,
308 default_ioport_writew
,
309 default_ioport_writel
311 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
313 func
= default_func
[index
];
314 func(ioport_opaque
[address
], address
, data
);
317 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
319 #ifdef DEBUG_UNUSED_IOPORT
320 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
325 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
327 #ifdef DEBUG_UNUSED_IOPORT
328 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
332 /* default is to make two byte accesses */
333 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
336 data
= ioport_read(0, address
);
337 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
338 data
|= ioport_read(0, address
) << 8;
342 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
344 ioport_write(0, address
, data
& 0xff);
345 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
346 ioport_write(0, address
, (data
>> 8) & 0xff);
349 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
351 #ifdef DEBUG_UNUSED_IOPORT
352 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
357 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
359 #ifdef DEBUG_UNUSED_IOPORT
360 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
364 /* size is the word size in byte */
365 int register_ioport_read(int start
, int length
, int size
,
366 IOPortReadFunc
*func
, void *opaque
)
372 } else if (size
== 2) {
374 } else if (size
== 4) {
377 hw_error("register_ioport_read: invalid size");
380 for(i
= start
; i
< start
+ length
; i
+= size
) {
381 ioport_read_table
[bsize
][i
] = func
;
382 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
383 hw_error("register_ioport_read: invalid opaque");
384 ioport_opaque
[i
] = opaque
;
389 /* size is the word size in byte */
390 int register_ioport_write(int start
, int length
, int size
,
391 IOPortWriteFunc
*func
, void *opaque
)
397 } else if (size
== 2) {
399 } else if (size
== 4) {
402 hw_error("register_ioport_write: invalid size");
405 for(i
= start
; i
< start
+ length
; i
+= size
) {
406 ioport_write_table
[bsize
][i
] = func
;
407 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
408 hw_error("register_ioport_write: invalid opaque");
409 ioport_opaque
[i
] = opaque
;
414 void isa_unassign_ioport(int start
, int length
)
418 for(i
= start
; i
< start
+ length
; i
++) {
419 ioport_read_table
[0][i
] = default_ioport_readb
;
420 ioport_read_table
[1][i
] = default_ioport_readw
;
421 ioport_read_table
[2][i
] = default_ioport_readl
;
423 ioport_write_table
[0][i
] = default_ioport_writeb
;
424 ioport_write_table
[1][i
] = default_ioport_writew
;
425 ioport_write_table
[2][i
] = default_ioport_writel
;
427 ioport_opaque
[i
] = NULL
;
431 /***********************************************************/
433 void cpu_outb(CPUState
*env
, int addr
, int val
)
436 if (loglevel
& CPU_LOG_IOPORT
)
437 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
439 ioport_write(0, addr
, val
);
442 env
->last_io_time
= cpu_get_time_fast();
446 void cpu_outw(CPUState
*env
, int addr
, int val
)
449 if (loglevel
& CPU_LOG_IOPORT
)
450 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
452 ioport_write(1, addr
, val
);
455 env
->last_io_time
= cpu_get_time_fast();
459 void cpu_outl(CPUState
*env
, int addr
, int val
)
462 if (loglevel
& CPU_LOG_IOPORT
)
463 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
465 ioport_write(2, addr
, val
);
468 env
->last_io_time
= cpu_get_time_fast();
472 int cpu_inb(CPUState
*env
, int addr
)
475 val
= ioport_read(0, addr
);
477 if (loglevel
& CPU_LOG_IOPORT
)
478 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
482 env
->last_io_time
= cpu_get_time_fast();
487 int cpu_inw(CPUState
*env
, int addr
)
490 val
= ioport_read(1, addr
);
492 if (loglevel
& CPU_LOG_IOPORT
)
493 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
497 env
->last_io_time
= cpu_get_time_fast();
502 int cpu_inl(CPUState
*env
, int addr
)
505 val
= ioport_read(2, addr
);
507 if (loglevel
& CPU_LOG_IOPORT
)
508 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
512 env
->last_io_time
= cpu_get_time_fast();
517 /***********************************************************/
518 void hw_error(const char *fmt
, ...)
524 fprintf(stderr
, "qemu: hardware error: ");
525 vfprintf(stderr
, fmt
, ap
);
526 fprintf(stderr
, "\n");
527 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
528 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
530 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
532 cpu_dump_state(env
, stderr
, fprintf
, 0);
542 static QEMUBalloonEvent
*qemu_balloon_event
;
543 void *qemu_balloon_event_opaque
;
545 void qemu_add_balloon_handler(QEMUBalloonEvent
*func
, void *opaque
)
547 qemu_balloon_event
= func
;
548 qemu_balloon_event_opaque
= opaque
;
551 void qemu_balloon(ram_addr_t target
)
553 if (qemu_balloon_event
)
554 qemu_balloon_event(qemu_balloon_event_opaque
, target
);
557 ram_addr_t
qemu_balloon_status(void)
559 if (qemu_balloon_event
)
560 return qemu_balloon_event(qemu_balloon_event_opaque
, 0);
564 /***********************************************************/
567 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
568 static void *qemu_put_kbd_event_opaque
;
569 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
570 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
572 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
574 qemu_put_kbd_event_opaque
= opaque
;
575 qemu_put_kbd_event
= func
;
578 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
579 void *opaque
, int absolute
,
582 QEMUPutMouseEntry
*s
, *cursor
;
584 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
588 s
->qemu_put_mouse_event
= func
;
589 s
->qemu_put_mouse_event_opaque
= opaque
;
590 s
->qemu_put_mouse_event_absolute
= absolute
;
591 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
594 if (!qemu_put_mouse_event_head
) {
595 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
599 cursor
= qemu_put_mouse_event_head
;
600 while (cursor
->next
!= NULL
)
601 cursor
= cursor
->next
;
604 qemu_put_mouse_event_current
= s
;
609 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
611 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
613 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
616 cursor
= qemu_put_mouse_event_head
;
617 while (cursor
!= NULL
&& cursor
!= entry
) {
619 cursor
= cursor
->next
;
622 if (cursor
== NULL
) // does not exist or list empty
624 else if (prev
== NULL
) { // entry is head
625 qemu_put_mouse_event_head
= cursor
->next
;
626 if (qemu_put_mouse_event_current
== entry
)
627 qemu_put_mouse_event_current
= cursor
->next
;
628 qemu_free(entry
->qemu_put_mouse_event_name
);
633 prev
->next
= entry
->next
;
635 if (qemu_put_mouse_event_current
== entry
)
636 qemu_put_mouse_event_current
= prev
;
638 qemu_free(entry
->qemu_put_mouse_event_name
);
642 void kbd_put_keycode(int keycode
)
644 if (qemu_put_kbd_event
) {
645 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
649 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
651 QEMUPutMouseEvent
*mouse_event
;
652 void *mouse_event_opaque
;
655 if (!qemu_put_mouse_event_current
) {
660 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
662 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
665 if (graphic_rotate
) {
666 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
669 width
= graphic_width
- 1;
670 mouse_event(mouse_event_opaque
,
671 width
- dy
, dx
, dz
, buttons_state
);
673 mouse_event(mouse_event_opaque
,
674 dx
, dy
, dz
, buttons_state
);
678 int kbd_mouse_is_absolute(void)
680 if (!qemu_put_mouse_event_current
)
683 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
686 void do_info_mice(void)
688 QEMUPutMouseEntry
*cursor
;
691 if (!qemu_put_mouse_event_head
) {
692 term_printf("No mouse devices connected\n");
696 term_printf("Mouse devices available:\n");
697 cursor
= qemu_put_mouse_event_head
;
698 while (cursor
!= NULL
) {
699 term_printf("%c Mouse #%d: %s\n",
700 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
701 index
, cursor
->qemu_put_mouse_event_name
);
703 cursor
= cursor
->next
;
707 void do_mouse_set(int index
)
709 QEMUPutMouseEntry
*cursor
;
712 if (!qemu_put_mouse_event_head
) {
713 term_printf("No mouse devices connected\n");
717 cursor
= qemu_put_mouse_event_head
;
718 while (cursor
!= NULL
&& index
!= i
) {
720 cursor
= cursor
->next
;
724 qemu_put_mouse_event_current
= cursor
;
726 term_printf("Mouse at given index not found\n");
729 /* compute with 96 bit intermediate result: (a*b)/c */
730 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
735 #ifdef WORDS_BIGENDIAN
745 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
746 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
749 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
753 /***********************************************************/
754 /* real time host monotonic timer */
756 #define QEMU_TIMER_BASE 1000000000LL
760 static int64_t clock_freq
;
762 static void init_get_clock(void)
766 ret
= QueryPerformanceFrequency(&freq
);
768 fprintf(stderr
, "Could not calibrate ticks\n");
771 clock_freq
= freq
.QuadPart
;
774 static int64_t get_clock(void)
777 QueryPerformanceCounter(&ti
);
778 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
783 static int use_rt_clock
;
785 static void init_get_clock(void)
788 #if defined(__linux__)
791 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
798 static int64_t get_clock(void)
800 #if defined(__linux__)
803 clock_gettime(CLOCK_MONOTONIC
, &ts
);
804 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
808 /* XXX: using gettimeofday leads to problems if the date
809 changes, so it should be avoided. */
811 gettimeofday(&tv
, NULL
);
812 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
817 /* Return the virtual CPU time, based on the instruction counter. */
818 static int64_t cpu_get_icount(void)
821 CPUState
*env
= cpu_single_env
;;
822 icount
= qemu_icount
;
825 fprintf(stderr
, "Bad clock read\n");
826 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
828 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
831 /***********************************************************/
832 /* guest cycle counter */
834 static int64_t cpu_ticks_prev
;
835 static int64_t cpu_ticks_offset
;
836 static int64_t cpu_clock_offset
;
837 static int cpu_ticks_enabled
;
839 /* return the host CPU cycle counter and handle stop/restart */
840 int64_t cpu_get_ticks(void)
843 return cpu_get_icount();
845 if (!cpu_ticks_enabled
) {
846 return cpu_ticks_offset
;
849 ticks
= cpu_get_real_ticks();
850 if (cpu_ticks_prev
> ticks
) {
851 /* Note: non increasing ticks may happen if the host uses
853 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
855 cpu_ticks_prev
= ticks
;
856 return ticks
+ cpu_ticks_offset
;
860 /* return the host CPU monotonic timer and handle stop/restart */
861 static int64_t cpu_get_clock(void)
864 if (!cpu_ticks_enabled
) {
865 return cpu_clock_offset
;
868 return ti
+ cpu_clock_offset
;
872 /* enable cpu_get_ticks() */
873 void cpu_enable_ticks(void)
875 if (!cpu_ticks_enabled
) {
876 cpu_ticks_offset
-= cpu_get_real_ticks();
877 cpu_clock_offset
-= get_clock();
878 cpu_ticks_enabled
= 1;
882 /* disable cpu_get_ticks() : the clock is stopped. You must not call
883 cpu_get_ticks() after that. */
884 void cpu_disable_ticks(void)
886 if (cpu_ticks_enabled
) {
887 cpu_ticks_offset
= cpu_get_ticks();
888 cpu_clock_offset
= cpu_get_clock();
889 cpu_ticks_enabled
= 0;
893 /***********************************************************/
896 #define QEMU_TIMER_REALTIME 0
897 #define QEMU_TIMER_VIRTUAL 1
901 /* XXX: add frequency */
909 struct QEMUTimer
*next
;
912 struct qemu_alarm_timer
{
916 int (*start
)(struct qemu_alarm_timer
*t
);
917 void (*stop
)(struct qemu_alarm_timer
*t
);
918 void (*rearm
)(struct qemu_alarm_timer
*t
);
922 #define ALARM_FLAG_DYNTICKS 0x1
923 #define ALARM_FLAG_EXPIRED 0x2
925 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
927 return t
->flags
& ALARM_FLAG_DYNTICKS
;
930 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
932 if (!alarm_has_dynticks(t
))
938 /* TODO: MIN_TIMER_REARM_US should be optimized */
939 #define MIN_TIMER_REARM_US 250
941 static struct qemu_alarm_timer
*alarm_timer
;
945 struct qemu_alarm_win32
{
949 } alarm_win32_data
= {0, NULL
, -1};
951 static int win32_start_timer(struct qemu_alarm_timer
*t
);
952 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
953 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
957 static int unix_start_timer(struct qemu_alarm_timer
*t
);
958 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
962 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
963 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
964 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
966 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
967 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
969 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
970 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
972 #endif /* __linux__ */
976 /* Correlation between real and virtual time is always going to be
977 fairly approximate, so ignore small variation.
978 When the guest is idle real and virtual time will be aligned in
980 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
982 static void icount_adjust(void)
987 static int64_t last_delta
;
988 /* If the VM is not running, then do nothing. */
992 cur_time
= cpu_get_clock();
993 cur_icount
= qemu_get_clock(vm_clock
);
994 delta
= cur_icount
- cur_time
;
995 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
997 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
998 && icount_time_shift
> 0) {
999 /* The guest is getting too far ahead. Slow time down. */
1000 icount_time_shift
--;
1003 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
1004 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
1005 /* The guest is getting too far behind. Speed time up. */
1006 icount_time_shift
++;
1009 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
1012 static void icount_adjust_rt(void * opaque
)
1014 qemu_mod_timer(icount_rt_timer
,
1015 qemu_get_clock(rt_clock
) + 1000);
1019 static void icount_adjust_vm(void * opaque
)
1021 qemu_mod_timer(icount_vm_timer
,
1022 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1026 static void init_icount_adjust(void)
1028 /* Have both realtime and virtual time triggers for speed adjustment.
1029 The realtime trigger catches emulated time passing too slowly,
1030 the virtual time trigger catches emulated time passing too fast.
1031 Realtime triggers occur even when idle, so use them less frequently
1032 than VM triggers. */
1033 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1034 qemu_mod_timer(icount_rt_timer
,
1035 qemu_get_clock(rt_clock
) + 1000);
1036 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1037 qemu_mod_timer(icount_vm_timer
,
1038 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1041 static struct qemu_alarm_timer alarm_timers
[] = {
1044 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1045 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1046 /* HPET - if available - is preferred */
1047 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1048 /* ...otherwise try RTC */
1049 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1051 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1053 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1054 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1055 {"win32", 0, win32_start_timer
,
1056 win32_stop_timer
, NULL
, &alarm_win32_data
},
1061 static void show_available_alarms(void)
1065 printf("Available alarm timers, in order of precedence:\n");
1066 for (i
= 0; alarm_timers
[i
].name
; i
++)
1067 printf("%s\n", alarm_timers
[i
].name
);
1070 static void configure_alarms(char const *opt
)
1074 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1077 struct qemu_alarm_timer tmp
;
1079 if (!strcmp(opt
, "?")) {
1080 show_available_alarms();
1086 /* Reorder the array */
1087 name
= strtok(arg
, ",");
1089 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1090 if (!strcmp(alarm_timers
[i
].name
, name
))
1095 fprintf(stderr
, "Unknown clock %s\n", name
);
1104 tmp
= alarm_timers
[i
];
1105 alarm_timers
[i
] = alarm_timers
[cur
];
1106 alarm_timers
[cur
] = tmp
;
1110 name
= strtok(NULL
, ",");
1116 /* Disable remaining timers */
1117 for (i
= cur
; i
< count
; i
++)
1118 alarm_timers
[i
].name
= NULL
;
1120 show_available_alarms();
1125 QEMUClock
*rt_clock
;
1126 QEMUClock
*vm_clock
;
1128 static QEMUTimer
*active_timers
[2];
1130 static QEMUClock
*qemu_new_clock(int type
)
1133 clock
= qemu_mallocz(sizeof(QEMUClock
));
1140 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1144 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1147 ts
->opaque
= opaque
;
1151 void qemu_free_timer(QEMUTimer
*ts
)
1156 /* stop a timer, but do not dealloc it */
1157 void qemu_del_timer(QEMUTimer
*ts
)
1161 /* NOTE: this code must be signal safe because
1162 qemu_timer_expired() can be called from a signal. */
1163 pt
= &active_timers
[ts
->clock
->type
];
1176 /* modify the current timer so that it will be fired when current_time
1177 >= expire_time. The corresponding callback will be called. */
1178 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1184 /* add the timer in the sorted list */
1185 /* NOTE: this code must be signal safe because
1186 qemu_timer_expired() can be called from a signal. */
1187 pt
= &active_timers
[ts
->clock
->type
];
1192 if (t
->expire_time
> expire_time
)
1196 ts
->expire_time
= expire_time
;
1200 /* Rearm if necessary */
1201 if (pt
== &active_timers
[ts
->clock
->type
]) {
1202 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1203 qemu_rearm_alarm_timer(alarm_timer
);
1205 /* Interrupt execution to force deadline recalculation. */
1206 if (use_icount
&& cpu_single_env
) {
1207 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1212 int qemu_timer_pending(QEMUTimer
*ts
)
1215 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1222 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1226 return (timer_head
->expire_time
<= current_time
);
1229 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1235 if (!ts
|| ts
->expire_time
> current_time
)
1237 /* remove timer from the list before calling the callback */
1238 *ptimer_head
= ts
->next
;
1241 /* run the callback (the timer list can be modified) */
1246 int64_t qemu_get_clock(QEMUClock
*clock
)
1248 switch(clock
->type
) {
1249 case QEMU_TIMER_REALTIME
:
1250 return get_clock() / 1000000;
1252 case QEMU_TIMER_VIRTUAL
:
1254 return cpu_get_icount();
1256 return cpu_get_clock();
1261 static void init_timers(void)
1264 ticks_per_sec
= QEMU_TIMER_BASE
;
1265 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1266 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1270 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1272 uint64_t expire_time
;
1274 if (qemu_timer_pending(ts
)) {
1275 expire_time
= ts
->expire_time
;
1279 qemu_put_be64(f
, expire_time
);
1282 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1284 uint64_t expire_time
;
1286 expire_time
= qemu_get_be64(f
);
1287 if (expire_time
!= -1) {
1288 qemu_mod_timer(ts
, expire_time
);
1294 static void timer_save(QEMUFile
*f
, void *opaque
)
1296 if (cpu_ticks_enabled
) {
1297 hw_error("cannot save state if virtual timers are running");
1299 qemu_put_be64(f
, cpu_ticks_offset
);
1300 qemu_put_be64(f
, ticks_per_sec
);
1301 qemu_put_be64(f
, cpu_clock_offset
);
1304 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1306 if (version_id
!= 1 && version_id
!= 2)
1308 if (cpu_ticks_enabled
) {
1311 cpu_ticks_offset
=qemu_get_be64(f
);
1312 ticks_per_sec
=qemu_get_be64(f
);
1313 if (version_id
== 2) {
1314 cpu_clock_offset
=qemu_get_be64(f
);
1320 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1321 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1323 static void host_alarm_handler(int host_signum
)
1327 #define DISP_FREQ 1000
1329 static int64_t delta_min
= INT64_MAX
;
1330 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1332 ti
= qemu_get_clock(vm_clock
);
1333 if (last_clock
!= 0) {
1334 delta
= ti
- last_clock
;
1335 if (delta
< delta_min
)
1337 if (delta
> delta_max
)
1340 if (++count
== DISP_FREQ
) {
1341 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1342 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1343 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1344 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1345 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1347 delta_min
= INT64_MAX
;
1356 alarm_has_dynticks(alarm_timer
) ||
1358 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1359 qemu_get_clock(vm_clock
))) ||
1360 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1361 qemu_get_clock(rt_clock
))) {
1363 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1364 SetEvent(data
->host_alarm
);
1366 CPUState
*env
= next_cpu
;
1368 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1371 /* stop the currently executing cpu because a timer occured */
1372 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1374 if (env
->kqemu_enabled
) {
1375 kqemu_cpu_interrupt(env
);
1383 static int64_t qemu_next_deadline(void)
1387 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1388 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1389 qemu_get_clock(vm_clock
);
1391 /* To avoid problems with overflow limit this to 2^32. */
1401 #if defined(__linux__) || defined(_WIN32)
1402 static uint64_t qemu_next_deadline_dyntick(void)
1410 delta
= (qemu_next_deadline() + 999) / 1000;
1412 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1413 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1414 qemu_get_clock(rt_clock
))*1000;
1415 if (rtdelta
< delta
)
1419 if (delta
< MIN_TIMER_REARM_US
)
1420 delta
= MIN_TIMER_REARM_US
;
1428 #if defined(__linux__)
1430 #define RTC_FREQ 1024
1432 static void enable_sigio_timer(int fd
)
1434 struct sigaction act
;
1437 sigfillset(&act
.sa_mask
);
1439 act
.sa_handler
= host_alarm_handler
;
1441 sigaction(SIGIO
, &act
, NULL
);
1442 fcntl(fd
, F_SETFL
, O_ASYNC
);
1443 fcntl(fd
, F_SETOWN
, getpid());
1446 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1448 struct hpet_info info
;
1451 fd
= open("/dev/hpet", O_RDONLY
);
1456 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1458 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1459 "error, but for better emulation accuracy type:\n"
1460 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1464 /* Check capabilities */
1465 r
= ioctl(fd
, HPET_INFO
, &info
);
1469 /* Enable periodic mode */
1470 r
= ioctl(fd
, HPET_EPI
, 0);
1471 if (info
.hi_flags
&& (r
< 0))
1474 /* Enable interrupt */
1475 r
= ioctl(fd
, HPET_IE_ON
, 0);
1479 enable_sigio_timer(fd
);
1480 t
->priv
= (void *)(long)fd
;
1488 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1490 int fd
= (long)t
->priv
;
1495 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1498 unsigned long current_rtc_freq
= 0;
1500 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1503 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1504 if (current_rtc_freq
!= RTC_FREQ
&&
1505 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1506 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1507 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1508 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1511 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1517 enable_sigio_timer(rtc_fd
);
1519 t
->priv
= (void *)(long)rtc_fd
;
1524 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1526 int rtc_fd
= (long)t
->priv
;
1531 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1535 struct sigaction act
;
1537 sigfillset(&act
.sa_mask
);
1539 act
.sa_handler
= host_alarm_handler
;
1541 sigaction(SIGALRM
, &act
, NULL
);
1543 ev
.sigev_value
.sival_int
= 0;
1544 ev
.sigev_notify
= SIGEV_SIGNAL
;
1545 ev
.sigev_signo
= SIGALRM
;
1547 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1548 perror("timer_create");
1550 /* disable dynticks */
1551 fprintf(stderr
, "Dynamic Ticks disabled\n");
1556 t
->priv
= (void *)host_timer
;
1561 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1563 timer_t host_timer
= (timer_t
)t
->priv
;
1565 timer_delete(host_timer
);
1568 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1570 timer_t host_timer
= (timer_t
)t
->priv
;
1571 struct itimerspec timeout
;
1572 int64_t nearest_delta_us
= INT64_MAX
;
1575 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1576 !active_timers
[QEMU_TIMER_VIRTUAL
])
1579 nearest_delta_us
= qemu_next_deadline_dyntick();
1581 /* check whether a timer is already running */
1582 if (timer_gettime(host_timer
, &timeout
)) {
1584 fprintf(stderr
, "Internal timer error: aborting\n");
1587 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1588 if (current_us
&& current_us
<= nearest_delta_us
)
1591 timeout
.it_interval
.tv_sec
= 0;
1592 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1593 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1594 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1595 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1597 fprintf(stderr
, "Internal timer error: aborting\n");
1602 #endif /* defined(__linux__) */
1604 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1606 struct sigaction act
;
1607 struct itimerval itv
;
1611 sigfillset(&act
.sa_mask
);
1613 act
.sa_handler
= host_alarm_handler
;
1615 sigaction(SIGALRM
, &act
, NULL
);
1617 itv
.it_interval
.tv_sec
= 0;
1618 /* for i386 kernel 2.6 to get 1 ms */
1619 itv
.it_interval
.tv_usec
= 999;
1620 itv
.it_value
.tv_sec
= 0;
1621 itv
.it_value
.tv_usec
= 10 * 1000;
1623 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1630 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1632 struct itimerval itv
;
1634 memset(&itv
, 0, sizeof(itv
));
1635 setitimer(ITIMER_REAL
, &itv
, NULL
);
1638 #endif /* !defined(_WIN32) */
1642 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1645 struct qemu_alarm_win32
*data
= t
->priv
;
1648 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1649 if (!data
->host_alarm
) {
1650 perror("Failed CreateEvent");
1654 memset(&tc
, 0, sizeof(tc
));
1655 timeGetDevCaps(&tc
, sizeof(tc
));
1657 if (data
->period
< tc
.wPeriodMin
)
1658 data
->period
= tc
.wPeriodMin
;
1660 timeBeginPeriod(data
->period
);
1662 flags
= TIME_CALLBACK_FUNCTION
;
1663 if (alarm_has_dynticks(t
))
1664 flags
|= TIME_ONESHOT
;
1666 flags
|= TIME_PERIODIC
;
1668 data
->timerId
= timeSetEvent(1, // interval (ms)
1669 data
->period
, // resolution
1670 host_alarm_handler
, // function
1671 (DWORD
)t
, // parameter
1674 if (!data
->timerId
) {
1675 perror("Failed to initialize win32 alarm timer");
1677 timeEndPeriod(data
->period
);
1678 CloseHandle(data
->host_alarm
);
1682 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1687 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1689 struct qemu_alarm_win32
*data
= t
->priv
;
1691 timeKillEvent(data
->timerId
);
1692 timeEndPeriod(data
->period
);
1694 CloseHandle(data
->host_alarm
);
1697 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1699 struct qemu_alarm_win32
*data
= t
->priv
;
1700 uint64_t nearest_delta_us
;
1702 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1703 !active_timers
[QEMU_TIMER_VIRTUAL
])
1706 nearest_delta_us
= qemu_next_deadline_dyntick();
1707 nearest_delta_us
/= 1000;
1709 timeKillEvent(data
->timerId
);
1711 data
->timerId
= timeSetEvent(1,
1715 TIME_ONESHOT
| TIME_PERIODIC
);
1717 if (!data
->timerId
) {
1718 perror("Failed to re-arm win32 alarm timer");
1720 timeEndPeriod(data
->period
);
1721 CloseHandle(data
->host_alarm
);
1728 static void init_timer_alarm(void)
1730 struct qemu_alarm_timer
*t
;
1733 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1734 t
= &alarm_timers
[i
];
1742 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1743 fprintf(stderr
, "Terminating\n");
1750 static void quit_timers(void)
1752 alarm_timer
->stop(alarm_timer
);
1756 /***********************************************************/
1757 /* host time/date access */
1758 void qemu_get_timedate(struct tm
*tm
, int offset
)
1765 if (rtc_date_offset
== -1) {
1769 ret
= localtime(&ti
);
1771 ti
-= rtc_date_offset
;
1775 memcpy(tm
, ret
, sizeof(struct tm
));
1778 int qemu_timedate_diff(struct tm
*tm
)
1782 if (rtc_date_offset
== -1)
1784 seconds
= mktimegm(tm
);
1786 seconds
= mktime(tm
);
1788 seconds
= mktimegm(tm
) + rtc_date_offset
;
1790 return seconds
- time(NULL
);
1793 /***********************************************************/
1794 /* character device */
1796 static void qemu_chr_event(CharDriverState
*s
, int event
)
1800 s
->chr_event(s
->handler_opaque
, event
);
1803 static void qemu_chr_reset_bh(void *opaque
)
1805 CharDriverState
*s
= opaque
;
1806 qemu_chr_event(s
, CHR_EVENT_RESET
);
1807 qemu_bh_delete(s
->bh
);
1811 void qemu_chr_reset(CharDriverState
*s
)
1813 if (s
->bh
== NULL
) {
1814 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1815 qemu_bh_schedule(s
->bh
);
1819 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1821 return s
->chr_write(s
, buf
, len
);
1824 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1828 return s
->chr_ioctl(s
, cmd
, arg
);
1831 int qemu_chr_can_read(CharDriverState
*s
)
1833 if (!s
->chr_can_read
)
1835 return s
->chr_can_read(s
->handler_opaque
);
1838 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1840 s
->chr_read(s
->handler_opaque
, buf
, len
);
1843 void qemu_chr_accept_input(CharDriverState
*s
)
1845 if (s
->chr_accept_input
)
1846 s
->chr_accept_input(s
);
1849 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1854 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1855 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1859 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1861 if (s
->chr_send_event
)
1862 s
->chr_send_event(s
, event
);
1865 void qemu_chr_add_handlers(CharDriverState
*s
,
1866 IOCanRWHandler
*fd_can_read
,
1867 IOReadHandler
*fd_read
,
1868 IOEventHandler
*fd_event
,
1871 s
->chr_can_read
= fd_can_read
;
1872 s
->chr_read
= fd_read
;
1873 s
->chr_event
= fd_event
;
1874 s
->handler_opaque
= opaque
;
1875 if (s
->chr_update_read_handler
)
1876 s
->chr_update_read_handler(s
);
1879 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1884 static CharDriverState
*qemu_chr_open_null(void)
1886 CharDriverState
*chr
;
1888 chr
= qemu_mallocz(sizeof(CharDriverState
));
1891 chr
->chr_write
= null_chr_write
;
1895 /* MUX driver for serial I/O splitting */
1896 static int term_timestamps
;
1897 static int64_t term_timestamps_start
;
1899 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1900 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1902 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1903 IOReadHandler
*chr_read
[MAX_MUX
];
1904 IOEventHandler
*chr_event
[MAX_MUX
];
1905 void *ext_opaque
[MAX_MUX
];
1906 CharDriverState
*drv
;
1907 unsigned char buffer
[MUX_BUFFER_SIZE
];
1911 int term_got_escape
;
1916 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1918 MuxDriver
*d
= chr
->opaque
;
1920 if (!term_timestamps
) {
1921 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1926 for(i
= 0; i
< len
; i
++) {
1927 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1928 if (buf
[i
] == '\n') {
1934 if (term_timestamps_start
== -1)
1935 term_timestamps_start
= ti
;
1936 ti
-= term_timestamps_start
;
1937 secs
= ti
/ 1000000000;
1938 snprintf(buf1
, sizeof(buf1
),
1939 "[%02d:%02d:%02d.%03d] ",
1943 (int)((ti
/ 1000000) % 1000));
1944 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1951 static const char * const mux_help
[] = {
1952 "% h print this help\n\r",
1953 "% x exit emulator\n\r",
1954 "% s save disk data back to file (if -snapshot)\n\r",
1955 "% t toggle console timestamps\n\r"
1956 "% b send break (magic sysrq)\n\r",
1957 "% c switch between console and monitor\n\r",
1962 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1963 static void mux_print_help(CharDriverState
*chr
)
1966 char ebuf
[15] = "Escape-Char";
1967 char cbuf
[50] = "\n\r";
1969 if (term_escape_char
> 0 && term_escape_char
< 26) {
1970 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1971 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1973 snprintf(cbuf
, sizeof(cbuf
),
1974 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1977 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1978 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1979 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1980 if (mux_help
[i
][j
] == '%')
1981 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1983 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1988 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1990 if (d
->term_got_escape
) {
1991 d
->term_got_escape
= 0;
1992 if (ch
== term_escape_char
)
1997 mux_print_help(chr
);
2001 const char *term
= "QEMU: Terminated\n\r";
2002 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
2009 for (i
= 0; i
< nb_drives
; i
++) {
2010 bdrv_commit(drives_table
[i
].bdrv
);
2015 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2018 /* Switch to the next registered device */
2020 if (chr
->focus
>= d
->mux_cnt
)
2024 term_timestamps
= !term_timestamps
;
2025 term_timestamps_start
= -1;
2028 } else if (ch
== term_escape_char
) {
2029 d
->term_got_escape
= 1;
2037 static void mux_chr_accept_input(CharDriverState
*chr
)
2040 MuxDriver
*d
= chr
->opaque
;
2042 while (d
->prod
!= d
->cons
&&
2043 d
->chr_can_read
[m
] &&
2044 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
2045 d
->chr_read
[m
](d
->ext_opaque
[m
],
2046 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2050 static int mux_chr_can_read(void *opaque
)
2052 CharDriverState
*chr
= opaque
;
2053 MuxDriver
*d
= chr
->opaque
;
2055 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2057 if (d
->chr_can_read
[chr
->focus
])
2058 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2062 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2064 CharDriverState
*chr
= opaque
;
2065 MuxDriver
*d
= chr
->opaque
;
2069 mux_chr_accept_input (opaque
);
2071 for(i
= 0; i
< size
; i
++)
2072 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2073 if (d
->prod
== d
->cons
&&
2074 d
->chr_can_read
[m
] &&
2075 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2076 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2078 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2082 static void mux_chr_event(void *opaque
, int event
)
2084 CharDriverState
*chr
= opaque
;
2085 MuxDriver
*d
= chr
->opaque
;
2088 /* Send the event to all registered listeners */
2089 for (i
= 0; i
< d
->mux_cnt
; i
++)
2090 if (d
->chr_event
[i
])
2091 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2094 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2096 MuxDriver
*d
= chr
->opaque
;
2098 if (d
->mux_cnt
>= MAX_MUX
) {
2099 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2102 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2103 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2104 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2105 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2106 /* Fix up the real driver with mux routines */
2107 if (d
->mux_cnt
== 0) {
2108 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2109 mux_chr_event
, chr
);
2111 chr
->focus
= d
->mux_cnt
;
2115 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2117 CharDriverState
*chr
;
2120 chr
= qemu_mallocz(sizeof(CharDriverState
));
2123 d
= qemu_mallocz(sizeof(MuxDriver
));
2132 chr
->chr_write
= mux_chr_write
;
2133 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2134 chr
->chr_accept_input
= mux_chr_accept_input
;
2141 static void socket_cleanup(void)
2146 static int socket_init(void)
2151 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2153 err
= WSAGetLastError();
2154 fprintf(stderr
, "WSAStartup: %d\n", err
);
2157 atexit(socket_cleanup
);
2161 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2167 ret
= send(fd
, buf
, len
, 0);
2170 errno
= WSAGetLastError();
2171 if (errno
!= WSAEWOULDBLOCK
) {
2174 } else if (ret
== 0) {
2186 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2192 ret
= write(fd
, buf
, len
);
2194 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2196 } else if (ret
== 0) {
2206 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2208 return unix_write(fd
, buf
, len1
);
2210 #endif /* !_WIN32 */
2219 #define STDIO_MAX_CLIENTS 1
2220 static int stdio_nb_clients
= 0;
2222 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2224 FDCharDriver
*s
= chr
->opaque
;
2225 return unix_write(s
->fd_out
, buf
, len
);
2228 static int fd_chr_read_poll(void *opaque
)
2230 CharDriverState
*chr
= opaque
;
2231 FDCharDriver
*s
= chr
->opaque
;
2233 s
->max_size
= qemu_chr_can_read(chr
);
2237 static void fd_chr_read(void *opaque
)
2239 CharDriverState
*chr
= opaque
;
2240 FDCharDriver
*s
= chr
->opaque
;
2245 if (len
> s
->max_size
)
2249 size
= read(s
->fd_in
, buf
, len
);
2251 /* FD has been closed. Remove it from the active list. */
2252 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2256 qemu_chr_read(chr
, buf
, size
);
2260 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2262 FDCharDriver
*s
= chr
->opaque
;
2264 if (s
->fd_in
>= 0) {
2265 if (nographic
&& s
->fd_in
== 0) {
2267 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2268 fd_chr_read
, NULL
, chr
);
2273 static void fd_chr_close(struct CharDriverState
*chr
)
2275 FDCharDriver
*s
= chr
->opaque
;
2277 if (s
->fd_in
>= 0) {
2278 if (nographic
&& s
->fd_in
== 0) {
2280 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2287 /* open a character device to a unix fd */
2288 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2290 CharDriverState
*chr
;
2293 chr
= qemu_mallocz(sizeof(CharDriverState
));
2296 s
= qemu_mallocz(sizeof(FDCharDriver
));
2304 chr
->chr_write
= fd_chr_write
;
2305 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2306 chr
->chr_close
= fd_chr_close
;
2308 qemu_chr_reset(chr
);
2313 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2317 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2320 return qemu_chr_open_fd(-1, fd_out
);
2323 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2326 char filename_in
[256], filename_out
[256];
2328 snprintf(filename_in
, 256, "%s.in", filename
);
2329 snprintf(filename_out
, 256, "%s.out", filename
);
2330 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2331 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2332 if (fd_in
< 0 || fd_out
< 0) {
2337 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2341 return qemu_chr_open_fd(fd_in
, fd_out
);
2345 /* for STDIO, we handle the case where several clients use it
2348 #define TERM_FIFO_MAX_SIZE 1
2350 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2351 static int term_fifo_size
;
2353 static int stdio_read_poll(void *opaque
)
2355 CharDriverState
*chr
= opaque
;
2357 /* try to flush the queue if needed */
2358 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2359 qemu_chr_read(chr
, term_fifo
, 1);
2362 /* see if we can absorb more chars */
2363 if (term_fifo_size
== 0)
2369 static void stdio_read(void *opaque
)
2373 CharDriverState
*chr
= opaque
;
2375 size
= read(0, buf
, 1);
2377 /* stdin has been closed. Remove it from the active list. */
2378 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2382 if (qemu_chr_can_read(chr
) > 0) {
2383 qemu_chr_read(chr
, buf
, 1);
2384 } else if (term_fifo_size
== 0) {
2385 term_fifo
[term_fifo_size
++] = buf
[0];
2390 /* init terminal so that we can grab keys */
2391 static struct termios oldtty
;
2392 static int old_fd0_flags
;
2393 static int term_atexit_done
;
2395 static void term_exit(void)
2397 tcsetattr (0, TCSANOW
, &oldtty
);
2398 fcntl(0, F_SETFL
, old_fd0_flags
);
2401 static void term_init(void)
2405 tcgetattr (0, &tty
);
2407 old_fd0_flags
= fcntl(0, F_GETFL
);
2409 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2410 |INLCR
|IGNCR
|ICRNL
|IXON
);
2411 tty
.c_oflag
|= OPOST
;
2412 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2413 /* if graphical mode, we allow Ctrl-C handling */
2415 tty
.c_lflag
&= ~ISIG
;
2416 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2419 tty
.c_cc
[VTIME
] = 0;
2421 tcsetattr (0, TCSANOW
, &tty
);
2423 if (!term_atexit_done
++)
2426 fcntl(0, F_SETFL
, O_NONBLOCK
);
2429 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2433 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2437 static CharDriverState
*qemu_chr_open_stdio(void)
2439 CharDriverState
*chr
;
2441 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2443 chr
= qemu_chr_open_fd(0, 1);
2444 chr
->chr_close
= qemu_chr_close_stdio
;
2445 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2453 /* Once Solaris has openpty(), this is going to be removed. */
2454 int openpty(int *amaster
, int *aslave
, char *name
,
2455 struct termios
*termp
, struct winsize
*winp
)
2458 int mfd
= -1, sfd
= -1;
2460 *amaster
= *aslave
= -1;
2462 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2466 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2469 if ((slave
= ptsname(mfd
)) == NULL
)
2472 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2475 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2476 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2484 ioctl(sfd
, TIOCSWINSZ
, winp
);
2495 void cfmakeraw (struct termios
*termios_p
)
2497 termios_p
->c_iflag
&=
2498 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2499 termios_p
->c_oflag
&= ~OPOST
;
2500 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2501 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2502 termios_p
->c_cflag
|= CS8
;
2504 termios_p
->c_cc
[VMIN
] = 0;
2505 termios_p
->c_cc
[VTIME
] = 0;
2509 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2510 || defined(__NetBSD__) || defined(__OpenBSD__)
2520 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2521 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2523 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2525 PtyCharDriver
*s
= chr
->opaque
;
2527 if (!s
->connected
) {
2528 /* guest sends data, check for (re-)connect */
2529 pty_chr_update_read_handler(chr
);
2532 return unix_write(s
->fd
, buf
, len
);
2535 static int pty_chr_read_poll(void *opaque
)
2537 CharDriverState
*chr
= opaque
;
2538 PtyCharDriver
*s
= chr
->opaque
;
2540 s
->read_bytes
= qemu_chr_can_read(chr
);
2541 return s
->read_bytes
;
2544 static void pty_chr_read(void *opaque
)
2546 CharDriverState
*chr
= opaque
;
2547 PtyCharDriver
*s
= chr
->opaque
;
2552 if (len
> s
->read_bytes
)
2553 len
= s
->read_bytes
;
2556 size
= read(s
->fd
, buf
, len
);
2557 if ((size
== -1 && errno
== EIO
) ||
2559 pty_chr_state(chr
, 0);
2563 pty_chr_state(chr
, 1);
2564 qemu_chr_read(chr
, buf
, size
);
2568 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2570 PtyCharDriver
*s
= chr
->opaque
;
2572 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2573 pty_chr_read
, NULL
, chr
);
2576 * Short timeout here: just need wait long enougth that qemu makes
2577 * it through the poll loop once. When reconnected we want a
2578 * short timeout so we notice it almost instantly. Otherwise
2579 * read() gives us -EIO instantly, making pty_chr_state() reset the
2580 * timeout to the normal (much longer) poll interval before the
2583 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2586 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2588 PtyCharDriver
*s
= chr
->opaque
;
2591 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2594 /* (re-)connect poll interval for idle guests: once per second.
2595 * We check more frequently in case the guests sends data to
2596 * the virtual device linked to our pty. */
2597 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2600 qemu_chr_reset(chr
);
2605 static void pty_chr_timer(void *opaque
)
2607 struct CharDriverState
*chr
= opaque
;
2608 PtyCharDriver
*s
= chr
->opaque
;
2613 /* If we arrive here without polling being cleared due
2614 * read returning -EIO, then we are (re-)connected */
2615 pty_chr_state(chr
, 1);
2620 pty_chr_update_read_handler(chr
);
2623 static void pty_chr_close(struct CharDriverState
*chr
)
2625 PtyCharDriver
*s
= chr
->opaque
;
2627 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2632 static CharDriverState
*qemu_chr_open_pty(void)
2634 CharDriverState
*chr
;
2638 #if defined(__OpenBSD__)
2639 char pty_name
[PATH_MAX
];
2640 #define q_ptsname(x) pty_name
2642 char *pty_name
= NULL
;
2643 #define q_ptsname(x) ptsname(x)
2646 chr
= qemu_mallocz(sizeof(CharDriverState
));
2649 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2655 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2659 /* Set raw attributes on the pty. */
2661 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2664 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2667 chr
->chr_write
= pty_chr_write
;
2668 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2669 chr
->chr_close
= pty_chr_close
;
2671 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2676 static void tty_serial_init(int fd
, int speed
,
2677 int parity
, int data_bits
, int stop_bits
)
2683 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2684 speed
, parity
, data_bits
, stop_bits
);
2686 tcgetattr (fd
, &tty
);
2689 if (speed
<= 50 * MARGIN
)
2691 else if (speed
<= 75 * MARGIN
)
2693 else if (speed
<= 300 * MARGIN
)
2695 else if (speed
<= 600 * MARGIN
)
2697 else if (speed
<= 1200 * MARGIN
)
2699 else if (speed
<= 2400 * MARGIN
)
2701 else if (speed
<= 4800 * MARGIN
)
2703 else if (speed
<= 9600 * MARGIN
)
2705 else if (speed
<= 19200 * MARGIN
)
2707 else if (speed
<= 38400 * MARGIN
)
2709 else if (speed
<= 57600 * MARGIN
)
2711 else if (speed
<= 115200 * MARGIN
)
2716 cfsetispeed(&tty
, spd
);
2717 cfsetospeed(&tty
, spd
);
2719 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2720 |INLCR
|IGNCR
|ICRNL
|IXON
);
2721 tty
.c_oflag
|= OPOST
;
2722 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2723 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2744 tty
.c_cflag
|= PARENB
;
2747 tty
.c_cflag
|= PARENB
| PARODD
;
2751 tty
.c_cflag
|= CSTOPB
;
2753 tcsetattr (fd
, TCSANOW
, &tty
);
2756 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2758 FDCharDriver
*s
= chr
->opaque
;
2761 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2763 QEMUSerialSetParams
*ssp
= arg
;
2764 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2765 ssp
->data_bits
, ssp
->stop_bits
);
2768 case CHR_IOCTL_SERIAL_SET_BREAK
:
2770 int enable
= *(int *)arg
;
2772 tcsendbreak(s
->fd_in
, 1);
2775 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2778 int *targ
= (int *)arg
;
2779 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2781 if (sarg
| TIOCM_CTS
)
2782 *targ
|= CHR_TIOCM_CTS
;
2783 if (sarg
| TIOCM_CAR
)
2784 *targ
|= CHR_TIOCM_CAR
;
2785 if (sarg
| TIOCM_DSR
)
2786 *targ
|= CHR_TIOCM_DSR
;
2787 if (sarg
| TIOCM_RI
)
2788 *targ
|= CHR_TIOCM_RI
;
2789 if (sarg
| TIOCM_DTR
)
2790 *targ
|= CHR_TIOCM_DTR
;
2791 if (sarg
| TIOCM_RTS
)
2792 *targ
|= CHR_TIOCM_RTS
;
2795 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2797 int sarg
= *(int *)arg
;
2799 if (sarg
| CHR_TIOCM_DTR
)
2801 if (sarg
| CHR_TIOCM_RTS
)
2803 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2812 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2814 CharDriverState
*chr
;
2817 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2818 tty_serial_init(fd
, 115200, 'N', 8, 1);
2819 chr
= qemu_chr_open_fd(fd
, fd
);
2824 chr
->chr_ioctl
= tty_serial_ioctl
;
2825 qemu_chr_reset(chr
);
2828 #else /* ! __linux__ && ! __sun__ */
2829 static CharDriverState
*qemu_chr_open_pty(void)
2833 #endif /* __linux__ || __sun__ */
2835 #if defined(__linux__)
2839 } ParallelCharDriver
;
2841 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2843 if (s
->mode
!= mode
) {
2845 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2852 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2854 ParallelCharDriver
*drv
= chr
->opaque
;
2859 case CHR_IOCTL_PP_READ_DATA
:
2860 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2862 *(uint8_t *)arg
= b
;
2864 case CHR_IOCTL_PP_WRITE_DATA
:
2865 b
= *(uint8_t *)arg
;
2866 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2869 case CHR_IOCTL_PP_READ_CONTROL
:
2870 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2872 /* Linux gives only the lowest bits, and no way to know data
2873 direction! For better compatibility set the fixed upper
2875 *(uint8_t *)arg
= b
| 0xc0;
2877 case CHR_IOCTL_PP_WRITE_CONTROL
:
2878 b
= *(uint8_t *)arg
;
2879 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2882 case CHR_IOCTL_PP_READ_STATUS
:
2883 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2885 *(uint8_t *)arg
= b
;
2887 case CHR_IOCTL_PP_DATA_DIR
:
2888 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2891 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2892 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2893 struct ParallelIOArg
*parg
= arg
;
2894 int n
= read(fd
, parg
->buffer
, parg
->count
);
2895 if (n
!= parg
->count
) {
2900 case CHR_IOCTL_PP_EPP_READ
:
2901 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2902 struct ParallelIOArg
*parg
= arg
;
2903 int n
= read(fd
, parg
->buffer
, parg
->count
);
2904 if (n
!= parg
->count
) {
2909 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2910 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2911 struct ParallelIOArg
*parg
= arg
;
2912 int n
= write(fd
, parg
->buffer
, parg
->count
);
2913 if (n
!= parg
->count
) {
2918 case CHR_IOCTL_PP_EPP_WRITE
:
2919 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2920 struct ParallelIOArg
*parg
= arg
;
2921 int n
= write(fd
, parg
->buffer
, parg
->count
);
2922 if (n
!= parg
->count
) {
2933 static void pp_close(CharDriverState
*chr
)
2935 ParallelCharDriver
*drv
= chr
->opaque
;
2938 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2939 ioctl(fd
, PPRELEASE
);
2944 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2946 CharDriverState
*chr
;
2947 ParallelCharDriver
*drv
;
2950 TFR(fd
= open(filename
, O_RDWR
));
2954 if (ioctl(fd
, PPCLAIM
) < 0) {
2959 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2965 drv
->mode
= IEEE1284_MODE_COMPAT
;
2967 chr
= qemu_mallocz(sizeof(CharDriverState
));
2973 chr
->chr_write
= null_chr_write
;
2974 chr
->chr_ioctl
= pp_ioctl
;
2975 chr
->chr_close
= pp_close
;
2978 qemu_chr_reset(chr
);
2982 #endif /* __linux__ */
2988 HANDLE hcom
, hrecv
, hsend
;
2989 OVERLAPPED orecv
, osend
;
2994 #define NSENDBUF 2048
2995 #define NRECVBUF 2048
2996 #define MAXCONNECT 1
2997 #define NTIMEOUT 5000
2999 static int win_chr_poll(void *opaque
);
3000 static int win_chr_pipe_poll(void *opaque
);
3002 static void win_chr_close(CharDriverState
*chr
)
3004 WinCharState
*s
= chr
->opaque
;
3007 CloseHandle(s
->hsend
);
3011 CloseHandle(s
->hrecv
);
3015 CloseHandle(s
->hcom
);
3019 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
3021 qemu_del_polling_cb(win_chr_poll
, chr
);
3024 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
3026 WinCharState
*s
= chr
->opaque
;
3028 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
3033 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3035 fprintf(stderr
, "Failed CreateEvent\n");
3038 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3040 fprintf(stderr
, "Failed CreateEvent\n");
3044 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
3045 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3046 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3047 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3052 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3053 fprintf(stderr
, "Failed SetupComm\n");
3057 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3058 size
= sizeof(COMMCONFIG
);
3059 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3060 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3061 CommConfigDialog(filename
, NULL
, &comcfg
);
3063 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3064 fprintf(stderr
, "Failed SetCommState\n");
3068 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3069 fprintf(stderr
, "Failed SetCommMask\n");
3073 cto
.ReadIntervalTimeout
= MAXDWORD
;
3074 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3075 fprintf(stderr
, "Failed SetCommTimeouts\n");
3079 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3080 fprintf(stderr
, "Failed ClearCommError\n");
3083 qemu_add_polling_cb(win_chr_poll
, chr
);
3091 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3093 WinCharState
*s
= chr
->opaque
;
3094 DWORD len
, ret
, size
, err
;
3097 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3098 s
->osend
.hEvent
= s
->hsend
;
3101 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3103 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3105 err
= GetLastError();
3106 if (err
== ERROR_IO_PENDING
) {
3107 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3125 static int win_chr_read_poll(CharDriverState
*chr
)
3127 WinCharState
*s
= chr
->opaque
;
3129 s
->max_size
= qemu_chr_can_read(chr
);
3133 static void win_chr_readfile(CharDriverState
*chr
)
3135 WinCharState
*s
= chr
->opaque
;
3140 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3141 s
->orecv
.hEvent
= s
->hrecv
;
3142 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3144 err
= GetLastError();
3145 if (err
== ERROR_IO_PENDING
) {
3146 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3151 qemu_chr_read(chr
, buf
, size
);
3155 static void win_chr_read(CharDriverState
*chr
)
3157 WinCharState
*s
= chr
->opaque
;
3159 if (s
->len
> s
->max_size
)
3160 s
->len
= s
->max_size
;
3164 win_chr_readfile(chr
);
3167 static int win_chr_poll(void *opaque
)
3169 CharDriverState
*chr
= opaque
;
3170 WinCharState
*s
= chr
->opaque
;
3174 ClearCommError(s
->hcom
, &comerr
, &status
);
3175 if (status
.cbInQue
> 0) {
3176 s
->len
= status
.cbInQue
;
3177 win_chr_read_poll(chr
);
3184 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3186 CharDriverState
*chr
;
3189 chr
= qemu_mallocz(sizeof(CharDriverState
));
3192 s
= qemu_mallocz(sizeof(WinCharState
));
3198 chr
->chr_write
= win_chr_write
;
3199 chr
->chr_close
= win_chr_close
;
3201 if (win_chr_init(chr
, filename
) < 0) {
3206 qemu_chr_reset(chr
);
3210 static int win_chr_pipe_poll(void *opaque
)
3212 CharDriverState
*chr
= opaque
;
3213 WinCharState
*s
= chr
->opaque
;
3216 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3219 win_chr_read_poll(chr
);
3226 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3228 WinCharState
*s
= chr
->opaque
;
3236 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3238 fprintf(stderr
, "Failed CreateEvent\n");
3241 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3243 fprintf(stderr
, "Failed CreateEvent\n");
3247 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3248 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3249 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3251 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3252 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3253 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3258 ZeroMemory(&ov
, sizeof(ov
));
3259 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3260 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3262 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3266 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3268 fprintf(stderr
, "Failed GetOverlappedResult\n");
3270 CloseHandle(ov
.hEvent
);
3277 CloseHandle(ov
.hEvent
);
3280 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3289 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3291 CharDriverState
*chr
;
3294 chr
= qemu_mallocz(sizeof(CharDriverState
));
3297 s
= qemu_mallocz(sizeof(WinCharState
));
3303 chr
->chr_write
= win_chr_write
;
3304 chr
->chr_close
= win_chr_close
;
3306 if (win_chr_pipe_init(chr
, filename
) < 0) {
3311 qemu_chr_reset(chr
);
3315 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3317 CharDriverState
*chr
;
3320 chr
= qemu_mallocz(sizeof(CharDriverState
));
3323 s
= qemu_mallocz(sizeof(WinCharState
));
3330 chr
->chr_write
= win_chr_write
;
3331 qemu_chr_reset(chr
);
3335 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3337 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3340 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3344 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3345 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3346 if (fd_out
== INVALID_HANDLE_VALUE
)
3349 return qemu_chr_open_win_file(fd_out
);
3351 #endif /* !_WIN32 */
3353 /***********************************************************/
3354 /* UDP Net console */
3358 struct sockaddr_in daddr
;
3365 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3367 NetCharDriver
*s
= chr
->opaque
;
3369 return sendto(s
->fd
, buf
, len
, 0,
3370 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3373 static int udp_chr_read_poll(void *opaque
)
3375 CharDriverState
*chr
= opaque
;
3376 NetCharDriver
*s
= chr
->opaque
;
3378 s
->max_size
= qemu_chr_can_read(chr
);
3380 /* If there were any stray characters in the queue process them
3383 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3384 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3386 s
->max_size
= qemu_chr_can_read(chr
);
3391 static void udp_chr_read(void *opaque
)
3393 CharDriverState
*chr
= opaque
;
3394 NetCharDriver
*s
= chr
->opaque
;
3396 if (s
->max_size
== 0)
3398 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3399 s
->bufptr
= s
->bufcnt
;
3404 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3405 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3407 s
->max_size
= qemu_chr_can_read(chr
);
3411 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3413 NetCharDriver
*s
= chr
->opaque
;
3416 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3417 udp_chr_read
, NULL
, chr
);
3422 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3424 int parse_host_src_port(struct sockaddr_in
*haddr
,
3425 struct sockaddr_in
*saddr
,
3428 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3430 CharDriverState
*chr
= NULL
;
3431 NetCharDriver
*s
= NULL
;
3433 struct sockaddr_in saddr
;
3435 chr
= qemu_mallocz(sizeof(CharDriverState
));
3438 s
= qemu_mallocz(sizeof(NetCharDriver
));
3442 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3444 perror("socket(PF_INET, SOCK_DGRAM)");
3448 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3449 printf("Could not parse: %s\n", def
);
3453 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3463 chr
->chr_write
= udp_chr_write
;
3464 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3477 /***********************************************************/
3478 /* TCP Net console */
3489 static void tcp_chr_accept(void *opaque
);
3491 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3493 TCPCharDriver
*s
= chr
->opaque
;
3495 return send_all(s
->fd
, buf
, len
);
3497 /* XXX: indicate an error ? */
3502 static int tcp_chr_read_poll(void *opaque
)
3504 CharDriverState
*chr
= opaque
;
3505 TCPCharDriver
*s
= chr
->opaque
;
3508 s
->max_size
= qemu_chr_can_read(chr
);
3513 #define IAC_BREAK 243
3514 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3516 uint8_t *buf
, int *size
)
3518 /* Handle any telnet client's basic IAC options to satisfy char by
3519 * char mode with no echo. All IAC options will be removed from
3520 * the buf and the do_telnetopt variable will be used to track the
3521 * state of the width of the IAC information.
3523 * IAC commands come in sets of 3 bytes with the exception of the
3524 * "IAC BREAK" command and the double IAC.
3530 for (i
= 0; i
< *size
; i
++) {
3531 if (s
->do_telnetopt
> 1) {
3532 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3533 /* Double IAC means send an IAC */
3537 s
->do_telnetopt
= 1;
3539 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3540 /* Handle IAC break commands by sending a serial break */
3541 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3546 if (s
->do_telnetopt
>= 4) {
3547 s
->do_telnetopt
= 1;
3550 if ((unsigned char)buf
[i
] == IAC
) {
3551 s
->do_telnetopt
= 2;
3562 static void tcp_chr_read(void *opaque
)
3564 CharDriverState
*chr
= opaque
;
3565 TCPCharDriver
*s
= chr
->opaque
;
3569 if (!s
->connected
|| s
->max_size
<= 0)
3572 if (len
> s
->max_size
)
3574 size
= recv(s
->fd
, buf
, len
, 0);
3576 /* connection closed */
3578 if (s
->listen_fd
>= 0) {
3579 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3581 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3584 } else if (size
> 0) {
3585 if (s
->do_telnetopt
)
3586 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3588 qemu_chr_read(chr
, buf
, size
);
3592 static void tcp_chr_connect(void *opaque
)
3594 CharDriverState
*chr
= opaque
;
3595 TCPCharDriver
*s
= chr
->opaque
;
3598 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3599 tcp_chr_read
, NULL
, chr
);
3600 qemu_chr_reset(chr
);
3603 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3604 static void tcp_chr_telnet_init(int fd
)
3607 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3608 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3609 send(fd
, (char *)buf
, 3, 0);
3610 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3611 send(fd
, (char *)buf
, 3, 0);
3612 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3613 send(fd
, (char *)buf
, 3, 0);
3614 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3615 send(fd
, (char *)buf
, 3, 0);
3618 static void socket_set_nodelay(int fd
)
3621 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3624 static void tcp_chr_accept(void *opaque
)
3626 CharDriverState
*chr
= opaque
;
3627 TCPCharDriver
*s
= chr
->opaque
;
3628 struct sockaddr_in saddr
;
3630 struct sockaddr_un uaddr
;
3632 struct sockaddr
*addr
;
3639 len
= sizeof(uaddr
);
3640 addr
= (struct sockaddr
*)&uaddr
;
3644 len
= sizeof(saddr
);
3645 addr
= (struct sockaddr
*)&saddr
;
3647 fd
= accept(s
->listen_fd
, addr
, &len
);
3648 if (fd
< 0 && errno
!= EINTR
) {
3650 } else if (fd
>= 0) {
3651 if (s
->do_telnetopt
)
3652 tcp_chr_telnet_init(fd
);
3656 socket_set_nonblock(fd
);
3658 socket_set_nodelay(fd
);
3660 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3661 tcp_chr_connect(chr
);
3664 static void tcp_chr_close(CharDriverState
*chr
)
3666 TCPCharDriver
*s
= chr
->opaque
;
3669 if (s
->listen_fd
>= 0)
3670 closesocket(s
->listen_fd
);
3674 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3678 CharDriverState
*chr
= NULL
;
3679 TCPCharDriver
*s
= NULL
;
3680 int fd
= -1, ret
, err
, val
;
3682 int is_waitconnect
= 1;
3685 struct sockaddr_in saddr
;
3687 struct sockaddr_un uaddr
;
3689 struct sockaddr
*addr
;
3694 addr
= (struct sockaddr
*)&uaddr
;
3695 addrlen
= sizeof(uaddr
);
3696 if (parse_unix_path(&uaddr
, host_str
) < 0)
3701 addr
= (struct sockaddr
*)&saddr
;
3702 addrlen
= sizeof(saddr
);
3703 if (parse_host_port(&saddr
, host_str
) < 0)
3708 while((ptr
= strchr(ptr
,','))) {
3710 if (!strncmp(ptr
,"server",6)) {
3712 } else if (!strncmp(ptr
,"nowait",6)) {
3714 } else if (!strncmp(ptr
,"nodelay",6)) {
3717 printf("Unknown option: %s\n", ptr
);
3724 chr
= qemu_mallocz(sizeof(CharDriverState
));
3727 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3733 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3736 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3741 if (!is_waitconnect
)
3742 socket_set_nonblock(fd
);
3747 s
->is_unix
= is_unix
;
3748 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3751 chr
->chr_write
= tcp_chr_write
;
3752 chr
->chr_close
= tcp_chr_close
;
3755 /* allow fast reuse */
3759 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3765 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3768 ret
= bind(fd
, addr
, addrlen
);
3772 ret
= listen(fd
, 0);
3777 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3779 s
->do_telnetopt
= 1;
3782 ret
= connect(fd
, addr
, addrlen
);
3784 err
= socket_error();
3785 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3786 } else if (err
== EINPROGRESS
) {
3789 } else if (err
== WSAEALREADY
) {
3801 socket_set_nodelay(fd
);
3803 tcp_chr_connect(chr
);
3805 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3808 if (is_listen
&& is_waitconnect
) {
3809 printf("QEMU waiting for connection on: %s\n", host_str
);
3810 tcp_chr_accept(chr
);
3811 socket_set_nonblock(s
->listen_fd
);
3823 CharDriverState
*qemu_chr_open(const char *filename
)
3827 if (!strcmp(filename
, "vc")) {
3828 return text_console_init(&display_state
, 0);
3829 } else if (strstart(filename
, "vc:", &p
)) {
3830 return text_console_init(&display_state
, p
);
3831 } else if (!strcmp(filename
, "null")) {
3832 return qemu_chr_open_null();
3834 if (strstart(filename
, "tcp:", &p
)) {
3835 return qemu_chr_open_tcp(p
, 0, 0);
3837 if (strstart(filename
, "telnet:", &p
)) {
3838 return qemu_chr_open_tcp(p
, 1, 0);
3840 if (strstart(filename
, "udp:", &p
)) {
3841 return qemu_chr_open_udp(p
);
3843 if (strstart(filename
, "mon:", &p
)) {
3844 CharDriverState
*drv
= qemu_chr_open(p
);
3846 drv
= qemu_chr_open_mux(drv
);
3847 monitor_init(drv
, !nographic
);
3850 printf("Unable to open driver: %s\n", p
);
3854 if (strstart(filename
, "unix:", &p
)) {
3855 return qemu_chr_open_tcp(p
, 0, 1);
3856 } else if (strstart(filename
, "file:", &p
)) {
3857 return qemu_chr_open_file_out(p
);
3858 } else if (strstart(filename
, "pipe:", &p
)) {
3859 return qemu_chr_open_pipe(p
);
3860 } else if (!strcmp(filename
, "pty")) {
3861 return qemu_chr_open_pty();
3862 } else if (!strcmp(filename
, "stdio")) {
3863 return qemu_chr_open_stdio();
3865 #if defined(__linux__)
3866 if (strstart(filename
, "/dev/parport", NULL
)) {
3867 return qemu_chr_open_pp(filename
);
3870 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3871 || defined(__NetBSD__) || defined(__OpenBSD__)
3872 if (strstart(filename
, "/dev/", NULL
)) {
3873 return qemu_chr_open_tty(filename
);
3877 if (strstart(filename
, "COM", NULL
)) {
3878 return qemu_chr_open_win(filename
);
3880 if (strstart(filename
, "pipe:", &p
)) {
3881 return qemu_chr_open_win_pipe(p
);
3883 if (strstart(filename
, "con:", NULL
)) {
3884 return qemu_chr_open_win_con(filename
);
3886 if (strstart(filename
, "file:", &p
)) {
3887 return qemu_chr_open_win_file_out(p
);
3890 #ifdef CONFIG_BRLAPI
3891 if (!strcmp(filename
, "braille")) {
3892 return chr_baum_init();
3900 void qemu_chr_close(CharDriverState
*chr
)
3903 chr
->chr_close(chr
);
3907 /***********************************************************/
3908 /* network device redirectors */
3910 __attribute__ (( unused
))
3911 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3915 for(i
=0;i
<size
;i
+=16) {
3919 fprintf(f
, "%08x ", i
);
3922 fprintf(f
, " %02x", buf
[i
+j
]);
3927 for(j
=0;j
<len
;j
++) {
3929 if (c
< ' ' || c
> '~')
3931 fprintf(f
, "%c", c
);
3937 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3944 offset
= strtol(p
, &last_char
, 0);
3945 if (0 == errno
&& '\0' == *last_char
&&
3946 offset
>= 0 && offset
<= 0xFFFFFF) {
3947 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3948 macaddr
[4] = (offset
& 0xFF00) >> 8;
3949 macaddr
[5] = offset
& 0xFF;
3952 for(i
= 0; i
< 6; i
++) {
3953 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3958 if (*p
!= ':' && *p
!= '-')
3969 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3974 p1
= strchr(p
, sep
);
3980 if (len
> buf_size
- 1)
3982 memcpy(buf
, p
, len
);
3989 int parse_host_src_port(struct sockaddr_in
*haddr
,
3990 struct sockaddr_in
*saddr
,
3991 const char *input_str
)
3993 char *str
= strdup(input_str
);
3994 char *host_str
= str
;
3996 const char *src_str2
;
4000 * Chop off any extra arguments at the end of the string which
4001 * would start with a comma, then fill in the src port information
4002 * if it was provided else use the "any address" and "any port".
4004 if ((ptr
= strchr(str
,',')))
4007 if ((src_str
= strchr(input_str
,'@'))) {
4012 if (parse_host_port(haddr
, host_str
) < 0)
4016 if (!src_str
|| *src_str
== '\0')
4019 if (parse_host_port(saddr
, src_str2
) < 0)
4030 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
4038 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4040 saddr
->sin_family
= AF_INET
;
4041 if (buf
[0] == '\0') {
4042 saddr
->sin_addr
.s_addr
= 0;
4044 if (isdigit(buf
[0])) {
4045 if (!inet_aton(buf
, &saddr
->sin_addr
))
4048 if ((he
= gethostbyname(buf
)) == NULL
)
4050 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4053 port
= strtol(p
, (char **)&r
, 0);
4056 saddr
->sin_port
= htons(port
);
4061 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4066 len
= MIN(108, strlen(str
));
4067 p
= strchr(str
, ',');
4069 len
= MIN(len
, p
- str
);
4071 memset(uaddr
, 0, sizeof(*uaddr
));
4073 uaddr
->sun_family
= AF_UNIX
;
4074 memcpy(uaddr
->sun_path
, str
, len
);
4080 /* find or alloc a new VLAN */
4081 VLANState
*qemu_find_vlan(int id
)
4083 VLANState
**pvlan
, *vlan
;
4084 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4088 vlan
= qemu_mallocz(sizeof(VLANState
));
4093 pvlan
= &first_vlan
;
4094 while (*pvlan
!= NULL
)
4095 pvlan
= &(*pvlan
)->next
;
4100 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4101 IOReadHandler
*fd_read
,
4102 IOCanRWHandler
*fd_can_read
,
4105 VLANClientState
*vc
, **pvc
;
4106 vc
= qemu_mallocz(sizeof(VLANClientState
));
4109 vc
->fd_read
= fd_read
;
4110 vc
->fd_can_read
= fd_can_read
;
4111 vc
->opaque
= opaque
;
4115 pvc
= &vlan
->first_client
;
4116 while (*pvc
!= NULL
)
4117 pvc
= &(*pvc
)->next
;
4122 void qemu_del_vlan_client(VLANClientState
*vc
)
4124 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4126 while (*pvc
!= NULL
)
4132 pvc
= &(*pvc
)->next
;
4135 int qemu_can_send_packet(VLANClientState
*vc1
)
4137 VLANState
*vlan
= vc1
->vlan
;
4138 VLANClientState
*vc
;
4140 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4142 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4149 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4151 VLANState
*vlan
= vc1
->vlan
;
4152 VLANClientState
*vc
;
4156 printf("vlan %d send:\n", vlan
->id
);
4157 hex_dump(stdout
, buf
, size
);
4159 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4161 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
4162 vc
->fd_read(vc
->opaque
, buf
, size
);
4171 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
4178 for (i
= 0; i
< iovcnt
; i
++) {
4181 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
4182 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
4186 vc
->fd_read(vc
->opaque
, buffer
, offset
);
4191 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
4194 VLANState
*vlan
= vc1
->vlan
;
4195 VLANClientState
*vc
;
4196 ssize_t max_len
= 0;
4198 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4205 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
4206 else if (vc
->fd_read
)
4207 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
4209 max_len
= MAX(max_len
, len
);
4215 #if defined(CONFIG_SLIRP)
4217 /* slirp network adapter */
4219 static int slirp_inited
;
4220 static VLANClientState
*slirp_vc
;
4222 int slirp_can_output(void)
4224 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4227 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4230 printf("slirp output:\n");
4231 hex_dump(stdout
, pkt
, pkt_len
);
4235 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4238 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4241 printf("slirp input:\n");
4242 hex_dump(stdout
, buf
, size
);
4244 slirp_input(buf
, size
);
4247 static int net_slirp_init(VLANState
*vlan
)
4249 if (!slirp_inited
) {
4253 slirp_vc
= qemu_new_vlan_client(vlan
,
4254 slirp_receive
, NULL
, NULL
);
4255 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4259 static void net_slirp_redir(const char *redir_str
)
4264 struct in_addr guest_addr
;
4265 int host_port
, guest_port
;
4267 if (!slirp_inited
) {
4273 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4275 if (!strcmp(buf
, "tcp")) {
4277 } else if (!strcmp(buf
, "udp")) {
4283 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4285 host_port
= strtol(buf
, &r
, 0);
4289 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4291 if (buf
[0] == '\0') {
4292 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4294 if (!inet_aton(buf
, &guest_addr
))
4297 guest_port
= strtol(p
, &r
, 0);
4301 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4302 fprintf(stderr
, "qemu: could not set up redirection\n");
4307 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4315 static void erase_dir(char *dir_name
)
4319 char filename
[1024];
4321 /* erase all the files in the directory */
4322 if ((d
= opendir(dir_name
)) != 0) {
4327 if (strcmp(de
->d_name
, ".") != 0 &&
4328 strcmp(de
->d_name
, "..") != 0) {
4329 snprintf(filename
, sizeof(filename
), "%s/%s",
4330 smb_dir
, de
->d_name
);
4331 if (unlink(filename
) != 0) /* is it a directory? */
4332 erase_dir(filename
);
4340 /* automatic user mode samba server configuration */
4341 static void smb_exit(void)
4346 /* automatic user mode samba server configuration */
4347 static void net_slirp_smb(const char *exported_dir
)
4349 char smb_conf
[1024];
4350 char smb_cmdline
[1024];
4353 if (!slirp_inited
) {
4358 /* XXX: better tmp dir construction */
4359 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4360 if (mkdir(smb_dir
, 0700) < 0) {
4361 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4364 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4366 f
= fopen(smb_conf
, "w");
4368 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4375 "socket address=127.0.0.1\n"
4376 "pid directory=%s\n"
4377 "lock directory=%s\n"
4378 "log file=%s/log.smbd\n"
4379 "smb passwd file=%s/smbpasswd\n"
4380 "security = share\n"
4395 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4396 SMBD_COMMAND
, smb_conf
);
4398 slirp_add_exec(0, smb_cmdline
, 4, 139);
4401 #endif /* !defined(_WIN32) */
4402 void do_info_slirp(void)
4407 #endif /* CONFIG_SLIRP */
4411 int tap_has_vnet_hdr(void *opaque
)
4416 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4420 #else /* !defined(_WIN32) */
4422 #ifndef IFF_VNET_HDR
4423 #define TAP_BUFSIZE 4096
4425 #include <linux/virtio_net.h>
4427 #define ETH_DATA_LEN 1500
4428 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4429 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4430 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4433 typedef struct TAPState
{
4434 VLANClientState
*vc
;
4436 char down_script
[1024];
4437 char buf
[TAP_BUFSIZE
];
4439 unsigned int has_vnet_hdr
: 1;
4440 unsigned int using_vnet_hdr
: 1;
4443 static ssize_t
tap_writev(void *opaque
, const struct iovec
*iov
,
4446 TAPState
*s
= opaque
;
4450 len
= writev(s
->fd
, iov
, iovcnt
);
4451 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4456 static ssize_t
tap_receive_iov(void *opaque
, const struct iovec
*iov
,
4460 TAPState
*s
= opaque
;
4462 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4463 struct iovec
*iov_copy
;
4464 struct virtio_net_hdr hdr
= { 0, };
4466 iov_copy
= alloca(sizeof(struct iovec
) * (iovcnt
+ 1));
4468 iov_copy
[0].iov_base
= &hdr
;
4469 iov_copy
[0].iov_len
= sizeof(hdr
);
4471 memcpy(&iov_copy
[1], iov
, sizeof(struct iovec
) * iovcnt
);
4473 return tap_writev(opaque
, iov_copy
, iovcnt
+ 1);
4477 return tap_writev(opaque
, iov
, iovcnt
);
4480 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4482 struct iovec iov
[2];
4486 TAPState
*s
= opaque
;
4487 struct virtio_net_hdr hdr
= { 0, };
4489 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4490 iov
[i
].iov_base
= &hdr
;
4491 iov
[i
].iov_len
= sizeof(hdr
);
4496 iov
[i
].iov_base
= (char *) buf
;
4497 iov
[i
].iov_len
= size
;
4500 tap_writev(opaque
, iov
, i
);
4503 static int tap_can_send(void *opaque
)
4505 TAPState
*s
= opaque
;
4506 VLANClientState
*vc
;
4507 int can_receive
= 0;
4509 /* Check to see if any of our clients can receive a packet */
4510 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4511 /* Skip ourselves */
4515 if (!vc
->fd_can_read
) {
4516 /* no fd_can_read handler, they always can receive */
4519 can_receive
= vc
->fd_can_read(vc
->opaque
);
4521 /* Once someone can receive, we try to send a packet */
4529 static int tap_send_packet(TAPState
*s
)
4531 uint8_t *buf
= s
->buf
;
4535 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4536 buf
+= sizeof(struct virtio_net_hdr
);
4537 size
-= sizeof(struct virtio_net_hdr
);
4541 return qemu_send_packet(s
->vc
, buf
, size
);
4544 static void tap_send(void *opaque
)
4546 TAPState
*s
= opaque
;
4548 /* First try to send any buffered packet */
4552 /* If noone can receive the packet, buffer it */
4553 err
= tap_send_packet(s
);
4558 /* Read packets until we hit EAGAIN */
4563 sbuf
.maxlen
= sizeof(s
->buf
);
4565 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4568 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4572 if (s
->size
== -1 && errno
== EINTR
)
4578 /* If noone can receive the packet, buffer it */
4579 err
= tap_send_packet(s
);
4583 } while (s
->size
> 0);
4586 int tap_has_vnet_hdr(void *opaque
)
4588 VLANClientState
*vc
= opaque
;
4589 TAPState
*s
= vc
->opaque
;
4591 return s
? s
->has_vnet_hdr
: 0;
4594 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4596 VLANClientState
*vc
= opaque
;
4597 TAPState
*s
= vc
->opaque
;
4599 if (!s
|| !s
->has_vnet_hdr
)
4602 s
->using_vnet_hdr
= using_vnet_hdr
!= 0;
4605 static int tap_probe_vnet_hdr(int fd
)
4607 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4610 if (ioctl(fd
, TUNGETIFF
, &ifr
) != 0) {
4611 fprintf(stderr
, "TUNGETIFF ioctl() failed: %s\n", strerror(errno
));
4615 return ifr
.ifr_flags
& IFF_VNET_HDR
;
4621 #ifdef TUNSETOFFLOAD
4622 static void tap_set_offload(VLANClientState
*vc
, int csum
, int tso4
, int tso6
,
4625 TAPState
*s
= vc
->opaque
;
4626 unsigned int offload
= 0;
4629 offload
|= TUN_F_CSUM
;
4631 offload
|= TUN_F_TSO4
;
4633 offload
|= TUN_F_TSO6
;
4634 if ((tso4
|| tso6
) && ecn
)
4635 offload
|= TUN_F_TSO_ECN
;
4638 if (ioctl(s
->fd
, TUNSETOFFLOAD
, offload
) != 0)
4639 fprintf(stderr
, "TUNSETOFFLOAD ioctl() failed: %s\n",
4642 #endif /* TUNSETOFFLOAD */
4646 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
, int vnet_hdr
)
4650 s
= qemu_mallocz(sizeof(TAPState
));
4654 s
->has_vnet_hdr
= vnet_hdr
!= 0;
4655 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4656 s
->vc
->fd_readv
= tap_receive_iov
;
4657 #ifdef TUNSETOFFLOAD
4658 s
->vc
->set_offload
= tap_set_offload
;
4660 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4661 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4665 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4666 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4672 TFR(fd
= open("/dev/tap", O_RDWR
));
4674 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4679 dev
= devname(s
.st_rdev
, S_IFCHR
);
4680 pstrcpy(ifname
, ifname_size
, dev
);
4682 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4685 #elif defined(__sun__)
4686 #define TUNNEWPPA (('T'<<16) | 0x0001)
4688 * Allocate TAP device, returns opened fd.
4689 * Stores dev name in the first arg(must be large enough).
4691 int tap_alloc(char *dev
, size_t dev_size
)
4693 int tap_fd
, if_fd
, ppa
= -1;
4694 static int ip_fd
= 0;
4697 static int arp_fd
= 0;
4698 int ip_muxid
, arp_muxid
;
4699 struct strioctl strioc_if
, strioc_ppa
;
4700 int link_type
= I_PLINK
;;
4702 char actual_name
[32] = "";
4704 memset(&ifr
, 0x0, sizeof(ifr
));
4708 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4712 /* Check if IP device was opened */
4716 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4718 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4722 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4724 syslog(LOG_ERR
, "Can't open /dev/tap");
4728 /* Assign a new PPA and get its unit number. */
4729 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4730 strioc_ppa
.ic_timout
= 0;
4731 strioc_ppa
.ic_len
= sizeof(ppa
);
4732 strioc_ppa
.ic_dp
= (char *)&ppa
;
4733 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4734 syslog (LOG_ERR
, "Can't assign new interface");
4736 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4738 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4741 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4742 syslog(LOG_ERR
, "Can't push IP module");
4746 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4747 syslog(LOG_ERR
, "Can't get flags\n");
4749 snprintf (actual_name
, 32, "tap%d", ppa
);
4750 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4753 /* Assign ppa according to the unit number returned by tun device */
4755 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4756 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4757 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4758 syslog (LOG_ERR
, "Can't get flags\n");
4759 /* Push arp module to if_fd */
4760 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4761 syslog (LOG_ERR
, "Can't push ARP module (2)");
4763 /* Push arp module to ip_fd */
4764 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4765 syslog (LOG_ERR
, "I_POP failed\n");
4766 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4767 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4769 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4771 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4773 /* Set ifname to arp */
4774 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4775 strioc_if
.ic_timout
= 0;
4776 strioc_if
.ic_len
= sizeof(ifr
);
4777 strioc_if
.ic_dp
= (char *)&ifr
;
4778 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4779 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4782 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4783 syslog(LOG_ERR
, "Can't link TAP device to IP");
4787 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4788 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4792 memset(&ifr
, 0x0, sizeof(ifr
));
4793 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4794 ifr
.lifr_ip_muxid
= ip_muxid
;
4795 ifr
.lifr_arp_muxid
= arp_muxid
;
4797 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4799 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4800 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4801 syslog (LOG_ERR
, "Can't set multiplexor id");
4804 snprintf(dev
, dev_size
, "tap%d", ppa
);
4808 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4812 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4813 fprintf(stderr
, "Cannot allocate TAP device\n");
4816 pstrcpy(ifname
, ifname_size
, dev
);
4817 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4821 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4826 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4828 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4831 memset(&ifr
, 0, sizeof(ifr
));
4832 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4834 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4836 unsigned int features
;
4838 if (ioctl(fd
, TUNGETFEATURES
, &features
) == 0 &&
4839 features
& IFF_VNET_HDR
) {
4841 ifr
.ifr_flags
|= IFF_VNET_HDR
;
4846 if (ifname
[0] != '\0')
4847 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4849 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4850 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4852 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4856 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4857 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4862 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4868 /* try to launch network script */
4872 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4873 for (i
= 0; i
< open_max
; i
++)
4874 if (i
!= STDIN_FILENO
&&
4875 i
!= STDOUT_FILENO
&&
4876 i
!= STDERR_FILENO
&&
4881 *parg
++ = (char *)setup_script
;
4882 *parg
++ = (char *)ifname
;
4884 execv(setup_script
, args
);
4887 while (waitpid(pid
, &status
, 0) != pid
);
4888 if (!WIFEXITED(status
) ||
4889 WEXITSTATUS(status
) != 0) {
4890 fprintf(stderr
, "%s: could not launch network script\n",
4898 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4899 const char *setup_script
, const char *down_script
)
4906 if (ifname1
!= NULL
)
4907 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4911 TFR(fd
= tap_open(ifname
, sizeof(ifname
), &vnet_hdr
));
4915 if (!setup_script
|| !strcmp(setup_script
, "no"))
4917 if (setup_script
[0] != '\0') {
4918 if (launch_script(setup_script
, ifname
, fd
))
4921 s
= net_tap_fd_init(vlan
, fd
, vnet_hdr
);
4925 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4926 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4927 if (down_script
&& strcmp(down_script
, "no"))
4928 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4932 #endif /* !_WIN32 */
4934 #if defined(CONFIG_VDE)
4935 typedef struct VDEState
{
4936 VLANClientState
*vc
;
4940 static void vde_to_qemu(void *opaque
)
4942 VDEState
*s
= opaque
;
4946 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4948 qemu_send_packet(s
->vc
, buf
, size
);
4952 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4954 VDEState
*s
= opaque
;
4957 ret
= vde_send(s
->vde
, buf
, size
, 0);
4958 if (ret
< 0 && errno
== EINTR
) {
4965 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4966 const char *group
, int mode
)
4969 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4970 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4972 struct vde_open_args args
= {
4974 .group
= init_group
,
4978 s
= qemu_mallocz(sizeof(VDEState
));
4981 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4986 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4987 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4988 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4989 sock
, vde_datafd(s
->vde
));
4994 /* network connection */
4995 typedef struct NetSocketState
{
4996 VLANClientState
*vc
;
4998 int state
; /* 0 = getting length, 1 = getting data */
5002 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
5005 typedef struct NetSocketListenState
{
5008 } NetSocketListenState
;
5010 /* XXX: we consider we can send the whole packet without blocking */
5011 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
5013 NetSocketState
*s
= opaque
;
5017 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
5018 send_all(s
->fd
, buf
, size
);
5021 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
5023 NetSocketState
*s
= opaque
;
5024 sendto(s
->fd
, buf
, size
, 0,
5025 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
5028 static void net_socket_send(void *opaque
)
5030 NetSocketState
*s
= opaque
;
5035 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
5037 err
= socket_error();
5038 if (err
!= EWOULDBLOCK
)
5040 } else if (size
== 0) {
5041 /* end of connection */
5043 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5049 /* reassemble a packet from the network */
5055 memcpy(s
->buf
+ s
->index
, buf
, l
);
5059 if (s
->index
== 4) {
5061 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
5067 l
= s
->packet_len
- s
->index
;
5070 memcpy(s
->buf
+ s
->index
, buf
, l
);
5074 if (s
->index
>= s
->packet_len
) {
5075 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
5084 static void net_socket_send_dgram(void *opaque
)
5086 NetSocketState
*s
= opaque
;
5089 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
5093 /* end of connection */
5094 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5097 qemu_send_packet(s
->vc
, s
->buf
, size
);
5100 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
5105 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
5106 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5107 inet_ntoa(mcastaddr
->sin_addr
),
5108 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
5112 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
5114 perror("socket(PF_INET, SOCK_DGRAM)");
5119 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
5120 (const char *)&val
, sizeof(val
));
5122 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5126 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
5132 /* Add host to multicast group */
5133 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
5134 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
5136 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
5137 (const char *)&imr
, sizeof(struct ip_mreq
));
5139 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5143 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5145 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
5146 (const char *)&val
, sizeof(val
));
5148 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5152 socket_set_nonblock(fd
);
5160 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
5163 struct sockaddr_in saddr
;
5165 socklen_t saddr_len
;
5168 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5169 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5170 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5174 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
5176 if (saddr
.sin_addr
.s_addr
==0) {
5177 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5181 /* clone dgram socket */
5182 newfd
= net_socket_mcast_create(&saddr
);
5184 /* error already reported by net_socket_mcast_create() */
5188 /* clone newfd to fd, close newfd */
5193 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5194 fd
, strerror(errno
));
5199 s
= qemu_mallocz(sizeof(NetSocketState
));
5204 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
5205 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
5207 /* mcast: save bound address as dst */
5208 if (is_connected
) s
->dgram_dst
=saddr
;
5210 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5211 "socket: fd=%d (%s mcast=%s:%d)",
5212 fd
, is_connected
? "cloned" : "",
5213 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5217 static void net_socket_connect(void *opaque
)
5219 NetSocketState
*s
= opaque
;
5220 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5223 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5227 s
= qemu_mallocz(sizeof(NetSocketState
));
5231 s
->vc
= qemu_new_vlan_client(vlan
,
5232 net_socket_receive
, NULL
, s
);
5233 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5234 "socket: fd=%d", fd
);
5236 net_socket_connect(s
);
5238 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5243 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5246 int so_type
=-1, optlen
=sizeof(so_type
);
5248 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5249 (socklen_t
*)&optlen
)< 0) {
5250 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5255 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5257 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5259 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5260 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5261 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5266 static void net_socket_accept(void *opaque
)
5268 NetSocketListenState
*s
= opaque
;
5270 struct sockaddr_in saddr
;
5275 len
= sizeof(saddr
);
5276 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5277 if (fd
< 0 && errno
!= EINTR
) {
5279 } else if (fd
>= 0) {
5283 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5287 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5288 "socket: connection from %s:%d",
5289 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5293 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5295 NetSocketListenState
*s
;
5297 struct sockaddr_in saddr
;
5299 if (parse_host_port(&saddr
, host_str
) < 0)
5302 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5306 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5311 socket_set_nonblock(fd
);
5313 /* allow fast reuse */
5315 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5317 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5322 ret
= listen(fd
, 0);
5329 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5333 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5336 int fd
, connected
, ret
, err
;
5337 struct sockaddr_in saddr
;
5339 if (parse_host_port(&saddr
, host_str
) < 0)
5342 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5347 socket_set_nonblock(fd
);
5351 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5353 err
= socket_error();
5354 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5355 } else if (err
== EINPROGRESS
) {
5358 } else if (err
== WSAEALREADY
) {
5371 s
= net_socket_fd_init(vlan
, fd
, connected
);
5374 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5375 "socket: connect to %s:%d",
5376 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5380 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5384 struct sockaddr_in saddr
;
5386 if (parse_host_port(&saddr
, host_str
) < 0)
5390 fd
= net_socket_mcast_create(&saddr
);
5394 s
= net_socket_fd_init(vlan
, fd
, 0);
5398 s
->dgram_dst
= saddr
;
5400 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5401 "socket: mcast=%s:%d",
5402 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5407 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5412 while (*p
!= '\0' && *p
!= '=') {
5413 if (q
&& (q
- buf
) < buf_size
- 1)
5423 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5428 while (*p
!= '\0') {
5430 if (*(p
+ 1) != ',')
5434 if (q
&& (q
- buf
) < buf_size
- 1)
5444 int get_param_value(char *buf
, int buf_size
,
5445 const char *tag
, const char *str
)
5452 p
= get_opt_name(option
, sizeof(option
), p
);
5456 if (!strcmp(tag
, option
)) {
5457 (void)get_opt_value(buf
, buf_size
, p
);
5460 p
= get_opt_value(NULL
, 0, p
);
5469 int check_params(char *buf
, int buf_size
,
5470 const char * const *params
, const char *str
)
5477 p
= get_opt_name(buf
, buf_size
, p
);
5481 for(i
= 0; params
[i
] != NULL
; i
++)
5482 if (!strcmp(params
[i
], buf
))
5484 if (params
[i
] == NULL
)
5486 p
= get_opt_value(NULL
, 0, p
);
5494 static int nic_get_free_idx(void)
5498 for (index
= 0; index
< MAX_NICS
; index
++)
5499 if (!nd_table
[index
].used
)
5504 int net_client_init(const char *device
, const char *p
)
5511 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5512 vlan_id
= strtol(buf
, NULL
, 0);
5514 vlan
= qemu_find_vlan(vlan_id
);
5516 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5519 if (!strcmp(device
, "nic")) {
5522 int idx
= nic_get_free_idx();
5524 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5525 fprintf(stderr
, "Too Many NICs\n");
5528 nd
= &nd_table
[idx
];
5529 macaddr
= nd
->macaddr
;
5535 macaddr
[5] = 0x56 + idx
;
5537 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5538 if (parse_macaddr(macaddr
, buf
) < 0) {
5539 fprintf(stderr
, "invalid syntax for ethernet address\n");
5543 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5544 nd
->model
= strdup(buf
);
5549 vlan
->nb_guest_devs
++;
5552 if (!strcmp(device
, "none")) {
5553 /* does nothing. It is needed to signal that no network cards
5558 if (!strcmp(device
, "user")) {
5559 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5560 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5562 vlan
->nb_host_devs
++;
5563 ret
= net_slirp_init(vlan
);
5567 if (!strcmp(device
, "tap")) {
5569 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5570 fprintf(stderr
, "tap: no interface name\n");
5573 vlan
->nb_host_devs
++;
5574 ret
= tap_win32_init(vlan
, ifname
);
5577 if (!strcmp(device
, "tap")) {
5579 char setup_script
[1024], down_script
[1024];
5581 vlan
->nb_host_devs
++;
5582 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5583 fd
= strtol(buf
, NULL
, 0);
5584 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5586 if (net_tap_fd_init(vlan
, fd
, tap_probe_vnet_hdr(fd
)))
5589 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5592 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5593 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5595 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5596 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5598 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5602 if (!strcmp(device
, "socket")) {
5603 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5605 fd
= strtol(buf
, NULL
, 0);
5607 if (net_socket_fd_init(vlan
, fd
, 1))
5609 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5610 ret
= net_socket_listen_init(vlan
, buf
);
5611 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5612 ret
= net_socket_connect_init(vlan
, buf
);
5613 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5614 ret
= net_socket_mcast_init(vlan
, buf
);
5616 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5619 vlan
->nb_host_devs
++;
5622 if (!strcmp(device
, "vde")) {
5623 char vde_sock
[1024], vde_group
[512];
5624 int vde_port
, vde_mode
;
5625 vlan
->nb_host_devs
++;
5626 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5629 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5630 vde_port
= strtol(buf
, NULL
, 10);
5634 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5635 vde_group
[0] = '\0';
5637 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5638 vde_mode
= strtol(buf
, NULL
, 8);
5642 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5646 fprintf(stderr
, "Unknown network device: %s\n", device
);
5650 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5656 void net_client_uninit(NICInfo
*nd
)
5658 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5661 free((void *)nd
->model
);
5664 static int net_client_parse(const char *str
)
5672 while (*p
!= '\0' && *p
!= ',') {
5673 if ((q
- device
) < sizeof(device
) - 1)
5681 return net_client_init(device
, p
);
5684 void do_info_network(void)
5687 VLANClientState
*vc
;
5689 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5690 term_printf("VLAN %d devices:\n", vlan
->id
);
5691 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5692 term_printf(" %s\n", vc
->info_str
);
5696 #define HD_ALIAS "index=%d,media=disk"
5698 #define CDROM_ALIAS "index=1,media=cdrom"
5700 #define CDROM_ALIAS "index=2,media=cdrom"
5702 #define FD_ALIAS "index=%d,if=floppy"
5703 #define PFLASH_ALIAS "if=pflash"
5704 #define MTD_ALIAS "if=mtd"
5705 #define SD_ALIAS "index=0,if=sd"
5707 static int drive_opt_get_free_idx(void)
5711 for (index
= 0; index
< MAX_DRIVES
; index
++)
5712 if (!drives_opt
[index
].used
) {
5713 drives_opt
[index
].used
= 1;
5720 static int drive_get_free_idx(void)
5724 for (index
= 0; index
< MAX_DRIVES
; index
++)
5725 if (!drives_table
[index
].used
) {
5726 drives_table
[index
].used
= 1;
5733 int drive_add(const char *file
, const char *fmt
, ...)
5736 int index
= drive_opt_get_free_idx();
5738 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5739 fprintf(stderr
, "qemu: too many drives\n");
5743 drives_opt
[index
].file
= file
;
5745 vsnprintf(drives_opt
[index
].opt
,
5746 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5753 void drive_remove(int index
)
5755 drives_opt
[index
].used
= 0;
5759 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5763 /* seek interface, bus and unit */
5765 for (index
= 0; index
< MAX_DRIVES
; index
++)
5766 if (drives_table
[index
].type
== type
&&
5767 drives_table
[index
].bus
== bus
&&
5768 drives_table
[index
].unit
== unit
&&
5769 drives_table
[index
].used
)
5775 int drive_get_max_bus(BlockInterfaceType type
)
5781 for (index
= 0; index
< nb_drives
; index
++) {
5782 if(drives_table
[index
].type
== type
&&
5783 drives_table
[index
].bus
> max_bus
)
5784 max_bus
= drives_table
[index
].bus
;
5789 static void bdrv_format_print(void *opaque
, const char *name
)
5791 fprintf(stderr
, " %s", name
);
5794 void drive_uninit(BlockDriverState
*bdrv
)
5798 for (i
= 0; i
< MAX_DRIVES
; i
++)
5799 if (drives_table
[i
].bdrv
== bdrv
) {
5800 drives_table
[i
].bdrv
= NULL
;
5801 drives_table
[i
].used
= 0;
5802 drive_remove(drives_table
[i
].drive_opt_idx
);
5808 int drive_init(struct drive_opt
*arg
, int snapshot
,
5809 QEMUMachine
*machine
)
5814 const char *mediastr
= "";
5815 BlockInterfaceType type
;
5816 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5817 int bus_id
, unit_id
;
5818 int cyls
, heads
, secs
, translation
;
5819 BlockDriverState
*bdrv
;
5820 BlockDriver
*drv
= NULL
;
5825 int drives_table_idx
;
5826 char *str
= arg
->opt
;
5827 static const char * const params
[] = { "bus", "unit", "if", "index",
5828 "cyls", "heads", "secs", "trans",
5829 "media", "snapshot", "file",
5830 "cache", "format", "boot", NULL
};
5832 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5833 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5839 cyls
= heads
= secs
= 0;
5842 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5846 if (!strcmp(machine
->name
, "realview") ||
5847 !strcmp(machine
->name
, "SS-5") ||
5848 !strcmp(machine
->name
, "SS-10") ||
5849 !strcmp(machine
->name
, "SS-600MP") ||
5850 !strcmp(machine
->name
, "versatilepb") ||
5851 !strcmp(machine
->name
, "versatileab")) {
5853 max_devs
= MAX_SCSI_DEVS
;
5854 pstrcpy(devname
, sizeof(devname
), "scsi");
5857 max_devs
= MAX_IDE_DEVS
;
5858 pstrcpy(devname
, sizeof(devname
), "ide");
5862 /* extract parameters */
5864 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5865 bus_id
= strtol(buf
, NULL
, 0);
5867 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5872 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5873 unit_id
= strtol(buf
, NULL
, 0);
5875 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5880 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5881 pstrcpy(devname
, sizeof(devname
), buf
);
5882 if (!strcmp(buf
, "ide")) {
5884 max_devs
= MAX_IDE_DEVS
;
5885 } else if (!strcmp(buf
, "scsi")) {
5887 max_devs
= MAX_SCSI_DEVS
;
5888 } else if (!strcmp(buf
, "floppy")) {
5891 } else if (!strcmp(buf
, "pflash")) {
5894 } else if (!strcmp(buf
, "mtd")) {
5897 } else if (!strcmp(buf
, "sd")) {
5900 } else if (!strcmp(buf
, "virtio")) {
5904 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5909 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5910 index
= strtol(buf
, NULL
, 0);
5912 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5917 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5918 cyls
= strtol(buf
, NULL
, 0);
5921 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5922 heads
= strtol(buf
, NULL
, 0);
5925 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5926 secs
= strtol(buf
, NULL
, 0);
5929 if (cyls
|| heads
|| secs
) {
5930 if (cyls
< 1 || cyls
> 16383) {
5931 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5934 if (heads
< 1 || heads
> 16) {
5935 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5938 if (secs
< 1 || secs
> 63) {
5939 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5944 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5947 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5951 if (!strcmp(buf
, "none"))
5952 translation
= BIOS_ATA_TRANSLATION_NONE
;
5953 else if (!strcmp(buf
, "lba"))
5954 translation
= BIOS_ATA_TRANSLATION_LBA
;
5955 else if (!strcmp(buf
, "auto"))
5956 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5958 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5963 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5964 if (!strcmp(buf
, "disk")) {
5966 } else if (!strcmp(buf
, "cdrom")) {
5967 if (cyls
|| secs
|| heads
) {
5969 "qemu: '%s' invalid physical CHS format\n", str
);
5972 media
= MEDIA_CDROM
;
5974 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5979 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5980 if (!strcmp(buf
, "on"))
5982 else if (!strcmp(buf
, "off"))
5985 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5990 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5991 if (!strcmp(buf
, "off"))
5993 else if (!strcmp(buf
, "on"))
5996 fprintf(stderr
, "qemu: invalid cache option\n");
6001 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
6002 if (strcmp(buf
, "?") == 0) {
6003 fprintf(stderr
, "qemu: Supported formats:");
6004 bdrv_iterate_format(bdrv_format_print
, NULL
);
6005 fprintf(stderr
, "\n");
6008 drv
= bdrv_find_format(buf
);
6010 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
6015 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
6016 if (!strcmp(buf
, "on")) {
6017 if (extboot_drive
!= -1) {
6018 fprintf(stderr
, "qemu: two bootable drives specified\n");
6021 extboot_drive
= nb_drives
;
6022 } else if (strcmp(buf
, "off")) {
6023 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
6028 if (arg
->file
== NULL
)
6029 get_param_value(file
, sizeof(file
), "file", str
);
6031 pstrcpy(file
, sizeof(file
), arg
->file
);
6033 /* compute bus and unit according index */
6036 if (bus_id
!= 0 || unit_id
!= -1) {
6038 "qemu: '%s' index cannot be used with bus and unit\n", str
);
6046 unit_id
= index
% max_devs
;
6047 bus_id
= index
/ max_devs
;
6051 /* if user doesn't specify a unit_id,
6052 * try to find the first free
6055 if (unit_id
== -1) {
6057 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
6059 if (max_devs
&& unit_id
>= max_devs
) {
6060 unit_id
-= max_devs
;
6068 if (max_devs
&& unit_id
>= max_devs
) {
6069 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
6070 str
, unit_id
, max_devs
- 1);
6075 * ignore multiple definitions
6078 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
6083 if (type
== IF_IDE
|| type
== IF_SCSI
)
6084 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
6086 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
6087 devname
, bus_id
, mediastr
, unit_id
);
6089 snprintf(buf
, sizeof(buf
), "%s%s%i",
6090 devname
, mediastr
, unit_id
);
6091 bdrv
= bdrv_new(buf
);
6092 drives_table_idx
= drive_get_free_idx();
6093 drives_table
[drives_table_idx
].bdrv
= bdrv
;
6094 drives_table
[drives_table_idx
].type
= type
;
6095 drives_table
[drives_table_idx
].bus
= bus_id
;
6096 drives_table
[drives_table_idx
].unit
= unit_id
;
6097 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
6106 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
6107 bdrv_set_translation_hint(bdrv
, translation
);
6111 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
6116 /* FIXME: This isn't really a floppy, but it's a reasonable
6119 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
6130 bdrv_flags
|= BDRV_O_SNAPSHOT
;
6132 bdrv_flags
|= BDRV_O_DIRECT
;
6133 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
6134 fprintf(stderr
, "qemu: could not open disk image %s\n",
6138 return drives_table_idx
;
6141 /***********************************************************/
6144 static USBPort
*used_usb_ports
;
6145 static USBPort
*free_usb_ports
;
6147 /* ??? Maybe change this to register a hub to keep track of the topology. */
6148 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
6149 usb_attachfn attach
)
6151 port
->opaque
= opaque
;
6152 port
->index
= index
;
6153 port
->attach
= attach
;
6154 port
->next
= free_usb_ports
;
6155 free_usb_ports
= port
;
6158 int usb_device_add_dev(USBDevice
*dev
)
6162 /* Find a USB port to add the device to. */
6163 port
= free_usb_ports
;
6167 /* Create a new hub and chain it on. */
6168 free_usb_ports
= NULL
;
6169 port
->next
= used_usb_ports
;
6170 used_usb_ports
= port
;
6172 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
6173 usb_attach(port
, hub
);
6174 port
= free_usb_ports
;
6177 free_usb_ports
= port
->next
;
6178 port
->next
= used_usb_ports
;
6179 used_usb_ports
= port
;
6180 usb_attach(port
, dev
);
6184 static int usb_device_add(const char *devname
)
6189 if (!free_usb_ports
)
6192 if (strstart(devname
, "host:", &p
)) {
6193 dev
= usb_host_device_open(p
);
6194 } else if (!strcmp(devname
, "mouse")) {
6195 dev
= usb_mouse_init();
6196 } else if (!strcmp(devname
, "tablet")) {
6197 dev
= usb_tablet_init();
6198 } else if (!strcmp(devname
, "keyboard")) {
6199 dev
= usb_keyboard_init();
6200 } else if (strstart(devname
, "disk:", &p
)) {
6201 dev
= usb_msd_init(p
);
6202 } else if (!strcmp(devname
, "wacom-tablet")) {
6203 dev
= usb_wacom_init();
6204 } else if (strstart(devname
, "serial:", &p
)) {
6205 dev
= usb_serial_init(p
);
6206 #ifdef CONFIG_BRLAPI
6207 } else if (!strcmp(devname
, "braille")) {
6208 dev
= usb_baum_init();
6210 } else if (strstart(devname
, "net:", &p
)) {
6213 if (net_client_init("nic", p
) < 0)
6215 nd_table
[nic
].model
= "usb";
6216 dev
= usb_net_init(&nd_table
[nic
]);
6223 return usb_device_add_dev(dev
);
6226 int usb_device_del_addr(int bus_num
, int addr
)
6232 if (!used_usb_ports
)
6238 lastp
= &used_usb_ports
;
6239 port
= used_usb_ports
;
6240 while (port
&& port
->dev
->addr
!= addr
) {
6241 lastp
= &port
->next
;
6249 *lastp
= port
->next
;
6250 usb_attach(port
, NULL
);
6251 dev
->handle_destroy(dev
);
6252 port
->next
= free_usb_ports
;
6253 free_usb_ports
= port
;
6257 static int usb_device_del(const char *devname
)
6262 if (strstart(devname
, "host:", &p
))
6263 return usb_host_device_close(p
);
6265 if (!used_usb_ports
)
6268 p
= strchr(devname
, '.');
6271 bus_num
= strtoul(devname
, NULL
, 0);
6272 addr
= strtoul(p
+ 1, NULL
, 0);
6274 return usb_device_del_addr(bus_num
, addr
);
6277 void do_usb_add(const char *devname
)
6279 usb_device_add(devname
);
6282 void do_usb_del(const char *devname
)
6284 usb_device_del(devname
);
6291 const char *speed_str
;
6294 term_printf("USB support not enabled\n");
6298 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6302 switch(dev
->speed
) {
6306 case USB_SPEED_FULL
:
6309 case USB_SPEED_HIGH
:
6316 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6317 0, dev
->addr
, speed_str
, dev
->devname
);
6321 /***********************************************************/
6322 /* PCMCIA/Cardbus */
6324 static struct pcmcia_socket_entry_s
{
6325 struct pcmcia_socket_s
*socket
;
6326 struct pcmcia_socket_entry_s
*next
;
6327 } *pcmcia_sockets
= 0;
6329 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6331 struct pcmcia_socket_entry_s
*entry
;
6333 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6334 entry
->socket
= socket
;
6335 entry
->next
= pcmcia_sockets
;
6336 pcmcia_sockets
= entry
;
6339 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6341 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6343 ptr
= &pcmcia_sockets
;
6344 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6345 if (entry
->socket
== socket
) {
6351 void pcmcia_info(void)
6353 struct pcmcia_socket_entry_s
*iter
;
6354 if (!pcmcia_sockets
)
6355 term_printf("No PCMCIA sockets\n");
6357 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6358 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6359 iter
->socket
->attached
? iter
->socket
->card_string
:
6363 /***********************************************************/
6366 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6370 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6374 static void dumb_refresh(DisplayState
*ds
)
6376 #if defined(CONFIG_SDL)
6381 static void dumb_display_init(DisplayState
*ds
)
6386 ds
->dpy_update
= dumb_update
;
6387 ds
->dpy_resize
= dumb_resize
;
6388 ds
->dpy_refresh
= dumb_refresh
;
6389 ds
->gui_timer_interval
= 500;
6393 /***********************************************************/
6396 #define MAX_IO_HANDLERS 64
6398 typedef struct IOHandlerRecord
{
6400 IOCanRWHandler
*fd_read_poll
;
6402 IOHandler
*fd_write
;
6405 /* temporary data */
6407 struct IOHandlerRecord
*next
;
6410 static IOHandlerRecord
*first_io_handler
;
6412 /* XXX: fd_read_poll should be suppressed, but an API change is
6413 necessary in the character devices to suppress fd_can_read(). */
6414 int qemu_set_fd_handler2(int fd
,
6415 IOCanRWHandler
*fd_read_poll
,
6417 IOHandler
*fd_write
,
6420 IOHandlerRecord
**pioh
, *ioh
;
6422 if (!fd_read
&& !fd_write
) {
6423 pioh
= &first_io_handler
;
6428 if (ioh
->fd
== fd
) {
6435 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6439 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6442 ioh
->next
= first_io_handler
;
6443 first_io_handler
= ioh
;
6446 ioh
->fd_read_poll
= fd_read_poll
;
6447 ioh
->fd_read
= fd_read
;
6448 ioh
->fd_write
= fd_write
;
6449 ioh
->opaque
= opaque
;
6456 int qemu_set_fd_handler(int fd
,
6458 IOHandler
*fd_write
,
6461 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6464 /***********************************************************/
6465 /* Polling handling */
6467 typedef struct PollingEntry
{
6470 struct PollingEntry
*next
;
6473 static PollingEntry
*first_polling_entry
;
6475 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6477 PollingEntry
**ppe
, *pe
;
6478 pe
= qemu_mallocz(sizeof(PollingEntry
));
6482 pe
->opaque
= opaque
;
6483 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6488 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6490 PollingEntry
**ppe
, *pe
;
6491 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6493 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6502 /***********************************************************/
6503 /* Wait objects support */
6504 typedef struct WaitObjects
{
6506 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6507 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6508 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6511 static WaitObjects wait_objects
= {0};
6513 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6515 WaitObjects
*w
= &wait_objects
;
6517 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6519 w
->events
[w
->num
] = handle
;
6520 w
->func
[w
->num
] = func
;
6521 w
->opaque
[w
->num
] = opaque
;
6526 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6529 WaitObjects
*w
= &wait_objects
;
6532 for (i
= 0; i
< w
->num
; i
++) {
6533 if (w
->events
[i
] == handle
)
6536 w
->events
[i
] = w
->events
[i
+ 1];
6537 w
->func
[i
] = w
->func
[i
+ 1];
6538 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6546 #define SELF_ANNOUNCE_ROUNDS 5
6547 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6548 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6549 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6551 static int announce_self_create(uint8_t *buf
,
6554 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6555 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6557 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6559 memset(buf
, 0xff, 6); /* h_dst */
6560 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6561 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6562 memcpy(buf
+ 14, &magic
, 4); /* magic */
6564 return 18; /* len */
6567 static void qemu_announce_self(void)
6571 VLANClientState
*vc
;
6574 for (i
= 0; i
< nb_nics
; i
++) {
6575 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6576 vlan
= nd_table
[i
].vlan
;
6577 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6578 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6579 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6580 vc
->fd_read(vc
->opaque
, buf
, len
);
6585 /***********************************************************/
6586 /* savevm/loadvm support */
6588 #define IO_BUF_SIZE 32768
6591 QEMUFilePutBufferFunc
*put_buffer
;
6592 QEMUFileGetBufferFunc
*get_buffer
;
6593 QEMUFileCloseFunc
*close
;
6596 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6599 int buf_size
; /* 0 when writing */
6600 uint8_t buf
[IO_BUF_SIZE
];
6603 typedef struct QEMUFileFD
6608 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6610 QEMUFileFD
*s
= opaque
;
6615 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6617 if (errno
== EINTR
|| errno
== EAGAIN
)
6624 QEMUFile
*qemu_fopen_fd(int fd
)
6626 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6628 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6631 typedef struct QEMUFileUnix
6636 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6638 QEMUFileUnix
*s
= opaque
;
6639 fseek(s
->outfile
, pos
, SEEK_SET
);
6640 fwrite(buf
, 1, size
, s
->outfile
);
6643 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6645 QEMUFileUnix
*s
= opaque
;
6646 fseek(s
->outfile
, pos
, SEEK_SET
);
6647 return fread(buf
, 1, size
, s
->outfile
);
6650 static void file_close(void *opaque
)
6652 QEMUFileUnix
*s
= opaque
;
6657 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6661 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6665 s
->outfile
= fopen(filename
, mode
);
6669 if (!strcmp(mode
, "wb"))
6670 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6671 else if (!strcmp(mode
, "rb"))
6672 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6681 typedef struct QEMUFileBdrv
6683 BlockDriverState
*bs
;
6684 int64_t base_offset
;
6687 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6689 QEMUFileBdrv
*s
= opaque
;
6690 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6693 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6695 QEMUFileBdrv
*s
= opaque
;
6696 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6699 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6703 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6708 s
->base_offset
= offset
;
6711 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6713 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6716 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6717 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6721 f
= qemu_mallocz(sizeof(QEMUFile
));
6726 f
->put_buffer
= put_buffer
;
6727 f
->get_buffer
= get_buffer
;
6733 void qemu_fflush(QEMUFile
*f
)
6738 if (f
->buf_index
> 0) {
6739 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6740 f
->buf_offset
+= f
->buf_index
;
6745 static void qemu_fill_buffer(QEMUFile
*f
)
6752 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6758 f
->buf_offset
+= len
;
6761 void qemu_fclose(QEMUFile
*f
)
6765 f
->close(f
->opaque
);
6769 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, size_t size
)
6773 l
= IO_BUF_SIZE
- f
->buf_index
;
6776 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6780 if (f
->buf_index
>= IO_BUF_SIZE
)
6785 void qemu_put_byte(QEMUFile
*f
, int8_t v
)
6787 f
->buf
[f
->buf_index
++] = v
;
6788 if (f
->buf_index
>= IO_BUF_SIZE
)
6792 size_t qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, size_t size1
)
6798 l
= f
->buf_size
- f
->buf_index
;
6800 qemu_fill_buffer(f
);
6801 l
= f
->buf_size
- f
->buf_index
;
6807 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6812 return size1
- size
;
6815 int8_t qemu_get_byte(QEMUFile
*f
)
6817 if (f
->buf_index
>= f
->buf_size
) {
6818 qemu_fill_buffer(f
);
6819 if (f
->buf_index
>= f
->buf_size
)
6822 return f
->buf
[f
->buf_index
++];
6825 int64_t qemu_ftell(QEMUFile
*f
)
6827 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6830 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6832 if (whence
== SEEK_SET
) {
6834 } else if (whence
== SEEK_CUR
) {
6835 pos
+= qemu_ftell(f
);
6837 /* SEEK_END not supported */
6840 if (f
->put_buffer
) {
6842 f
->buf_offset
= pos
;
6844 f
->buf_offset
= pos
;
6851 void qemu_put_be16(QEMUFile
*f
, uint16_t v
)
6853 qemu_put_byte(f
, v
>> 8);
6854 qemu_put_byte(f
, v
);
6857 void qemu_put_be32(QEMUFile
*f
, uint32_t v
)
6859 qemu_put_byte(f
, v
>> 24);
6860 qemu_put_byte(f
, v
>> 16);
6861 qemu_put_byte(f
, v
>> 8);
6862 qemu_put_byte(f
, v
);
6865 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6867 qemu_put_be32(f
, v
>> 32);
6868 qemu_put_be32(f
, v
);
6871 uint16_t qemu_get_be16(QEMUFile
*f
)
6874 v
= qemu_get_byte(f
) << 8;
6875 v
|= qemu_get_byte(f
);
6879 uint32_t qemu_get_be32(QEMUFile
*f
)
6882 v
= qemu_get_byte(f
) << 24;
6883 v
|= qemu_get_byte(f
) << 16;
6884 v
|= qemu_get_byte(f
) << 8;
6885 v
|= qemu_get_byte(f
);
6889 uint64_t qemu_get_be64(QEMUFile
*f
)
6892 v
= (uint64_t)qemu_get_be32(f
) << 32;
6893 v
|= qemu_get_be32(f
);
6897 typedef struct SaveStateEntry
{
6901 SaveStateHandler
*save_state
;
6902 LoadStateHandler
*load_state
;
6904 struct SaveStateEntry
*next
;
6907 static SaveStateEntry
*first_se
;
6909 /* TODO: Individual devices generally have very little idea about the rest
6910 of the system, so instance_id should be removed/replaced.
6911 Meanwhile pass -1 as instance_id if you do not already have a clearly
6912 distinguishing id for all instances of your device class. */
6913 int register_savevm(const char *idstr
,
6916 SaveStateHandler
*save_state
,
6917 LoadStateHandler
*load_state
,
6920 SaveStateEntry
*se
, **pse
;
6922 se
= qemu_malloc(sizeof(SaveStateEntry
));
6925 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6926 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6927 se
->version_id
= version_id
;
6928 se
->save_state
= save_state
;
6929 se
->load_state
= load_state
;
6930 se
->opaque
= opaque
;
6933 /* add at the end of list */
6935 while (*pse
!= NULL
) {
6936 if (instance_id
== -1
6937 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6938 && se
->instance_id
<= (*pse
)->instance_id
)
6939 se
->instance_id
= (*pse
)->instance_id
+ 1;
6940 pse
= &(*pse
)->next
;
6946 #define QEMU_VM_FILE_MAGIC 0x5145564d
6947 #define QEMU_VM_FILE_VERSION 0x00000002
6949 static int qemu_savevm_state(QEMUFile
*f
)
6953 int64_t cur_pos
, len_pos
, total_len_pos
;
6955 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6956 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6957 total_len_pos
= qemu_ftell(f
);
6958 qemu_put_be64(f
, 0); /* total size */
6960 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6961 if (se
->save_state
== NULL
)
6962 /* this one has a loader only, for backwards compatibility */
6966 len
= strlen(se
->idstr
);
6967 qemu_put_byte(f
, len
);
6968 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6970 qemu_put_be32(f
, se
->instance_id
);
6971 qemu_put_be32(f
, se
->version_id
);
6973 /* record size: filled later */
6974 len_pos
= qemu_ftell(f
);
6975 qemu_put_be32(f
, 0);
6976 se
->save_state(f
, se
->opaque
);
6978 /* fill record size */
6979 cur_pos
= qemu_ftell(f
);
6980 len
= cur_pos
- len_pos
- 4;
6981 qemu_fseek(f
, len_pos
, SEEK_SET
);
6982 qemu_put_be32(f
, len
);
6983 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6985 cur_pos
= qemu_ftell(f
);
6986 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6987 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6988 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6994 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6998 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6999 if (!strcmp(se
->idstr
, idstr
) &&
7000 instance_id
== se
->instance_id
)
7006 static int qemu_loadvm_state(QEMUFile
*f
)
7009 int len
, ret
, instance_id
, record_len
, version_id
;
7010 int64_t total_len
, end_pos
, cur_pos
;
7014 v
= qemu_get_be32(f
);
7015 if (v
!= QEMU_VM_FILE_MAGIC
)
7017 v
= qemu_get_be32(f
);
7018 if (v
!= QEMU_VM_FILE_VERSION
) {
7023 total_len
= qemu_get_be64(f
);
7024 end_pos
= total_len
+ qemu_ftell(f
);
7026 if (qemu_ftell(f
) >= end_pos
)
7028 len
= qemu_get_byte(f
);
7029 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
7031 instance_id
= qemu_get_be32(f
);
7032 version_id
= qemu_get_be32(f
);
7033 record_len
= qemu_get_be32(f
);
7035 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7036 idstr
, instance_id
, version_id
, record_len
);
7038 cur_pos
= qemu_ftell(f
);
7039 se
= find_se(idstr
, instance_id
);
7041 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7042 instance_id
, idstr
);
7044 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7046 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7047 instance_id
, idstr
);
7051 /* always seek to exact end of record */
7052 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
7059 int qemu_live_savevm_state(QEMUFile
*f
)
7064 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
7065 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
7067 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
7068 len
= strlen(se
->idstr
);
7070 qemu_put_byte(f
, len
);
7071 qemu_put_buffer(f
, se
->idstr
, len
);
7072 qemu_put_be32(f
, se
->instance_id
);
7073 qemu_put_be32(f
, se
->version_id
);
7075 se
->save_state(f
, se
->opaque
);
7078 qemu_put_byte(f
, 0);
7084 int qemu_live_loadvm_state(QEMUFile
*f
)
7087 int len
, ret
, instance_id
, version_id
;
7091 v
= qemu_get_be32(f
);
7092 if (v
!= QEMU_VM_FILE_MAGIC
)
7094 v
= qemu_get_be32(f
);
7095 if (v
!= QEMU_VM_FILE_VERSION
) {
7102 len
= qemu_get_byte(f
);
7105 qemu_get_buffer(f
, idstr
, len
);
7107 instance_id
= qemu_get_be32(f
);
7108 version_id
= qemu_get_be32(f
);
7109 se
= find_se(idstr
, instance_id
);
7111 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7112 instance_id
, idstr
);
7114 if (version_id
> se
->version_id
) { /* src version > dst version */
7115 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7116 idstr
, version_id
, se
->version_id
);
7120 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7122 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7123 instance_id
, idstr
);
7130 qemu_announce_self();
7136 /* device can contain snapshots */
7137 static int bdrv_can_snapshot(BlockDriverState
*bs
)
7140 !bdrv_is_removable(bs
) &&
7141 !bdrv_is_read_only(bs
));
7144 /* device must be snapshots in order to have a reliable snapshot */
7145 static int bdrv_has_snapshot(BlockDriverState
*bs
)
7148 !bdrv_is_removable(bs
) &&
7149 !bdrv_is_read_only(bs
));
7152 static BlockDriverState
*get_bs_snapshots(void)
7154 BlockDriverState
*bs
;
7158 return bs_snapshots
;
7159 for(i
= 0; i
<= nb_drives
; i
++) {
7160 bs
= drives_table
[i
].bdrv
;
7161 if (bdrv_can_snapshot(bs
))
7170 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
7173 QEMUSnapshotInfo
*sn_tab
, *sn
;
7177 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7180 for(i
= 0; i
< nb_sns
; i
++) {
7182 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
7192 void do_savevm(const char *name
)
7194 BlockDriverState
*bs
, *bs1
;
7195 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
7196 int must_delete
, ret
, i
;
7197 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7199 int saved_vm_running
;
7206 bs
= get_bs_snapshots();
7208 term_printf("No block device can accept snapshots\n");
7212 /* ??? Should this occur after vm_stop? */
7215 saved_vm_running
= vm_running
;
7220 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
7225 memset(sn
, 0, sizeof(*sn
));
7227 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
7228 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
7231 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
7234 /* fill auxiliary fields */
7237 sn
->date_sec
= tb
.time
;
7238 sn
->date_nsec
= tb
.millitm
* 1000000;
7240 gettimeofday(&tv
, NULL
);
7241 sn
->date_sec
= tv
.tv_sec
;
7242 sn
->date_nsec
= tv
.tv_usec
* 1000;
7244 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7246 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7247 term_printf("Device %s does not support VM state snapshots\n",
7248 bdrv_get_device_name(bs
));
7252 /* save the VM state */
7253 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7255 term_printf("Could not open VM state file\n");
7258 ret
= qemu_savevm_state(f
);
7259 sn
->vm_state_size
= qemu_ftell(f
);
7262 term_printf("Error %d while writing VM\n", ret
);
7266 /* create the snapshots */
7268 for(i
= 0; i
< nb_drives
; i
++) {
7269 bs1
= drives_table
[i
].bdrv
;
7270 if (bdrv_has_snapshot(bs1
)) {
7272 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7274 term_printf("Error while deleting snapshot on '%s'\n",
7275 bdrv_get_device_name(bs1
));
7278 ret
= bdrv_snapshot_create(bs1
, sn
);
7280 term_printf("Error while creating snapshot on '%s'\n",
7281 bdrv_get_device_name(bs1
));
7287 if (saved_vm_running
)
7291 void do_loadvm(const char *name
)
7293 BlockDriverState
*bs
, *bs1
;
7294 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7297 int saved_vm_running
;
7299 bs
= get_bs_snapshots();
7301 term_printf("No block device supports snapshots\n");
7305 /* Flush all IO requests so they don't interfere with the new state. */
7308 saved_vm_running
= vm_running
;
7311 for(i
= 0; i
<= nb_drives
; i
++) {
7312 bs1
= drives_table
[i
].bdrv
;
7313 if (bdrv_has_snapshot(bs1
)) {
7314 ret
= bdrv_snapshot_goto(bs1
, name
);
7317 term_printf("Warning: ");
7320 term_printf("Snapshots not supported on device '%s'\n",
7321 bdrv_get_device_name(bs1
));
7324 term_printf("Could not find snapshot '%s' on device '%s'\n",
7325 name
, bdrv_get_device_name(bs1
));
7328 term_printf("Error %d while activating snapshot on '%s'\n",
7329 ret
, bdrv_get_device_name(bs1
));
7332 /* fatal on snapshot block device */
7339 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7340 term_printf("Device %s does not support VM state snapshots\n",
7341 bdrv_get_device_name(bs
));
7345 /* restore the VM state */
7346 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7348 term_printf("Could not open VM state file\n");
7351 ret
= qemu_loadvm_state(f
);
7354 term_printf("Error %d while loading VM state\n", ret
);
7357 if (saved_vm_running
)
7361 void do_delvm(const char *name
)
7363 BlockDriverState
*bs
, *bs1
;
7366 bs
= get_bs_snapshots();
7368 term_printf("No block device supports snapshots\n");
7372 for(i
= 0; i
<= nb_drives
; i
++) {
7373 bs1
= drives_table
[i
].bdrv
;
7374 if (bdrv_has_snapshot(bs1
)) {
7375 ret
= bdrv_snapshot_delete(bs1
, name
);
7377 if (ret
== -ENOTSUP
)
7378 term_printf("Snapshots not supported on device '%s'\n",
7379 bdrv_get_device_name(bs1
));
7381 term_printf("Error %d while deleting snapshot on '%s'\n",
7382 ret
, bdrv_get_device_name(bs1
));
7388 void do_info_snapshots(void)
7390 BlockDriverState
*bs
, *bs1
;
7391 QEMUSnapshotInfo
*sn_tab
, *sn
;
7395 bs
= get_bs_snapshots();
7397 term_printf("No available block device supports snapshots\n");
7400 term_printf("Snapshot devices:");
7401 for(i
= 0; i
<= nb_drives
; i
++) {
7402 bs1
= drives_table
[i
].bdrv
;
7403 if (bdrv_has_snapshot(bs1
)) {
7405 term_printf(" %s", bdrv_get_device_name(bs1
));
7410 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7412 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7415 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7416 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7417 for(i
= 0; i
< nb_sns
; i
++) {
7419 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7424 /***********************************************************/
7425 /* ram save/restore */
7427 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7431 v
= qemu_get_byte(f
);
7434 if (qemu_get_buffer(f
, buf
, len
) != len
)
7438 v
= qemu_get_byte(f
);
7439 memset(buf
, v
, len
);
7447 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7452 if (qemu_get_be32(f
) != phys_ram_size
)
7454 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7455 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7457 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7464 #define BDRV_HASH_BLOCK_SIZE 1024
7465 #define IOBUF_SIZE 4096
7466 #define RAM_CBLOCK_MAGIC 0xfabe
7468 typedef struct RamCompressState
{
7471 uint8_t buf
[IOBUF_SIZE
];
7474 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7477 memset(s
, 0, sizeof(*s
));
7479 ret
= deflateInit2(&s
->zstream
, 1,
7481 9, Z_DEFAULT_STRATEGY
);
7484 s
->zstream
.avail_out
= IOBUF_SIZE
;
7485 s
->zstream
.next_out
= s
->buf
;
7489 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7491 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7492 qemu_put_be16(s
->f
, len
);
7493 qemu_put_buffer(s
->f
, buf
, len
);
7496 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7500 s
->zstream
.avail_in
= len
;
7501 s
->zstream
.next_in
= (uint8_t *)buf
;
7502 while (s
->zstream
.avail_in
> 0) {
7503 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7506 if (s
->zstream
.avail_out
== 0) {
7507 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7508 s
->zstream
.avail_out
= IOBUF_SIZE
;
7509 s
->zstream
.next_out
= s
->buf
;
7515 static void ram_compress_close(RamCompressState
*s
)
7519 /* compress last bytes */
7521 ret
= deflate(&s
->zstream
, Z_FINISH
);
7522 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7523 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7525 ram_put_cblock(s
, s
->buf
, len
);
7527 s
->zstream
.avail_out
= IOBUF_SIZE
;
7528 s
->zstream
.next_out
= s
->buf
;
7529 if (ret
== Z_STREAM_END
)
7536 deflateEnd(&s
->zstream
);
7539 typedef struct RamDecompressState
{
7542 uint8_t buf
[IOBUF_SIZE
];
7543 } RamDecompressState
;
7545 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7548 memset(s
, 0, sizeof(*s
));
7550 ret
= inflateInit(&s
->zstream
);
7556 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7560 s
->zstream
.avail_out
= len
;
7561 s
->zstream
.next_out
= buf
;
7562 while (s
->zstream
.avail_out
> 0) {
7563 if (s
->zstream
.avail_in
== 0) {
7564 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7566 clen
= qemu_get_be16(s
->f
);
7567 if (clen
> IOBUF_SIZE
)
7569 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7570 s
->zstream
.avail_in
= clen
;
7571 s
->zstream
.next_in
= s
->buf
;
7573 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7574 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7581 static void ram_decompress_close(RamDecompressState
*s
)
7583 inflateEnd(&s
->zstream
);
7586 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7590 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7591 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7593 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7594 qemu_put_be32(f
, addr
);
7595 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7598 qemu_put_be32(f
, 1);
7601 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7604 RamCompressState s1
, *s
= &s1
;
7607 qemu_put_be32(f
, phys_ram_size
);
7608 if (ram_compress_open(s
, f
) < 0)
7610 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7611 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7614 if (tight_savevm_enabled
) {
7618 /* find if the memory block is available on a virtual
7621 for(j
= 0; j
< nb_drives
; j
++) {
7622 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7624 BDRV_HASH_BLOCK_SIZE
);
7625 if (sector_num
>= 0)
7629 goto normal_compress
;
7632 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7633 ram_compress_buf(s
, buf
, 10);
7639 ram_compress_buf(s
, buf
, 1);
7640 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7643 ram_compress_close(s
);
7646 static void ram_save(QEMUFile
*f
, void *opaque
)
7648 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7650 qemu_put_byte(f
, in_migration
);
7653 ram_save_live(f
, opaque
);
7655 ram_save_static(f
, opaque
);
7658 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7663 addr
= qemu_get_be32(f
);
7667 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7673 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7675 RamDecompressState s1
, *s
= &s1
;
7679 if (qemu_get_be32(f
) != phys_ram_size
)
7681 if (ram_decompress_open(s
, f
) < 0)
7683 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7684 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7686 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7687 fprintf(stderr
, "Error while reading ram block header\n");
7691 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7692 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7701 ram_decompress_buf(s
, buf
+ 1, 9);
7703 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7704 if (bs_index
>= nb_drives
) {
7705 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7708 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7710 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7711 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7712 bs_index
, sector_num
);
7719 printf("Error block header\n");
7723 ram_decompress_close(s
);
7727 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7731 switch (version_id
) {
7733 ret
= ram_load_v1(f
, opaque
);
7736 if (qemu_get_byte(f
)) {
7737 ret
= ram_load_live(f
, opaque
);
7741 ret
= ram_load_static(f
, opaque
);
7751 /***********************************************************/
7752 /* bottom halves (can be seen as timers which expire ASAP) */
7761 static QEMUBH
*first_bh
= NULL
;
7763 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7766 bh
= qemu_mallocz(sizeof(QEMUBH
));
7770 bh
->opaque
= opaque
;
7774 int qemu_bh_poll(void)
7793 void qemu_bh_schedule(QEMUBH
*bh
)
7795 CPUState
*env
= cpu_single_env
;
7799 bh
->next
= first_bh
;
7802 /* stop the currently executing CPU to execute the BH ASAP */
7804 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7809 void qemu_bh_cancel(QEMUBH
*bh
)
7812 if (bh
->scheduled
) {
7815 pbh
= &(*pbh
)->next
;
7821 void qemu_bh_delete(QEMUBH
*bh
)
7827 /***********************************************************/
7828 /* machine registration */
7830 QEMUMachine
*first_machine
= NULL
;
7831 QEMUMachine
*current_machine
= NULL
;
7833 int qemu_register_machine(QEMUMachine
*m
)
7836 pm
= &first_machine
;
7844 static QEMUMachine
*find_machine(const char *name
)
7848 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7849 if (!strcmp(m
->name
, name
))
7855 /***********************************************************/
7856 /* main execution loop */
7858 static void gui_update(void *opaque
)
7860 DisplayState
*ds
= opaque
;
7861 ds
->dpy_refresh(ds
);
7862 qemu_mod_timer(ds
->gui_timer
,
7863 (ds
->gui_timer_interval
?
7864 ds
->gui_timer_interval
:
7865 GUI_REFRESH_INTERVAL
)
7866 + qemu_get_clock(rt_clock
));
7869 struct vm_change_state_entry
{
7870 VMChangeStateHandler
*cb
;
7872 LIST_ENTRY (vm_change_state_entry
) entries
;
7875 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7877 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7880 VMChangeStateEntry
*e
;
7882 e
= qemu_mallocz(sizeof (*e
));
7888 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7892 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7894 LIST_REMOVE (e
, entries
);
7898 static void vm_state_notify(int running
)
7900 VMChangeStateEntry
*e
;
7902 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7903 e
->cb(e
->opaque
, running
);
7907 /* XXX: support several handlers */
7908 static VMStopHandler
*vm_stop_cb
;
7909 static void *vm_stop_opaque
;
7911 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7914 vm_stop_opaque
= opaque
;
7918 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7929 qemu_rearm_alarm_timer(alarm_timer
);
7933 void vm_stop(int reason
)
7936 cpu_disable_ticks();
7940 vm_stop_cb(vm_stop_opaque
, reason
);
7947 /* reset/shutdown handler */
7949 typedef struct QEMUResetEntry
{
7950 QEMUResetHandler
*func
;
7952 struct QEMUResetEntry
*next
;
7955 static QEMUResetEntry
*first_reset_entry
;
7956 static int reset_requested
;
7957 static int shutdown_requested
;
7958 static int powerdown_requested
;
7960 int qemu_shutdown_requested(void)
7962 int r
= shutdown_requested
;
7963 shutdown_requested
= 0;
7967 int qemu_reset_requested(void)
7969 int r
= reset_requested
;
7970 reset_requested
= 0;
7974 int qemu_powerdown_requested(void)
7976 int r
= powerdown_requested
;
7977 powerdown_requested
= 0;
7981 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7983 QEMUResetEntry
**pre
, *re
;
7985 pre
= &first_reset_entry
;
7986 while (*pre
!= NULL
)
7987 pre
= &(*pre
)->next
;
7988 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7990 re
->opaque
= opaque
;
7995 void qemu_system_reset(void)
7999 /* reset all devices */
8000 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
8001 re
->func(re
->opaque
);
8005 void qemu_system_reset_request(void)
8008 shutdown_requested
= 1;
8010 reset_requested
= 1;
8013 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8017 void qemu_system_shutdown_request(void)
8019 shutdown_requested
= 1;
8021 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8024 void qemu_system_powerdown_request(void)
8026 powerdown_requested
= 1;
8028 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
8031 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
8036 /* KVM holds a mutex while QEMU code is running, we need hooks to
8037 release the mutex whenever QEMU code sleeps. */
8041 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
8048 void main_loop_wait(int timeout
)
8050 IOHandlerRecord
*ioh
;
8051 fd_set rfds
, wfds
, xfds
;
8060 /* XXX: need to suppress polling by better using win32 events */
8062 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
8063 ret
|= pe
->func(pe
->opaque
);
8068 WaitObjects
*w
= &wait_objects
;
8070 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
8071 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
8072 if (w
->func
[ret
- WAIT_OBJECT_0
])
8073 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
8075 /* Check for additional signaled events */
8076 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
8078 /* Check if event is signaled */
8079 ret2
= WaitForSingleObject(w
->events
[i
], 0);
8080 if(ret2
== WAIT_OBJECT_0
) {
8082 w
->func
[i
](w
->opaque
[i
]);
8083 } else if (ret2
== WAIT_TIMEOUT
) {
8085 err
= GetLastError();
8086 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
8089 } else if (ret
== WAIT_TIMEOUT
) {
8091 err
= GetLastError();
8092 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
8096 /* poll any events */
8097 /* XXX: separate device handlers from system ones */
8102 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8106 (!ioh
->fd_read_poll
||
8107 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
8108 FD_SET(ioh
->fd
, &rfds
);
8112 if (ioh
->fd_write
) {
8113 FD_SET(ioh
->fd
, &wfds
);
8123 tv
.tv_sec
= timeout
/ 1000;
8124 tv
.tv_usec
= (timeout
% 1000) * 1000;
8126 #if defined(CONFIG_SLIRP)
8128 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
8131 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
8133 IOHandlerRecord
**pioh
;
8135 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8136 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
8137 ioh
->fd_read(ioh
->opaque
);
8138 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
8139 FD_CLR(ioh
->fd
, &rfds
);
8141 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
8142 ioh
->fd_write(ioh
->opaque
);
8146 /* remove deleted IO handlers */
8147 pioh
= &first_io_handler
;
8157 #if defined(CONFIG_SLIRP)
8164 slirp_select_poll(&rfds
, &wfds
, &xfds
);
8169 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
8170 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
8171 qemu_get_clock(vm_clock
));
8172 /* run dma transfers, if any */
8176 /* real time timers */
8177 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
8178 qemu_get_clock(rt_clock
));
8180 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
8181 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
8182 qemu_rearm_alarm_timer(alarm_timer
);
8185 /* Check bottom-halves last in case any of the earlier events triggered
8191 static int main_loop(void)
8194 #ifdef CONFIG_PROFILER
8200 if (kvm_enabled()) {
8202 cpu_disable_ticks();
8206 cur_cpu
= first_cpu
;
8207 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
8214 #ifdef CONFIG_PROFILER
8215 ti
= profile_getclock();
8220 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
8221 env
->icount_decr
.u16
.low
= 0;
8222 env
->icount_extra
= 0;
8223 count
= qemu_next_deadline();
8224 count
= (count
+ (1 << icount_time_shift
) - 1)
8225 >> icount_time_shift
;
8226 qemu_icount
+= count
;
8227 decr
= (count
> 0xffff) ? 0xffff : count
;
8229 env
->icount_decr
.u16
.low
= decr
;
8230 env
->icount_extra
= count
;
8232 ret
= cpu_exec(env
);
8233 #ifdef CONFIG_PROFILER
8234 qemu_time
+= profile_getclock() - ti
;
8237 /* Fold pending instructions back into the
8238 instruction counter, and clear the interrupt flag. */
8239 qemu_icount
-= (env
->icount_decr
.u16
.low
8240 + env
->icount_extra
);
8241 env
->icount_decr
.u32
= 0;
8242 env
->icount_extra
= 0;
8244 next_cpu
= env
->next_cpu
?: first_cpu
;
8245 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8246 ret
= EXCP_INTERRUPT
;
8250 if (ret
== EXCP_HLT
) {
8251 /* Give the next CPU a chance to run. */
8255 if (ret
!= EXCP_HALTED
)
8257 /* all CPUs are halted ? */
8263 if (shutdown_requested
) {
8264 ret
= EXCP_INTERRUPT
;
8272 if (reset_requested
) {
8273 reset_requested
= 0;
8274 qemu_system_reset();
8276 kvm_load_registers(env
);
8277 ret
= EXCP_INTERRUPT
;
8279 if (powerdown_requested
) {
8280 powerdown_requested
= 0;
8281 qemu_system_powerdown();
8282 ret
= EXCP_INTERRUPT
;
8284 if (unlikely(ret
== EXCP_DEBUG
)) {
8285 vm_stop(EXCP_DEBUG
);
8287 /* If all cpus are halted then wait until the next IRQ */
8288 /* XXX: use timeout computed from timers */
8289 if (ret
== EXCP_HALTED
) {
8293 /* Advance virtual time to the next event. */
8294 if (use_icount
== 1) {
8295 /* When not using an adaptive execution frequency
8296 we tend to get badly out of sync with real time,
8297 so just delay for a reasonable amount of time. */
8300 delta
= cpu_get_icount() - cpu_get_clock();
8303 /* If virtual time is ahead of real time then just
8305 timeout
= (delta
/ 1000000) + 1;
8307 /* Wait for either IO to occur or the next
8309 add
= qemu_next_deadline();
8310 /* We advance the timer before checking for IO.
8311 Limit the amount we advance so that early IO
8312 activity won't get the guest too far ahead. */
8316 add
= (add
+ (1 << icount_time_shift
) - 1)
8317 >> icount_time_shift
;
8319 timeout
= delta
/ 1000000;
8330 if (shutdown_requested
)
8334 #ifdef CONFIG_PROFILER
8335 ti
= profile_getclock();
8337 main_loop_wait(timeout
);
8338 #ifdef CONFIG_PROFILER
8339 dev_time
+= profile_getclock() - ti
;
8342 cpu_disable_ticks();
8346 static void help(int exitcode
)
8348 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8349 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8350 "usage: %s [options] [disk_image]\n"
8352 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8354 "Standard options:\n"
8355 "-M machine select emulated machine (-M ? for list)\n"
8356 "-cpu cpu select CPU (-cpu ? for list)\n"
8357 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8358 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8359 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8360 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8361 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8362 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8363 " [,cache=on|off][,format=f][,boot=on|off]\n"
8364 " use 'file' as a drive image\n"
8365 "-mtdblock file use 'file' as on-board Flash memory image\n"
8366 "-sd file use 'file' as SecureDigital card image\n"
8367 "-pflash file use 'file' as a parallel flash image\n"
8368 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8369 "-snapshot write to temporary files instead of disk image files\n"
8371 "-no-frame open SDL window without a frame and window decorations\n"
8372 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8373 "-no-quit disable SDL window close capability\n"
8376 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8378 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8379 "-smp n set the number of CPUs to 'n' [default=1]\n"
8380 "-nographic disable graphical output and redirect serial I/Os to console\n"
8381 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8383 "-k language use keyboard layout (for example \"fr\" for French)\n"
8386 "-audio-help print list of audio drivers and their options\n"
8387 "-soundhw c1,... enable audio support\n"
8388 " and only specified sound cards (comma separated list)\n"
8389 " use -soundhw ? to get the list of supported cards\n"
8390 " use -soundhw all to enable all of them\n"
8392 "-localtime set the real time clock to local time [default=utc]\n"
8393 "-full-screen start in full screen\n"
8395 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8397 "-usb enable the USB driver (will be the default soon)\n"
8398 "-usbdevice name add the host or guest USB device 'name'\n"
8399 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8400 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8402 "-name string set the name of the guest\n"
8403 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
8405 "Network options:\n"
8406 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8407 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8409 "-net user[,vlan=n][,hostname=host]\n"
8410 " connect the user mode network stack to VLAN 'n' and send\n"
8411 " hostname 'host' to DHCP clients\n"
8414 "-net tap[,vlan=n],ifname=name\n"
8415 " connect the host TAP network interface to VLAN 'n'\n"
8417 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8418 " connect the host TAP network interface to VLAN 'n' and use the\n"
8419 " network scripts 'file' (default=%s)\n"
8420 " and 'dfile' (default=%s);\n"
8421 " use '[down]script=no' to disable script execution;\n"
8422 " use 'fd=h' to connect to an already opened TAP interface\n"
8424 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8425 " connect the vlan 'n' to another VLAN using a socket connection\n"
8426 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8427 " connect the vlan 'n' to multicast maddr and port\n"
8429 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8430 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8431 " on host and listening for incoming connections on 'socketpath'.\n"
8432 " Use group 'groupname' and mode 'octalmode' to change default\n"
8433 " ownership and permissions for communication port.\n"
8435 "-net none use it alone to have zero network devices; if no -net option\n"
8436 " is provided, the default is '-net nic -net user'\n"
8439 "-tftp dir allow tftp access to files in dir [-net user]\n"
8440 "-bootp file advertise file in BOOTP replies\n"
8442 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8444 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8445 " redirect TCP or UDP connections from host to guest [-net user]\n"
8448 "Linux boot specific:\n"
8449 "-kernel bzImage use 'bzImage' as kernel image\n"
8450 "-append cmdline use 'cmdline' as kernel command line\n"
8451 "-initrd file use 'file' as initial ram disk\n"
8453 "Debug/Expert options:\n"
8454 "-monitor dev redirect the monitor to char device 'dev'\n"
8455 "-serial dev redirect the serial port to char device 'dev'\n"
8456 "-parallel dev redirect the parallel port to char device 'dev'\n"
8457 "-pidfile file Write PID to 'file'\n"
8458 "-S freeze CPU at startup (use 'c' to start execution)\n"
8459 "-s wait gdb connection to port\n"
8460 "-p port set gdb connection port [default=%s]\n"
8461 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8462 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8463 " translation (t=none or lba) (usually qemu can guess them)\n"
8464 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8466 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8467 "-no-kqemu disable KQEMU kernel module usage\n"
8470 #ifndef NO_CPU_EMULATION
8471 "-no-kvm disable KVM hardware virtualization\n"
8473 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8474 "-no-kvm-pit disable KVM kernel mode PIT\n"
8477 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8478 " (default is CL-GD5446 PCI VGA)\n"
8479 "-no-acpi disable ACPI\n"
8481 #ifdef CONFIG_CURSES
8482 "-curses use a curses/ncurses interface instead of SDL\n"
8484 "-no-reboot exit instead of rebooting\n"
8485 "-no-shutdown stop before shutdown\n"
8486 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8487 "-vnc display start a VNC server on display\n"
8489 "-daemonize daemonize QEMU after initializing\n"
8491 "-tdf inject timer interrupts that got lost\n"
8492 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8493 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8494 "-option-rom rom load a file, rom, into the option ROM space\n"
8496 "-prom-env variable=value set OpenBIOS nvram variables\n"
8498 "-clock force the use of the given methods for timer alarm.\n"
8499 " To see what timers are available use -clock ?\n"
8500 "-startdate select initial date of the clock\n"
8501 "-icount [N|auto]\n"
8502 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8504 "During emulation, the following keys are useful:\n"
8505 "ctrl-alt-f toggle full screen\n"
8506 "ctrl-alt-n switch to virtual console 'n'\n"
8507 "ctrl-alt toggle mouse and keyboard grab\n"
8509 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8514 DEFAULT_NETWORK_SCRIPT
,
8515 DEFAULT_NETWORK_DOWN_SCRIPT
,
8517 DEFAULT_GDBSTUB_PORT
,
8522 #define HAS_ARG 0x0001
8537 QEMU_OPTION_mtdblock
,
8541 QEMU_OPTION_snapshot
,
8543 QEMU_OPTION_no_fd_bootchk
,
8546 QEMU_OPTION_nographic
,
8547 QEMU_OPTION_portrait
,
8549 QEMU_OPTION_audio_help
,
8550 QEMU_OPTION_soundhw
,
8571 QEMU_OPTION_localtime
,
8572 QEMU_OPTION_cirrusvga
,
8575 QEMU_OPTION_std_vga
,
8577 QEMU_OPTION_monitor
,
8579 QEMU_OPTION_parallel
,
8581 QEMU_OPTION_full_screen
,
8582 QEMU_OPTION_no_frame
,
8583 QEMU_OPTION_alt_grab
,
8584 QEMU_OPTION_no_quit
,
8585 QEMU_OPTION_pidfile
,
8586 QEMU_OPTION_no_kqemu
,
8587 QEMU_OPTION_kernel_kqemu
,
8588 QEMU_OPTION_win2k_hack
,
8590 QEMU_OPTION_usbdevice
,
8593 QEMU_OPTION_no_acpi
,
8596 QEMU_OPTION_no_kvm_irqchip
,
8597 QEMU_OPTION_no_kvm_pit
,
8598 QEMU_OPTION_no_reboot
,
8599 QEMU_OPTION_no_shutdown
,
8600 QEMU_OPTION_show_cursor
,
8601 QEMU_OPTION_daemonize
,
8602 QEMU_OPTION_option_rom
,
8603 QEMU_OPTION_semihosting
,
8604 QEMU_OPTION_cpu_vendor
,
8606 QEMU_OPTION_prom_env
,
8607 QEMU_OPTION_old_param
,
8609 QEMU_OPTION_startdate
,
8610 QEMU_OPTION_tb_size
,
8613 QEMU_OPTION_incoming
,
8615 QEMU_OPTION_kvm_shadow_memory
,
8616 QEMU_OPTION_mempath
,
8619 typedef struct QEMUOption
{
8625 const QEMUOption qemu_options
[] = {
8626 { "h", 0, QEMU_OPTION_h
},
8627 { "help", 0, QEMU_OPTION_h
},
8629 { "M", HAS_ARG
, QEMU_OPTION_M
},
8630 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8631 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8632 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8633 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8634 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8635 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8636 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8637 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8638 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8639 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8640 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8641 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8642 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8643 { "snapshot", 0, QEMU_OPTION_snapshot
},
8645 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8647 { "m", HAS_ARG
, QEMU_OPTION_m
},
8648 { "nographic", 0, QEMU_OPTION_nographic
},
8649 { "portrait", 0, QEMU_OPTION_portrait
},
8650 { "k", HAS_ARG
, QEMU_OPTION_k
},
8652 { "audio-help", 0, QEMU_OPTION_audio_help
},
8653 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8656 { "net", HAS_ARG
, QEMU_OPTION_net
},
8658 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8659 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8661 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8663 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8666 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8667 { "append", HAS_ARG
, QEMU_OPTION_append
},
8668 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8670 { "S", 0, QEMU_OPTION_S
},
8671 { "s", 0, QEMU_OPTION_s
},
8672 { "p", HAS_ARG
, QEMU_OPTION_p
},
8673 { "d", HAS_ARG
, QEMU_OPTION_d
},
8674 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8675 { "L", HAS_ARG
, QEMU_OPTION_L
},
8676 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8678 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8679 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8682 #ifndef NO_CPU_EMULATION
8683 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8685 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8686 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8688 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8689 { "g", 1, QEMU_OPTION_g
},
8691 { "localtime", 0, QEMU_OPTION_localtime
},
8692 { "std-vga", 0, QEMU_OPTION_std_vga
},
8693 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8694 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8695 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8696 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8697 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8698 { "incoming", 1, QEMU_OPTION_incoming
},
8699 { "full-screen", 0, QEMU_OPTION_full_screen
},
8701 { "no-frame", 0, QEMU_OPTION_no_frame
},
8702 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8703 { "no-quit", 0, QEMU_OPTION_no_quit
},
8705 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8706 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8707 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8708 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8709 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8710 #ifdef CONFIG_CURSES
8711 { "curses", 0, QEMU_OPTION_curses
},
8713 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
8715 /* temporary options */
8716 { "usb", 0, QEMU_OPTION_usb
},
8717 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8718 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8719 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8720 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8721 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8722 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8723 { "daemonize", 0, QEMU_OPTION_daemonize
},
8724 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8725 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8726 { "semihosting", 0, QEMU_OPTION_semihosting
},
8728 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8729 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8730 { "name", HAS_ARG
, QEMU_OPTION_name
},
8731 #if defined(TARGET_SPARC)
8732 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8734 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8735 #if defined(TARGET_ARM)
8736 { "old-param", 0, QEMU_OPTION_old_param
},
8738 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8739 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8740 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8741 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8742 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8746 /* password input */
8748 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8753 if (!bdrv_is_encrypted(bs
))
8756 term_printf("%s is encrypted.\n", name
);
8757 for(i
= 0; i
< 3; i
++) {
8758 monitor_readline("Password: ", 1, password
, sizeof(password
));
8759 if (bdrv_set_key(bs
, password
) == 0)
8761 term_printf("invalid password\n");
8766 static BlockDriverState
*get_bdrv(int index
)
8768 if (index
> nb_drives
)
8770 return drives_table
[index
].bdrv
;
8773 static void read_passwords(void)
8775 BlockDriverState
*bs
;
8778 for(i
= 0; i
< 6; i
++) {
8781 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8786 struct soundhw soundhw
[] = {
8787 #ifdef HAS_AUDIO_CHOICE
8788 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8794 { .init_isa
= pcspk_audio_init
}
8799 "Creative Sound Blaster 16",
8802 { .init_isa
= SB16_init
}
8805 #ifdef CONFIG_CS4231A
8811 { .init_isa
= cs4231a_init
}
8819 "Yamaha YMF262 (OPL3)",
8821 "Yamaha YM3812 (OPL2)",
8825 { .init_isa
= Adlib_init
}
8832 "Gravis Ultrasound GF1",
8835 { .init_isa
= GUS_init
}
8842 "Intel 82801AA AC97 Audio",
8845 { .init_pci
= ac97_init
}
8851 "ENSONIQ AudioPCI ES1370",
8854 { .init_pci
= es1370_init
}
8858 { NULL
, NULL
, 0, 0, { NULL
} }
8861 static void select_soundhw (const char *optarg
)
8865 if (*optarg
== '?') {
8868 printf ("Valid sound card names (comma separated):\n");
8869 for (c
= soundhw
; c
->name
; ++c
) {
8870 printf ("%-11s %s\n", c
->name
, c
->descr
);
8872 printf ("\n-soundhw all will enable all of the above\n");
8873 exit (*optarg
!= '?');
8881 if (!strcmp (optarg
, "all")) {
8882 for (c
= soundhw
; c
->name
; ++c
) {
8890 e
= strchr (p
, ',');
8891 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8893 for (c
= soundhw
; c
->name
; ++c
) {
8894 if (!strncmp (c
->name
, p
, l
)) {
8903 "Unknown sound card name (too big to show)\n");
8906 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8911 p
+= l
+ (e
!= NULL
);
8915 goto show_valid_cards
;
8921 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8923 exit(STATUS_CONTROL_C_EXIT
);
8928 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8932 if(strlen(str
) != 36)
8935 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8936 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8937 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8945 #define MAX_NET_CLIENTS 32
8947 static int saved_argc
;
8948 static char **saved_argv
;
8950 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8954 *opt_daemonize
= daemonize
;
8955 *opt_incoming
= incoming
;
8959 static int gethugepagesize(void)
8963 char *needle
= "Hugepagesize:";
8965 unsigned long hugepagesize
;
8967 fd
= open("/proc/meminfo", O_RDONLY
);
8973 ret
= read(fd
, buf
, sizeof(buf
));
8979 size
= strstr(buf
, needle
);
8982 size
+= strlen(needle
);
8983 hugepagesize
= strtol(size
, NULL
, 0);
8984 return hugepagesize
;
8987 void *alloc_mem_area(size_t memory
, unsigned long *len
, const char *path
)
8993 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8996 hpagesize
= gethugepagesize() * 1024;
9000 fd
= mkstemp(filename
);
9009 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
9012 * ftruncate is not supported by hugetlbfs in older
9013 * hosts, so don't bother checking for errors.
9014 * If anything goes wrong with it under other filesystems,
9017 ftruncate(fd
, memory
);
9019 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
9020 if (area
== MAP_FAILED
) {
9030 void *qemu_alloc_physram(unsigned long memory
)
9033 unsigned long map_len
= memory
;
9037 area
= alloc_mem_area(memory
, &map_len
, mem_path
);
9040 area
= qemu_vmalloc(memory
);
9042 if (kvm_setup_guest_memory(area
, map_len
))
9050 static void termsig_handler(int signal
)
9052 qemu_system_shutdown_request();
9055 static void termsig_setup(void)
9057 struct sigaction act
;
9059 memset(&act
, 0, sizeof(act
));
9060 act
.sa_handler
= termsig_handler
;
9061 sigaction(SIGINT
, &act
, NULL
);
9062 sigaction(SIGHUP
, &act
, NULL
);
9063 sigaction(SIGTERM
, &act
, NULL
);
9068 int main(int argc
, char **argv
)
9070 #ifdef CONFIG_GDBSTUB
9072 const char *gdbstub_port
;
9074 uint32_t boot_devices_bitmap
= 0;
9076 int snapshot
, linux_boot
, net_boot
;
9077 const char *initrd_filename
;
9078 const char *kernel_filename
, *kernel_cmdline
;
9079 const char *boot_devices
= "";
9080 DisplayState
*ds
= &display_state
;
9081 int cyls
, heads
, secs
, translation
;
9082 const char *net_clients
[MAX_NET_CLIENTS
];
9086 const char *r
, *optarg
;
9087 CharDriverState
*monitor_hd
;
9088 const char *monitor_device
;
9089 const char *serial_devices
[MAX_SERIAL_PORTS
];
9090 int serial_device_index
;
9091 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
9092 int parallel_device_index
;
9093 const char *loadvm
= NULL
;
9094 QEMUMachine
*machine
;
9095 const char *cpu_model
;
9096 const char *usb_devices
[MAX_USB_CMDLINE
];
9097 int usb_devices_index
;
9100 const char *pid_file
= NULL
;
9106 LIST_INIT (&vm_change_state_head
);
9109 struct sigaction act
;
9110 sigfillset(&act
.sa_mask
);
9112 act
.sa_handler
= SIG_IGN
;
9113 sigaction(SIGPIPE
, &act
, NULL
);
9116 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
9117 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9118 QEMU to run on a single CPU */
9123 h
= GetCurrentProcess();
9124 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
9125 for(i
= 0; i
< 32; i
++) {
9126 if (mask
& (1 << i
))
9131 SetProcessAffinityMask(h
, mask
);
9137 register_machines();
9138 machine
= first_machine
;
9140 initrd_filename
= NULL
;
9142 vga_ram_size
= VGA_RAM_SIZE
;
9143 #ifdef CONFIG_GDBSTUB
9145 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
9150 kernel_filename
= NULL
;
9151 kernel_cmdline
= "";
9152 cyls
= heads
= secs
= 0;
9153 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9154 monitor_device
= "vc";
9156 serial_devices
[0] = "vc:80Cx24C";
9157 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
9158 serial_devices
[i
] = NULL
;
9159 serial_device_index
= 0;
9161 parallel_devices
[0] = "vc:640x480";
9162 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
9163 parallel_devices
[i
] = NULL
;
9164 parallel_device_index
= 0;
9166 usb_devices_index
= 0;
9183 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
9185 const QEMUOption
*popt
;
9188 /* Treat --foo the same as -foo. */
9191 popt
= qemu_options
;
9194 fprintf(stderr
, "%s: invalid option -- '%s'\n",
9198 if (!strcmp(popt
->name
, r
+ 1))
9202 if (popt
->flags
& HAS_ARG
) {
9203 if (optind
>= argc
) {
9204 fprintf(stderr
, "%s: option '%s' requires an argument\n",
9208 optarg
= argv
[optind
++];
9213 switch(popt
->index
) {
9215 machine
= find_machine(optarg
);
9218 printf("Supported machines are:\n");
9219 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
9220 printf("%-10s %s%s\n",
9222 m
== first_machine
? " (default)" : "");
9224 exit(*optarg
!= '?');
9227 case QEMU_OPTION_cpu
:
9228 /* hw initialization will check this */
9229 if (*optarg
== '?') {
9230 /* XXX: implement xxx_cpu_list for targets that still miss it */
9231 #if defined(cpu_list)
9232 cpu_list(stdout
, &fprintf
);
9239 case QEMU_OPTION_initrd
:
9240 initrd_filename
= optarg
;
9242 case QEMU_OPTION_hda
:
9244 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
9246 hda_index
= drive_add(optarg
, HD_ALIAS
9247 ",cyls=%d,heads=%d,secs=%d%s",
9248 0, cyls
, heads
, secs
,
9249 translation
== BIOS_ATA_TRANSLATION_LBA
?
9251 translation
== BIOS_ATA_TRANSLATION_NONE
?
9252 ",trans=none" : "");
9254 case QEMU_OPTION_hdb
:
9255 case QEMU_OPTION_hdc
:
9256 case QEMU_OPTION_hdd
:
9257 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
9259 case QEMU_OPTION_drive
:
9260 drive_add(NULL
, "%s", optarg
);
9262 case QEMU_OPTION_mtdblock
:
9263 drive_add(optarg
, MTD_ALIAS
);
9265 case QEMU_OPTION_sd
:
9266 drive_add(optarg
, SD_ALIAS
);
9268 case QEMU_OPTION_pflash
:
9269 drive_add(optarg
, PFLASH_ALIAS
);
9271 case QEMU_OPTION_snapshot
:
9274 case QEMU_OPTION_hdachs
:
9278 cyls
= strtol(p
, (char **)&p
, 0);
9279 if (cyls
< 1 || cyls
> 16383)
9284 heads
= strtol(p
, (char **)&p
, 0);
9285 if (heads
< 1 || heads
> 16)
9290 secs
= strtol(p
, (char **)&p
, 0);
9291 if (secs
< 1 || secs
> 63)
9295 if (!strcmp(p
, "none"))
9296 translation
= BIOS_ATA_TRANSLATION_NONE
;
9297 else if (!strcmp(p
, "lba"))
9298 translation
= BIOS_ATA_TRANSLATION_LBA
;
9299 else if (!strcmp(p
, "auto"))
9300 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9303 } else if (*p
!= '\0') {
9305 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9308 if (hda_index
!= -1)
9309 snprintf(drives_opt
[hda_index
].opt
,
9310 sizeof(drives_opt
[hda_index
].opt
),
9311 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9312 0, cyls
, heads
, secs
,
9313 translation
== BIOS_ATA_TRANSLATION_LBA
?
9315 translation
== BIOS_ATA_TRANSLATION_NONE
?
9316 ",trans=none" : "");
9319 case QEMU_OPTION_nographic
:
9322 #ifdef CONFIG_CURSES
9323 case QEMU_OPTION_curses
:
9327 case QEMU_OPTION_portrait
:
9330 case QEMU_OPTION_kernel
:
9331 kernel_filename
= optarg
;
9333 case QEMU_OPTION_append
:
9334 kernel_cmdline
= optarg
;
9336 case QEMU_OPTION_cdrom
:
9337 drive_add(optarg
, CDROM_ALIAS
);
9339 case QEMU_OPTION_boot
:
9340 boot_devices
= optarg
;
9341 /* We just do some generic consistency checks */
9343 /* Could easily be extended to 64 devices if needed */
9346 boot_devices_bitmap
= 0;
9347 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9348 /* Allowed boot devices are:
9349 * a b : floppy disk drives
9350 * c ... f : IDE disk drives
9351 * g ... m : machine implementation dependant drives
9352 * n ... p : network devices
9353 * It's up to each machine implementation to check
9354 * if the given boot devices match the actual hardware
9355 * implementation and firmware features.
9357 if (*p
< 'a' || *p
> 'q') {
9358 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9361 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9363 "Boot device '%c' was given twice\n",*p
);
9366 boot_devices_bitmap
|= 1 << (*p
- 'a');
9370 case QEMU_OPTION_fda
:
9371 case QEMU_OPTION_fdb
:
9372 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9375 case QEMU_OPTION_no_fd_bootchk
:
9379 case QEMU_OPTION_net
:
9380 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9381 fprintf(stderr
, "qemu: too many network clients\n");
9384 net_clients
[nb_net_clients
] = optarg
;
9388 case QEMU_OPTION_tftp
:
9389 tftp_prefix
= optarg
;
9391 case QEMU_OPTION_bootp
:
9392 bootp_filename
= optarg
;
9395 case QEMU_OPTION_smb
:
9396 net_slirp_smb(optarg
);
9399 case QEMU_OPTION_redir
:
9400 net_slirp_redir(optarg
);
9404 case QEMU_OPTION_audio_help
:
9408 case QEMU_OPTION_soundhw
:
9409 select_soundhw (optarg
);
9415 case QEMU_OPTION_m
: {
9419 value
= strtoul(optarg
, &ptr
, 10);
9421 case 0: case 'M': case 'm':
9428 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9432 /* On 32-bit hosts, QEMU is limited by virtual address space */
9433 if (value
> (2047 << 20)
9435 && HOST_LONG_BITS
== 32
9438 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9441 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9442 fprintf(stderr
, "qemu: ram size too large\n");
9453 mask
= cpu_str_to_log_mask(optarg
);
9455 printf("Log items (comma separated):\n");
9456 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9457 printf("%-10s %s\n", item
->name
, item
->help
);
9464 #ifdef CONFIG_GDBSTUB
9469 gdbstub_port
= optarg
;
9475 case QEMU_OPTION_bios
:
9482 keyboard_layout
= optarg
;
9484 case QEMU_OPTION_localtime
:
9487 case QEMU_OPTION_cirrusvga
:
9488 cirrus_vga_enabled
= 1;
9491 case QEMU_OPTION_vmsvga
:
9492 cirrus_vga_enabled
= 0;
9495 case QEMU_OPTION_std_vga
:
9496 cirrus_vga_enabled
= 0;
9504 w
= strtol(p
, (char **)&p
, 10);
9507 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9513 h
= strtol(p
, (char **)&p
, 10);
9518 depth
= strtol(p
, (char **)&p
, 10);
9519 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9520 depth
!= 24 && depth
!= 32)
9522 } else if (*p
== '\0') {
9523 depth
= graphic_depth
;
9530 graphic_depth
= depth
;
9533 case QEMU_OPTION_echr
:
9536 term_escape_char
= strtol(optarg
, &r
, 0);
9538 printf("Bad argument to echr\n");
9541 case QEMU_OPTION_monitor
:
9542 monitor_device
= optarg
;
9544 case QEMU_OPTION_serial
:
9545 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9546 fprintf(stderr
, "qemu: too many serial ports\n");
9549 serial_devices
[serial_device_index
] = optarg
;
9550 serial_device_index
++;
9552 case QEMU_OPTION_parallel
:
9553 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9554 fprintf(stderr
, "qemu: too many parallel ports\n");
9557 parallel_devices
[parallel_device_index
] = optarg
;
9558 parallel_device_index
++;
9560 case QEMU_OPTION_loadvm
:
9563 case QEMU_OPTION_incoming
:
9566 case QEMU_OPTION_full_screen
:
9570 case QEMU_OPTION_no_frame
:
9573 case QEMU_OPTION_alt_grab
:
9576 case QEMU_OPTION_no_quit
:
9580 case QEMU_OPTION_pidfile
:
9584 case QEMU_OPTION_win2k_hack
:
9585 win2k_install_hack
= 1;
9589 case QEMU_OPTION_no_kqemu
:
9592 case QEMU_OPTION_kernel_kqemu
:
9597 case QEMU_OPTION_no_kvm
:
9600 case QEMU_OPTION_no_kvm_irqchip
: {
9601 extern int kvm_irqchip
, kvm_pit
;
9606 case QEMU_OPTION_no_kvm_pit
: {
9612 case QEMU_OPTION_usb
:
9615 case QEMU_OPTION_usbdevice
:
9617 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9618 fprintf(stderr
, "Too many USB devices\n");
9621 usb_devices
[usb_devices_index
] = optarg
;
9622 usb_devices_index
++;
9624 case QEMU_OPTION_smp
:
9625 smp_cpus
= atoi(optarg
);
9626 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9627 fprintf(stderr
, "Invalid number of CPUs\n");
9631 case QEMU_OPTION_vnc
:
9632 vnc_display
= optarg
;
9634 case QEMU_OPTION_no_acpi
:
9637 case QEMU_OPTION_no_reboot
:
9640 case QEMU_OPTION_no_shutdown
:
9643 case QEMU_OPTION_show_cursor
:
9646 case QEMU_OPTION_uuid
:
9647 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
9648 fprintf(stderr
, "Fail to parse UUID string."
9649 " Wrong format.\n");
9653 case QEMU_OPTION_daemonize
:
9656 case QEMU_OPTION_option_rom
:
9657 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9658 fprintf(stderr
, "Too many option ROMs\n");
9661 option_rom
[nb_option_roms
] = optarg
;
9664 case QEMU_OPTION_semihosting
:
9665 semihosting_enabled
= 1;
9667 case QEMU_OPTION_tdf
:
9670 case QEMU_OPTION_kvm_shadow_memory
:
9671 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9673 case QEMU_OPTION_mempath
:
9676 case QEMU_OPTION_name
:
9680 case QEMU_OPTION_prom_env
:
9681 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9682 fprintf(stderr
, "Too many prom variables\n");
9685 prom_envs
[nb_prom_envs
] = optarg
;
9689 case QEMU_OPTION_cpu_vendor
:
9690 cpu_vendor_string
= optarg
;
9693 case QEMU_OPTION_old_param
:
9697 case QEMU_OPTION_clock
:
9698 configure_alarms(optarg
);
9700 case QEMU_OPTION_startdate
:
9703 time_t rtc_start_date
;
9704 if (!strcmp(optarg
, "now")) {
9705 rtc_date_offset
= -1;
9707 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9715 } else if (sscanf(optarg
, "%d-%d-%d",
9718 &tm
.tm_mday
) == 3) {
9727 rtc_start_date
= mktimegm(&tm
);
9728 if (rtc_start_date
== -1) {
9730 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9731 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9734 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9738 case QEMU_OPTION_tb_size
:
9739 tb_size
= strtol(optarg
, NULL
, 0);
9743 case QEMU_OPTION_icount
:
9745 if (strcmp(optarg
, "auto") == 0) {
9746 icount_time_shift
= -1;
9748 icount_time_shift
= strtol(optarg
, NULL
, 0);
9756 if (serial_device_index
== 0)
9757 serial_devices
[0] = "stdio";
9758 if (parallel_device_index
== 0)
9759 parallel_devices
[0] = "null";
9760 if (strncmp(monitor_device
, "vc", 2) == 0)
9761 monitor_device
= "stdio";
9768 if (pipe(fds
) == -1)
9779 len
= read(fds
[0], &status
, 1);
9780 if (len
== -1 && (errno
== EINTR
))
9785 else if (status
== 1) {
9786 fprintf(stderr
, "Could not acquire pidfile\n");
9803 signal(SIGTSTP
, SIG_IGN
);
9804 signal(SIGTTOU
, SIG_IGN
);
9805 signal(SIGTTIN
, SIG_IGN
);
9810 if (kvm_enabled()) {
9811 if (kvm_qemu_init() < 0) {
9812 extern int kvm_allowed
;
9813 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9814 #ifdef NO_CPU_EMULATION
9815 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9823 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9826 write(fds
[1], &status
, 1);
9828 fprintf(stderr
, "Could not acquire pid file\n");
9836 linux_boot
= (kernel_filename
!= NULL
);
9837 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9839 if (!linux_boot
&& net_boot
== 0 &&
9840 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9843 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9844 fprintf(stderr
, "-append only allowed with -kernel option\n");
9848 if (!linux_boot
&& initrd_filename
!= NULL
) {
9849 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9853 /* boot to floppy or the default cd if no hard disk defined yet */
9854 if (!boot_devices
[0]) {
9855 boot_devices
= "cad";
9857 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9861 if (use_icount
&& icount_time_shift
< 0) {
9863 /* 125MIPS seems a reasonable initial guess at the guest speed.
9864 It will be corrected fairly quickly anyway. */
9865 icount_time_shift
= 3;
9866 init_icount_adjust();
9873 /* init network clients */
9874 if (nb_net_clients
== 0) {
9875 /* if no clients, we use a default config */
9876 net_clients
[nb_net_clients
++] = "nic";
9878 net_clients
[nb_net_clients
++] = "user";
9882 for(i
= 0;i
< nb_net_clients
; i
++) {
9883 if (net_client_parse(net_clients
[i
]) < 0)
9886 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9887 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9889 if (vlan
->nb_guest_devs
== 0)
9890 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9891 if (vlan
->nb_host_devs
== 0)
9893 "Warning: vlan %d is not connected to host network\n",
9898 /* XXX: this should be moved in the PC machine instantiation code */
9899 if (net_boot
!= 0) {
9901 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9902 const char *model
= nd_table
[i
].model
;
9904 if (net_boot
& (1 << i
)) {
9907 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9908 if (get_image_size(buf
) > 0) {
9909 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9910 fprintf(stderr
, "Too many option ROMs\n");
9913 option_rom
[nb_option_roms
] = strdup(buf
);
9920 fprintf(stderr
, "No valid PXE rom found for network device\n");
9926 /* init the memory */
9927 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9929 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9931 if (ram_size
< phys_ram_size
) {
9932 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9933 machine
->name
, (unsigned long long) phys_ram_size
);
9937 phys_ram_size
= ram_size
;
9939 ram_size
= phys_ram_size
;
9942 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9944 phys_ram_size
+= ram_size
;
9947 /* Initialize kvm */
9948 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9949 #define KVM_EXTRA_PAGES 3
9951 #define KVM_EXTRA_PAGES 0
9953 if (kvm_enabled()) {
9954 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9955 if (kvm_qemu_create_context() < 0) {
9956 fprintf(stderr
, "Could not create KVM context\n");
9961 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9962 if (!phys_ram_base
) {
9963 fprintf(stderr
, "Could not allocate physical memory\n");
9967 /* init the dynamic translator */
9968 cpu_exec_init_all(tb_size
* 1024 * 1024);
9972 /* we always create the cdrom drive, even if no disk is there */
9974 if (nb_drives_opt
< MAX_DRIVES
)
9975 drive_add(NULL
, CDROM_ALIAS
);
9977 /* we always create at least one floppy */
9979 if (nb_drives_opt
< MAX_DRIVES
)
9980 drive_add(NULL
, FD_ALIAS
, 0);
9982 /* we always create one sd slot, even if no card is in it */
9984 if (nb_drives_opt
< MAX_DRIVES
)
9985 drive_add(NULL
, SD_ALIAS
);
9987 /* open the virtual block devices
9988 * note that migration with device
9989 * hot add/remove is broken.
9991 for(i
= 0; i
< nb_drives_opt
; i
++)
9992 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9995 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9996 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9999 memset(&display_state
, 0, sizeof(display_state
));
10002 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
10005 /* nearly nothing to do */
10006 dumb_display_init(ds
);
10007 } else if (vnc_display
!= NULL
) {
10008 vnc_display_init(ds
);
10009 if (vnc_display_open(ds
, vnc_display
) < 0)
10012 #if defined(CONFIG_CURSES)
10014 curses_display_init(ds
, full_screen
);
10018 #if defined(CONFIG_SDL)
10019 sdl_display_init(ds
, full_screen
, no_frame
);
10020 #elif defined(CONFIG_COCOA)
10021 cocoa_display_init(ds
, full_screen
);
10023 dumb_display_init(ds
);
10028 /* must be after terminal init, SDL library changes signal handlers */
10032 /* Maintain compatibility with multiple stdio monitors */
10033 if (!strcmp(monitor_device
,"stdio")) {
10034 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10035 const char *devname
= serial_devices
[i
];
10036 if (devname
&& !strcmp(devname
,"mon:stdio")) {
10037 monitor_device
= NULL
;
10039 } else if (devname
&& !strcmp(devname
,"stdio")) {
10040 monitor_device
= NULL
;
10041 serial_devices
[i
] = "mon:stdio";
10046 if (monitor_device
) {
10047 monitor_hd
= qemu_chr_open(monitor_device
);
10049 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
10052 monitor_init(monitor_hd
, !nographic
);
10055 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10056 const char *devname
= serial_devices
[i
];
10057 if (devname
&& strcmp(devname
, "none")) {
10058 serial_hds
[i
] = qemu_chr_open(devname
);
10059 if (!serial_hds
[i
]) {
10060 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
10064 if (strstart(devname
, "vc", 0))
10065 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
10069 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
10070 const char *devname
= parallel_devices
[i
];
10071 if (devname
&& strcmp(devname
, "none")) {
10072 parallel_hds
[i
] = qemu_chr_open(devname
);
10073 if (!parallel_hds
[i
]) {
10074 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
10078 if (strstart(devname
, "vc", 0))
10079 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
10086 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
10087 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
10089 current_machine
= machine
;
10091 /* init USB devices */
10093 for(i
= 0; i
< usb_devices_index
; i
++) {
10094 if (usb_device_add(usb_devices
[i
]) < 0) {
10095 fprintf(stderr
, "Warning: could not add USB device %s\n",
10101 if (display_state
.dpy_refresh
) {
10102 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
10103 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
10106 #ifdef CONFIG_GDBSTUB
10108 /* XXX: use standard host:port notation and modify options
10110 if (gdbserver_start(gdbstub_port
) < 0) {
10111 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
10124 rc
= migrate_incoming(incoming
);
10126 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
10132 /* XXX: simplify init */
10140 uint8_t status
= 0;
10145 len
= write(fds
[1], &status
, 1);
10146 if (len
== -1 && (errno
== EINTR
))
10153 TFR(fd
= open("/dev/null", O_RDWR
));
10167 #if !defined(_WIN32)
10168 /* close network clients */
10169 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
10170 VLANClientState
*vc
;
10172 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
10173 if (vc
->fd_read
== tap_receive
) {
10175 TAPState
*s
= vc
->opaque
;
10177 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
10179 launch_script(s
->down_script
, ifname
, s
->fd
);
10181 #if defined(CONFIG_VDE)
10182 if (vc
->fd_read
== vde_from_qemu
) {
10183 VDEState
*s
= vc
->opaque
;