4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
40 #include "migration.h"
52 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
66 #if !defined(__APPLE__) && !defined(__OpenBSD__)
72 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
73 #include <freebsd/stdlib.h>
77 #include <linux/if_tun.h>
80 #include <linux/rtc.h>
82 /* For the benefit of older linux systems which don't supply it,
83 we use a local copy of hpet.h. */
84 /* #include <linux/hpet.h> */
87 #include <linux/ppdev.h>
88 #include <linux/parport.h>
91 #include <sys/ethernet.h>
92 #include <sys/sockio.h>
93 #include <netinet/arp.h>
94 #include <netinet/in.h>
95 #include <netinet/in_systm.h>
96 #include <netinet/ip.h>
97 #include <netinet/ip_icmp.h> // must come after ip.h
98 #include <netinet/udp.h>
99 #include <netinet/tcp.h>
106 #include <winsock2.h>
107 int inet_aton(const char *cp
, struct in_addr
*ia
);
110 #if defined(CONFIG_SLIRP)
111 #include "libslirp.h"
114 #if defined(CONFIG_VDE)
115 #include <libvdeplug.h>
120 #include <sys/timeb.h>
121 #include <mmsystem.h>
122 #define getopt_long_only getopt_long
123 #define memalign(align, size) malloc(size)
126 #include "qemu_socket.h"
132 #endif /* CONFIG_SDL */
136 #define main qemu_main
137 #endif /* CONFIG_COCOA */
141 #include "exec-all.h"
143 #include "qemu-kvm.h"
145 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
146 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
148 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
150 #define SMBD_COMMAND "/usr/sbin/smbd"
153 //#define DEBUG_UNUSED_IOPORT
154 //#define DEBUG_IOPORT
157 #define DEFAULT_RAM_SIZE 144
159 #define DEFAULT_RAM_SIZE 128
162 /* Max number of USB devices that can be specified on the commandline. */
163 #define MAX_USB_CMDLINE 8
165 /* XXX: use a two level table to limit memory usage */
166 #define MAX_IOPORTS 65536
168 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
169 const char *bios_name
= NULL
;
170 void *ioport_opaque
[MAX_IOPORTS
];
171 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
172 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
173 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
174 to store the VM snapshots */
175 DriveInfo drives_table
[MAX_DRIVES
+1];
177 int extboot_drive
= -1;
178 /* point to the block driver where the snapshots are managed */
179 BlockDriverState
*bs_snapshots
;
181 static DisplayState display_state
;
184 const char* keyboard_layout
= NULL
;
185 int64_t ticks_per_sec
;
187 int pit_min_timer_count
= 0;
189 NICInfo nd_table
[MAX_NICS
];
191 static int rtc_utc
= 1;
192 static int rtc_date_offset
= -1; /* -1 means no change */
193 int cirrus_vga_enabled
= 1;
194 int vmsvga_enabled
= 0;
196 int graphic_width
= 1024;
197 int graphic_height
= 768;
198 int graphic_depth
= 8;
200 int graphic_width
= 800;
201 int graphic_height
= 600;
202 int graphic_depth
= 15;
207 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
208 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
210 int win2k_install_hack
= 0;
213 static VLANState
*first_vlan
;
215 const char *vnc_display
;
216 #if defined(TARGET_SPARC)
218 #elif defined(TARGET_I386)
220 #elif defined(TARGET_IA64)
225 int acpi_enabled
= 1;
230 int graphic_rotate
= 0;
232 const char *incoming
;
233 const char *option_rom
[MAX_OPTION_ROMS
];
235 int semihosting_enabled
= 0;
237 int time_drift_fix
= 0;
238 unsigned int kvm_shadow_memory
= 0;
239 const char *mem_path
= NULL
;
241 const char *cpu_vendor_string
;
245 const char *qemu_name
;
248 unsigned int nb_prom_envs
= 0;
249 const char *prom_envs
[MAX_PROM_ENVS
];
252 struct drive_opt drives_opt
[MAX_DRIVES
];
254 static CPUState
*cur_cpu
;
255 static CPUState
*next_cpu
;
256 static int event_pending
= 1;
257 /* Conversion factor from emulated instructions to virtual clock ticks. */
258 static int icount_time_shift
;
259 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
260 #define MAX_ICOUNT_SHIFT 10
261 /* Compensate for varying guest execution speed. */
262 static int64_t qemu_icount_bias
;
263 QEMUTimer
*icount_rt_timer
;
264 QEMUTimer
*icount_vm_timer
;
266 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
268 /* KVM runs the main loop in a separate thread. If we update one of the lists
269 * that are polled before or after select(), we need to make sure to break out
270 * of the select() to ensure the new item is serviced.
272 static void main_loop_break(void)
275 qemu_kvm_notify_work();
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base
= 0;
284 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
285 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
287 static uint32_t ioport_read(int index
, uint32_t address
)
289 static IOPortReadFunc
*default_func
[3] = {
290 default_ioport_readb
,
291 default_ioport_readw
,
294 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
296 func
= default_func
[index
];
297 return func(ioport_opaque
[address
], address
);
300 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
302 static IOPortWriteFunc
*default_func
[3] = {
303 default_ioport_writeb
,
304 default_ioport_writew
,
305 default_ioport_writel
307 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
309 func
= default_func
[index
];
310 func(ioport_opaque
[address
], address
, data
);
313 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
315 #ifdef DEBUG_UNUSED_IOPORT
316 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
321 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
323 #ifdef DEBUG_UNUSED_IOPORT
324 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
328 /* default is to make two byte accesses */
329 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
332 data
= ioport_read(0, address
);
333 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
334 data
|= ioport_read(0, address
) << 8;
338 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
340 ioport_write(0, address
, data
& 0xff);
341 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
342 ioport_write(0, address
, (data
>> 8) & 0xff);
345 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
347 #ifdef DEBUG_UNUSED_IOPORT
348 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
353 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
355 #ifdef DEBUG_UNUSED_IOPORT
356 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
360 /* size is the word size in byte */
361 int register_ioport_read(int start
, int length
, int size
,
362 IOPortReadFunc
*func
, void *opaque
)
368 } else if (size
== 2) {
370 } else if (size
== 4) {
373 hw_error("register_ioport_read: invalid size");
376 for(i
= start
; i
< start
+ length
; i
+= size
) {
377 ioport_read_table
[bsize
][i
] = func
;
378 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
379 hw_error("register_ioport_read: invalid opaque");
380 ioport_opaque
[i
] = opaque
;
385 /* size is the word size in byte */
386 int register_ioport_write(int start
, int length
, int size
,
387 IOPortWriteFunc
*func
, void *opaque
)
393 } else if (size
== 2) {
395 } else if (size
== 4) {
398 hw_error("register_ioport_write: invalid size");
401 for(i
= start
; i
< start
+ length
; i
+= size
) {
402 ioport_write_table
[bsize
][i
] = func
;
403 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
404 hw_error("register_ioport_write: invalid opaque");
405 ioport_opaque
[i
] = opaque
;
410 void isa_unassign_ioport(int start
, int length
)
414 for(i
= start
; i
< start
+ length
; i
++) {
415 ioport_read_table
[0][i
] = default_ioport_readb
;
416 ioport_read_table
[1][i
] = default_ioport_readw
;
417 ioport_read_table
[2][i
] = default_ioport_readl
;
419 ioport_write_table
[0][i
] = default_ioport_writeb
;
420 ioport_write_table
[1][i
] = default_ioport_writew
;
421 ioport_write_table
[2][i
] = default_ioport_writel
;
423 ioport_opaque
[i
] = NULL
;
427 /***********************************************************/
429 void cpu_outb(CPUState
*env
, int addr
, int val
)
432 if (loglevel
& CPU_LOG_IOPORT
)
433 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
435 ioport_write(0, addr
, val
);
438 env
->last_io_time
= cpu_get_time_fast();
442 void cpu_outw(CPUState
*env
, int addr
, int val
)
445 if (loglevel
& CPU_LOG_IOPORT
)
446 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
448 ioport_write(1, addr
, val
);
451 env
->last_io_time
= cpu_get_time_fast();
455 void cpu_outl(CPUState
*env
, int addr
, int val
)
458 if (loglevel
& CPU_LOG_IOPORT
)
459 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
461 ioport_write(2, addr
, val
);
464 env
->last_io_time
= cpu_get_time_fast();
468 int cpu_inb(CPUState
*env
, int addr
)
471 val
= ioport_read(0, addr
);
473 if (loglevel
& CPU_LOG_IOPORT
)
474 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
478 env
->last_io_time
= cpu_get_time_fast();
483 int cpu_inw(CPUState
*env
, int addr
)
486 val
= ioport_read(1, addr
);
488 if (loglevel
& CPU_LOG_IOPORT
)
489 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
493 env
->last_io_time
= cpu_get_time_fast();
498 int cpu_inl(CPUState
*env
, int addr
)
501 val
= ioport_read(2, addr
);
503 if (loglevel
& CPU_LOG_IOPORT
)
504 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
508 env
->last_io_time
= cpu_get_time_fast();
513 /***********************************************************/
514 void hw_error(const char *fmt
, ...)
520 fprintf(stderr
, "qemu: hardware error: ");
521 vfprintf(stderr
, fmt
, ap
);
522 fprintf(stderr
, "\n");
523 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
524 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
526 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
528 cpu_dump_state(env
, stderr
, fprintf
, 0);
535 /***********************************************************/
538 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
539 static void *qemu_put_kbd_event_opaque
;
540 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
541 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
543 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
545 qemu_put_kbd_event_opaque
= opaque
;
546 qemu_put_kbd_event
= func
;
549 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
550 void *opaque
, int absolute
,
553 QEMUPutMouseEntry
*s
, *cursor
;
555 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
559 s
->qemu_put_mouse_event
= func
;
560 s
->qemu_put_mouse_event_opaque
= opaque
;
561 s
->qemu_put_mouse_event_absolute
= absolute
;
562 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
565 if (!qemu_put_mouse_event_head
) {
566 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
570 cursor
= qemu_put_mouse_event_head
;
571 while (cursor
->next
!= NULL
)
572 cursor
= cursor
->next
;
575 qemu_put_mouse_event_current
= s
;
580 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
582 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
584 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
587 cursor
= qemu_put_mouse_event_head
;
588 while (cursor
!= NULL
&& cursor
!= entry
) {
590 cursor
= cursor
->next
;
593 if (cursor
== NULL
) // does not exist or list empty
595 else if (prev
== NULL
) { // entry is head
596 qemu_put_mouse_event_head
= cursor
->next
;
597 if (qemu_put_mouse_event_current
== entry
)
598 qemu_put_mouse_event_current
= cursor
->next
;
599 qemu_free(entry
->qemu_put_mouse_event_name
);
604 prev
->next
= entry
->next
;
606 if (qemu_put_mouse_event_current
== entry
)
607 qemu_put_mouse_event_current
= prev
;
609 qemu_free(entry
->qemu_put_mouse_event_name
);
613 void kbd_put_keycode(int keycode
)
615 if (qemu_put_kbd_event
) {
616 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
620 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
622 QEMUPutMouseEvent
*mouse_event
;
623 void *mouse_event_opaque
;
626 if (!qemu_put_mouse_event_current
) {
631 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
633 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
636 if (graphic_rotate
) {
637 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
640 width
= graphic_width
- 1;
641 mouse_event(mouse_event_opaque
,
642 width
- dy
, dx
, dz
, buttons_state
);
644 mouse_event(mouse_event_opaque
,
645 dx
, dy
, dz
, buttons_state
);
649 int kbd_mouse_is_absolute(void)
651 if (!qemu_put_mouse_event_current
)
654 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
657 void do_info_mice(void)
659 QEMUPutMouseEntry
*cursor
;
662 if (!qemu_put_mouse_event_head
) {
663 term_printf("No mouse devices connected\n");
667 term_printf("Mouse devices available:\n");
668 cursor
= qemu_put_mouse_event_head
;
669 while (cursor
!= NULL
) {
670 term_printf("%c Mouse #%d: %s\n",
671 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
672 index
, cursor
->qemu_put_mouse_event_name
);
674 cursor
= cursor
->next
;
678 void do_mouse_set(int index
)
680 QEMUPutMouseEntry
*cursor
;
683 if (!qemu_put_mouse_event_head
) {
684 term_printf("No mouse devices connected\n");
688 cursor
= qemu_put_mouse_event_head
;
689 while (cursor
!= NULL
&& index
!= i
) {
691 cursor
= cursor
->next
;
695 qemu_put_mouse_event_current
= cursor
;
697 term_printf("Mouse at given index not found\n");
700 /* compute with 96 bit intermediate result: (a*b)/c */
701 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
706 #ifdef WORDS_BIGENDIAN
716 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
717 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
720 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
724 /***********************************************************/
725 /* real time host monotonic timer */
727 #define QEMU_TIMER_BASE 1000000000LL
731 static int64_t clock_freq
;
733 static void init_get_clock(void)
737 ret
= QueryPerformanceFrequency(&freq
);
739 fprintf(stderr
, "Could not calibrate ticks\n");
742 clock_freq
= freq
.QuadPart
;
745 static int64_t get_clock(void)
748 QueryPerformanceCounter(&ti
);
749 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
754 static int use_rt_clock
;
756 static void init_get_clock(void)
759 #if defined(__linux__)
762 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
769 static int64_t get_clock(void)
771 #if defined(__linux__)
774 clock_gettime(CLOCK_MONOTONIC
, &ts
);
775 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
779 /* XXX: using gettimeofday leads to problems if the date
780 changes, so it should be avoided. */
782 gettimeofday(&tv
, NULL
);
783 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
788 /* Return the virtual CPU time, based on the instruction counter. */
789 static int64_t cpu_get_icount(void)
792 CPUState
*env
= cpu_single_env
;;
793 icount
= qemu_icount
;
796 fprintf(stderr
, "Bad clock read\n");
797 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
799 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
802 /***********************************************************/
803 /* guest cycle counter */
805 static int64_t cpu_ticks_prev
;
806 static int64_t cpu_ticks_offset
;
807 static int64_t cpu_clock_offset
;
808 static int cpu_ticks_enabled
;
810 /* return the host CPU cycle counter and handle stop/restart */
811 int64_t cpu_get_ticks(void)
814 return cpu_get_icount();
816 if (!cpu_ticks_enabled
) {
817 return cpu_ticks_offset
;
820 ticks
= cpu_get_real_ticks();
821 if (cpu_ticks_prev
> ticks
) {
822 /* Note: non increasing ticks may happen if the host uses
824 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
826 cpu_ticks_prev
= ticks
;
827 return ticks
+ cpu_ticks_offset
;
831 /* return the host CPU monotonic timer and handle stop/restart */
832 static int64_t cpu_get_clock(void)
835 if (!cpu_ticks_enabled
) {
836 return cpu_clock_offset
;
839 return ti
+ cpu_clock_offset
;
843 /* enable cpu_get_ticks() */
844 void cpu_enable_ticks(void)
846 if (!cpu_ticks_enabled
) {
847 cpu_ticks_offset
-= cpu_get_real_ticks();
848 cpu_clock_offset
-= get_clock();
849 cpu_ticks_enabled
= 1;
853 /* disable cpu_get_ticks() : the clock is stopped. You must not call
854 cpu_get_ticks() after that. */
855 void cpu_disable_ticks(void)
857 if (cpu_ticks_enabled
) {
858 cpu_ticks_offset
= cpu_get_ticks();
859 cpu_clock_offset
= cpu_get_clock();
860 cpu_ticks_enabled
= 0;
864 /***********************************************************/
867 #define QEMU_TIMER_REALTIME 0
868 #define QEMU_TIMER_VIRTUAL 1
872 /* XXX: add frequency */
880 struct QEMUTimer
*next
;
883 struct qemu_alarm_timer
{
887 int (*start
)(struct qemu_alarm_timer
*t
);
888 void (*stop
)(struct qemu_alarm_timer
*t
);
889 void (*rearm
)(struct qemu_alarm_timer
*t
);
893 #define ALARM_FLAG_DYNTICKS 0x1
894 #define ALARM_FLAG_EXPIRED 0x2
896 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
898 return t
->flags
& ALARM_FLAG_DYNTICKS
;
901 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
903 if (!alarm_has_dynticks(t
))
909 /* TODO: MIN_TIMER_REARM_US should be optimized */
910 #define MIN_TIMER_REARM_US 250
912 static struct qemu_alarm_timer
*alarm_timer
;
916 struct qemu_alarm_win32
{
920 } alarm_win32_data
= {0, NULL
, -1};
922 static int win32_start_timer(struct qemu_alarm_timer
*t
);
923 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
924 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
928 static int unix_start_timer(struct qemu_alarm_timer
*t
);
929 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
933 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
934 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
935 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
937 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
938 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
940 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
941 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
943 #endif /* __linux__ */
947 /* Correlation between real and virtual time is always going to be
948 fairly approximate, so ignore small variation.
949 When the guest is idle real and virtual time will be aligned in
951 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
953 static void icount_adjust(void)
958 static int64_t last_delta
;
959 /* If the VM is not running, then do nothing. */
963 cur_time
= cpu_get_clock();
964 cur_icount
= qemu_get_clock(vm_clock
);
965 delta
= cur_icount
- cur_time
;
966 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
968 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
969 && icount_time_shift
> 0) {
970 /* The guest is getting too far ahead. Slow time down. */
974 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
975 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
976 /* The guest is getting too far behind. Speed time up. */
980 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
983 static void icount_adjust_rt(void * opaque
)
985 qemu_mod_timer(icount_rt_timer
,
986 qemu_get_clock(rt_clock
) + 1000);
990 static void icount_adjust_vm(void * opaque
)
992 qemu_mod_timer(icount_vm_timer
,
993 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
997 static void init_icount_adjust(void)
999 /* Have both realtime and virtual time triggers for speed adjustment.
1000 The realtime trigger catches emulated time passing too slowly,
1001 the virtual time trigger catches emulated time passing too fast.
1002 Realtime triggers occur even when idle, so use them less frequently
1003 than VM triggers. */
1004 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1005 qemu_mod_timer(icount_rt_timer
,
1006 qemu_get_clock(rt_clock
) + 1000);
1007 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1008 qemu_mod_timer(icount_vm_timer
,
1009 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1012 static struct qemu_alarm_timer alarm_timers
[] = {
1015 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1016 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1017 /* HPET - if available - is preferred */
1018 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1019 /* ...otherwise try RTC */
1020 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1022 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1024 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1025 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1026 {"win32", 0, win32_start_timer
,
1027 win32_stop_timer
, NULL
, &alarm_win32_data
},
1032 static void show_available_alarms(void)
1036 printf("Available alarm timers, in order of precedence:\n");
1037 for (i
= 0; alarm_timers
[i
].name
; i
++)
1038 printf("%s\n", alarm_timers
[i
].name
);
1041 static void configure_alarms(char const *opt
)
1045 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1048 struct qemu_alarm_timer tmp
;
1050 if (!strcmp(opt
, "?")) {
1051 show_available_alarms();
1057 /* Reorder the array */
1058 name
= strtok(arg
, ",");
1060 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1061 if (!strcmp(alarm_timers
[i
].name
, name
))
1066 fprintf(stderr
, "Unknown clock %s\n", name
);
1075 tmp
= alarm_timers
[i
];
1076 alarm_timers
[i
] = alarm_timers
[cur
];
1077 alarm_timers
[cur
] = tmp
;
1081 name
= strtok(NULL
, ",");
1087 /* Disable remaining timers */
1088 for (i
= cur
; i
< count
; i
++)
1089 alarm_timers
[i
].name
= NULL
;
1091 show_available_alarms();
1096 QEMUClock
*rt_clock
;
1097 QEMUClock
*vm_clock
;
1099 static QEMUTimer
*active_timers
[2];
1101 static QEMUClock
*qemu_new_clock(int type
)
1104 clock
= qemu_mallocz(sizeof(QEMUClock
));
1111 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1115 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1118 ts
->opaque
= opaque
;
1122 void qemu_free_timer(QEMUTimer
*ts
)
1127 /* stop a timer, but do not dealloc it */
1128 void qemu_del_timer(QEMUTimer
*ts
)
1132 /* NOTE: this code must be signal safe because
1133 qemu_timer_expired() can be called from a signal. */
1134 pt
= &active_timers
[ts
->clock
->type
];
1147 /* modify the current timer so that it will be fired when current_time
1148 >= expire_time. The corresponding callback will be called. */
1149 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1155 /* add the timer in the sorted list */
1156 /* NOTE: this code must be signal safe because
1157 qemu_timer_expired() can be called from a signal. */
1158 pt
= &active_timers
[ts
->clock
->type
];
1163 if (t
->expire_time
> expire_time
)
1167 ts
->expire_time
= expire_time
;
1171 /* Rearm if necessary */
1172 if (pt
== &active_timers
[ts
->clock
->type
]) {
1173 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1174 qemu_rearm_alarm_timer(alarm_timer
);
1176 /* Interrupt execution to force deadline recalculation. */
1177 if (use_icount
&& cpu_single_env
) {
1178 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1183 int qemu_timer_pending(QEMUTimer
*ts
)
1186 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1193 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1197 return (timer_head
->expire_time
<= current_time
);
1200 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1206 if (!ts
|| ts
->expire_time
> current_time
)
1208 /* remove timer from the list before calling the callback */
1209 *ptimer_head
= ts
->next
;
1212 /* run the callback (the timer list can be modified) */
1217 int64_t qemu_get_clock(QEMUClock
*clock
)
1219 switch(clock
->type
) {
1220 case QEMU_TIMER_REALTIME
:
1221 return get_clock() / 1000000;
1223 case QEMU_TIMER_VIRTUAL
:
1225 return cpu_get_icount();
1227 return cpu_get_clock();
1232 static void init_timers(void)
1235 ticks_per_sec
= QEMU_TIMER_BASE
;
1236 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1237 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1241 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1243 uint64_t expire_time
;
1245 if (qemu_timer_pending(ts
)) {
1246 expire_time
= ts
->expire_time
;
1250 qemu_put_be64(f
, expire_time
);
1253 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1255 uint64_t expire_time
;
1257 expire_time
= qemu_get_be64(f
);
1258 if (expire_time
!= -1) {
1259 qemu_mod_timer(ts
, expire_time
);
1265 static void timer_save(QEMUFile
*f
, void *opaque
)
1267 if (cpu_ticks_enabled
) {
1268 hw_error("cannot save state if virtual timers are running");
1270 qemu_put_be64(f
, cpu_ticks_offset
);
1271 qemu_put_be64(f
, ticks_per_sec
);
1272 qemu_put_be64(f
, cpu_clock_offset
);
1275 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1277 if (version_id
!= 1 && version_id
!= 2)
1279 if (cpu_ticks_enabled
) {
1282 cpu_ticks_offset
=qemu_get_be64(f
);
1283 ticks_per_sec
=qemu_get_be64(f
);
1284 if (version_id
== 2) {
1285 cpu_clock_offset
=qemu_get_be64(f
);
1291 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1292 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1294 static void host_alarm_handler(int host_signum
)
1298 #define DISP_FREQ 1000
1300 static int64_t delta_min
= INT64_MAX
;
1301 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1303 ti
= qemu_get_clock(vm_clock
);
1304 if (last_clock
!= 0) {
1305 delta
= ti
- last_clock
;
1306 if (delta
< delta_min
)
1308 if (delta
> delta_max
)
1311 if (++count
== DISP_FREQ
) {
1312 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1313 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1314 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1315 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1316 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1318 delta_min
= INT64_MAX
;
1327 alarm_has_dynticks(alarm_timer
) ||
1329 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1330 qemu_get_clock(vm_clock
))) ||
1331 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1332 qemu_get_clock(rt_clock
))) {
1334 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1335 SetEvent(data
->host_alarm
);
1337 CPUState
*env
= next_cpu
;
1339 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1342 /* stop the currently executing cpu because a timer occured */
1343 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1345 if (env
->kqemu_enabled
) {
1346 kqemu_cpu_interrupt(env
);
1354 static int64_t qemu_next_deadline(void)
1358 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1359 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1360 qemu_get_clock(vm_clock
);
1362 /* To avoid problems with overflow limit this to 2^32. */
1372 static uint64_t qemu_next_deadline_dyntick(void)
1380 delta
= (qemu_next_deadline() + 999) / 1000;
1382 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1383 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1384 qemu_get_clock(rt_clock
))*1000;
1385 if (rtdelta
< delta
)
1389 if (delta
< MIN_TIMER_REARM_US
)
1390 delta
= MIN_TIMER_REARM_US
;
1397 #if defined(__linux__)
1399 #define RTC_FREQ 1024
1401 static void enable_sigio_timer(int fd
)
1403 struct sigaction act
;
1406 sigfillset(&act
.sa_mask
);
1408 act
.sa_handler
= host_alarm_handler
;
1410 sigaction(SIGIO
, &act
, NULL
);
1411 fcntl(fd
, F_SETFL
, O_ASYNC
);
1412 fcntl(fd
, F_SETOWN
, getpid());
1415 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1417 struct hpet_info info
;
1420 fd
= open("/dev/hpet", O_RDONLY
);
1425 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1427 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1428 "error, but for better emulation accuracy type:\n"
1429 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1433 /* Check capabilities */
1434 r
= ioctl(fd
, HPET_INFO
, &info
);
1438 /* Enable periodic mode */
1439 r
= ioctl(fd
, HPET_EPI
, 0);
1440 if (info
.hi_flags
&& (r
< 0))
1443 /* Enable interrupt */
1444 r
= ioctl(fd
, HPET_IE_ON
, 0);
1448 enable_sigio_timer(fd
);
1449 t
->priv
= (void *)(long)fd
;
1457 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1459 int fd
= (long)t
->priv
;
1464 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1467 unsigned long current_rtc_freq
= 0;
1469 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1472 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1473 if (current_rtc_freq
!= RTC_FREQ
&&
1474 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1475 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1476 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1477 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1480 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1486 enable_sigio_timer(rtc_fd
);
1488 t
->priv
= (void *)(long)rtc_fd
;
1493 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1495 int rtc_fd
= (long)t
->priv
;
1500 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1504 struct sigaction act
;
1506 sigfillset(&act
.sa_mask
);
1508 act
.sa_handler
= host_alarm_handler
;
1510 sigaction(SIGALRM
, &act
, NULL
);
1512 ev
.sigev_value
.sival_int
= 0;
1513 ev
.sigev_notify
= SIGEV_SIGNAL
;
1514 ev
.sigev_signo
= SIGALRM
;
1516 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1517 perror("timer_create");
1519 /* disable dynticks */
1520 fprintf(stderr
, "Dynamic Ticks disabled\n");
1525 t
->priv
= (void *)host_timer
;
1530 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1532 timer_t host_timer
= (timer_t
)t
->priv
;
1534 timer_delete(host_timer
);
1537 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1539 timer_t host_timer
= (timer_t
)t
->priv
;
1540 struct itimerspec timeout
;
1541 int64_t nearest_delta_us
= INT64_MAX
;
1544 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1545 !active_timers
[QEMU_TIMER_VIRTUAL
])
1548 nearest_delta_us
= qemu_next_deadline_dyntick();
1550 /* check whether a timer is already running */
1551 if (timer_gettime(host_timer
, &timeout
)) {
1553 fprintf(stderr
, "Internal timer error: aborting\n");
1556 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1557 if (current_us
&& current_us
<= nearest_delta_us
)
1560 timeout
.it_interval
.tv_sec
= 0;
1561 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1562 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1563 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1564 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1566 fprintf(stderr
, "Internal timer error: aborting\n");
1571 #endif /* defined(__linux__) */
1573 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1575 struct sigaction act
;
1576 struct itimerval itv
;
1580 sigfillset(&act
.sa_mask
);
1582 act
.sa_handler
= host_alarm_handler
;
1584 sigaction(SIGALRM
, &act
, NULL
);
1586 itv
.it_interval
.tv_sec
= 0;
1587 /* for i386 kernel 2.6 to get 1 ms */
1588 itv
.it_interval
.tv_usec
= 999;
1589 itv
.it_value
.tv_sec
= 0;
1590 itv
.it_value
.tv_usec
= 10 * 1000;
1592 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1599 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1601 struct itimerval itv
;
1603 memset(&itv
, 0, sizeof(itv
));
1604 setitimer(ITIMER_REAL
, &itv
, NULL
);
1607 #endif /* !defined(_WIN32) */
1611 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1614 struct qemu_alarm_win32
*data
= t
->priv
;
1617 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1618 if (!data
->host_alarm
) {
1619 perror("Failed CreateEvent");
1623 memset(&tc
, 0, sizeof(tc
));
1624 timeGetDevCaps(&tc
, sizeof(tc
));
1626 if (data
->period
< tc
.wPeriodMin
)
1627 data
->period
= tc
.wPeriodMin
;
1629 timeBeginPeriod(data
->period
);
1631 flags
= TIME_CALLBACK_FUNCTION
;
1632 if (alarm_has_dynticks(t
))
1633 flags
|= TIME_ONESHOT
;
1635 flags
|= TIME_PERIODIC
;
1637 data
->timerId
= timeSetEvent(1, // interval (ms)
1638 data
->period
, // resolution
1639 host_alarm_handler
, // function
1640 (DWORD
)t
, // parameter
1643 if (!data
->timerId
) {
1644 perror("Failed to initialize win32 alarm timer");
1646 timeEndPeriod(data
->period
);
1647 CloseHandle(data
->host_alarm
);
1651 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1656 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1658 struct qemu_alarm_win32
*data
= t
->priv
;
1660 timeKillEvent(data
->timerId
);
1661 timeEndPeriod(data
->period
);
1663 CloseHandle(data
->host_alarm
);
1666 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1668 struct qemu_alarm_win32
*data
= t
->priv
;
1669 uint64_t nearest_delta_us
;
1671 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1672 !active_timers
[QEMU_TIMER_VIRTUAL
])
1675 nearest_delta_us
= qemu_next_deadline_dyntick();
1676 nearest_delta_us
/= 1000;
1678 timeKillEvent(data
->timerId
);
1680 data
->timerId
= timeSetEvent(1,
1684 TIME_ONESHOT
| TIME_PERIODIC
);
1686 if (!data
->timerId
) {
1687 perror("Failed to re-arm win32 alarm timer");
1689 timeEndPeriod(data
->period
);
1690 CloseHandle(data
->host_alarm
);
1697 static void init_timer_alarm(void)
1699 struct qemu_alarm_timer
*t
;
1702 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1703 t
= &alarm_timers
[i
];
1711 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1712 fprintf(stderr
, "Terminating\n");
1719 static void quit_timers(void)
1721 alarm_timer
->stop(alarm_timer
);
1725 /***********************************************************/
1726 /* host time/date access */
1727 void qemu_get_timedate(struct tm
*tm
, int offset
)
1734 if (rtc_date_offset
== -1) {
1738 ret
= localtime(&ti
);
1740 ti
-= rtc_date_offset
;
1744 memcpy(tm
, ret
, sizeof(struct tm
));
1747 int qemu_timedate_diff(struct tm
*tm
)
1751 if (rtc_date_offset
== -1)
1753 seconds
= mktimegm(tm
);
1755 seconds
= mktime(tm
);
1757 seconds
= mktimegm(tm
) + rtc_date_offset
;
1759 return seconds
- time(NULL
);
1762 /***********************************************************/
1763 /* character device */
1765 static void qemu_chr_event(CharDriverState
*s
, int event
)
1769 s
->chr_event(s
->handler_opaque
, event
);
1772 static void qemu_chr_reset_bh(void *opaque
)
1774 CharDriverState
*s
= opaque
;
1775 qemu_chr_event(s
, CHR_EVENT_RESET
);
1776 qemu_bh_delete(s
->bh
);
1780 void qemu_chr_reset(CharDriverState
*s
)
1782 if (s
->bh
== NULL
) {
1783 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1784 qemu_bh_schedule(s
->bh
);
1788 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1790 return s
->chr_write(s
, buf
, len
);
1793 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1797 return s
->chr_ioctl(s
, cmd
, arg
);
1800 int qemu_chr_can_read(CharDriverState
*s
)
1802 if (!s
->chr_can_read
)
1804 return s
->chr_can_read(s
->handler_opaque
);
1807 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1809 s
->chr_read(s
->handler_opaque
, buf
, len
);
1812 void qemu_chr_accept_input(CharDriverState
*s
)
1814 if (s
->chr_accept_input
)
1815 s
->chr_accept_input(s
);
1818 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1823 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1824 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1828 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1830 if (s
->chr_send_event
)
1831 s
->chr_send_event(s
, event
);
1834 void qemu_chr_add_handlers(CharDriverState
*s
,
1835 IOCanRWHandler
*fd_can_read
,
1836 IOReadHandler
*fd_read
,
1837 IOEventHandler
*fd_event
,
1840 s
->chr_can_read
= fd_can_read
;
1841 s
->chr_read
= fd_read
;
1842 s
->chr_event
= fd_event
;
1843 s
->handler_opaque
= opaque
;
1844 if (s
->chr_update_read_handler
)
1845 s
->chr_update_read_handler(s
);
1848 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1853 static CharDriverState
*qemu_chr_open_null(void)
1855 CharDriverState
*chr
;
1857 chr
= qemu_mallocz(sizeof(CharDriverState
));
1860 chr
->chr_write
= null_chr_write
;
1864 /* MUX driver for serial I/O splitting */
1865 static int term_timestamps
;
1866 static int64_t term_timestamps_start
;
1868 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1869 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1871 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1872 IOReadHandler
*chr_read
[MAX_MUX
];
1873 IOEventHandler
*chr_event
[MAX_MUX
];
1874 void *ext_opaque
[MAX_MUX
];
1875 CharDriverState
*drv
;
1876 unsigned char buffer
[MUX_BUFFER_SIZE
];
1880 int term_got_escape
;
1885 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1887 MuxDriver
*d
= chr
->opaque
;
1889 if (!term_timestamps
) {
1890 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1895 for(i
= 0; i
< len
; i
++) {
1896 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1897 if (buf
[i
] == '\n') {
1903 if (term_timestamps_start
== -1)
1904 term_timestamps_start
= ti
;
1905 ti
-= term_timestamps_start
;
1906 secs
= ti
/ 1000000000;
1907 snprintf(buf1
, sizeof(buf1
),
1908 "[%02d:%02d:%02d.%03d] ",
1912 (int)((ti
/ 1000000) % 1000));
1913 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1920 static char *mux_help
[] = {
1921 "% h print this help\n\r",
1922 "% x exit emulator\n\r",
1923 "% s save disk data back to file (if -snapshot)\n\r",
1924 "% t toggle console timestamps\n\r"
1925 "% b send break (magic sysrq)\n\r",
1926 "% c switch between console and monitor\n\r",
1931 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1932 static void mux_print_help(CharDriverState
*chr
)
1935 char ebuf
[15] = "Escape-Char";
1936 char cbuf
[50] = "\n\r";
1938 if (term_escape_char
> 0 && term_escape_char
< 26) {
1939 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1940 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1942 snprintf(cbuf
, sizeof(cbuf
),
1943 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1946 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1947 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1948 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1949 if (mux_help
[i
][j
] == '%')
1950 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1952 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1957 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1959 if (d
->term_got_escape
) {
1960 d
->term_got_escape
= 0;
1961 if (ch
== term_escape_char
)
1966 mux_print_help(chr
);
1970 char *term
= "QEMU: Terminated\n\r";
1971 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1978 for (i
= 0; i
< nb_drives
; i
++) {
1979 bdrv_commit(drives_table
[i
].bdrv
);
1984 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1987 /* Switch to the next registered device */
1989 if (chr
->focus
>= d
->mux_cnt
)
1993 term_timestamps
= !term_timestamps
;
1994 term_timestamps_start
= -1;
1997 } else if (ch
== term_escape_char
) {
1998 d
->term_got_escape
= 1;
2006 static void mux_chr_accept_input(CharDriverState
*chr
)
2009 MuxDriver
*d
= chr
->opaque
;
2011 while (d
->prod
!= d
->cons
&&
2012 d
->chr_can_read
[m
] &&
2013 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
2014 d
->chr_read
[m
](d
->ext_opaque
[m
],
2015 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2019 static int mux_chr_can_read(void *opaque
)
2021 CharDriverState
*chr
= opaque
;
2022 MuxDriver
*d
= chr
->opaque
;
2024 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2026 if (d
->chr_can_read
[chr
->focus
])
2027 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2031 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2033 CharDriverState
*chr
= opaque
;
2034 MuxDriver
*d
= chr
->opaque
;
2038 mux_chr_accept_input (opaque
);
2040 for(i
= 0; i
< size
; i
++)
2041 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2042 if (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
], &buf
[i
], 1);
2047 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2051 static void mux_chr_event(void *opaque
, int event
)
2053 CharDriverState
*chr
= opaque
;
2054 MuxDriver
*d
= chr
->opaque
;
2057 /* Send the event to all registered listeners */
2058 for (i
= 0; i
< d
->mux_cnt
; i
++)
2059 if (d
->chr_event
[i
])
2060 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2063 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2065 MuxDriver
*d
= chr
->opaque
;
2067 if (d
->mux_cnt
>= MAX_MUX
) {
2068 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2071 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2072 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2073 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2074 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2075 /* Fix up the real driver with mux routines */
2076 if (d
->mux_cnt
== 0) {
2077 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2078 mux_chr_event
, chr
);
2080 chr
->focus
= d
->mux_cnt
;
2084 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2086 CharDriverState
*chr
;
2089 chr
= qemu_mallocz(sizeof(CharDriverState
));
2092 d
= qemu_mallocz(sizeof(MuxDriver
));
2101 chr
->chr_write
= mux_chr_write
;
2102 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2103 chr
->chr_accept_input
= mux_chr_accept_input
;
2110 static void socket_cleanup(void)
2115 static int socket_init(void)
2120 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2122 err
= WSAGetLastError();
2123 fprintf(stderr
, "WSAStartup: %d\n", err
);
2126 atexit(socket_cleanup
);
2130 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2136 ret
= send(fd
, buf
, len
, 0);
2139 errno
= WSAGetLastError();
2140 if (errno
!= WSAEWOULDBLOCK
) {
2143 } else if (ret
== 0) {
2153 void socket_set_nonblock(int fd
)
2155 unsigned long opt
= 1;
2156 ioctlsocket(fd
, FIONBIO
, &opt
);
2161 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2167 ret
= write(fd
, buf
, len
);
2169 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2171 } else if (ret
== 0) {
2181 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2183 return unix_write(fd
, buf
, len1
);
2186 void socket_set_nonblock(int fd
)
2189 f
= fcntl(fd
, F_GETFL
);
2190 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2192 #endif /* !_WIN32 */
2201 #define STDIO_MAX_CLIENTS 1
2202 static int stdio_nb_clients
= 0;
2204 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2206 FDCharDriver
*s
= chr
->opaque
;
2207 return unix_write(s
->fd_out
, buf
, len
);
2210 static int fd_chr_read_poll(void *opaque
)
2212 CharDriverState
*chr
= opaque
;
2213 FDCharDriver
*s
= chr
->opaque
;
2215 s
->max_size
= qemu_chr_can_read(chr
);
2219 static void fd_chr_read(void *opaque
)
2221 CharDriverState
*chr
= opaque
;
2222 FDCharDriver
*s
= chr
->opaque
;
2227 if (len
> s
->max_size
)
2231 size
= read(s
->fd_in
, buf
, len
);
2233 /* FD has been closed. Remove it from the active list. */
2234 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2238 qemu_chr_read(chr
, buf
, size
);
2242 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2244 FDCharDriver
*s
= chr
->opaque
;
2246 if (s
->fd_in
>= 0) {
2247 if (nographic
&& s
->fd_in
== 0) {
2249 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2250 fd_chr_read
, NULL
, chr
);
2255 static void fd_chr_close(struct CharDriverState
*chr
)
2257 FDCharDriver
*s
= chr
->opaque
;
2259 if (s
->fd_in
>= 0) {
2260 if (nographic
&& s
->fd_in
== 0) {
2262 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2269 /* open a character device to a unix fd */
2270 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2272 CharDriverState
*chr
;
2275 chr
= qemu_mallocz(sizeof(CharDriverState
));
2278 s
= qemu_mallocz(sizeof(FDCharDriver
));
2286 chr
->chr_write
= fd_chr_write
;
2287 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2288 chr
->chr_close
= fd_chr_close
;
2290 qemu_chr_reset(chr
);
2295 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2299 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2302 return qemu_chr_open_fd(-1, fd_out
);
2305 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2308 char filename_in
[256], filename_out
[256];
2310 snprintf(filename_in
, 256, "%s.in", filename
);
2311 snprintf(filename_out
, 256, "%s.out", filename
);
2312 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2313 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2314 if (fd_in
< 0 || fd_out
< 0) {
2319 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2323 return qemu_chr_open_fd(fd_in
, fd_out
);
2327 /* for STDIO, we handle the case where several clients use it
2330 #define TERM_FIFO_MAX_SIZE 1
2332 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2333 static int term_fifo_size
;
2335 static int stdio_read_poll(void *opaque
)
2337 CharDriverState
*chr
= opaque
;
2339 /* try to flush the queue if needed */
2340 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2341 qemu_chr_read(chr
, term_fifo
, 1);
2344 /* see if we can absorb more chars */
2345 if (term_fifo_size
== 0)
2351 static void stdio_read(void *opaque
)
2355 CharDriverState
*chr
= opaque
;
2357 size
= read(0, buf
, 1);
2359 /* stdin has been closed. Remove it from the active list. */
2360 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2364 if (qemu_chr_can_read(chr
) > 0) {
2365 qemu_chr_read(chr
, buf
, 1);
2366 } else if (term_fifo_size
== 0) {
2367 term_fifo
[term_fifo_size
++] = buf
[0];
2372 /* init terminal so that we can grab keys */
2373 static struct termios oldtty
;
2374 static int old_fd0_flags
;
2375 static int term_atexit_done
;
2377 static void term_exit(void)
2379 tcsetattr (0, TCSANOW
, &oldtty
);
2380 fcntl(0, F_SETFL
, old_fd0_flags
);
2383 static void term_init(void)
2387 tcgetattr (0, &tty
);
2389 old_fd0_flags
= fcntl(0, F_GETFL
);
2391 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2392 |INLCR
|IGNCR
|ICRNL
|IXON
);
2393 tty
.c_oflag
|= OPOST
;
2394 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2395 /* if graphical mode, we allow Ctrl-C handling */
2397 tty
.c_lflag
&= ~ISIG
;
2398 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2401 tty
.c_cc
[VTIME
] = 0;
2403 tcsetattr (0, TCSANOW
, &tty
);
2405 if (!term_atexit_done
++)
2408 fcntl(0, F_SETFL
, O_NONBLOCK
);
2411 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2415 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2419 static CharDriverState
*qemu_chr_open_stdio(void)
2421 CharDriverState
*chr
;
2423 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2425 chr
= qemu_chr_open_fd(0, 1);
2426 chr
->chr_close
= qemu_chr_close_stdio
;
2427 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2435 /* Once Solaris has openpty(), this is going to be removed. */
2436 int openpty(int *amaster
, int *aslave
, char *name
,
2437 struct termios
*termp
, struct winsize
*winp
)
2440 int mfd
= -1, sfd
= -1;
2442 *amaster
= *aslave
= -1;
2444 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2448 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2451 if ((slave
= ptsname(mfd
)) == NULL
)
2454 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2457 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2458 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2466 ioctl(sfd
, TIOCSWINSZ
, winp
);
2477 void cfmakeraw (struct termios
*termios_p
)
2479 termios_p
->c_iflag
&=
2480 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2481 termios_p
->c_oflag
&= ~OPOST
;
2482 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2483 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2484 termios_p
->c_cflag
|= CS8
;
2486 termios_p
->c_cc
[VMIN
] = 0;
2487 termios_p
->c_cc
[VTIME
] = 0;
2491 #if defined(__linux__) || defined(__sun__)
2501 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2502 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2504 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2506 PtyCharDriver
*s
= chr
->opaque
;
2508 if (!s
->connected
) {
2509 /* guest sends data, check for (re-)connect */
2510 pty_chr_update_read_handler(chr
);
2513 return unix_write(s
->fd
, buf
, len
);
2516 static int pty_chr_read_poll(void *opaque
)
2518 CharDriverState
*chr
= opaque
;
2519 PtyCharDriver
*s
= chr
->opaque
;
2521 s
->read_bytes
= qemu_chr_can_read(chr
);
2522 return s
->read_bytes
;
2525 static void pty_chr_read(void *opaque
)
2527 CharDriverState
*chr
= opaque
;
2528 PtyCharDriver
*s
= chr
->opaque
;
2533 if (len
> s
->read_bytes
)
2534 len
= s
->read_bytes
;
2537 size
= read(s
->fd
, buf
, len
);
2538 if ((size
== -1 && errno
== EIO
) ||
2540 pty_chr_state(chr
, 0);
2544 pty_chr_state(chr
, 1);
2545 qemu_chr_read(chr
, buf
, size
);
2549 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2551 PtyCharDriver
*s
= chr
->opaque
;
2553 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2554 pty_chr_read
, NULL
, chr
);
2557 * Short timeout here: just need wait long enougth that qemu makes
2558 * it through the poll loop once. When reconnected we want a
2559 * short timeout so we notice it almost instantly. Otherwise
2560 * read() gives us -EIO instantly, making pty_chr_state() reset the
2561 * timeout to the normal (much longer) poll interval before the
2564 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2567 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2569 PtyCharDriver
*s
= chr
->opaque
;
2572 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2575 /* (re-)connect poll interval for idle guests: once per second.
2576 * We check more frequently in case the guests sends data to
2577 * the virtual device linked to our pty. */
2578 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2581 qemu_chr_reset(chr
);
2586 static void pty_chr_timer(void *opaque
)
2588 struct CharDriverState
*chr
= opaque
;
2589 PtyCharDriver
*s
= chr
->opaque
;
2594 /* If we arrive here without polling being cleared due
2595 * read returning -EIO, then we are (re-)connected */
2596 pty_chr_state(chr
, 1);
2601 pty_chr_update_read_handler(chr
);
2604 static void pty_chr_close(struct CharDriverState
*chr
)
2606 PtyCharDriver
*s
= chr
->opaque
;
2608 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2613 static CharDriverState
*qemu_chr_open_pty(void)
2615 CharDriverState
*chr
;
2620 chr
= qemu_mallocz(sizeof(CharDriverState
));
2623 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2629 if (openpty(&s
->fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2633 /* Set raw attributes on the pty. */
2635 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2638 fprintf(stderr
, "char device redirected to %s\n", ptsname(s
->fd
));
2641 chr
->chr_write
= pty_chr_write
;
2642 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2643 chr
->chr_close
= pty_chr_close
;
2645 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2650 static void tty_serial_init(int fd
, int speed
,
2651 int parity
, int data_bits
, int stop_bits
)
2657 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2658 speed
, parity
, data_bits
, stop_bits
);
2660 tcgetattr (fd
, &tty
);
2663 if (speed
<= 50 * MARGIN
)
2665 else if (speed
<= 75 * MARGIN
)
2667 else if (speed
<= 300 * MARGIN
)
2669 else if (speed
<= 600 * MARGIN
)
2671 else if (speed
<= 1200 * MARGIN
)
2673 else if (speed
<= 2400 * MARGIN
)
2675 else if (speed
<= 4800 * MARGIN
)
2677 else if (speed
<= 9600 * MARGIN
)
2679 else if (speed
<= 19200 * MARGIN
)
2681 else if (speed
<= 38400 * MARGIN
)
2683 else if (speed
<= 57600 * MARGIN
)
2685 else if (speed
<= 115200 * MARGIN
)
2690 cfsetispeed(&tty
, spd
);
2691 cfsetospeed(&tty
, spd
);
2693 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2694 |INLCR
|IGNCR
|ICRNL
|IXON
);
2695 tty
.c_oflag
|= OPOST
;
2696 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2697 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2718 tty
.c_cflag
|= PARENB
;
2721 tty
.c_cflag
|= PARENB
| PARODD
;
2725 tty
.c_cflag
|= CSTOPB
;
2727 tcsetattr (fd
, TCSANOW
, &tty
);
2730 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2732 FDCharDriver
*s
= chr
->opaque
;
2735 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2737 QEMUSerialSetParams
*ssp
= arg
;
2738 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2739 ssp
->data_bits
, ssp
->stop_bits
);
2742 case CHR_IOCTL_SERIAL_SET_BREAK
:
2744 int enable
= *(int *)arg
;
2746 tcsendbreak(s
->fd_in
, 1);
2749 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2752 int *targ
= (int *)arg
;
2753 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2755 if (sarg
| TIOCM_CTS
)
2756 *targ
|= CHR_TIOCM_CTS
;
2757 if (sarg
| TIOCM_CAR
)
2758 *targ
|= CHR_TIOCM_CAR
;
2759 if (sarg
| TIOCM_DSR
)
2760 *targ
|= CHR_TIOCM_DSR
;
2761 if (sarg
| TIOCM_RI
)
2762 *targ
|= CHR_TIOCM_RI
;
2763 if (sarg
| TIOCM_DTR
)
2764 *targ
|= CHR_TIOCM_DTR
;
2765 if (sarg
| TIOCM_RTS
)
2766 *targ
|= CHR_TIOCM_RTS
;
2769 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2771 int sarg
= *(int *)arg
;
2773 if (sarg
| CHR_TIOCM_DTR
)
2775 if (sarg
| CHR_TIOCM_RTS
)
2777 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2786 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2788 CharDriverState
*chr
;
2791 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2792 tty_serial_init(fd
, 115200, 'N', 8, 1);
2793 chr
= qemu_chr_open_fd(fd
, fd
);
2798 chr
->chr_ioctl
= tty_serial_ioctl
;
2799 qemu_chr_reset(chr
);
2802 #else /* ! __linux__ && ! __sun__ */
2803 static CharDriverState
*qemu_chr_open_pty(void)
2807 #endif /* __linux__ || __sun__ */
2809 #if defined(__linux__)
2813 } ParallelCharDriver
;
2815 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2817 if (s
->mode
!= mode
) {
2819 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2826 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2828 ParallelCharDriver
*drv
= chr
->opaque
;
2833 case CHR_IOCTL_PP_READ_DATA
:
2834 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2836 *(uint8_t *)arg
= b
;
2838 case CHR_IOCTL_PP_WRITE_DATA
:
2839 b
= *(uint8_t *)arg
;
2840 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2843 case CHR_IOCTL_PP_READ_CONTROL
:
2844 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2846 /* Linux gives only the lowest bits, and no way to know data
2847 direction! For better compatibility set the fixed upper
2849 *(uint8_t *)arg
= b
| 0xc0;
2851 case CHR_IOCTL_PP_WRITE_CONTROL
:
2852 b
= *(uint8_t *)arg
;
2853 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2856 case CHR_IOCTL_PP_READ_STATUS
:
2857 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2859 *(uint8_t *)arg
= b
;
2861 case CHR_IOCTL_PP_DATA_DIR
:
2862 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2865 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2866 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2867 struct ParallelIOArg
*parg
= arg
;
2868 int n
= read(fd
, parg
->buffer
, parg
->count
);
2869 if (n
!= parg
->count
) {
2874 case CHR_IOCTL_PP_EPP_READ
:
2875 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2876 struct ParallelIOArg
*parg
= arg
;
2877 int n
= read(fd
, parg
->buffer
, parg
->count
);
2878 if (n
!= parg
->count
) {
2883 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2884 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2885 struct ParallelIOArg
*parg
= arg
;
2886 int n
= write(fd
, parg
->buffer
, parg
->count
);
2887 if (n
!= parg
->count
) {
2892 case CHR_IOCTL_PP_EPP_WRITE
:
2893 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2894 struct ParallelIOArg
*parg
= arg
;
2895 int n
= write(fd
, parg
->buffer
, parg
->count
);
2896 if (n
!= parg
->count
) {
2907 static void pp_close(CharDriverState
*chr
)
2909 ParallelCharDriver
*drv
= chr
->opaque
;
2912 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2913 ioctl(fd
, PPRELEASE
);
2918 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2920 CharDriverState
*chr
;
2921 ParallelCharDriver
*drv
;
2924 TFR(fd
= open(filename
, O_RDWR
));
2928 if (ioctl(fd
, PPCLAIM
) < 0) {
2933 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2939 drv
->mode
= IEEE1284_MODE_COMPAT
;
2941 chr
= qemu_mallocz(sizeof(CharDriverState
));
2947 chr
->chr_write
= null_chr_write
;
2948 chr
->chr_ioctl
= pp_ioctl
;
2949 chr
->chr_close
= pp_close
;
2952 qemu_chr_reset(chr
);
2956 #endif /* __linux__ */
2962 HANDLE hcom
, hrecv
, hsend
;
2963 OVERLAPPED orecv
, osend
;
2968 #define NSENDBUF 2048
2969 #define NRECVBUF 2048
2970 #define MAXCONNECT 1
2971 #define NTIMEOUT 5000
2973 static int win_chr_poll(void *opaque
);
2974 static int win_chr_pipe_poll(void *opaque
);
2976 static void win_chr_close(CharDriverState
*chr
)
2978 WinCharState
*s
= chr
->opaque
;
2981 CloseHandle(s
->hsend
);
2985 CloseHandle(s
->hrecv
);
2989 CloseHandle(s
->hcom
);
2993 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2995 qemu_del_polling_cb(win_chr_poll
, chr
);
2998 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
3000 WinCharState
*s
= chr
->opaque
;
3002 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
3007 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3009 fprintf(stderr
, "Failed CreateEvent\n");
3012 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3014 fprintf(stderr
, "Failed CreateEvent\n");
3018 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
3019 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
3020 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3021 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3026 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3027 fprintf(stderr
, "Failed SetupComm\n");
3031 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3032 size
= sizeof(COMMCONFIG
);
3033 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3034 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3035 CommConfigDialog(filename
, NULL
, &comcfg
);
3037 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3038 fprintf(stderr
, "Failed SetCommState\n");
3042 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3043 fprintf(stderr
, "Failed SetCommMask\n");
3047 cto
.ReadIntervalTimeout
= MAXDWORD
;
3048 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3049 fprintf(stderr
, "Failed SetCommTimeouts\n");
3053 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3054 fprintf(stderr
, "Failed ClearCommError\n");
3057 qemu_add_polling_cb(win_chr_poll
, chr
);
3065 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3067 WinCharState
*s
= chr
->opaque
;
3068 DWORD len
, ret
, size
, err
;
3071 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3072 s
->osend
.hEvent
= s
->hsend
;
3075 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3077 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3079 err
= GetLastError();
3080 if (err
== ERROR_IO_PENDING
) {
3081 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3099 static int win_chr_read_poll(CharDriverState
*chr
)
3101 WinCharState
*s
= chr
->opaque
;
3103 s
->max_size
= qemu_chr_can_read(chr
);
3107 static void win_chr_readfile(CharDriverState
*chr
)
3109 WinCharState
*s
= chr
->opaque
;
3114 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3115 s
->orecv
.hEvent
= s
->hrecv
;
3116 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3118 err
= GetLastError();
3119 if (err
== ERROR_IO_PENDING
) {
3120 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3125 qemu_chr_read(chr
, buf
, size
);
3129 static void win_chr_read(CharDriverState
*chr
)
3131 WinCharState
*s
= chr
->opaque
;
3133 if (s
->len
> s
->max_size
)
3134 s
->len
= s
->max_size
;
3138 win_chr_readfile(chr
);
3141 static int win_chr_poll(void *opaque
)
3143 CharDriverState
*chr
= opaque
;
3144 WinCharState
*s
= chr
->opaque
;
3148 ClearCommError(s
->hcom
, &comerr
, &status
);
3149 if (status
.cbInQue
> 0) {
3150 s
->len
= status
.cbInQue
;
3151 win_chr_read_poll(chr
);
3158 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3160 CharDriverState
*chr
;
3163 chr
= qemu_mallocz(sizeof(CharDriverState
));
3166 s
= qemu_mallocz(sizeof(WinCharState
));
3172 chr
->chr_write
= win_chr_write
;
3173 chr
->chr_close
= win_chr_close
;
3175 if (win_chr_init(chr
, filename
) < 0) {
3180 qemu_chr_reset(chr
);
3184 static int win_chr_pipe_poll(void *opaque
)
3186 CharDriverState
*chr
= opaque
;
3187 WinCharState
*s
= chr
->opaque
;
3190 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3193 win_chr_read_poll(chr
);
3200 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3202 WinCharState
*s
= chr
->opaque
;
3210 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3212 fprintf(stderr
, "Failed CreateEvent\n");
3215 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3217 fprintf(stderr
, "Failed CreateEvent\n");
3221 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3222 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3223 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3225 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3226 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3227 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3232 ZeroMemory(&ov
, sizeof(ov
));
3233 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3234 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3236 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3240 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3242 fprintf(stderr
, "Failed GetOverlappedResult\n");
3244 CloseHandle(ov
.hEvent
);
3251 CloseHandle(ov
.hEvent
);
3254 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3263 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3265 CharDriverState
*chr
;
3268 chr
= qemu_mallocz(sizeof(CharDriverState
));
3271 s
= qemu_mallocz(sizeof(WinCharState
));
3277 chr
->chr_write
= win_chr_write
;
3278 chr
->chr_close
= win_chr_close
;
3280 if (win_chr_pipe_init(chr
, filename
) < 0) {
3285 qemu_chr_reset(chr
);
3289 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3291 CharDriverState
*chr
;
3294 chr
= qemu_mallocz(sizeof(CharDriverState
));
3297 s
= qemu_mallocz(sizeof(WinCharState
));
3304 chr
->chr_write
= win_chr_write
;
3305 qemu_chr_reset(chr
);
3309 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3311 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3314 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3318 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3319 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3320 if (fd_out
== INVALID_HANDLE_VALUE
)
3323 return qemu_chr_open_win_file(fd_out
);
3325 #endif /* !_WIN32 */
3327 /***********************************************************/
3328 /* UDP Net console */
3332 struct sockaddr_in daddr
;
3339 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3341 NetCharDriver
*s
= chr
->opaque
;
3343 return sendto(s
->fd
, buf
, len
, 0,
3344 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3347 static int udp_chr_read_poll(void *opaque
)
3349 CharDriverState
*chr
= opaque
;
3350 NetCharDriver
*s
= chr
->opaque
;
3352 s
->max_size
= qemu_chr_can_read(chr
);
3354 /* If there were any stray characters in the queue process them
3357 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3358 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3360 s
->max_size
= qemu_chr_can_read(chr
);
3365 static void udp_chr_read(void *opaque
)
3367 CharDriverState
*chr
= opaque
;
3368 NetCharDriver
*s
= chr
->opaque
;
3370 if (s
->max_size
== 0)
3372 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3373 s
->bufptr
= s
->bufcnt
;
3378 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3379 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3381 s
->max_size
= qemu_chr_can_read(chr
);
3385 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3387 NetCharDriver
*s
= chr
->opaque
;
3390 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3391 udp_chr_read
, NULL
, chr
);
3396 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3398 int parse_host_src_port(struct sockaddr_in
*haddr
,
3399 struct sockaddr_in
*saddr
,
3402 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3404 CharDriverState
*chr
= NULL
;
3405 NetCharDriver
*s
= NULL
;
3407 struct sockaddr_in saddr
;
3409 chr
= qemu_mallocz(sizeof(CharDriverState
));
3412 s
= qemu_mallocz(sizeof(NetCharDriver
));
3416 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3418 perror("socket(PF_INET, SOCK_DGRAM)");
3422 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3423 printf("Could not parse: %s\n", def
);
3427 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3437 chr
->chr_write
= udp_chr_write
;
3438 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3451 /***********************************************************/
3452 /* TCP Net console */
3463 static void tcp_chr_accept(void *opaque
);
3465 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3467 TCPCharDriver
*s
= chr
->opaque
;
3469 return send_all(s
->fd
, buf
, len
);
3471 /* XXX: indicate an error ? */
3476 static int tcp_chr_read_poll(void *opaque
)
3478 CharDriverState
*chr
= opaque
;
3479 TCPCharDriver
*s
= chr
->opaque
;
3482 s
->max_size
= qemu_chr_can_read(chr
);
3487 #define IAC_BREAK 243
3488 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3490 uint8_t *buf
, int *size
)
3492 /* Handle any telnet client's basic IAC options to satisfy char by
3493 * char mode with no echo. All IAC options will be removed from
3494 * the buf and the do_telnetopt variable will be used to track the
3495 * state of the width of the IAC information.
3497 * IAC commands come in sets of 3 bytes with the exception of the
3498 * "IAC BREAK" command and the double IAC.
3504 for (i
= 0; i
< *size
; i
++) {
3505 if (s
->do_telnetopt
> 1) {
3506 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3507 /* Double IAC means send an IAC */
3511 s
->do_telnetopt
= 1;
3513 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3514 /* Handle IAC break commands by sending a serial break */
3515 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3520 if (s
->do_telnetopt
>= 4) {
3521 s
->do_telnetopt
= 1;
3524 if ((unsigned char)buf
[i
] == IAC
) {
3525 s
->do_telnetopt
= 2;
3536 static void tcp_chr_read(void *opaque
)
3538 CharDriverState
*chr
= opaque
;
3539 TCPCharDriver
*s
= chr
->opaque
;
3543 if (!s
->connected
|| s
->max_size
<= 0)
3546 if (len
> s
->max_size
)
3548 size
= recv(s
->fd
, buf
, len
, 0);
3550 /* connection closed */
3552 if (s
->listen_fd
>= 0) {
3553 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3555 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3558 } else if (size
> 0) {
3559 if (s
->do_telnetopt
)
3560 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3562 qemu_chr_read(chr
, buf
, size
);
3566 static void tcp_chr_connect(void *opaque
)
3568 CharDriverState
*chr
= opaque
;
3569 TCPCharDriver
*s
= chr
->opaque
;
3572 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3573 tcp_chr_read
, NULL
, chr
);
3574 qemu_chr_reset(chr
);
3577 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3578 static void tcp_chr_telnet_init(int fd
)
3581 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3582 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3583 send(fd
, (char *)buf
, 3, 0);
3584 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3585 send(fd
, (char *)buf
, 3, 0);
3586 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3587 send(fd
, (char *)buf
, 3, 0);
3588 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3589 send(fd
, (char *)buf
, 3, 0);
3592 static void socket_set_nodelay(int fd
)
3595 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3598 static void tcp_chr_accept(void *opaque
)
3600 CharDriverState
*chr
= opaque
;
3601 TCPCharDriver
*s
= chr
->opaque
;
3602 struct sockaddr_in saddr
;
3604 struct sockaddr_un uaddr
;
3606 struct sockaddr
*addr
;
3613 len
= sizeof(uaddr
);
3614 addr
= (struct sockaddr
*)&uaddr
;
3618 len
= sizeof(saddr
);
3619 addr
= (struct sockaddr
*)&saddr
;
3621 fd
= accept(s
->listen_fd
, addr
, &len
);
3622 if (fd
< 0 && errno
!= EINTR
) {
3624 } else if (fd
>= 0) {
3625 if (s
->do_telnetopt
)
3626 tcp_chr_telnet_init(fd
);
3630 socket_set_nonblock(fd
);
3632 socket_set_nodelay(fd
);
3634 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3635 tcp_chr_connect(chr
);
3638 static void tcp_chr_close(CharDriverState
*chr
)
3640 TCPCharDriver
*s
= chr
->opaque
;
3643 if (s
->listen_fd
>= 0)
3644 closesocket(s
->listen_fd
);
3648 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3652 CharDriverState
*chr
= NULL
;
3653 TCPCharDriver
*s
= NULL
;
3654 int fd
= -1, ret
, err
, val
;
3656 int is_waitconnect
= 1;
3659 struct sockaddr_in saddr
;
3661 struct sockaddr_un uaddr
;
3663 struct sockaddr
*addr
;
3668 addr
= (struct sockaddr
*)&uaddr
;
3669 addrlen
= sizeof(uaddr
);
3670 if (parse_unix_path(&uaddr
, host_str
) < 0)
3675 addr
= (struct sockaddr
*)&saddr
;
3676 addrlen
= sizeof(saddr
);
3677 if (parse_host_port(&saddr
, host_str
) < 0)
3682 while((ptr
= strchr(ptr
,','))) {
3684 if (!strncmp(ptr
,"server",6)) {
3686 } else if (!strncmp(ptr
,"nowait",6)) {
3688 } else if (!strncmp(ptr
,"nodelay",6)) {
3691 printf("Unknown option: %s\n", ptr
);
3698 chr
= qemu_mallocz(sizeof(CharDriverState
));
3701 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3707 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3710 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3715 if (!is_waitconnect
)
3716 socket_set_nonblock(fd
);
3721 s
->is_unix
= is_unix
;
3722 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3725 chr
->chr_write
= tcp_chr_write
;
3726 chr
->chr_close
= tcp_chr_close
;
3729 /* allow fast reuse */
3733 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3739 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3742 ret
= bind(fd
, addr
, addrlen
);
3746 ret
= listen(fd
, 0);
3751 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3753 s
->do_telnetopt
= 1;
3756 ret
= connect(fd
, addr
, addrlen
);
3758 err
= socket_error();
3759 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3760 } else if (err
== EINPROGRESS
) {
3763 } else if (err
== WSAEALREADY
) {
3775 socket_set_nodelay(fd
);
3777 tcp_chr_connect(chr
);
3779 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3782 if (is_listen
&& is_waitconnect
) {
3783 printf("QEMU waiting for connection on: %s\n", host_str
);
3784 tcp_chr_accept(chr
);
3785 socket_set_nonblock(s
->listen_fd
);
3797 CharDriverState
*qemu_chr_open(const char *filename
)
3801 if (!strcmp(filename
, "vc")) {
3802 return text_console_init(&display_state
, 0);
3803 } else if (strstart(filename
, "vc:", &p
)) {
3804 return text_console_init(&display_state
, p
);
3805 } else if (!strcmp(filename
, "null")) {
3806 return qemu_chr_open_null();
3808 if (strstart(filename
, "tcp:", &p
)) {
3809 return qemu_chr_open_tcp(p
, 0, 0);
3811 if (strstart(filename
, "telnet:", &p
)) {
3812 return qemu_chr_open_tcp(p
, 1, 0);
3814 if (strstart(filename
, "udp:", &p
)) {
3815 return qemu_chr_open_udp(p
);
3817 if (strstart(filename
, "mon:", &p
)) {
3818 CharDriverState
*drv
= qemu_chr_open(p
);
3820 drv
= qemu_chr_open_mux(drv
);
3821 monitor_init(drv
, !nographic
);
3824 printf("Unable to open driver: %s\n", p
);
3828 if (strstart(filename
, "unix:", &p
)) {
3829 return qemu_chr_open_tcp(p
, 0, 1);
3830 } else if (strstart(filename
, "file:", &p
)) {
3831 return qemu_chr_open_file_out(p
);
3832 } else if (strstart(filename
, "pipe:", &p
)) {
3833 return qemu_chr_open_pipe(p
);
3834 } else if (!strcmp(filename
, "pty")) {
3835 return qemu_chr_open_pty();
3836 } else if (!strcmp(filename
, "stdio")) {
3837 return qemu_chr_open_stdio();
3839 #if defined(__linux__)
3840 if (strstart(filename
, "/dev/parport", NULL
)) {
3841 return qemu_chr_open_pp(filename
);
3844 #if defined(__linux__) || defined(__sun__)
3845 if (strstart(filename
, "/dev/", NULL
)) {
3846 return qemu_chr_open_tty(filename
);
3850 if (strstart(filename
, "COM", NULL
)) {
3851 return qemu_chr_open_win(filename
);
3853 if (strstart(filename
, "pipe:", &p
)) {
3854 return qemu_chr_open_win_pipe(p
);
3856 if (strstart(filename
, "con:", NULL
)) {
3857 return qemu_chr_open_win_con(filename
);
3859 if (strstart(filename
, "file:", &p
)) {
3860 return qemu_chr_open_win_file_out(p
);
3863 #ifdef CONFIG_BRLAPI
3864 if (!strcmp(filename
, "braille")) {
3865 return chr_baum_init();
3873 void qemu_chr_close(CharDriverState
*chr
)
3876 chr
->chr_close(chr
);
3880 /***********************************************************/
3881 /* network device redirectors */
3883 __attribute__ (( unused
))
3884 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3888 for(i
=0;i
<size
;i
+=16) {
3892 fprintf(f
, "%08x ", i
);
3895 fprintf(f
, " %02x", buf
[i
+j
]);
3900 for(j
=0;j
<len
;j
++) {
3902 if (c
< ' ' || c
> '~')
3904 fprintf(f
, "%c", c
);
3910 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3917 offset
= strtol(p
, &last_char
, 0);
3918 if (0 == errno
&& '\0' == *last_char
&&
3919 offset
>= 0 && offset
<= 0xFFFFFF) {
3920 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3921 macaddr
[4] = (offset
& 0xFF00) >> 8;
3922 macaddr
[5] = offset
& 0xFF;
3925 for(i
= 0; i
< 6; i
++) {
3926 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3931 if (*p
!= ':' && *p
!= '-')
3942 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3947 p1
= strchr(p
, sep
);
3953 if (len
> buf_size
- 1)
3955 memcpy(buf
, p
, len
);
3962 int parse_host_src_port(struct sockaddr_in
*haddr
,
3963 struct sockaddr_in
*saddr
,
3964 const char *input_str
)
3966 char *str
= strdup(input_str
);
3967 char *host_str
= str
;
3972 * Chop off any extra arguments at the end of the string which
3973 * would start with a comma, then fill in the src port information
3974 * if it was provided else use the "any address" and "any port".
3976 if ((ptr
= strchr(str
,',')))
3979 if ((src_str
= strchr(input_str
,'@'))) {
3984 if (parse_host_port(haddr
, host_str
) < 0)
3987 if (!src_str
|| *src_str
== '\0')
3990 if (parse_host_port(saddr
, src_str
) < 0)
4001 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
4009 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4011 saddr
->sin_family
= AF_INET
;
4012 if (buf
[0] == '\0') {
4013 saddr
->sin_addr
.s_addr
= 0;
4015 if (isdigit(buf
[0])) {
4016 if (!inet_aton(buf
, &saddr
->sin_addr
))
4019 if ((he
= gethostbyname(buf
)) == NULL
)
4021 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4024 port
= strtol(p
, (char **)&r
, 0);
4027 saddr
->sin_port
= htons(port
);
4032 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4037 len
= MIN(108, strlen(str
));
4038 p
= strchr(str
, ',');
4040 len
= MIN(len
, p
- str
);
4042 memset(uaddr
, 0, sizeof(*uaddr
));
4044 uaddr
->sun_family
= AF_UNIX
;
4045 memcpy(uaddr
->sun_path
, str
, len
);
4051 /* find or alloc a new VLAN */
4052 VLANState
*qemu_find_vlan(int id
)
4054 VLANState
**pvlan
, *vlan
;
4055 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4059 vlan
= qemu_mallocz(sizeof(VLANState
));
4064 pvlan
= &first_vlan
;
4065 while (*pvlan
!= NULL
)
4066 pvlan
= &(*pvlan
)->next
;
4071 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4072 IOReadHandler
*fd_read
,
4073 IOCanRWHandler
*fd_can_read
,
4076 VLANClientState
*vc
, **pvc
;
4077 vc
= qemu_mallocz(sizeof(VLANClientState
));
4080 vc
->fd_read
= fd_read
;
4081 vc
->fd_can_read
= fd_can_read
;
4082 vc
->opaque
= opaque
;
4086 pvc
= &vlan
->first_client
;
4087 while (*pvc
!= NULL
)
4088 pvc
= &(*pvc
)->next
;
4093 void qemu_del_vlan_client(VLANClientState
*vc
)
4095 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4097 while (*pvc
!= NULL
)
4103 pvc
= &(*pvc
)->next
;
4106 int qemu_can_send_packet(VLANClientState
*vc1
)
4108 VLANState
*vlan
= vc1
->vlan
;
4109 VLANClientState
*vc
;
4111 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4113 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4120 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4122 VLANState
*vlan
= vc1
->vlan
;
4123 VLANClientState
*vc
;
4127 printf("vlan %d send:\n", vlan
->id
);
4128 hex_dump(stdout
, buf
, size
);
4130 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4132 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
4133 vc
->fd_read(vc
->opaque
, buf
, size
);
4142 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
4149 for (i
= 0; i
< iovcnt
; i
++) {
4152 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
4153 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
4157 vc
->fd_read(vc
->opaque
, buffer
, offset
);
4162 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
4165 VLANState
*vlan
= vc1
->vlan
;
4166 VLANClientState
*vc
;
4167 ssize_t max_len
= 0;
4169 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4176 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
4177 else if (vc
->fd_read
)
4178 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
4180 max_len
= MAX(max_len
, len
);
4186 #if defined(CONFIG_SLIRP)
4188 /* slirp network adapter */
4190 static int slirp_inited
;
4191 static VLANClientState
*slirp_vc
;
4193 int slirp_can_output(void)
4195 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4198 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4201 printf("slirp output:\n");
4202 hex_dump(stdout
, pkt
, pkt_len
);
4206 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4209 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4212 printf("slirp input:\n");
4213 hex_dump(stdout
, buf
, size
);
4215 slirp_input(buf
, size
);
4218 static int net_slirp_init(VLANState
*vlan
)
4220 if (!slirp_inited
) {
4224 slirp_vc
= qemu_new_vlan_client(vlan
,
4225 slirp_receive
, NULL
, NULL
);
4226 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4230 static void net_slirp_redir(const char *redir_str
)
4235 struct in_addr guest_addr
;
4236 int host_port
, guest_port
;
4238 if (!slirp_inited
) {
4244 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4246 if (!strcmp(buf
, "tcp")) {
4248 } else if (!strcmp(buf
, "udp")) {
4254 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4256 host_port
= strtol(buf
, &r
, 0);
4260 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4262 if (buf
[0] == '\0') {
4263 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4265 if (!inet_aton(buf
, &guest_addr
))
4268 guest_port
= strtol(p
, &r
, 0);
4272 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4273 fprintf(stderr
, "qemu: could not set up redirection\n");
4278 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4286 static void erase_dir(char *dir_name
)
4290 char filename
[1024];
4292 /* erase all the files in the directory */
4293 if ((d
= opendir(dir_name
)) != 0) {
4298 if (strcmp(de
->d_name
, ".") != 0 &&
4299 strcmp(de
->d_name
, "..") != 0) {
4300 snprintf(filename
, sizeof(filename
), "%s/%s",
4301 smb_dir
, de
->d_name
);
4302 if (unlink(filename
) != 0) /* is it a directory? */
4303 erase_dir(filename
);
4311 /* automatic user mode samba server configuration */
4312 static void smb_exit(void)
4317 /* automatic user mode samba server configuration */
4318 static void net_slirp_smb(const char *exported_dir
)
4320 char smb_conf
[1024];
4321 char smb_cmdline
[1024];
4324 if (!slirp_inited
) {
4329 /* XXX: better tmp dir construction */
4330 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4331 if (mkdir(smb_dir
, 0700) < 0) {
4332 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4335 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4337 f
= fopen(smb_conf
, "w");
4339 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4346 "socket address=127.0.0.1\n"
4347 "pid directory=%s\n"
4348 "lock directory=%s\n"
4349 "log file=%s/log.smbd\n"
4350 "smb passwd file=%s/smbpasswd\n"
4351 "security = share\n"
4366 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4367 SMBD_COMMAND
, smb_conf
);
4369 slirp_add_exec(0, smb_cmdline
, 4, 139);
4372 #endif /* !defined(_WIN32) */
4373 void do_info_slirp(void)
4378 #endif /* CONFIG_SLIRP */
4382 int tap_has_vnet_hdr(void *opaque
)
4387 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4391 #else /* !defined(_WIN32) */
4393 #ifndef IFF_VNET_HDR
4394 #define TAP_BUFSIZE 4096
4396 #include <linux/virtio_net.h>
4398 #define ETH_DATA_LEN 1500
4399 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4400 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4401 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4404 typedef struct TAPState
{
4405 VLANClientState
*vc
;
4407 char down_script
[1024];
4408 char buf
[TAP_BUFSIZE
];
4410 unsigned int has_vnet_hdr
: 1;
4411 unsigned int using_vnet_hdr
: 1;
4414 static ssize_t
tap_writev(void *opaque
, const struct iovec
*iov
,
4417 TAPState
*s
= opaque
;
4421 len
= writev(s
->fd
, iov
, iovcnt
);
4422 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4427 static ssize_t
tap_receive_iov(void *opaque
, const struct iovec
*iov
,
4431 TAPState
*s
= opaque
;
4433 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4434 struct iovec
*iov_copy
;
4435 struct virtio_net_hdr hdr
= { 0, };
4437 iov_copy
= alloca(sizeof(struct iovec
) * (iovcnt
+ 1));
4439 iov_copy
[0].iov_base
= &hdr
;
4440 iov_copy
[0].iov_len
= sizeof(hdr
);
4442 memcpy(&iov_copy
[1], iov
, sizeof(struct iovec
) * iovcnt
);
4444 return tap_writev(opaque
, iov_copy
, iovcnt
+ 1);
4448 return tap_writev(opaque
, iov
, iovcnt
);
4451 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4453 struct iovec iov
[2];
4457 TAPState
*s
= opaque
;
4458 struct virtio_net_hdr hdr
= { 0, };
4460 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4461 iov
[i
].iov_base
= &hdr
;
4462 iov
[i
].iov_len
= sizeof(hdr
);
4467 iov
[i
].iov_base
= (char *) buf
;
4468 iov
[i
].iov_len
= size
;
4471 tap_writev(opaque
, iov
, i
);
4474 static int tap_can_send(void *opaque
)
4476 TAPState
*s
= opaque
;
4477 VLANClientState
*vc
;
4478 int can_receive
= 0;
4480 /* Check to see if any of our clients can receive a packet */
4481 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4482 /* Skip ourselves */
4486 if (!vc
->fd_can_read
) {
4487 /* no fd_can_read handler, they always can receive */
4490 can_receive
= vc
->fd_can_read(vc
->opaque
);
4492 /* Once someone can receive, we try to send a packet */
4500 static int tap_send_packet(TAPState
*s
)
4502 uint8_t *buf
= s
->buf
;
4506 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4507 buf
+= sizeof(struct virtio_net_hdr
);
4508 size
-= sizeof(struct virtio_net_hdr
);
4512 return qemu_send_packet(s
->vc
, buf
, size
);
4515 static void tap_send(void *opaque
)
4517 TAPState
*s
= opaque
;
4519 /* First try to send any buffered packet */
4523 /* If noone can receive the packet, buffer it */
4524 err
= tap_send_packet(s
);
4529 /* Read packets until we hit EAGAIN */
4534 sbuf
.maxlen
= sizeof(s
->buf
);
4536 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4539 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4543 if (s
->size
== -1 && errno
== EINTR
)
4549 /* If noone can receive the packet, buffer it */
4550 err
= tap_send_packet(s
);
4554 } while (s
->size
> 0);
4557 int tap_has_vnet_hdr(void *opaque
)
4559 VLANClientState
*vc
= opaque
;
4560 TAPState
*s
= vc
->opaque
;
4562 return s
? s
->has_vnet_hdr
: 0;
4565 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4567 VLANClientState
*vc
= opaque
;
4568 TAPState
*s
= vc
->opaque
;
4570 if (!s
|| !s
->has_vnet_hdr
)
4573 s
->using_vnet_hdr
= using_vnet_hdr
!= 0;
4576 static int tap_probe_vnet_hdr(int fd
)
4578 #if defined(TUNGETIFF) && defined(IFF_VNET_HDR)
4581 if (ioctl(fd
, TUNGETIFF
, &ifr
) != 0) {
4582 fprintf(stderr
, "TUNGETIFF ioctl() failed: %s\n", strerror(errno
));
4586 return ifr
.ifr_flags
& IFF_VNET_HDR
;
4592 #ifdef TUNSETOFFLOAD
4593 static void tap_set_offload(VLANClientState
*vc
, int csum
, int tso4
, int tso6
,
4596 TAPState
*s
= vc
->opaque
;
4597 unsigned int offload
= 0;
4600 offload
|= TUN_F_CSUM
;
4602 offload
|= TUN_F_TSO4
;
4604 offload
|= TUN_F_TSO6
;
4605 if ((tso4
|| tso6
) && ecn
)
4606 offload
|= TUN_F_TSO_ECN
;
4609 if (ioctl(s
->fd
, TUNSETOFFLOAD
, offload
) != 0)
4610 fprintf(stderr
, "TUNSETOFFLOAD ioctl() failed: %s\n",
4613 #endif /* TUNSETOFFLOAD */
4617 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
, int vnet_hdr
)
4621 s
= qemu_mallocz(sizeof(TAPState
));
4625 s
->has_vnet_hdr
= vnet_hdr
!= 0;
4626 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4627 s
->vc
->fd_readv
= tap_receive_iov
;
4628 #ifdef TUNSETOFFLOAD
4629 s
->vc
->set_offload
= tap_set_offload
;
4631 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4632 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4636 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4637 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4643 TFR(fd
= open("/dev/tap", O_RDWR
));
4645 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4650 dev
= devname(s
.st_rdev
, S_IFCHR
);
4651 pstrcpy(ifname
, ifname_size
, dev
);
4653 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4656 #elif defined(__sun__)
4657 #define TUNNEWPPA (('T'<<16) | 0x0001)
4659 * Allocate TAP device, returns opened fd.
4660 * Stores dev name in the first arg(must be large enough).
4662 int tap_alloc(char *dev
, size_t dev_size
)
4664 int tap_fd
, if_fd
, ppa
= -1;
4665 static int ip_fd
= 0;
4668 static int arp_fd
= 0;
4669 int ip_muxid
, arp_muxid
;
4670 struct strioctl strioc_if
, strioc_ppa
;
4671 int link_type
= I_PLINK
;;
4673 char actual_name
[32] = "";
4675 memset(&ifr
, 0x0, sizeof(ifr
));
4679 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4683 /* Check if IP device was opened */
4687 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4689 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4693 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4695 syslog(LOG_ERR
, "Can't open /dev/tap");
4699 /* Assign a new PPA and get its unit number. */
4700 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4701 strioc_ppa
.ic_timout
= 0;
4702 strioc_ppa
.ic_len
= sizeof(ppa
);
4703 strioc_ppa
.ic_dp
= (char *)&ppa
;
4704 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4705 syslog (LOG_ERR
, "Can't assign new interface");
4707 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4709 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4712 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4713 syslog(LOG_ERR
, "Can't push IP module");
4717 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4718 syslog(LOG_ERR
, "Can't get flags\n");
4720 snprintf (actual_name
, 32, "tap%d", ppa
);
4721 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4724 /* Assign ppa according to the unit number returned by tun device */
4726 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4727 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4728 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4729 syslog (LOG_ERR
, "Can't get flags\n");
4730 /* Push arp module to if_fd */
4731 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4732 syslog (LOG_ERR
, "Can't push ARP module (2)");
4734 /* Push arp module to ip_fd */
4735 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4736 syslog (LOG_ERR
, "I_POP failed\n");
4737 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4738 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4740 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4742 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4744 /* Set ifname to arp */
4745 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4746 strioc_if
.ic_timout
= 0;
4747 strioc_if
.ic_len
= sizeof(ifr
);
4748 strioc_if
.ic_dp
= (char *)&ifr
;
4749 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4750 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4753 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4754 syslog(LOG_ERR
, "Can't link TAP device to IP");
4758 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4759 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4763 memset(&ifr
, 0x0, sizeof(ifr
));
4764 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4765 ifr
.lifr_ip_muxid
= ip_muxid
;
4766 ifr
.lifr_arp_muxid
= arp_muxid
;
4768 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4770 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4771 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4772 syslog (LOG_ERR
, "Can't set multiplexor id");
4775 snprintf(dev
, dev_size
, "tap%d", ppa
);
4779 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4783 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4784 fprintf(stderr
, "Cannot allocate TAP device\n");
4787 pstrcpy(ifname
, ifname_size
, dev
);
4788 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4792 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4797 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4799 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4802 memset(&ifr
, 0, sizeof(ifr
));
4803 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4805 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4807 unsigned int features
;
4809 if (ioctl(fd
, TUNGETFEATURES
, &features
) == 0 &&
4810 features
& IFF_VNET_HDR
) {
4812 ifr
.ifr_flags
|= IFF_VNET_HDR
;
4817 if (ifname
[0] != '\0')
4818 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4820 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4821 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4823 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4827 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4828 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4833 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4839 /* try to launch network script */
4843 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4844 for (i
= 0; i
< open_max
; i
++)
4845 if (i
!= STDIN_FILENO
&&
4846 i
!= STDOUT_FILENO
&&
4847 i
!= STDERR_FILENO
&&
4852 *parg
++ = (char *)setup_script
;
4853 *parg
++ = (char *)ifname
;
4855 execv(setup_script
, args
);
4858 while (waitpid(pid
, &status
, 0) != pid
);
4859 if (!WIFEXITED(status
) ||
4860 WEXITSTATUS(status
) != 0) {
4861 fprintf(stderr
, "%s: could not launch network script\n",
4869 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4870 const char *setup_script
, const char *down_script
)
4877 if (ifname1
!= NULL
)
4878 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4882 TFR(fd
= tap_open(ifname
, sizeof(ifname
), &vnet_hdr
));
4886 if (!setup_script
|| !strcmp(setup_script
, "no"))
4888 if (setup_script
[0] != '\0') {
4889 if (launch_script(setup_script
, ifname
, fd
))
4892 s
= net_tap_fd_init(vlan
, fd
, vnet_hdr
);
4896 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4897 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4898 if (down_script
&& strcmp(down_script
, "no"))
4899 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4903 #endif /* !_WIN32 */
4905 #if defined(CONFIG_VDE)
4906 typedef struct VDEState
{
4907 VLANClientState
*vc
;
4911 static void vde_to_qemu(void *opaque
)
4913 VDEState
*s
= opaque
;
4917 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4919 qemu_send_packet(s
->vc
, buf
, size
);
4923 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4925 VDEState
*s
= opaque
;
4928 ret
= vde_send(s
->vde
, buf
, size
, 0);
4929 if (ret
< 0 && errno
== EINTR
) {
4936 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4937 const char *group
, int mode
)
4940 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4941 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4943 struct vde_open_args args
= {
4945 .group
= init_group
,
4949 s
= qemu_mallocz(sizeof(VDEState
));
4952 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4957 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4958 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4959 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4960 sock
, vde_datafd(s
->vde
));
4965 /* network connection */
4966 typedef struct NetSocketState
{
4967 VLANClientState
*vc
;
4969 int state
; /* 0 = getting length, 1 = getting data */
4973 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4976 typedef struct NetSocketListenState
{
4979 } NetSocketListenState
;
4981 /* XXX: we consider we can send the whole packet without blocking */
4982 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4984 NetSocketState
*s
= opaque
;
4988 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4989 send_all(s
->fd
, buf
, size
);
4992 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4994 NetSocketState
*s
= opaque
;
4995 sendto(s
->fd
, buf
, size
, 0,
4996 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4999 static void net_socket_send(void *opaque
)
5001 NetSocketState
*s
= opaque
;
5006 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
5008 err
= socket_error();
5009 if (err
!= EWOULDBLOCK
)
5011 } else if (size
== 0) {
5012 /* end of connection */
5014 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5020 /* reassemble a packet from the network */
5026 memcpy(s
->buf
+ s
->index
, buf
, l
);
5030 if (s
->index
== 4) {
5032 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
5038 l
= s
->packet_len
- s
->index
;
5041 memcpy(s
->buf
+ s
->index
, buf
, l
);
5045 if (s
->index
>= s
->packet_len
) {
5046 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
5055 static void net_socket_send_dgram(void *opaque
)
5057 NetSocketState
*s
= opaque
;
5060 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
5064 /* end of connection */
5065 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5068 qemu_send_packet(s
->vc
, s
->buf
, size
);
5071 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
5076 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
5077 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5078 inet_ntoa(mcastaddr
->sin_addr
),
5079 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
5083 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
5085 perror("socket(PF_INET, SOCK_DGRAM)");
5090 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
5091 (const char *)&val
, sizeof(val
));
5093 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5097 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
5103 /* Add host to multicast group */
5104 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
5105 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
5107 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
5108 (const char *)&imr
, sizeof(struct ip_mreq
));
5110 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5114 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5116 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
5117 (const char *)&val
, sizeof(val
));
5119 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5123 socket_set_nonblock(fd
);
5131 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
5134 struct sockaddr_in saddr
;
5136 socklen_t saddr_len
;
5139 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5140 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5141 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5145 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
5147 if (saddr
.sin_addr
.s_addr
==0) {
5148 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5152 /* clone dgram socket */
5153 newfd
= net_socket_mcast_create(&saddr
);
5155 /* error already reported by net_socket_mcast_create() */
5159 /* clone newfd to fd, close newfd */
5164 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5165 fd
, strerror(errno
));
5170 s
= qemu_mallocz(sizeof(NetSocketState
));
5175 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
5176 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
5178 /* mcast: save bound address as dst */
5179 if (is_connected
) s
->dgram_dst
=saddr
;
5181 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5182 "socket: fd=%d (%s mcast=%s:%d)",
5183 fd
, is_connected
? "cloned" : "",
5184 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5188 static void net_socket_connect(void *opaque
)
5190 NetSocketState
*s
= opaque
;
5191 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5194 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5198 s
= qemu_mallocz(sizeof(NetSocketState
));
5202 s
->vc
= qemu_new_vlan_client(vlan
,
5203 net_socket_receive
, NULL
, s
);
5204 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5205 "socket: fd=%d", fd
);
5207 net_socket_connect(s
);
5209 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5214 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5217 int so_type
=-1, optlen
=sizeof(so_type
);
5219 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5220 (socklen_t
*)&optlen
)< 0) {
5221 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5226 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5228 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5230 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5231 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5232 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5237 static void net_socket_accept(void *opaque
)
5239 NetSocketListenState
*s
= opaque
;
5241 struct sockaddr_in saddr
;
5246 len
= sizeof(saddr
);
5247 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5248 if (fd
< 0 && errno
!= EINTR
) {
5250 } else if (fd
>= 0) {
5254 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5258 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5259 "socket: connection from %s:%d",
5260 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5264 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5266 NetSocketListenState
*s
;
5268 struct sockaddr_in saddr
;
5270 if (parse_host_port(&saddr
, host_str
) < 0)
5273 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5277 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5282 socket_set_nonblock(fd
);
5284 /* allow fast reuse */
5286 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5288 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5293 ret
= listen(fd
, 0);
5300 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5304 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5307 int fd
, connected
, ret
, err
;
5308 struct sockaddr_in saddr
;
5310 if (parse_host_port(&saddr
, host_str
) < 0)
5313 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5318 socket_set_nonblock(fd
);
5322 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5324 err
= socket_error();
5325 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5326 } else if (err
== EINPROGRESS
) {
5329 } else if (err
== WSAEALREADY
) {
5342 s
= net_socket_fd_init(vlan
, fd
, connected
);
5345 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5346 "socket: connect to %s:%d",
5347 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5351 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5355 struct sockaddr_in saddr
;
5357 if (parse_host_port(&saddr
, host_str
) < 0)
5361 fd
= net_socket_mcast_create(&saddr
);
5365 s
= net_socket_fd_init(vlan
, fd
, 0);
5369 s
->dgram_dst
= saddr
;
5371 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5372 "socket: mcast=%s:%d",
5373 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5378 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5383 while (*p
!= '\0' && *p
!= '=') {
5384 if (q
&& (q
- buf
) < buf_size
- 1)
5394 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5399 while (*p
!= '\0') {
5401 if (*(p
+ 1) != ',')
5405 if (q
&& (q
- buf
) < buf_size
- 1)
5415 int get_param_value(char *buf
, int buf_size
,
5416 const char *tag
, const char *str
)
5423 p
= get_opt_name(option
, sizeof(option
), p
);
5427 if (!strcmp(tag
, option
)) {
5428 (void)get_opt_value(buf
, buf_size
, p
);
5431 p
= get_opt_value(NULL
, 0, p
);
5440 int check_params(char *buf
, int buf_size
,
5441 char **params
, const char *str
)
5448 p
= get_opt_name(buf
, buf_size
, p
);
5452 for(i
= 0; params
[i
] != NULL
; i
++)
5453 if (!strcmp(params
[i
], buf
))
5455 if (params
[i
] == NULL
)
5457 p
= get_opt_value(NULL
, 0, p
);
5465 static int nic_get_free_idx(void)
5469 for (index
= 0; index
< MAX_NICS
; index
++)
5470 if (!nd_table
[index
].used
)
5475 int net_client_init(const char *device
, const char *p
)
5482 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5483 vlan_id
= strtol(buf
, NULL
, 0);
5485 vlan
= qemu_find_vlan(vlan_id
);
5487 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5490 if (!strcmp(device
, "nic")) {
5493 int idx
= nic_get_free_idx();
5495 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5496 fprintf(stderr
, "Too Many NICs\n");
5499 nd
= &nd_table
[idx
];
5500 macaddr
= nd
->macaddr
;
5506 macaddr
[5] = 0x56 + idx
;
5508 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5509 if (parse_macaddr(macaddr
, buf
) < 0) {
5510 fprintf(stderr
, "invalid syntax for ethernet address\n");
5514 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5515 nd
->model
= strdup(buf
);
5520 vlan
->nb_guest_devs
++;
5523 if (!strcmp(device
, "none")) {
5524 /* does nothing. It is needed to signal that no network cards
5529 if (!strcmp(device
, "user")) {
5530 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5531 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5533 vlan
->nb_host_devs
++;
5534 ret
= net_slirp_init(vlan
);
5538 if (!strcmp(device
, "tap")) {
5540 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5541 fprintf(stderr
, "tap: no interface name\n");
5544 vlan
->nb_host_devs
++;
5545 ret
= tap_win32_init(vlan
, ifname
);
5548 if (!strcmp(device
, "tap")) {
5550 char setup_script
[1024], down_script
[1024];
5552 vlan
->nb_host_devs
++;
5553 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5554 fd
= strtol(buf
, NULL
, 0);
5555 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5557 if (net_tap_fd_init(vlan
, fd
, tap_probe_vnet_hdr(fd
)))
5560 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5563 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5564 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5566 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5567 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5569 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5573 if (!strcmp(device
, "socket")) {
5574 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5576 fd
= strtol(buf
, NULL
, 0);
5578 if (net_socket_fd_init(vlan
, fd
, 1))
5580 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5581 ret
= net_socket_listen_init(vlan
, buf
);
5582 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5583 ret
= net_socket_connect_init(vlan
, buf
);
5584 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5585 ret
= net_socket_mcast_init(vlan
, buf
);
5587 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5590 vlan
->nb_host_devs
++;
5593 if (!strcmp(device
, "vde")) {
5594 char vde_sock
[1024], vde_group
[512];
5595 int vde_port
, vde_mode
;
5596 vlan
->nb_host_devs
++;
5597 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5600 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5601 vde_port
= strtol(buf
, NULL
, 10);
5605 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5606 vde_group
[0] = '\0';
5608 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5609 vde_mode
= strtol(buf
, NULL
, 8);
5613 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5617 fprintf(stderr
, "Unknown network device: %s\n", device
);
5621 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5627 void net_client_uninit(NICInfo
*nd
)
5629 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5632 free((void *)nd
->model
);
5635 static int net_client_parse(const char *str
)
5643 while (*p
!= '\0' && *p
!= ',') {
5644 if ((q
- device
) < sizeof(device
) - 1)
5652 return net_client_init(device
, p
);
5655 void do_info_network(void)
5658 VLANClientState
*vc
;
5660 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5661 term_printf("VLAN %d devices:\n", vlan
->id
);
5662 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5663 term_printf(" %s\n", vc
->info_str
);
5667 #define HD_ALIAS "index=%d,media=disk"
5669 #define CDROM_ALIAS "index=1,media=cdrom"
5671 #define CDROM_ALIAS "index=2,media=cdrom"
5673 #define FD_ALIAS "index=%d,if=floppy"
5674 #define PFLASH_ALIAS "if=pflash"
5675 #define MTD_ALIAS "if=mtd"
5676 #define SD_ALIAS "index=0,if=sd"
5678 static int drive_opt_get_free_idx(void)
5682 for (index
= 0; index
< MAX_DRIVES
; index
++)
5683 if (!drives_opt
[index
].used
) {
5684 drives_opt
[index
].used
= 1;
5691 static int drive_get_free_idx(void)
5695 for (index
= 0; index
< MAX_DRIVES
; index
++)
5696 if (!drives_table
[index
].used
) {
5697 drives_table
[index
].used
= 1;
5704 int drive_add(const char *file
, const char *fmt
, ...)
5707 int index
= drive_opt_get_free_idx();
5709 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5710 fprintf(stderr
, "qemu: too many drives\n");
5714 drives_opt
[index
].file
= file
;
5716 vsnprintf(drives_opt
[index
].opt
,
5717 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5724 void drive_remove(int index
)
5726 drives_opt
[index
].used
= 0;
5730 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5734 /* seek interface, bus and unit */
5736 for (index
= 0; index
< MAX_DRIVES
; index
++)
5737 if (drives_table
[index
].type
== type
&&
5738 drives_table
[index
].bus
== bus
&&
5739 drives_table
[index
].unit
== unit
&&
5740 drives_table
[index
].used
)
5746 int drive_get_max_bus(BlockInterfaceType type
)
5752 for (index
= 0; index
< nb_drives
; index
++) {
5753 if(drives_table
[index
].type
== type
&&
5754 drives_table
[index
].bus
> max_bus
)
5755 max_bus
= drives_table
[index
].bus
;
5760 static void bdrv_format_print(void *opaque
, const char *name
)
5762 fprintf(stderr
, " %s", name
);
5765 void drive_uninit(BlockDriverState
*bdrv
)
5769 for (i
= 0; i
< MAX_DRIVES
; i
++)
5770 if (drives_table
[i
].bdrv
== bdrv
) {
5771 drives_table
[i
].bdrv
= NULL
;
5772 drives_table
[i
].used
= 0;
5773 drive_remove(drives_table
[i
].drive_opt_idx
);
5779 int drive_init(struct drive_opt
*arg
, int snapshot
,
5780 QEMUMachine
*machine
)
5785 const char *mediastr
= "";
5786 BlockInterfaceType type
;
5787 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5788 int bus_id
, unit_id
;
5789 int cyls
, heads
, secs
, translation
;
5790 BlockDriverState
*bdrv
;
5791 BlockDriver
*drv
= NULL
;
5796 int drives_table_idx
;
5797 char *str
= arg
->opt
;
5798 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5799 "secs", "trans", "media", "snapshot", "file",
5800 "cache", "format", "boot", NULL
};
5802 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5803 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5809 cyls
= heads
= secs
= 0;
5812 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5816 if (!strcmp(machine
->name
, "realview") ||
5817 !strcmp(machine
->name
, "SS-5") ||
5818 !strcmp(machine
->name
, "SS-10") ||
5819 !strcmp(machine
->name
, "SS-600MP") ||
5820 !strcmp(machine
->name
, "versatilepb") ||
5821 !strcmp(machine
->name
, "versatileab")) {
5823 max_devs
= MAX_SCSI_DEVS
;
5824 pstrcpy(devname
, sizeof(devname
), "scsi");
5827 max_devs
= MAX_IDE_DEVS
;
5828 pstrcpy(devname
, sizeof(devname
), "ide");
5832 /* extract parameters */
5834 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5835 bus_id
= strtol(buf
, NULL
, 0);
5837 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5842 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5843 unit_id
= strtol(buf
, NULL
, 0);
5845 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5850 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5851 pstrcpy(devname
, sizeof(devname
), buf
);
5852 if (!strcmp(buf
, "ide")) {
5854 max_devs
= MAX_IDE_DEVS
;
5855 } else if (!strcmp(buf
, "scsi")) {
5857 max_devs
= MAX_SCSI_DEVS
;
5858 } else if (!strcmp(buf
, "floppy")) {
5861 } else if (!strcmp(buf
, "pflash")) {
5864 } else if (!strcmp(buf
, "mtd")) {
5867 } else if (!strcmp(buf
, "sd")) {
5870 } else if (!strcmp(buf
, "virtio")) {
5874 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5879 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5880 index
= strtol(buf
, NULL
, 0);
5882 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5887 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5888 cyls
= strtol(buf
, NULL
, 0);
5891 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5892 heads
= strtol(buf
, NULL
, 0);
5895 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5896 secs
= strtol(buf
, NULL
, 0);
5899 if (cyls
|| heads
|| secs
) {
5900 if (cyls
< 1 || cyls
> 16383) {
5901 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5904 if (heads
< 1 || heads
> 16) {
5905 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5908 if (secs
< 1 || secs
> 63) {
5909 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5914 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5917 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5921 if (!strcmp(buf
, "none"))
5922 translation
= BIOS_ATA_TRANSLATION_NONE
;
5923 else if (!strcmp(buf
, "lba"))
5924 translation
= BIOS_ATA_TRANSLATION_LBA
;
5925 else if (!strcmp(buf
, "auto"))
5926 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5928 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5933 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5934 if (!strcmp(buf
, "disk")) {
5936 } else if (!strcmp(buf
, "cdrom")) {
5937 if (cyls
|| secs
|| heads
) {
5939 "qemu: '%s' invalid physical CHS format\n", str
);
5942 media
= MEDIA_CDROM
;
5944 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5949 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5950 if (!strcmp(buf
, "on"))
5952 else if (!strcmp(buf
, "off"))
5955 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5960 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5961 if (!strcmp(buf
, "off"))
5963 else if (!strcmp(buf
, "on"))
5966 fprintf(stderr
, "qemu: invalid cache option\n");
5971 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5972 if (strcmp(buf
, "?") == 0) {
5973 fprintf(stderr
, "qemu: Supported formats:");
5974 bdrv_iterate_format(bdrv_format_print
, NULL
);
5975 fprintf(stderr
, "\n");
5978 drv
= bdrv_find_format(buf
);
5980 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5985 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5986 if (!strcmp(buf
, "on")) {
5987 if (extboot_drive
!= -1) {
5988 fprintf(stderr
, "qemu: two bootable drives specified\n");
5991 extboot_drive
= nb_drives
;
5992 } else if (strcmp(buf
, "off")) {
5993 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5998 if (arg
->file
== NULL
)
5999 get_param_value(file
, sizeof(file
), "file", str
);
6001 pstrcpy(file
, sizeof(file
), arg
->file
);
6003 /* compute bus and unit according index */
6006 if (bus_id
!= 0 || unit_id
!= -1) {
6008 "qemu: '%s' index cannot be used with bus and unit\n", str
);
6016 unit_id
= index
% max_devs
;
6017 bus_id
= index
/ max_devs
;
6021 /* if user doesn't specify a unit_id,
6022 * try to find the first free
6025 if (unit_id
== -1) {
6027 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
6029 if (max_devs
&& unit_id
>= max_devs
) {
6030 unit_id
-= max_devs
;
6038 if (max_devs
&& unit_id
>= max_devs
) {
6039 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
6040 str
, unit_id
, max_devs
- 1);
6045 * ignore multiple definitions
6048 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
6053 if (type
== IF_IDE
|| type
== IF_SCSI
)
6054 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
6056 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
6057 devname
, bus_id
, mediastr
, unit_id
);
6059 snprintf(buf
, sizeof(buf
), "%s%s%i",
6060 devname
, mediastr
, unit_id
);
6061 bdrv
= bdrv_new(buf
);
6062 drives_table_idx
= drive_get_free_idx();
6063 drives_table
[drives_table_idx
].bdrv
= bdrv
;
6064 drives_table
[drives_table_idx
].type
= type
;
6065 drives_table
[drives_table_idx
].bus
= bus_id
;
6066 drives_table
[drives_table_idx
].unit
= unit_id
;
6067 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
6076 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
6077 bdrv_set_translation_hint(bdrv
, translation
);
6081 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
6086 /* FIXME: This isn't really a floppy, but it's a reasonable
6089 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
6100 bdrv_flags
|= BDRV_O_SNAPSHOT
;
6102 bdrv_flags
|= BDRV_O_DIRECT
;
6103 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
6104 fprintf(stderr
, "qemu: could not open disk image %s\n",
6108 return drives_table_idx
;
6111 /***********************************************************/
6114 static USBPort
*used_usb_ports
;
6115 static USBPort
*free_usb_ports
;
6117 /* ??? Maybe change this to register a hub to keep track of the topology. */
6118 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
6119 usb_attachfn attach
)
6121 port
->opaque
= opaque
;
6122 port
->index
= index
;
6123 port
->attach
= attach
;
6124 port
->next
= free_usb_ports
;
6125 free_usb_ports
= port
;
6128 int usb_device_add_dev(USBDevice
*dev
)
6132 /* Find a USB port to add the device to. */
6133 port
= free_usb_ports
;
6137 /* Create a new hub and chain it on. */
6138 free_usb_ports
= NULL
;
6139 port
->next
= used_usb_ports
;
6140 used_usb_ports
= port
;
6142 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
6143 usb_attach(port
, hub
);
6144 port
= free_usb_ports
;
6147 free_usb_ports
= port
->next
;
6148 port
->next
= used_usb_ports
;
6149 used_usb_ports
= port
;
6150 usb_attach(port
, dev
);
6154 static int usb_device_add(const char *devname
)
6160 if (!free_usb_ports
)
6163 if (strstart(devname
, "host:", &p
)) {
6164 dev
= usb_host_device_open(p
);
6165 } else if (!strcmp(devname
, "mouse")) {
6166 dev
= usb_mouse_init();
6167 } else if (!strcmp(devname
, "tablet")) {
6168 dev
= usb_tablet_init();
6169 } else if (!strcmp(devname
, "keyboard")) {
6170 dev
= usb_keyboard_init();
6171 } else if (strstart(devname
, "disk:", &p
)) {
6172 dev
= usb_msd_init(p
);
6173 } else if (!strcmp(devname
, "wacom-tablet")) {
6174 dev
= usb_wacom_init();
6175 } else if (strstart(devname
, "serial:", &p
)) {
6176 dev
= usb_serial_init(p
);
6177 #ifdef CONFIG_BRLAPI
6178 } else if (!strcmp(devname
, "braille")) {
6179 dev
= usb_baum_init();
6181 } else if (strstart(devname
, "net:", &p
)) {
6184 if (net_client_init("nic", p
) < 0)
6186 nd_table
[nic
].model
= "usb";
6187 dev
= usb_net_init(&nd_table
[nic
]);
6194 return usb_device_add_dev(dev
);
6197 int usb_device_del_addr(int bus_num
, int addr
)
6203 if (!used_usb_ports
)
6209 lastp
= &used_usb_ports
;
6210 port
= used_usb_ports
;
6211 while (port
&& port
->dev
->addr
!= addr
) {
6212 lastp
= &port
->next
;
6220 *lastp
= port
->next
;
6221 usb_attach(port
, NULL
);
6222 dev
->handle_destroy(dev
);
6223 port
->next
= free_usb_ports
;
6224 free_usb_ports
= port
;
6228 static int usb_device_del(const char *devname
)
6233 if (!used_usb_ports
)
6236 p
= strchr(devname
, '.');
6239 bus_num
= strtoul(devname
, NULL
, 0);
6240 addr
= strtoul(p
+ 1, NULL
, 0);
6242 return usb_device_del_addr(bus_num
, addr
);
6245 void do_usb_add(const char *devname
)
6247 usb_device_add(devname
);
6250 void do_usb_del(const char *devname
)
6252 usb_device_del(devname
);
6259 const char *speed_str
;
6262 term_printf("USB support not enabled\n");
6266 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6270 switch(dev
->speed
) {
6274 case USB_SPEED_FULL
:
6277 case USB_SPEED_HIGH
:
6284 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6285 0, dev
->addr
, speed_str
, dev
->devname
);
6289 /***********************************************************/
6290 /* PCMCIA/Cardbus */
6292 static struct pcmcia_socket_entry_s
{
6293 struct pcmcia_socket_s
*socket
;
6294 struct pcmcia_socket_entry_s
*next
;
6295 } *pcmcia_sockets
= 0;
6297 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6299 struct pcmcia_socket_entry_s
*entry
;
6301 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6302 entry
->socket
= socket
;
6303 entry
->next
= pcmcia_sockets
;
6304 pcmcia_sockets
= entry
;
6307 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6309 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6311 ptr
= &pcmcia_sockets
;
6312 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6313 if (entry
->socket
== socket
) {
6319 void pcmcia_info(void)
6321 struct pcmcia_socket_entry_s
*iter
;
6322 if (!pcmcia_sockets
)
6323 term_printf("No PCMCIA sockets\n");
6325 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6326 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6327 iter
->socket
->attached
? iter
->socket
->card_string
:
6331 /***********************************************************/
6334 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6338 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6342 static void dumb_refresh(DisplayState
*ds
)
6344 #if defined(CONFIG_SDL)
6349 static void dumb_display_init(DisplayState
*ds
)
6354 ds
->dpy_update
= dumb_update
;
6355 ds
->dpy_resize
= dumb_resize
;
6356 ds
->dpy_refresh
= dumb_refresh
;
6357 ds
->gui_timer_interval
= 500;
6361 /***********************************************************/
6364 #define MAX_IO_HANDLERS 64
6366 typedef struct IOHandlerRecord
{
6368 IOCanRWHandler
*fd_read_poll
;
6370 IOHandler
*fd_write
;
6373 /* temporary data */
6375 struct IOHandlerRecord
*next
;
6378 static IOHandlerRecord
*first_io_handler
;
6380 /* XXX: fd_read_poll should be suppressed, but an API change is
6381 necessary in the character devices to suppress fd_can_read(). */
6382 int qemu_set_fd_handler2(int fd
,
6383 IOCanRWHandler
*fd_read_poll
,
6385 IOHandler
*fd_write
,
6388 IOHandlerRecord
**pioh
, *ioh
;
6390 if (!fd_read
&& !fd_write
) {
6391 pioh
= &first_io_handler
;
6396 if (ioh
->fd
== fd
) {
6403 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6407 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6410 ioh
->next
= first_io_handler
;
6411 first_io_handler
= ioh
;
6414 ioh
->fd_read_poll
= fd_read_poll
;
6415 ioh
->fd_read
= fd_read
;
6416 ioh
->fd_write
= fd_write
;
6417 ioh
->opaque
= opaque
;
6424 int qemu_set_fd_handler(int fd
,
6426 IOHandler
*fd_write
,
6429 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6432 /***********************************************************/
6433 /* Polling handling */
6435 typedef struct PollingEntry
{
6438 struct PollingEntry
*next
;
6441 static PollingEntry
*first_polling_entry
;
6443 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6445 PollingEntry
**ppe
, *pe
;
6446 pe
= qemu_mallocz(sizeof(PollingEntry
));
6450 pe
->opaque
= opaque
;
6451 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6456 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6458 PollingEntry
**ppe
, *pe
;
6459 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6461 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6470 /***********************************************************/
6471 /* Wait objects support */
6472 typedef struct WaitObjects
{
6474 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6475 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6476 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6479 static WaitObjects wait_objects
= {0};
6481 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6483 WaitObjects
*w
= &wait_objects
;
6485 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6487 w
->events
[w
->num
] = handle
;
6488 w
->func
[w
->num
] = func
;
6489 w
->opaque
[w
->num
] = opaque
;
6494 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6497 WaitObjects
*w
= &wait_objects
;
6500 for (i
= 0; i
< w
->num
; i
++) {
6501 if (w
->events
[i
] == handle
)
6504 w
->events
[i
] = w
->events
[i
+ 1];
6505 w
->func
[i
] = w
->func
[i
+ 1];
6506 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6514 #define SELF_ANNOUNCE_ROUNDS 5
6515 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6516 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6517 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6519 static int announce_self_create(uint8_t *buf
,
6522 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6523 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6525 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6527 memset(buf
, 0xff, 6); /* h_dst */
6528 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6529 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6530 memcpy(buf
+ 14, &magic
, 4); /* magic */
6532 return 18; /* len */
6535 static void qemu_announce_self(void)
6539 VLANClientState
*vc
;
6542 for (i
= 0; i
< nb_nics
; i
++) {
6543 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6544 vlan
= nd_table
[i
].vlan
;
6545 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6546 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6547 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6548 vc
->fd_read(vc
->opaque
, buf
, len
);
6553 /***********************************************************/
6554 /* savevm/loadvm support */
6556 #define IO_BUF_SIZE 32768
6559 QEMUFilePutBufferFunc
*put_buffer
;
6560 QEMUFileGetBufferFunc
*get_buffer
;
6561 QEMUFileCloseFunc
*close
;
6564 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6567 int buf_size
; /* 0 when writing */
6568 uint8_t buf
[IO_BUF_SIZE
];
6571 typedef struct QEMUFileFD
6576 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6578 QEMUFileFD
*s
= opaque
;
6583 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6585 if (errno
== EINTR
|| errno
== EAGAIN
)
6592 QEMUFile
*qemu_fopen_fd(int fd
)
6594 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6596 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6599 typedef struct QEMUFileUnix
6604 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6606 QEMUFileUnix
*s
= opaque
;
6607 fseek(s
->outfile
, pos
, SEEK_SET
);
6608 fwrite(buf
, 1, size
, s
->outfile
);
6611 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6613 QEMUFileUnix
*s
= opaque
;
6614 fseek(s
->outfile
, pos
, SEEK_SET
);
6615 return fread(buf
, 1, size
, s
->outfile
);
6618 static void file_close(void *opaque
)
6620 QEMUFileUnix
*s
= opaque
;
6625 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6629 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6633 s
->outfile
= fopen(filename
, mode
);
6637 if (!strcmp(mode
, "wb"))
6638 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6639 else if (!strcmp(mode
, "rb"))
6640 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6649 typedef struct QEMUFileBdrv
6651 BlockDriverState
*bs
;
6652 int64_t base_offset
;
6655 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6657 QEMUFileBdrv
*s
= opaque
;
6658 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6661 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6663 QEMUFileBdrv
*s
= opaque
;
6664 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6667 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6671 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6676 s
->base_offset
= offset
;
6679 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6681 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6684 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6685 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6689 f
= qemu_mallocz(sizeof(QEMUFile
));
6694 f
->put_buffer
= put_buffer
;
6695 f
->get_buffer
= get_buffer
;
6701 void qemu_fflush(QEMUFile
*f
)
6706 if (f
->buf_index
> 0) {
6707 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6708 f
->buf_offset
+= f
->buf_index
;
6713 static void qemu_fill_buffer(QEMUFile
*f
)
6720 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6726 f
->buf_offset
+= len
;
6729 void qemu_fclose(QEMUFile
*f
)
6733 f
->close(f
->opaque
);
6737 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6741 l
= IO_BUF_SIZE
- f
->buf_index
;
6744 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6748 if (f
->buf_index
>= IO_BUF_SIZE
)
6753 void qemu_put_byte(QEMUFile
*f
, int v
)
6755 f
->buf
[f
->buf_index
++] = v
;
6756 if (f
->buf_index
>= IO_BUF_SIZE
)
6760 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6766 l
= f
->buf_size
- f
->buf_index
;
6768 qemu_fill_buffer(f
);
6769 l
= f
->buf_size
- f
->buf_index
;
6775 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6780 return size1
- size
;
6783 int qemu_get_byte(QEMUFile
*f
)
6785 if (f
->buf_index
>= f
->buf_size
) {
6786 qemu_fill_buffer(f
);
6787 if (f
->buf_index
>= f
->buf_size
)
6790 return f
->buf
[f
->buf_index
++];
6793 int64_t qemu_ftell(QEMUFile
*f
)
6795 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6798 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6800 if (whence
== SEEK_SET
) {
6802 } else if (whence
== SEEK_CUR
) {
6803 pos
+= qemu_ftell(f
);
6805 /* SEEK_END not supported */
6808 if (f
->put_buffer
) {
6810 f
->buf_offset
= pos
;
6812 f
->buf_offset
= pos
;
6819 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6821 qemu_put_byte(f
, v
>> 8);
6822 qemu_put_byte(f
, v
);
6825 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6827 qemu_put_byte(f
, v
>> 24);
6828 qemu_put_byte(f
, v
>> 16);
6829 qemu_put_byte(f
, v
>> 8);
6830 qemu_put_byte(f
, v
);
6833 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6835 qemu_put_be32(f
, v
>> 32);
6836 qemu_put_be32(f
, v
);
6839 unsigned int qemu_get_be16(QEMUFile
*f
)
6842 v
= qemu_get_byte(f
) << 8;
6843 v
|= qemu_get_byte(f
);
6847 unsigned int qemu_get_be32(QEMUFile
*f
)
6850 v
= qemu_get_byte(f
) << 24;
6851 v
|= qemu_get_byte(f
) << 16;
6852 v
|= qemu_get_byte(f
) << 8;
6853 v
|= qemu_get_byte(f
);
6857 uint64_t qemu_get_be64(QEMUFile
*f
)
6860 v
= (uint64_t)qemu_get_be32(f
) << 32;
6861 v
|= qemu_get_be32(f
);
6865 typedef struct SaveStateEntry
{
6869 SaveStateHandler
*save_state
;
6870 LoadStateHandler
*load_state
;
6872 struct SaveStateEntry
*next
;
6875 static SaveStateEntry
*first_se
;
6877 /* TODO: Individual devices generally have very little idea about the rest
6878 of the system, so instance_id should be removed/replaced.
6879 Meanwhile pass -1 as instance_id if you do not already have a clearly
6880 distinguishing id for all instances of your device class. */
6881 int register_savevm(const char *idstr
,
6884 SaveStateHandler
*save_state
,
6885 LoadStateHandler
*load_state
,
6888 SaveStateEntry
*se
, **pse
;
6890 se
= qemu_malloc(sizeof(SaveStateEntry
));
6893 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6894 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6895 se
->version_id
= version_id
;
6896 se
->save_state
= save_state
;
6897 se
->load_state
= load_state
;
6898 se
->opaque
= opaque
;
6901 /* add at the end of list */
6903 while (*pse
!= NULL
) {
6904 if (instance_id
== -1
6905 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6906 && se
->instance_id
<= (*pse
)->instance_id
)
6907 se
->instance_id
= (*pse
)->instance_id
+ 1;
6908 pse
= &(*pse
)->next
;
6914 #define QEMU_VM_FILE_MAGIC 0x5145564d
6915 #define QEMU_VM_FILE_VERSION 0x00000002
6917 static int qemu_savevm_state(QEMUFile
*f
)
6921 int64_t cur_pos
, len_pos
, total_len_pos
;
6923 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6924 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6925 total_len_pos
= qemu_ftell(f
);
6926 qemu_put_be64(f
, 0); /* total size */
6928 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6929 if (se
->save_state
== NULL
)
6930 /* this one has a loader only, for backwards compatibility */
6934 len
= strlen(se
->idstr
);
6935 qemu_put_byte(f
, len
);
6936 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6938 qemu_put_be32(f
, se
->instance_id
);
6939 qemu_put_be32(f
, se
->version_id
);
6941 /* record size: filled later */
6942 len_pos
= qemu_ftell(f
);
6943 qemu_put_be32(f
, 0);
6944 se
->save_state(f
, se
->opaque
);
6946 /* fill record size */
6947 cur_pos
= qemu_ftell(f
);
6948 len
= cur_pos
- len_pos
- 4;
6949 qemu_fseek(f
, len_pos
, SEEK_SET
);
6950 qemu_put_be32(f
, len
);
6951 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6953 cur_pos
= qemu_ftell(f
);
6954 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6955 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6956 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6962 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6966 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6967 if (!strcmp(se
->idstr
, idstr
) &&
6968 instance_id
== se
->instance_id
)
6974 static int qemu_loadvm_state(QEMUFile
*f
)
6977 int len
, ret
, instance_id
, record_len
, version_id
;
6978 int64_t total_len
, end_pos
, cur_pos
;
6982 v
= qemu_get_be32(f
);
6983 if (v
!= QEMU_VM_FILE_MAGIC
)
6985 v
= qemu_get_be32(f
);
6986 if (v
!= QEMU_VM_FILE_VERSION
) {
6991 total_len
= qemu_get_be64(f
);
6992 end_pos
= total_len
+ qemu_ftell(f
);
6994 if (qemu_ftell(f
) >= end_pos
)
6996 len
= qemu_get_byte(f
);
6997 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6999 instance_id
= qemu_get_be32(f
);
7000 version_id
= qemu_get_be32(f
);
7001 record_len
= qemu_get_be32(f
);
7003 printf("idstr=%s instance=0x%x version=%d len=%d\n",
7004 idstr
, instance_id
, version_id
, record_len
);
7006 cur_pos
= qemu_ftell(f
);
7007 se
= find_se(idstr
, instance_id
);
7009 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7010 instance_id
, idstr
);
7012 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7014 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7015 instance_id
, idstr
);
7019 /* always seek to exact end of record */
7020 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
7027 int qemu_live_savevm_state(QEMUFile
*f
)
7032 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
7033 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
7035 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
7036 len
= strlen(se
->idstr
);
7038 qemu_put_byte(f
, len
);
7039 qemu_put_buffer(f
, se
->idstr
, len
);
7040 qemu_put_be32(f
, se
->instance_id
);
7041 qemu_put_be32(f
, se
->version_id
);
7043 se
->save_state(f
, se
->opaque
);
7046 qemu_put_byte(f
, 0);
7052 int qemu_live_loadvm_state(QEMUFile
*f
)
7055 int len
, ret
, instance_id
, version_id
;
7059 v
= qemu_get_be32(f
);
7060 if (v
!= QEMU_VM_FILE_MAGIC
)
7062 v
= qemu_get_be32(f
);
7063 if (v
!= QEMU_VM_FILE_VERSION
) {
7070 len
= qemu_get_byte(f
);
7073 qemu_get_buffer(f
, idstr
, len
);
7075 instance_id
= qemu_get_be32(f
);
7076 version_id
= qemu_get_be32(f
);
7077 se
= find_se(idstr
, instance_id
);
7079 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7080 instance_id
, idstr
);
7082 if (version_id
> se
->version_id
) { /* src version > dst version */
7083 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7084 idstr
, version_id
, se
->version_id
);
7088 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7090 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7091 instance_id
, idstr
);
7098 qemu_announce_self();
7104 /* device can contain snapshots */
7105 static int bdrv_can_snapshot(BlockDriverState
*bs
)
7108 !bdrv_is_removable(bs
) &&
7109 !bdrv_is_read_only(bs
));
7112 /* device must be snapshots in order to have a reliable snapshot */
7113 static int bdrv_has_snapshot(BlockDriverState
*bs
)
7116 !bdrv_is_removable(bs
) &&
7117 !bdrv_is_read_only(bs
));
7120 static BlockDriverState
*get_bs_snapshots(void)
7122 BlockDriverState
*bs
;
7126 return bs_snapshots
;
7127 for(i
= 0; i
<= nb_drives
; i
++) {
7128 bs
= drives_table
[i
].bdrv
;
7129 if (bdrv_can_snapshot(bs
))
7138 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
7141 QEMUSnapshotInfo
*sn_tab
, *sn
;
7145 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7148 for(i
= 0; i
< nb_sns
; i
++) {
7150 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
7160 void do_savevm(const char *name
)
7162 BlockDriverState
*bs
, *bs1
;
7163 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
7164 int must_delete
, ret
, i
;
7165 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7167 int saved_vm_running
;
7174 bs
= get_bs_snapshots();
7176 term_printf("No block device can accept snapshots\n");
7180 /* ??? Should this occur after vm_stop? */
7183 saved_vm_running
= vm_running
;
7188 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
7193 memset(sn
, 0, sizeof(*sn
));
7195 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
7196 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
7199 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
7202 /* fill auxiliary fields */
7205 sn
->date_sec
= tb
.time
;
7206 sn
->date_nsec
= tb
.millitm
* 1000000;
7208 gettimeofday(&tv
, NULL
);
7209 sn
->date_sec
= tv
.tv_sec
;
7210 sn
->date_nsec
= tv
.tv_usec
* 1000;
7212 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7214 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7215 term_printf("Device %s does not support VM state snapshots\n",
7216 bdrv_get_device_name(bs
));
7220 /* save the VM state */
7221 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7223 term_printf("Could not open VM state file\n");
7226 ret
= qemu_savevm_state(f
);
7227 sn
->vm_state_size
= qemu_ftell(f
);
7230 term_printf("Error %d while writing VM\n", ret
);
7234 /* create the snapshots */
7236 for(i
= 0; i
< nb_drives
; i
++) {
7237 bs1
= drives_table
[i
].bdrv
;
7238 if (bdrv_has_snapshot(bs1
)) {
7240 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7242 term_printf("Error while deleting snapshot on '%s'\n",
7243 bdrv_get_device_name(bs1
));
7246 ret
= bdrv_snapshot_create(bs1
, sn
);
7248 term_printf("Error while creating snapshot on '%s'\n",
7249 bdrv_get_device_name(bs1
));
7255 if (saved_vm_running
)
7259 void do_loadvm(const char *name
)
7261 BlockDriverState
*bs
, *bs1
;
7262 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7265 int saved_vm_running
;
7267 bs
= get_bs_snapshots();
7269 term_printf("No block device supports snapshots\n");
7273 /* Flush all IO requests so they don't interfere with the new state. */
7276 saved_vm_running
= vm_running
;
7279 for(i
= 0; i
<= nb_drives
; i
++) {
7280 bs1
= drives_table
[i
].bdrv
;
7281 if (bdrv_has_snapshot(bs1
)) {
7282 ret
= bdrv_snapshot_goto(bs1
, name
);
7285 term_printf("Warning: ");
7288 term_printf("Snapshots not supported on device '%s'\n",
7289 bdrv_get_device_name(bs1
));
7292 term_printf("Could not find snapshot '%s' on device '%s'\n",
7293 name
, bdrv_get_device_name(bs1
));
7296 term_printf("Error %d while activating snapshot on '%s'\n",
7297 ret
, bdrv_get_device_name(bs1
));
7300 /* fatal on snapshot block device */
7307 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7308 term_printf("Device %s does not support VM state snapshots\n",
7309 bdrv_get_device_name(bs
));
7313 /* restore the VM state */
7314 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7316 term_printf("Could not open VM state file\n");
7319 ret
= qemu_loadvm_state(f
);
7322 term_printf("Error %d while loading VM state\n", ret
);
7325 if (saved_vm_running
)
7329 void do_delvm(const char *name
)
7331 BlockDriverState
*bs
, *bs1
;
7334 bs
= get_bs_snapshots();
7336 term_printf("No block device supports snapshots\n");
7340 for(i
= 0; i
<= nb_drives
; i
++) {
7341 bs1
= drives_table
[i
].bdrv
;
7342 if (bdrv_has_snapshot(bs1
)) {
7343 ret
= bdrv_snapshot_delete(bs1
, name
);
7345 if (ret
== -ENOTSUP
)
7346 term_printf("Snapshots not supported on device '%s'\n",
7347 bdrv_get_device_name(bs1
));
7349 term_printf("Error %d while deleting snapshot on '%s'\n",
7350 ret
, bdrv_get_device_name(bs1
));
7356 void do_info_snapshots(void)
7358 BlockDriverState
*bs
, *bs1
;
7359 QEMUSnapshotInfo
*sn_tab
, *sn
;
7363 bs
= get_bs_snapshots();
7365 term_printf("No available block device supports snapshots\n");
7368 term_printf("Snapshot devices:");
7369 for(i
= 0; i
<= nb_drives
; i
++) {
7370 bs1
= drives_table
[i
].bdrv
;
7371 if (bdrv_has_snapshot(bs1
)) {
7373 term_printf(" %s", bdrv_get_device_name(bs1
));
7378 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7380 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7383 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7384 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7385 for(i
= 0; i
< nb_sns
; i
++) {
7387 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7392 /***********************************************************/
7393 /* ram save/restore */
7395 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7399 v
= qemu_get_byte(f
);
7402 if (qemu_get_buffer(f
, buf
, len
) != len
)
7406 v
= qemu_get_byte(f
);
7407 memset(buf
, v
, len
);
7415 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7420 if (qemu_get_be32(f
) != phys_ram_size
)
7422 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7423 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7425 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7432 #define BDRV_HASH_BLOCK_SIZE 1024
7433 #define IOBUF_SIZE 4096
7434 #define RAM_CBLOCK_MAGIC 0xfabe
7436 typedef struct RamCompressState
{
7439 uint8_t buf
[IOBUF_SIZE
];
7442 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7445 memset(s
, 0, sizeof(*s
));
7447 ret
= deflateInit2(&s
->zstream
, 1,
7449 9, Z_DEFAULT_STRATEGY
);
7452 s
->zstream
.avail_out
= IOBUF_SIZE
;
7453 s
->zstream
.next_out
= s
->buf
;
7457 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7459 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7460 qemu_put_be16(s
->f
, len
);
7461 qemu_put_buffer(s
->f
, buf
, len
);
7464 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7468 s
->zstream
.avail_in
= len
;
7469 s
->zstream
.next_in
= (uint8_t *)buf
;
7470 while (s
->zstream
.avail_in
> 0) {
7471 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7474 if (s
->zstream
.avail_out
== 0) {
7475 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7476 s
->zstream
.avail_out
= IOBUF_SIZE
;
7477 s
->zstream
.next_out
= s
->buf
;
7483 static void ram_compress_close(RamCompressState
*s
)
7487 /* compress last bytes */
7489 ret
= deflate(&s
->zstream
, Z_FINISH
);
7490 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7491 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7493 ram_put_cblock(s
, s
->buf
, len
);
7495 s
->zstream
.avail_out
= IOBUF_SIZE
;
7496 s
->zstream
.next_out
= s
->buf
;
7497 if (ret
== Z_STREAM_END
)
7504 deflateEnd(&s
->zstream
);
7507 typedef struct RamDecompressState
{
7510 uint8_t buf
[IOBUF_SIZE
];
7511 } RamDecompressState
;
7513 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7516 memset(s
, 0, sizeof(*s
));
7518 ret
= inflateInit(&s
->zstream
);
7524 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7528 s
->zstream
.avail_out
= len
;
7529 s
->zstream
.next_out
= buf
;
7530 while (s
->zstream
.avail_out
> 0) {
7531 if (s
->zstream
.avail_in
== 0) {
7532 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7534 clen
= qemu_get_be16(s
->f
);
7535 if (clen
> IOBUF_SIZE
)
7537 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7538 s
->zstream
.avail_in
= clen
;
7539 s
->zstream
.next_in
= s
->buf
;
7541 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7542 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7549 static void ram_decompress_close(RamDecompressState
*s
)
7551 inflateEnd(&s
->zstream
);
7554 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7558 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7559 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7561 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7562 qemu_put_be32(f
, addr
);
7563 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7566 qemu_put_be32(f
, 1);
7569 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7572 RamCompressState s1
, *s
= &s1
;
7575 qemu_put_be32(f
, phys_ram_size
);
7576 if (ram_compress_open(s
, f
) < 0)
7578 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7579 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7582 if (tight_savevm_enabled
) {
7586 /* find if the memory block is available on a virtual
7589 for(j
= 0; j
< nb_drives
; j
++) {
7590 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7592 BDRV_HASH_BLOCK_SIZE
);
7593 if (sector_num
>= 0)
7597 goto normal_compress
;
7600 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7601 ram_compress_buf(s
, buf
, 10);
7607 ram_compress_buf(s
, buf
, 1);
7608 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7611 ram_compress_close(s
);
7614 static void ram_save(QEMUFile
*f
, void *opaque
)
7616 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7618 qemu_put_byte(f
, in_migration
);
7621 ram_save_live(f
, opaque
);
7623 ram_save_static(f
, opaque
);
7626 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7631 addr
= qemu_get_be32(f
);
7635 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7641 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7643 RamDecompressState s1
, *s
= &s1
;
7647 if (qemu_get_be32(f
) != phys_ram_size
)
7649 if (ram_decompress_open(s
, f
) < 0)
7651 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7652 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7654 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7655 fprintf(stderr
, "Error while reading ram block header\n");
7659 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7660 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7669 ram_decompress_buf(s
, buf
+ 1, 9);
7671 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7672 if (bs_index
>= nb_drives
) {
7673 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7676 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7678 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7679 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7680 bs_index
, sector_num
);
7687 printf("Error block header\n");
7691 ram_decompress_close(s
);
7695 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7699 switch (version_id
) {
7701 ret
= ram_load_v1(f
, opaque
);
7704 if (qemu_get_byte(f
)) {
7705 ret
= ram_load_live(f
, opaque
);
7709 ret
= ram_load_static(f
, opaque
);
7719 /***********************************************************/
7720 /* bottom halves (can be seen as timers which expire ASAP) */
7729 static QEMUBH
*first_bh
= NULL
;
7731 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7734 bh
= qemu_mallocz(sizeof(QEMUBH
));
7738 bh
->opaque
= opaque
;
7742 int qemu_bh_poll(void)
7761 void qemu_bh_schedule(QEMUBH
*bh
)
7763 CPUState
*env
= cpu_single_env
;
7767 bh
->next
= first_bh
;
7770 /* stop the currently executing CPU to execute the BH ASAP */
7772 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7777 void qemu_bh_cancel(QEMUBH
*bh
)
7780 if (bh
->scheduled
) {
7783 pbh
= &(*pbh
)->next
;
7789 void qemu_bh_delete(QEMUBH
*bh
)
7795 /***********************************************************/
7796 /* machine registration */
7798 QEMUMachine
*first_machine
= NULL
;
7799 QEMUMachine
*current_machine
= NULL
;
7801 int qemu_register_machine(QEMUMachine
*m
)
7804 pm
= &first_machine
;
7812 static QEMUMachine
*find_machine(const char *name
)
7816 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7817 if (!strcmp(m
->name
, name
))
7823 /***********************************************************/
7824 /* main execution loop */
7826 static void gui_update(void *opaque
)
7828 DisplayState
*ds
= opaque
;
7829 ds
->dpy_refresh(ds
);
7830 qemu_mod_timer(ds
->gui_timer
,
7831 (ds
->gui_timer_interval
?
7832 ds
->gui_timer_interval
:
7833 GUI_REFRESH_INTERVAL
)
7834 + qemu_get_clock(rt_clock
));
7837 struct vm_change_state_entry
{
7838 VMChangeStateHandler
*cb
;
7840 LIST_ENTRY (vm_change_state_entry
) entries
;
7843 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7845 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7848 VMChangeStateEntry
*e
;
7850 e
= qemu_mallocz(sizeof (*e
));
7856 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7860 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7862 LIST_REMOVE (e
, entries
);
7866 static void vm_state_notify(int running
)
7868 VMChangeStateEntry
*e
;
7870 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7871 e
->cb(e
->opaque
, running
);
7875 /* XXX: support several handlers */
7876 static VMStopHandler
*vm_stop_cb
;
7877 static void *vm_stop_opaque
;
7879 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7882 vm_stop_opaque
= opaque
;
7886 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7897 qemu_rearm_alarm_timer(alarm_timer
);
7901 void vm_stop(int reason
)
7904 cpu_disable_ticks();
7908 vm_stop_cb(vm_stop_opaque
, reason
);
7915 /* reset/shutdown handler */
7917 typedef struct QEMUResetEntry
{
7918 QEMUResetHandler
*func
;
7920 struct QEMUResetEntry
*next
;
7923 static QEMUResetEntry
*first_reset_entry
;
7924 static int reset_requested
;
7925 static int shutdown_requested
;
7926 static int powerdown_requested
;
7928 int qemu_shutdown_requested(void)
7930 int r
= shutdown_requested
;
7931 shutdown_requested
= 0;
7935 int qemu_reset_requested(void)
7937 int r
= reset_requested
;
7938 reset_requested
= 0;
7942 int qemu_powerdown_requested(void)
7944 int r
= powerdown_requested
;
7945 powerdown_requested
= 0;
7949 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7951 QEMUResetEntry
**pre
, *re
;
7953 pre
= &first_reset_entry
;
7954 while (*pre
!= NULL
)
7955 pre
= &(*pre
)->next
;
7956 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7958 re
->opaque
= opaque
;
7963 void qemu_system_reset(void)
7967 /* reset all devices */
7968 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7969 re
->func(re
->opaque
);
7973 void qemu_system_reset_request(void)
7976 shutdown_requested
= 1;
7978 reset_requested
= 1;
7981 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7985 void qemu_system_shutdown_request(void)
7987 shutdown_requested
= 1;
7989 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7992 void qemu_system_powerdown_request(void)
7994 powerdown_requested
= 1;
7996 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7999 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
8004 /* KVM holds a mutex while QEMU code is running, we need hooks to
8005 release the mutex whenever QEMU code sleeps. */
8009 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
8016 void main_loop_wait(int timeout
)
8018 IOHandlerRecord
*ioh
;
8019 fd_set rfds
, wfds
, xfds
;
8028 /* XXX: need to suppress polling by better using win32 events */
8030 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
8031 ret
|= pe
->func(pe
->opaque
);
8036 WaitObjects
*w
= &wait_objects
;
8038 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
8039 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
8040 if (w
->func
[ret
- WAIT_OBJECT_0
])
8041 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
8043 /* Check for additional signaled events */
8044 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
8046 /* Check if event is signaled */
8047 ret2
= WaitForSingleObject(w
->events
[i
], 0);
8048 if(ret2
== WAIT_OBJECT_0
) {
8050 w
->func
[i
](w
->opaque
[i
]);
8051 } else if (ret2
== WAIT_TIMEOUT
) {
8053 err
= GetLastError();
8054 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
8057 } else if (ret
== WAIT_TIMEOUT
) {
8059 err
= GetLastError();
8060 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
8064 /* poll any events */
8065 /* XXX: separate device handlers from system ones */
8070 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8074 (!ioh
->fd_read_poll
||
8075 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
8076 FD_SET(ioh
->fd
, &rfds
);
8080 if (ioh
->fd_write
) {
8081 FD_SET(ioh
->fd
, &wfds
);
8091 tv
.tv_sec
= timeout
/ 1000;
8092 tv
.tv_usec
= (timeout
% 1000) * 1000;
8094 #if defined(CONFIG_SLIRP)
8096 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
8099 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
8101 IOHandlerRecord
**pioh
;
8103 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8104 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
8105 ioh
->fd_read(ioh
->opaque
);
8106 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
8107 FD_CLR(ioh
->fd
, &rfds
);
8109 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
8110 ioh
->fd_write(ioh
->opaque
);
8114 /* remove deleted IO handlers */
8115 pioh
= &first_io_handler
;
8125 #if defined(CONFIG_SLIRP)
8132 slirp_select_poll(&rfds
, &wfds
, &xfds
);
8137 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
8138 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
8139 qemu_get_clock(vm_clock
));
8140 /* run dma transfers, if any */
8144 /* real time timers */
8145 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
8146 qemu_get_clock(rt_clock
));
8148 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
8149 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
8150 qemu_rearm_alarm_timer(alarm_timer
);
8153 /* Check bottom-halves last in case any of the earlier events triggered
8159 static int main_loop(void)
8162 #ifdef CONFIG_PROFILER
8168 if (kvm_enabled()) {
8170 cpu_disable_ticks();
8174 cur_cpu
= first_cpu
;
8175 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
8182 #ifdef CONFIG_PROFILER
8183 ti
= profile_getclock();
8188 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
8189 env
->icount_decr
.u16
.low
= 0;
8190 env
->icount_extra
= 0;
8191 count
= qemu_next_deadline();
8192 count
= (count
+ (1 << icount_time_shift
) - 1)
8193 >> icount_time_shift
;
8194 qemu_icount
+= count
;
8195 decr
= (count
> 0xffff) ? 0xffff : count
;
8197 env
->icount_decr
.u16
.low
= decr
;
8198 env
->icount_extra
= count
;
8200 ret
= cpu_exec(env
);
8201 #ifdef CONFIG_PROFILER
8202 qemu_time
+= profile_getclock() - ti
;
8205 /* Fold pending instructions back into the
8206 instruction counter, and clear the interrupt flag. */
8207 qemu_icount
-= (env
->icount_decr
.u16
.low
8208 + env
->icount_extra
);
8209 env
->icount_decr
.u32
= 0;
8210 env
->icount_extra
= 0;
8212 next_cpu
= env
->next_cpu
?: first_cpu
;
8213 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8214 ret
= EXCP_INTERRUPT
;
8218 if (ret
== EXCP_HLT
) {
8219 /* Give the next CPU a chance to run. */
8223 if (ret
!= EXCP_HALTED
)
8225 /* all CPUs are halted ? */
8231 if (shutdown_requested
) {
8232 ret
= EXCP_INTERRUPT
;
8240 if (reset_requested
) {
8241 reset_requested
= 0;
8242 qemu_system_reset();
8244 kvm_load_registers(env
);
8245 ret
= EXCP_INTERRUPT
;
8247 if (powerdown_requested
) {
8248 powerdown_requested
= 0;
8249 qemu_system_powerdown();
8250 ret
= EXCP_INTERRUPT
;
8252 if (unlikely(ret
== EXCP_DEBUG
)) {
8253 vm_stop(EXCP_DEBUG
);
8255 /* If all cpus are halted then wait until the next IRQ */
8256 /* XXX: use timeout computed from timers */
8257 if (ret
== EXCP_HALTED
) {
8261 /* Advance virtual time to the next event. */
8262 if (use_icount
== 1) {
8263 /* When not using an adaptive execution frequency
8264 we tend to get badly out of sync with real time,
8265 so just delay for a reasonable amount of time. */
8268 delta
= cpu_get_icount() - cpu_get_clock();
8271 /* If virtual time is ahead of real time then just
8273 timeout
= (delta
/ 1000000) + 1;
8275 /* Wait for either IO to occur or the next
8277 add
= qemu_next_deadline();
8278 /* We advance the timer before checking for IO.
8279 Limit the amount we advance so that early IO
8280 activity won't get the guest too far ahead. */
8284 add
= (add
+ (1 << icount_time_shift
) - 1)
8285 >> icount_time_shift
;
8287 timeout
= delta
/ 1000000;
8298 if (shutdown_requested
)
8302 #ifdef CONFIG_PROFILER
8303 ti
= profile_getclock();
8305 main_loop_wait(timeout
);
8306 #ifdef CONFIG_PROFILER
8307 dev_time
+= profile_getclock() - ti
;
8310 cpu_disable_ticks();
8314 static void help(int exitcode
)
8316 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8317 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8318 "usage: %s [options] [disk_image]\n"
8320 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8322 "Standard options:\n"
8323 "-M machine select emulated machine (-M ? for list)\n"
8324 "-cpu cpu select CPU (-cpu ? for list)\n"
8325 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8326 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8327 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8328 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8329 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8330 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8331 " [,cache=on|off][,format=f][,boot=on|off]\n"
8332 " use 'file' as a drive image\n"
8333 "-mtdblock file use 'file' as on-board Flash memory image\n"
8334 "-sd file use 'file' as SecureDigital card image\n"
8335 "-pflash file use 'file' as a parallel flash image\n"
8336 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8337 "-snapshot write to temporary files instead of disk image files\n"
8339 "-no-frame open SDL window without a frame and window decorations\n"
8340 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8341 "-no-quit disable SDL window close capability\n"
8344 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8346 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8347 "-smp n set the number of CPUs to 'n' [default=1]\n"
8348 "-nographic disable graphical output and redirect serial I/Os to console\n"
8349 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8351 "-k language use keyboard layout (for example \"fr\" for French)\n"
8354 "-audio-help print list of audio drivers and their options\n"
8355 "-soundhw c1,... enable audio support\n"
8356 " and only specified sound cards (comma separated list)\n"
8357 " use -soundhw ? to get the list of supported cards\n"
8358 " use -soundhw all to enable all of them\n"
8360 "-localtime set the real time clock to local time [default=utc]\n"
8361 "-full-screen start in full screen\n"
8363 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8365 "-usb enable the USB driver (will be the default soon)\n"
8366 "-usbdevice name add the host or guest USB device 'name'\n"
8367 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8368 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8370 "-name string set the name of the guest\n"
8372 "Network options:\n"
8373 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8374 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8376 "-net user[,vlan=n][,hostname=host]\n"
8377 " connect the user mode network stack to VLAN 'n' and send\n"
8378 " hostname 'host' to DHCP clients\n"
8381 "-net tap[,vlan=n],ifname=name\n"
8382 " connect the host TAP network interface to VLAN 'n'\n"
8384 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8385 " connect the host TAP network interface to VLAN 'n' and use the\n"
8386 " network scripts 'file' (default=%s)\n"
8387 " and 'dfile' (default=%s);\n"
8388 " use '[down]script=no' to disable script execution;\n"
8389 " use 'fd=h' to connect to an already opened TAP interface\n"
8391 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8392 " connect the vlan 'n' to another VLAN using a socket connection\n"
8393 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8394 " connect the vlan 'n' to multicast maddr and port\n"
8396 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8397 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8398 " on host and listening for incoming connections on 'socketpath'.\n"
8399 " Use group 'groupname' and mode 'octalmode' to change default\n"
8400 " ownership and permissions for communication port.\n"
8402 "-net none use it alone to have zero network devices; if no -net option\n"
8403 " is provided, the default is '-net nic -net user'\n"
8406 "-tftp dir allow tftp access to files in dir [-net user]\n"
8407 "-bootp file advertise file in BOOTP replies\n"
8409 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8411 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8412 " redirect TCP or UDP connections from host to guest [-net user]\n"
8415 "Linux boot specific:\n"
8416 "-kernel bzImage use 'bzImage' as kernel image\n"
8417 "-append cmdline use 'cmdline' as kernel command line\n"
8418 "-initrd file use 'file' as initial ram disk\n"
8420 "Debug/Expert options:\n"
8421 "-monitor dev redirect the monitor to char device 'dev'\n"
8422 "-serial dev redirect the serial port to char device 'dev'\n"
8423 "-parallel dev redirect the parallel port to char device 'dev'\n"
8424 "-pidfile file Write PID to 'file'\n"
8425 "-S freeze CPU at startup (use 'c' to start execution)\n"
8426 "-s wait gdb connection to port\n"
8427 "-p port set gdb connection port [default=%s]\n"
8428 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8429 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8430 " translation (t=none or lba) (usually qemu can guess them)\n"
8431 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8433 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8434 "-no-kqemu disable KQEMU kernel module usage\n"
8437 #ifndef NO_CPU_EMULATION
8438 "-no-kvm disable KVM hardware virtualization\n"
8440 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8441 "-no-kvm-pit disable KVM kernel mode PIT\n"
8444 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8445 " (default is CL-GD5446 PCI VGA)\n"
8446 "-no-acpi disable ACPI\n"
8448 #ifdef CONFIG_CURSES
8449 "-curses use a curses/ncurses interface instead of SDL\n"
8451 "-no-reboot exit instead of rebooting\n"
8452 "-no-shutdown stop before shutdown\n"
8453 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8454 "-vnc display start a VNC server on display\n"
8456 "-daemonize daemonize QEMU after initializing\n"
8458 "-tdf inject timer interrupts that got lost\n"
8459 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8460 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8461 "-option-rom rom load a file, rom, into the option ROM space\n"
8463 "-prom-env variable=value set OpenBIOS nvram variables\n"
8465 "-clock force the use of the given methods for timer alarm.\n"
8466 " To see what timers are available use -clock ?\n"
8467 "-startdate select initial date of the clock\n"
8468 "-icount [N|auto]\n"
8469 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8471 "During emulation, the following keys are useful:\n"
8472 "ctrl-alt-f toggle full screen\n"
8473 "ctrl-alt-n switch to virtual console 'n'\n"
8474 "ctrl-alt toggle mouse and keyboard grab\n"
8476 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8481 DEFAULT_NETWORK_SCRIPT
,
8482 DEFAULT_NETWORK_DOWN_SCRIPT
,
8484 DEFAULT_GDBSTUB_PORT
,
8489 #define HAS_ARG 0x0001
8504 QEMU_OPTION_mtdblock
,
8508 QEMU_OPTION_snapshot
,
8510 QEMU_OPTION_no_fd_bootchk
,
8513 QEMU_OPTION_nographic
,
8514 QEMU_OPTION_portrait
,
8516 QEMU_OPTION_audio_help
,
8517 QEMU_OPTION_soundhw
,
8538 QEMU_OPTION_localtime
,
8539 QEMU_OPTION_cirrusvga
,
8542 QEMU_OPTION_std_vga
,
8544 QEMU_OPTION_monitor
,
8546 QEMU_OPTION_parallel
,
8548 QEMU_OPTION_full_screen
,
8549 QEMU_OPTION_no_frame
,
8550 QEMU_OPTION_alt_grab
,
8551 QEMU_OPTION_no_quit
,
8552 QEMU_OPTION_pidfile
,
8553 QEMU_OPTION_no_kqemu
,
8554 QEMU_OPTION_kernel_kqemu
,
8555 QEMU_OPTION_win2k_hack
,
8557 QEMU_OPTION_usbdevice
,
8560 QEMU_OPTION_no_acpi
,
8563 QEMU_OPTION_no_kvm_irqchip
,
8564 QEMU_OPTION_no_kvm_pit
,
8565 QEMU_OPTION_no_reboot
,
8566 QEMU_OPTION_no_shutdown
,
8567 QEMU_OPTION_show_cursor
,
8568 QEMU_OPTION_daemonize
,
8569 QEMU_OPTION_option_rom
,
8570 QEMU_OPTION_semihosting
,
8571 QEMU_OPTION_cpu_vendor
,
8573 QEMU_OPTION_prom_env
,
8574 QEMU_OPTION_old_param
,
8576 QEMU_OPTION_startdate
,
8577 QEMU_OPTION_tb_size
,
8579 QEMU_OPTION_incoming
,
8581 QEMU_OPTION_kvm_shadow_memory
,
8582 QEMU_OPTION_mempath
,
8585 typedef struct QEMUOption
{
8591 const QEMUOption qemu_options
[] = {
8592 { "h", 0, QEMU_OPTION_h
},
8593 { "help", 0, QEMU_OPTION_h
},
8595 { "M", HAS_ARG
, QEMU_OPTION_M
},
8596 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8597 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8598 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8599 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8600 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8601 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8602 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8603 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8604 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8605 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8606 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8607 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8608 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8609 { "snapshot", 0, QEMU_OPTION_snapshot
},
8611 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8613 { "m", HAS_ARG
, QEMU_OPTION_m
},
8614 { "nographic", 0, QEMU_OPTION_nographic
},
8615 { "portrait", 0, QEMU_OPTION_portrait
},
8616 { "k", HAS_ARG
, QEMU_OPTION_k
},
8618 { "audio-help", 0, QEMU_OPTION_audio_help
},
8619 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8622 { "net", HAS_ARG
, QEMU_OPTION_net
},
8624 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8625 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8627 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8629 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8632 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8633 { "append", HAS_ARG
, QEMU_OPTION_append
},
8634 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8636 { "S", 0, QEMU_OPTION_S
},
8637 { "s", 0, QEMU_OPTION_s
},
8638 { "p", HAS_ARG
, QEMU_OPTION_p
},
8639 { "d", HAS_ARG
, QEMU_OPTION_d
},
8640 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8641 { "L", HAS_ARG
, QEMU_OPTION_L
},
8642 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8644 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8645 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8648 #ifndef NO_CPU_EMULATION
8649 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8651 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8652 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8654 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8655 { "g", 1, QEMU_OPTION_g
},
8657 { "localtime", 0, QEMU_OPTION_localtime
},
8658 { "std-vga", 0, QEMU_OPTION_std_vga
},
8659 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8660 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8661 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8662 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8663 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8664 { "incoming", 1, QEMU_OPTION_incoming
},
8665 { "full-screen", 0, QEMU_OPTION_full_screen
},
8667 { "no-frame", 0, QEMU_OPTION_no_frame
},
8668 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8669 { "no-quit", 0, QEMU_OPTION_no_quit
},
8671 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8672 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8673 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8674 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8675 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8676 #ifdef CONFIG_CURSES
8677 { "curses", 0, QEMU_OPTION_curses
},
8680 /* temporary options */
8681 { "usb", 0, QEMU_OPTION_usb
},
8682 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8683 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8684 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8685 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8686 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8687 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8688 { "daemonize", 0, QEMU_OPTION_daemonize
},
8689 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8690 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8691 { "semihosting", 0, QEMU_OPTION_semihosting
},
8693 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8694 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8695 { "name", HAS_ARG
, QEMU_OPTION_name
},
8696 #if defined(TARGET_SPARC)
8697 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8699 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8700 #if defined(TARGET_ARM)
8701 { "old-param", 0, QEMU_OPTION_old_param
},
8703 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8704 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8705 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8706 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8707 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8711 /* password input */
8713 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8718 if (!bdrv_is_encrypted(bs
))
8721 term_printf("%s is encrypted.\n", name
);
8722 for(i
= 0; i
< 3; i
++) {
8723 monitor_readline("Password: ", 1, password
, sizeof(password
));
8724 if (bdrv_set_key(bs
, password
) == 0)
8726 term_printf("invalid password\n");
8731 static BlockDriverState
*get_bdrv(int index
)
8733 if (index
> nb_drives
)
8735 return drives_table
[index
].bdrv
;
8738 static void read_passwords(void)
8740 BlockDriverState
*bs
;
8743 for(i
= 0; i
< 6; i
++) {
8746 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8751 struct soundhw soundhw
[] = {
8752 #ifdef HAS_AUDIO_CHOICE
8753 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8759 { .init_isa
= pcspk_audio_init
}
8764 "Creative Sound Blaster 16",
8767 { .init_isa
= SB16_init
}
8770 #ifdef CONFIG_CS4231A
8776 { .init_isa
= cs4231a_init
}
8784 "Yamaha YMF262 (OPL3)",
8786 "Yamaha YM3812 (OPL2)",
8790 { .init_isa
= Adlib_init
}
8797 "Gravis Ultrasound GF1",
8800 { .init_isa
= GUS_init
}
8807 "Intel 82801AA AC97 Audio",
8810 { .init_pci
= ac97_init
}
8816 "ENSONIQ AudioPCI ES1370",
8819 { .init_pci
= es1370_init
}
8823 { NULL
, NULL
, 0, 0, { NULL
} }
8826 static void select_soundhw (const char *optarg
)
8830 if (*optarg
== '?') {
8833 printf ("Valid sound card names (comma separated):\n");
8834 for (c
= soundhw
; c
->name
; ++c
) {
8835 printf ("%-11s %s\n", c
->name
, c
->descr
);
8837 printf ("\n-soundhw all will enable all of the above\n");
8838 exit (*optarg
!= '?');
8846 if (!strcmp (optarg
, "all")) {
8847 for (c
= soundhw
; c
->name
; ++c
) {
8855 e
= strchr (p
, ',');
8856 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8858 for (c
= soundhw
; c
->name
; ++c
) {
8859 if (!strncmp (c
->name
, p
, l
)) {
8868 "Unknown sound card name (too big to show)\n");
8871 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8876 p
+= l
+ (e
!= NULL
);
8880 goto show_valid_cards
;
8886 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8888 exit(STATUS_CONTROL_C_EXIT
);
8893 #define MAX_NET_CLIENTS 32
8895 static int saved_argc
;
8896 static char **saved_argv
;
8898 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8902 *opt_daemonize
= daemonize
;
8903 *opt_incoming
= incoming
;
8907 static int gethugepagesize(void)
8911 char *needle
= "Hugepagesize:";
8913 unsigned long hugepagesize
;
8915 fd
= open("/proc/meminfo", O_RDONLY
);
8921 ret
= read(fd
, buf
, sizeof(buf
));
8927 size
= strstr(buf
, needle
);
8930 size
+= strlen(needle
);
8931 hugepagesize
= strtol(size
, NULL
, 0);
8932 return hugepagesize
;
8935 void *alloc_mem_area(unsigned long memory
, const char *path
)
8941 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8944 hpagesize
= gethugepagesize() * 1024;
8948 fd
= mkstemp(filename
);
8957 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8960 * ftruncate is not supported by hugetlbfs in older
8961 * hosts, so don't bother checking for errors.
8962 * If anything goes wrong with it under other filesystems,
8965 ftruncate(fd
, memory
);
8967 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8968 if (area
== MAP_FAILED
) {
8977 void *qemu_alloc_physram(unsigned long memory
)
8982 area
= alloc_mem_area(memory
, mem_path
);
8984 area
= qemu_vmalloc(memory
);
8991 static void termsig_handler(int signal
)
8993 qemu_system_shutdown_request();
8996 void termsig_setup(void)
8998 struct sigaction act
;
9000 memset(&act
, 0, sizeof(act
));
9001 act
.sa_handler
= termsig_handler
;
9002 sigaction(SIGINT
, &act
, NULL
);
9003 sigaction(SIGHUP
, &act
, NULL
);
9004 sigaction(SIGTERM
, &act
, NULL
);
9009 int main(int argc
, char **argv
)
9011 #ifdef CONFIG_GDBSTUB
9013 const char *gdbstub_port
;
9015 uint32_t boot_devices_bitmap
= 0;
9017 int snapshot
, linux_boot
, net_boot
;
9018 const char *initrd_filename
;
9019 const char *kernel_filename
, *kernel_cmdline
;
9020 const char *boot_devices
= "";
9021 DisplayState
*ds
= &display_state
;
9022 int cyls
, heads
, secs
, translation
;
9023 const char *net_clients
[MAX_NET_CLIENTS
];
9027 const char *r
, *optarg
;
9028 CharDriverState
*monitor_hd
;
9029 const char *monitor_device
;
9030 const char *serial_devices
[MAX_SERIAL_PORTS
];
9031 int serial_device_index
;
9032 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
9033 int parallel_device_index
;
9034 const char *loadvm
= NULL
;
9035 QEMUMachine
*machine
;
9036 const char *cpu_model
;
9037 const char *usb_devices
[MAX_USB_CMDLINE
];
9038 int usb_devices_index
;
9041 const char *pid_file
= NULL
;
9047 LIST_INIT (&vm_change_state_head
);
9050 struct sigaction act
;
9051 sigfillset(&act
.sa_mask
);
9053 act
.sa_handler
= SIG_IGN
;
9054 sigaction(SIGPIPE
, &act
, NULL
);
9057 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
9058 /* Note: cpu_interrupt() is currently not SMP safe, so we force
9059 QEMU to run on a single CPU */
9064 h
= GetCurrentProcess();
9065 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
9066 for(i
= 0; i
< 32; i
++) {
9067 if (mask
& (1 << i
))
9072 SetProcessAffinityMask(h
, mask
);
9078 register_machines();
9079 machine
= first_machine
;
9081 initrd_filename
= NULL
;
9083 vga_ram_size
= VGA_RAM_SIZE
;
9084 #ifdef CONFIG_GDBSTUB
9086 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
9091 kernel_filename
= NULL
;
9092 kernel_cmdline
= "";
9093 cyls
= heads
= secs
= 0;
9094 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9095 monitor_device
= "vc";
9097 serial_devices
[0] = "vc:80Cx24C";
9098 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
9099 serial_devices
[i
] = NULL
;
9100 serial_device_index
= 0;
9102 parallel_devices
[0] = "vc:640x480";
9103 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
9104 parallel_devices
[i
] = NULL
;
9105 parallel_device_index
= 0;
9107 usb_devices_index
= 0;
9124 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
9126 const QEMUOption
*popt
;
9129 /* Treat --foo the same as -foo. */
9132 popt
= qemu_options
;
9135 fprintf(stderr
, "%s: invalid option -- '%s'\n",
9139 if (!strcmp(popt
->name
, r
+ 1))
9143 if (popt
->flags
& HAS_ARG
) {
9144 if (optind
>= argc
) {
9145 fprintf(stderr
, "%s: option '%s' requires an argument\n",
9149 optarg
= argv
[optind
++];
9154 switch(popt
->index
) {
9156 machine
= find_machine(optarg
);
9159 printf("Supported machines are:\n");
9160 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
9161 printf("%-10s %s%s\n",
9163 m
== first_machine
? " (default)" : "");
9165 exit(*optarg
!= '?');
9168 case QEMU_OPTION_cpu
:
9169 /* hw initialization will check this */
9170 if (*optarg
== '?') {
9171 /* XXX: implement xxx_cpu_list for targets that still miss it */
9172 #if defined(cpu_list)
9173 cpu_list(stdout
, &fprintf
);
9180 case QEMU_OPTION_initrd
:
9181 initrd_filename
= optarg
;
9183 case QEMU_OPTION_hda
:
9185 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
9187 hda_index
= drive_add(optarg
, HD_ALIAS
9188 ",cyls=%d,heads=%d,secs=%d%s",
9189 0, cyls
, heads
, secs
,
9190 translation
== BIOS_ATA_TRANSLATION_LBA
?
9192 translation
== BIOS_ATA_TRANSLATION_NONE
?
9193 ",trans=none" : "");
9195 case QEMU_OPTION_hdb
:
9196 case QEMU_OPTION_hdc
:
9197 case QEMU_OPTION_hdd
:
9198 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
9200 case QEMU_OPTION_drive
:
9201 drive_add(NULL
, "%s", optarg
);
9203 case QEMU_OPTION_mtdblock
:
9204 drive_add(optarg
, MTD_ALIAS
);
9206 case QEMU_OPTION_sd
:
9207 drive_add(optarg
, SD_ALIAS
);
9209 case QEMU_OPTION_pflash
:
9210 drive_add(optarg
, PFLASH_ALIAS
);
9212 case QEMU_OPTION_snapshot
:
9215 case QEMU_OPTION_hdachs
:
9219 cyls
= strtol(p
, (char **)&p
, 0);
9220 if (cyls
< 1 || cyls
> 16383)
9225 heads
= strtol(p
, (char **)&p
, 0);
9226 if (heads
< 1 || heads
> 16)
9231 secs
= strtol(p
, (char **)&p
, 0);
9232 if (secs
< 1 || secs
> 63)
9236 if (!strcmp(p
, "none"))
9237 translation
= BIOS_ATA_TRANSLATION_NONE
;
9238 else if (!strcmp(p
, "lba"))
9239 translation
= BIOS_ATA_TRANSLATION_LBA
;
9240 else if (!strcmp(p
, "auto"))
9241 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9244 } else if (*p
!= '\0') {
9246 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9249 if (hda_index
!= -1)
9250 snprintf(drives_opt
[hda_index
].opt
,
9251 sizeof(drives_opt
[hda_index
].opt
),
9252 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9253 0, cyls
, heads
, secs
,
9254 translation
== BIOS_ATA_TRANSLATION_LBA
?
9256 translation
== BIOS_ATA_TRANSLATION_NONE
?
9257 ",trans=none" : "");
9260 case QEMU_OPTION_nographic
:
9263 #ifdef CONFIG_CURSES
9264 case QEMU_OPTION_curses
:
9268 case QEMU_OPTION_portrait
:
9271 case QEMU_OPTION_kernel
:
9272 kernel_filename
= optarg
;
9274 case QEMU_OPTION_append
:
9275 kernel_cmdline
= optarg
;
9277 case QEMU_OPTION_cdrom
:
9278 drive_add(optarg
, CDROM_ALIAS
);
9280 case QEMU_OPTION_boot
:
9281 boot_devices
= optarg
;
9282 /* We just do some generic consistency checks */
9284 /* Could easily be extended to 64 devices if needed */
9287 boot_devices_bitmap
= 0;
9288 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9289 /* Allowed boot devices are:
9290 * a b : floppy disk drives
9291 * c ... f : IDE disk drives
9292 * g ... m : machine implementation dependant drives
9293 * n ... p : network devices
9294 * It's up to each machine implementation to check
9295 * if the given boot devices match the actual hardware
9296 * implementation and firmware features.
9298 if (*p
< 'a' || *p
> 'q') {
9299 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9302 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9304 "Boot device '%c' was given twice\n",*p
);
9307 boot_devices_bitmap
|= 1 << (*p
- 'a');
9311 case QEMU_OPTION_fda
:
9312 case QEMU_OPTION_fdb
:
9313 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9316 case QEMU_OPTION_no_fd_bootchk
:
9320 case QEMU_OPTION_net
:
9321 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9322 fprintf(stderr
, "qemu: too many network clients\n");
9325 net_clients
[nb_net_clients
] = optarg
;
9329 case QEMU_OPTION_tftp
:
9330 tftp_prefix
= optarg
;
9332 case QEMU_OPTION_bootp
:
9333 bootp_filename
= optarg
;
9336 case QEMU_OPTION_smb
:
9337 net_slirp_smb(optarg
);
9340 case QEMU_OPTION_redir
:
9341 net_slirp_redir(optarg
);
9345 case QEMU_OPTION_audio_help
:
9349 case QEMU_OPTION_soundhw
:
9350 select_soundhw (optarg
);
9356 case QEMU_OPTION_m
: {
9360 value
= strtoul(optarg
, &ptr
, 10);
9362 case 0: case 'M': case 'm':
9369 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9373 /* On 32-bit hosts, QEMU is limited by virtual address space */
9374 if (value
> (2047 << 20)
9376 && HOST_LONG_BITS
== 32
9379 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9382 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9383 fprintf(stderr
, "qemu: ram size too large\n");
9394 mask
= cpu_str_to_log_mask(optarg
);
9396 printf("Log items (comma separated):\n");
9397 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9398 printf("%-10s %s\n", item
->name
, item
->help
);
9405 #ifdef CONFIG_GDBSTUB
9410 gdbstub_port
= optarg
;
9416 case QEMU_OPTION_bios
:
9423 keyboard_layout
= optarg
;
9425 case QEMU_OPTION_localtime
:
9428 case QEMU_OPTION_cirrusvga
:
9429 cirrus_vga_enabled
= 1;
9432 case QEMU_OPTION_vmsvga
:
9433 cirrus_vga_enabled
= 0;
9436 case QEMU_OPTION_std_vga
:
9437 cirrus_vga_enabled
= 0;
9445 w
= strtol(p
, (char **)&p
, 10);
9448 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9454 h
= strtol(p
, (char **)&p
, 10);
9459 depth
= strtol(p
, (char **)&p
, 10);
9460 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9461 depth
!= 24 && depth
!= 32)
9463 } else if (*p
== '\0') {
9464 depth
= graphic_depth
;
9471 graphic_depth
= depth
;
9474 case QEMU_OPTION_echr
:
9477 term_escape_char
= strtol(optarg
, &r
, 0);
9479 printf("Bad argument to echr\n");
9482 case QEMU_OPTION_monitor
:
9483 monitor_device
= optarg
;
9485 case QEMU_OPTION_serial
:
9486 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9487 fprintf(stderr
, "qemu: too many serial ports\n");
9490 serial_devices
[serial_device_index
] = optarg
;
9491 serial_device_index
++;
9493 case QEMU_OPTION_parallel
:
9494 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9495 fprintf(stderr
, "qemu: too many parallel ports\n");
9498 parallel_devices
[parallel_device_index
] = optarg
;
9499 parallel_device_index
++;
9501 case QEMU_OPTION_loadvm
:
9504 case QEMU_OPTION_incoming
:
9507 case QEMU_OPTION_full_screen
:
9511 case QEMU_OPTION_no_frame
:
9514 case QEMU_OPTION_alt_grab
:
9517 case QEMU_OPTION_no_quit
:
9521 case QEMU_OPTION_pidfile
:
9525 case QEMU_OPTION_win2k_hack
:
9526 win2k_install_hack
= 1;
9530 case QEMU_OPTION_no_kqemu
:
9533 case QEMU_OPTION_kernel_kqemu
:
9538 case QEMU_OPTION_no_kvm
:
9541 case QEMU_OPTION_no_kvm_irqchip
: {
9542 extern int kvm_irqchip
, kvm_pit
;
9547 case QEMU_OPTION_no_kvm_pit
: {
9553 case QEMU_OPTION_usb
:
9556 case QEMU_OPTION_usbdevice
:
9558 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9559 fprintf(stderr
, "Too many USB devices\n");
9562 usb_devices
[usb_devices_index
] = optarg
;
9563 usb_devices_index
++;
9565 case QEMU_OPTION_smp
:
9566 smp_cpus
= atoi(optarg
);
9567 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9568 fprintf(stderr
, "Invalid number of CPUs\n");
9572 case QEMU_OPTION_vnc
:
9573 vnc_display
= optarg
;
9575 case QEMU_OPTION_no_acpi
:
9578 case QEMU_OPTION_no_reboot
:
9581 case QEMU_OPTION_no_shutdown
:
9584 case QEMU_OPTION_show_cursor
:
9587 case QEMU_OPTION_daemonize
:
9590 case QEMU_OPTION_option_rom
:
9591 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9592 fprintf(stderr
, "Too many option ROMs\n");
9595 option_rom
[nb_option_roms
] = optarg
;
9598 case QEMU_OPTION_semihosting
:
9599 semihosting_enabled
= 1;
9601 case QEMU_OPTION_tdf
:
9604 case QEMU_OPTION_kvm_shadow_memory
:
9605 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9607 case QEMU_OPTION_mempath
:
9610 case QEMU_OPTION_name
:
9614 case QEMU_OPTION_prom_env
:
9615 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9616 fprintf(stderr
, "Too many prom variables\n");
9619 prom_envs
[nb_prom_envs
] = optarg
;
9623 case QEMU_OPTION_cpu_vendor
:
9624 cpu_vendor_string
= optarg
;
9627 case QEMU_OPTION_old_param
:
9631 case QEMU_OPTION_clock
:
9632 configure_alarms(optarg
);
9634 case QEMU_OPTION_startdate
:
9637 time_t rtc_start_date
;
9638 if (!strcmp(optarg
, "now")) {
9639 rtc_date_offset
= -1;
9641 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9649 } else if (sscanf(optarg
, "%d-%d-%d",
9652 &tm
.tm_mday
) == 3) {
9661 rtc_start_date
= mktimegm(&tm
);
9662 if (rtc_start_date
== -1) {
9664 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9665 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9668 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9672 case QEMU_OPTION_tb_size
:
9673 tb_size
= strtol(optarg
, NULL
, 0);
9677 case QEMU_OPTION_icount
:
9679 if (strcmp(optarg
, "auto") == 0) {
9680 icount_time_shift
= -1;
9682 icount_time_shift
= strtol(optarg
, NULL
, 0);
9690 if (serial_device_index
== 0)
9691 serial_devices
[0] = "stdio";
9692 if (parallel_device_index
== 0)
9693 parallel_devices
[0] = "null";
9694 if (strncmp(monitor_device
, "vc", 2) == 0)
9695 monitor_device
= "stdio";
9702 if (pipe(fds
) == -1)
9713 len
= read(fds
[0], &status
, 1);
9714 if (len
== -1 && (errno
== EINTR
))
9719 else if (status
== 1) {
9720 fprintf(stderr
, "Could not acquire pidfile\n");
9737 signal(SIGTSTP
, SIG_IGN
);
9738 signal(SIGTTOU
, SIG_IGN
);
9739 signal(SIGTTIN
, SIG_IGN
);
9744 if (kvm_enabled()) {
9745 if (kvm_qemu_init() < 0) {
9746 extern int kvm_allowed
;
9747 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9748 #ifdef NO_CPU_EMULATION
9749 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9757 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9760 write(fds
[1], &status
, 1);
9762 fprintf(stderr
, "Could not acquire pid file\n");
9770 linux_boot
= (kernel_filename
!= NULL
);
9771 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9773 if (!linux_boot
&& net_boot
== 0 &&
9774 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
9777 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9778 fprintf(stderr
, "-append only allowed with -kernel option\n");
9782 if (!linux_boot
&& initrd_filename
!= NULL
) {
9783 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9787 /* boot to floppy or the default cd if no hard disk defined yet */
9788 if (!boot_devices
[0]) {
9789 boot_devices
= "cad";
9791 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9796 if (use_icount
&& icount_time_shift
< 0) {
9798 /* 125MIPS seems a reasonable initial guess at the guest speed.
9799 It will be corrected fairly quickly anyway. */
9800 icount_time_shift
= 3;
9801 init_icount_adjust();
9808 /* init network clients */
9809 if (nb_net_clients
== 0) {
9810 /* if no clients, we use a default config */
9811 net_clients
[0] = "nic";
9812 net_clients
[1] = "user";
9816 for(i
= 0;i
< nb_net_clients
; i
++) {
9817 if (net_client_parse(net_clients
[i
]) < 0)
9820 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9821 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9823 if (vlan
->nb_guest_devs
== 0)
9824 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9825 if (vlan
->nb_host_devs
== 0)
9827 "Warning: vlan %d is not connected to host network\n",
9832 /* XXX: this should be moved in the PC machine instantiation code */
9833 if (net_boot
!= 0) {
9835 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9836 const char *model
= nd_table
[i
].model
;
9838 if (net_boot
& (1 << i
)) {
9841 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9842 if (get_image_size(buf
) > 0) {
9843 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9844 fprintf(stderr
, "Too many option ROMs\n");
9847 option_rom
[nb_option_roms
] = strdup(buf
);
9854 fprintf(stderr
, "No valid PXE rom found for network device\n");
9860 /* init the memory */
9861 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9863 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9865 if (ram_size
< phys_ram_size
) {
9866 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9867 machine
->name
, (unsigned long long) phys_ram_size
);
9871 phys_ram_size
= ram_size
;
9873 ram_size
= phys_ram_size
;
9876 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9878 phys_ram_size
+= ram_size
;
9881 /* Initialize kvm */
9882 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9883 #define KVM_EXTRA_PAGES 3
9885 #define KVM_EXTRA_PAGES 0
9887 if (kvm_enabled()) {
9888 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9889 if (kvm_qemu_create_context() < 0) {
9890 fprintf(stderr
, "Could not create KVM context\n");
9893 #ifdef KVM_CAP_USER_MEMORY
9897 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9899 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9900 if (!phys_ram_base
) {
9901 fprintf(stderr
, "Could not allocate physical memory\n");
9908 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9909 if (!phys_ram_base
) {
9910 fprintf(stderr
, "Could not allocate physical memory\n");
9915 /* init the dynamic translator */
9916 cpu_exec_init_all(tb_size
* 1024 * 1024);
9920 /* we always create the cdrom drive, even if no disk is there */
9922 if (nb_drives_opt
< MAX_DRIVES
)
9923 drive_add(NULL
, CDROM_ALIAS
);
9925 /* we always create at least one floppy */
9927 if (nb_drives_opt
< MAX_DRIVES
)
9928 drive_add(NULL
, FD_ALIAS
, 0);
9930 /* we always create one sd slot, even if no card is in it */
9932 if (nb_drives_opt
< MAX_DRIVES
)
9933 drive_add(NULL
, SD_ALIAS
);
9935 /* open the virtual block devices
9936 * note that migration with device
9937 * hot add/remove is broken.
9939 for(i
= 0; i
< nb_drives_opt
; i
++)
9940 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9943 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9944 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9947 memset(&display_state
, 0, sizeof(display_state
));
9950 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9953 /* nearly nothing to do */
9954 dumb_display_init(ds
);
9955 } else if (vnc_display
!= NULL
) {
9956 vnc_display_init(ds
);
9957 if (vnc_display_open(ds
, vnc_display
) < 0)
9960 #if defined(CONFIG_CURSES)
9962 curses_display_init(ds
, full_screen
);
9966 #if defined(CONFIG_SDL)
9967 sdl_display_init(ds
, full_screen
, no_frame
);
9968 #elif defined(CONFIG_COCOA)
9969 cocoa_display_init(ds
, full_screen
);
9971 dumb_display_init(ds
);
9976 /* must be after terminal init, SDL library changes signal handlers */
9980 /* Maintain compatibility with multiple stdio monitors */
9981 if (!strcmp(monitor_device
,"stdio")) {
9982 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9983 const char *devname
= serial_devices
[i
];
9984 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9985 monitor_device
= NULL
;
9987 } else if (devname
&& !strcmp(devname
,"stdio")) {
9988 monitor_device
= NULL
;
9989 serial_devices
[i
] = "mon:stdio";
9994 if (monitor_device
) {
9995 monitor_hd
= qemu_chr_open(monitor_device
);
9997 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
10000 monitor_init(monitor_hd
, !nographic
);
10003 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
10004 const char *devname
= serial_devices
[i
];
10005 if (devname
&& strcmp(devname
, "none")) {
10006 serial_hds
[i
] = qemu_chr_open(devname
);
10007 if (!serial_hds
[i
]) {
10008 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
10012 if (strstart(devname
, "vc", 0))
10013 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
10017 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
10018 const char *devname
= parallel_devices
[i
];
10019 if (devname
&& strcmp(devname
, "none")) {
10020 parallel_hds
[i
] = qemu_chr_open(devname
);
10021 if (!parallel_hds
[i
]) {
10022 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
10026 if (strstart(devname
, "vc", 0))
10027 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
10034 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
10035 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
10037 current_machine
= machine
;
10039 /* init USB devices */
10041 for(i
= 0; i
< usb_devices_index
; i
++) {
10042 if (usb_device_add(usb_devices
[i
]) < 0) {
10043 fprintf(stderr
, "Warning: could not add USB device %s\n",
10049 if (display_state
.dpy_refresh
) {
10050 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
10051 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
10054 #ifdef CONFIG_GDBSTUB
10056 /* XXX: use standard host:port notation and modify options
10058 if (gdbserver_start(gdbstub_port
) < 0) {
10059 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
10072 rc
= migrate_incoming(incoming
);
10074 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
10080 /* XXX: simplify init */
10088 uint8_t status
= 0;
10093 len
= write(fds
[1], &status
, 1);
10094 if (len
== -1 && (errno
== EINTR
))
10101 TFR(fd
= open("/dev/null", O_RDWR
));
10115 #if !defined(_WIN32)
10116 /* close network clients */
10117 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
10118 VLANClientState
*vc
;
10120 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
10121 if (vc
->fd_read
== tap_receive
) {
10123 TAPState
*s
= vc
->opaque
;
10125 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
10127 launch_script(s
->down_script
, ifname
, s
->fd
);
10129 #if defined(CONFIG_VDE)
10130 if (vc
->fd_read
== vde_from_qemu
) {
10131 VDEState
*s
= vc
->opaque
;