4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
40 #include "migration.h"
52 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
74 #include <linux/if_tun.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
103 #include <winsock2.h>
104 int inet_aton(const char *cp
, struct in_addr
*ia
);
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
111 #if defined(CONFIG_VDE)
112 #include <libvdeplug.h>
117 #include <sys/timeb.h>
118 #include <mmsystem.h>
119 #define getopt_long_only getopt_long
120 #define memalign(align, size) malloc(size)
123 #include "qemu_socket.h"
129 #endif /* CONFIG_SDL */
133 #define main qemu_main
134 #endif /* CONFIG_COCOA */
138 #include "exec-all.h"
140 #include "qemu-kvm.h"
142 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
145 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
147 #define SMBD_COMMAND "/usr/sbin/smbd"
150 //#define DEBUG_UNUSED_IOPORT
151 //#define DEBUG_IOPORT
154 #define DEFAULT_RAM_SIZE 144
156 #define DEFAULT_RAM_SIZE 128
159 #define GUI_REFRESH_INTERVAL 30
161 /* Max number of USB devices that can be specified on the commandline. */
162 #define MAX_USB_CMDLINE 8
164 /* XXX: use a two level table to limit memory usage */
165 #define MAX_IOPORTS 65536
167 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
168 const char *bios_name
= NULL
;
169 void *ioport_opaque
[MAX_IOPORTS
];
170 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
171 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
172 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
173 to store the VM snapshots */
174 DriveInfo drives_table
[MAX_DRIVES
+1];
176 int extboot_drive
= -1;
177 /* point to the block driver where the snapshots are managed */
178 BlockDriverState
*bs_snapshots
;
180 static DisplayState display_state
;
183 const char* keyboard_layout
= NULL
;
184 int64_t ticks_per_sec
;
186 int pit_min_timer_count
= 0;
188 NICInfo nd_table
[MAX_NICS
];
190 static int rtc_utc
= 1;
191 static int rtc_date_offset
= -1; /* -1 means no change */
192 int cirrus_vga_enabled
= 1;
193 int vmsvga_enabled
= 0;
195 int graphic_width
= 1024;
196 int graphic_height
= 768;
197 int graphic_depth
= 8;
199 int graphic_width
= 800;
200 int graphic_height
= 600;
201 int graphic_depth
= 15;
206 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
207 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
209 int win2k_install_hack
= 0;
212 static VLANState
*first_vlan
;
214 const char *vnc_display
;
215 #if defined(TARGET_SPARC)
217 #elif defined(TARGET_I386)
219 #elif defined(TARGET_IA64)
224 int acpi_enabled
= 1;
229 int graphic_rotate
= 0;
231 const char *incoming
;
232 const char *option_rom
[MAX_OPTION_ROMS
];
234 int semihosting_enabled
= 0;
236 int time_drift_fix
= 0;
237 unsigned int kvm_shadow_memory
= 0;
238 const char *mem_path
= NULL
;
240 const char *cpu_vendor_string
;
244 const char *qemu_name
;
247 unsigned int nb_prom_envs
= 0;
248 const char *prom_envs
[MAX_PROM_ENVS
];
251 struct drive_opt drives_opt
[MAX_DRIVES
];
253 static CPUState
*cur_cpu
;
254 static CPUState
*next_cpu
;
255 static int event_pending
= 1;
256 /* Conversion factor from emulated instructions to virtual clock ticks. */
257 static int icount_time_shift
;
258 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
259 #define MAX_ICOUNT_SHIFT 10
260 /* Compensate for varying guest execution speed. */
261 static int64_t qemu_icount_bias
;
262 QEMUTimer
*icount_rt_timer
;
263 QEMUTimer
*icount_vm_timer
;
265 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
267 /* KVM runs the main loop in a separate thread. If we update one of the lists
268 * that are polled before or after select(), we need to make sure to break out
269 * of the select() to ensure the new item is serviced.
271 static void main_loop_break(void)
274 qemu_kvm_notify_work();
277 /***********************************************************/
278 /* x86 ISA bus support */
280 target_phys_addr_t isa_mem_base
= 0;
283 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
284 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
286 static uint32_t ioport_read(int index
, uint32_t address
)
288 static IOPortReadFunc
*default_func
[3] = {
289 default_ioport_readb
,
290 default_ioport_readw
,
293 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
295 func
= default_func
[index
];
296 return func(ioport_opaque
[address
], address
);
299 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
301 static IOPortWriteFunc
*default_func
[3] = {
302 default_ioport_writeb
,
303 default_ioport_writew
,
304 default_ioport_writel
306 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
308 func
= default_func
[index
];
309 func(ioport_opaque
[address
], address
, data
);
312 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
314 #ifdef DEBUG_UNUSED_IOPORT
315 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
320 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
322 #ifdef DEBUG_UNUSED_IOPORT
323 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
327 /* default is to make two byte accesses */
328 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
331 data
= ioport_read(0, address
);
332 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
333 data
|= ioport_read(0, address
) << 8;
337 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
339 ioport_write(0, address
, data
& 0xff);
340 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
341 ioport_write(0, address
, (data
>> 8) & 0xff);
344 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
346 #ifdef DEBUG_UNUSED_IOPORT
347 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
352 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
354 #ifdef DEBUG_UNUSED_IOPORT
355 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
359 /* size is the word size in byte */
360 int register_ioport_read(int start
, int length
, int size
,
361 IOPortReadFunc
*func
, void *opaque
)
367 } else if (size
== 2) {
369 } else if (size
== 4) {
372 hw_error("register_ioport_read: invalid size");
375 for(i
= start
; i
< start
+ length
; i
+= size
) {
376 ioport_read_table
[bsize
][i
] = func
;
377 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
378 hw_error("register_ioport_read: invalid opaque");
379 ioport_opaque
[i
] = opaque
;
384 /* size is the word size in byte */
385 int register_ioport_write(int start
, int length
, int size
,
386 IOPortWriteFunc
*func
, void *opaque
)
392 } else if (size
== 2) {
394 } else if (size
== 4) {
397 hw_error("register_ioport_write: invalid size");
400 for(i
= start
; i
< start
+ length
; i
+= size
) {
401 ioport_write_table
[bsize
][i
] = func
;
402 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
403 hw_error("register_ioport_write: invalid opaque");
404 ioport_opaque
[i
] = opaque
;
409 void isa_unassign_ioport(int start
, int length
)
413 for(i
= start
; i
< start
+ length
; i
++) {
414 ioport_read_table
[0][i
] = default_ioport_readb
;
415 ioport_read_table
[1][i
] = default_ioport_readw
;
416 ioport_read_table
[2][i
] = default_ioport_readl
;
418 ioport_write_table
[0][i
] = default_ioport_writeb
;
419 ioport_write_table
[1][i
] = default_ioport_writew
;
420 ioport_write_table
[2][i
] = default_ioport_writel
;
422 ioport_opaque
[i
] = NULL
;
426 /***********************************************************/
428 void cpu_outb(CPUState
*env
, int addr
, int val
)
431 if (loglevel
& CPU_LOG_IOPORT
)
432 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
434 ioport_write(0, addr
, val
);
437 env
->last_io_time
= cpu_get_time_fast();
441 void cpu_outw(CPUState
*env
, int addr
, int val
)
444 if (loglevel
& CPU_LOG_IOPORT
)
445 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
447 ioport_write(1, addr
, val
);
450 env
->last_io_time
= cpu_get_time_fast();
454 void cpu_outl(CPUState
*env
, int addr
, int val
)
457 if (loglevel
& CPU_LOG_IOPORT
)
458 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
460 ioport_write(2, addr
, val
);
463 env
->last_io_time
= cpu_get_time_fast();
467 int cpu_inb(CPUState
*env
, int addr
)
470 val
= ioport_read(0, addr
);
472 if (loglevel
& CPU_LOG_IOPORT
)
473 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
477 env
->last_io_time
= cpu_get_time_fast();
482 int cpu_inw(CPUState
*env
, int addr
)
485 val
= ioport_read(1, addr
);
487 if (loglevel
& CPU_LOG_IOPORT
)
488 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
492 env
->last_io_time
= cpu_get_time_fast();
497 int cpu_inl(CPUState
*env
, int addr
)
500 val
= ioport_read(2, addr
);
502 if (loglevel
& CPU_LOG_IOPORT
)
503 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
507 env
->last_io_time
= cpu_get_time_fast();
512 /***********************************************************/
513 void hw_error(const char *fmt
, ...)
519 fprintf(stderr
, "qemu: hardware error: ");
520 vfprintf(stderr
, fmt
, ap
);
521 fprintf(stderr
, "\n");
522 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
523 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
525 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
527 cpu_dump_state(env
, stderr
, fprintf
, 0);
534 /***********************************************************/
537 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
538 static void *qemu_put_kbd_event_opaque
;
539 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
540 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
542 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
544 qemu_put_kbd_event_opaque
= opaque
;
545 qemu_put_kbd_event
= func
;
548 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
549 void *opaque
, int absolute
,
552 QEMUPutMouseEntry
*s
, *cursor
;
554 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
558 s
->qemu_put_mouse_event
= func
;
559 s
->qemu_put_mouse_event_opaque
= opaque
;
560 s
->qemu_put_mouse_event_absolute
= absolute
;
561 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
564 if (!qemu_put_mouse_event_head
) {
565 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
569 cursor
= qemu_put_mouse_event_head
;
570 while (cursor
->next
!= NULL
)
571 cursor
= cursor
->next
;
574 qemu_put_mouse_event_current
= s
;
579 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
581 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
583 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
586 cursor
= qemu_put_mouse_event_head
;
587 while (cursor
!= NULL
&& cursor
!= entry
) {
589 cursor
= cursor
->next
;
592 if (cursor
== NULL
) // does not exist or list empty
594 else if (prev
== NULL
) { // entry is head
595 qemu_put_mouse_event_head
= cursor
->next
;
596 if (qemu_put_mouse_event_current
== entry
)
597 qemu_put_mouse_event_current
= cursor
->next
;
598 qemu_free(entry
->qemu_put_mouse_event_name
);
603 prev
->next
= entry
->next
;
605 if (qemu_put_mouse_event_current
== entry
)
606 qemu_put_mouse_event_current
= prev
;
608 qemu_free(entry
->qemu_put_mouse_event_name
);
612 void kbd_put_keycode(int keycode
)
614 if (qemu_put_kbd_event
) {
615 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
619 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
621 QEMUPutMouseEvent
*mouse_event
;
622 void *mouse_event_opaque
;
625 if (!qemu_put_mouse_event_current
) {
630 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
632 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
635 if (graphic_rotate
) {
636 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
639 width
= graphic_width
- 1;
640 mouse_event(mouse_event_opaque
,
641 width
- dy
, dx
, dz
, buttons_state
);
643 mouse_event(mouse_event_opaque
,
644 dx
, dy
, dz
, buttons_state
);
648 int kbd_mouse_is_absolute(void)
650 if (!qemu_put_mouse_event_current
)
653 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
656 void do_info_mice(void)
658 QEMUPutMouseEntry
*cursor
;
661 if (!qemu_put_mouse_event_head
) {
662 term_printf("No mouse devices connected\n");
666 term_printf("Mouse devices available:\n");
667 cursor
= qemu_put_mouse_event_head
;
668 while (cursor
!= NULL
) {
669 term_printf("%c Mouse #%d: %s\n",
670 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
671 index
, cursor
->qemu_put_mouse_event_name
);
673 cursor
= cursor
->next
;
677 void do_mouse_set(int index
)
679 QEMUPutMouseEntry
*cursor
;
682 if (!qemu_put_mouse_event_head
) {
683 term_printf("No mouse devices connected\n");
687 cursor
= qemu_put_mouse_event_head
;
688 while (cursor
!= NULL
&& index
!= i
) {
690 cursor
= cursor
->next
;
694 qemu_put_mouse_event_current
= cursor
;
696 term_printf("Mouse at given index not found\n");
699 /* compute with 96 bit intermediate result: (a*b)/c */
700 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
705 #ifdef WORDS_BIGENDIAN
715 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
716 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
719 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
723 /***********************************************************/
724 /* real time host monotonic timer */
726 #define QEMU_TIMER_BASE 1000000000LL
730 static int64_t clock_freq
;
732 static void init_get_clock(void)
736 ret
= QueryPerformanceFrequency(&freq
);
738 fprintf(stderr
, "Could not calibrate ticks\n");
741 clock_freq
= freq
.QuadPart
;
744 static int64_t get_clock(void)
747 QueryPerformanceCounter(&ti
);
748 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
753 static int use_rt_clock
;
755 static void init_get_clock(void)
758 #if defined(__linux__)
761 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
768 static int64_t get_clock(void)
770 #if defined(__linux__)
773 clock_gettime(CLOCK_MONOTONIC
, &ts
);
774 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
778 /* XXX: using gettimeofday leads to problems if the date
779 changes, so it should be avoided. */
781 gettimeofday(&tv
, NULL
);
782 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
787 /* Return the virtual CPU time, based on the instruction counter. */
788 static int64_t cpu_get_icount(void)
791 CPUState
*env
= cpu_single_env
;;
792 icount
= qemu_icount
;
795 fprintf(stderr
, "Bad clock read\n");
796 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
798 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
801 /***********************************************************/
802 /* guest cycle counter */
804 static int64_t cpu_ticks_prev
;
805 static int64_t cpu_ticks_offset
;
806 static int64_t cpu_clock_offset
;
807 static int cpu_ticks_enabled
;
809 /* return the host CPU cycle counter and handle stop/restart */
810 int64_t cpu_get_ticks(void)
813 return cpu_get_icount();
815 if (!cpu_ticks_enabled
) {
816 return cpu_ticks_offset
;
819 ticks
= cpu_get_real_ticks();
820 if (cpu_ticks_prev
> ticks
) {
821 /* Note: non increasing ticks may happen if the host uses
823 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
825 cpu_ticks_prev
= ticks
;
826 return ticks
+ cpu_ticks_offset
;
830 /* return the host CPU monotonic timer and handle stop/restart */
831 static int64_t cpu_get_clock(void)
834 if (!cpu_ticks_enabled
) {
835 return cpu_clock_offset
;
838 return ti
+ cpu_clock_offset
;
842 /* enable cpu_get_ticks() */
843 void cpu_enable_ticks(void)
845 if (!cpu_ticks_enabled
) {
846 cpu_ticks_offset
-= cpu_get_real_ticks();
847 cpu_clock_offset
-= get_clock();
848 cpu_ticks_enabled
= 1;
852 /* disable cpu_get_ticks() : the clock is stopped. You must not call
853 cpu_get_ticks() after that. */
854 void cpu_disable_ticks(void)
856 if (cpu_ticks_enabled
) {
857 cpu_ticks_offset
= cpu_get_ticks();
858 cpu_clock_offset
= cpu_get_clock();
859 cpu_ticks_enabled
= 0;
863 /***********************************************************/
866 #define QEMU_TIMER_REALTIME 0
867 #define QEMU_TIMER_VIRTUAL 1
871 /* XXX: add frequency */
879 struct QEMUTimer
*next
;
882 struct qemu_alarm_timer
{
886 int (*start
)(struct qemu_alarm_timer
*t
);
887 void (*stop
)(struct qemu_alarm_timer
*t
);
888 void (*rearm
)(struct qemu_alarm_timer
*t
);
892 #define ALARM_FLAG_DYNTICKS 0x1
893 #define ALARM_FLAG_EXPIRED 0x2
895 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
897 return t
->flags
& ALARM_FLAG_DYNTICKS
;
900 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
902 if (!alarm_has_dynticks(t
))
908 /* TODO: MIN_TIMER_REARM_US should be optimized */
909 #define MIN_TIMER_REARM_US 250
911 static struct qemu_alarm_timer
*alarm_timer
;
915 struct qemu_alarm_win32
{
919 } alarm_win32_data
= {0, NULL
, -1};
921 static int win32_start_timer(struct qemu_alarm_timer
*t
);
922 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
923 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
927 static int unix_start_timer(struct qemu_alarm_timer
*t
);
928 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
932 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
933 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
934 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
936 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
937 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
939 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
940 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
942 #endif /* __linux__ */
946 /* Correlation between real and virtual time is always going to be
947 fairly approximate, so ignore small variation.
948 When the guest is idle real and virtual time will be aligned in
950 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
952 static void icount_adjust(void)
957 static int64_t last_delta
;
958 /* If the VM is not running, then do nothing. */
962 cur_time
= cpu_get_clock();
963 cur_icount
= qemu_get_clock(vm_clock
);
964 delta
= cur_icount
- cur_time
;
965 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
967 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
968 && icount_time_shift
> 0) {
969 /* The guest is getting too far ahead. Slow time down. */
973 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
974 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
975 /* The guest is getting too far behind. Speed time up. */
979 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
982 static void icount_adjust_rt(void * opaque
)
984 qemu_mod_timer(icount_rt_timer
,
985 qemu_get_clock(rt_clock
) + 1000);
989 static void icount_adjust_vm(void * opaque
)
991 qemu_mod_timer(icount_vm_timer
,
992 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
996 static void init_icount_adjust(void)
998 /* Have both realtime and virtual time triggers for speed adjustment.
999 The realtime trigger catches emulated time passing too slowly,
1000 the virtual time trigger catches emulated time passing too fast.
1001 Realtime triggers occur even when idle, so use them less frequently
1002 than VM triggers. */
1003 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
1004 qemu_mod_timer(icount_rt_timer
,
1005 qemu_get_clock(rt_clock
) + 1000);
1006 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
1007 qemu_mod_timer(icount_vm_timer
,
1008 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
1011 static struct qemu_alarm_timer alarm_timers
[] = {
1014 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
1015 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
1016 /* HPET - if available - is preferred */
1017 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1018 /* ...otherwise try RTC */
1019 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1021 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1023 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1024 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1025 {"win32", 0, win32_start_timer
,
1026 win32_stop_timer
, NULL
, &alarm_win32_data
},
1031 static void show_available_alarms(void)
1035 printf("Available alarm timers, in order of precedence:\n");
1036 for (i
= 0; alarm_timers
[i
].name
; i
++)
1037 printf("%s\n", alarm_timers
[i
].name
);
1040 static void configure_alarms(char const *opt
)
1044 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1047 struct qemu_alarm_timer tmp
;
1049 if (!strcmp(opt
, "?")) {
1050 show_available_alarms();
1056 /* Reorder the array */
1057 name
= strtok(arg
, ",");
1059 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1060 if (!strcmp(alarm_timers
[i
].name
, name
))
1065 fprintf(stderr
, "Unknown clock %s\n", name
);
1074 tmp
= alarm_timers
[i
];
1075 alarm_timers
[i
] = alarm_timers
[cur
];
1076 alarm_timers
[cur
] = tmp
;
1080 name
= strtok(NULL
, ",");
1086 /* Disable remaining timers */
1087 for (i
= cur
; i
< count
; i
++)
1088 alarm_timers
[i
].name
= NULL
;
1090 show_available_alarms();
1095 QEMUClock
*rt_clock
;
1096 QEMUClock
*vm_clock
;
1098 static QEMUTimer
*active_timers
[2];
1100 static QEMUClock
*qemu_new_clock(int type
)
1103 clock
= qemu_mallocz(sizeof(QEMUClock
));
1110 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1114 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1117 ts
->opaque
= opaque
;
1121 void qemu_free_timer(QEMUTimer
*ts
)
1126 /* stop a timer, but do not dealloc it */
1127 void qemu_del_timer(QEMUTimer
*ts
)
1131 /* NOTE: this code must be signal safe because
1132 qemu_timer_expired() can be called from a signal. */
1133 pt
= &active_timers
[ts
->clock
->type
];
1146 /* modify the current timer so that it will be fired when current_time
1147 >= expire_time. The corresponding callback will be called. */
1148 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1154 /* add the timer in the sorted list */
1155 /* NOTE: this code must be signal safe because
1156 qemu_timer_expired() can be called from a signal. */
1157 pt
= &active_timers
[ts
->clock
->type
];
1162 if (t
->expire_time
> expire_time
)
1166 ts
->expire_time
= expire_time
;
1170 /* Rearm if necessary */
1171 if (pt
== &active_timers
[ts
->clock
->type
]) {
1172 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1173 qemu_rearm_alarm_timer(alarm_timer
);
1175 /* Interrupt execution to force deadline recalculation. */
1176 if (use_icount
&& cpu_single_env
) {
1177 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1182 int qemu_timer_pending(QEMUTimer
*ts
)
1185 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1192 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1196 return (timer_head
->expire_time
<= current_time
);
1199 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1205 if (!ts
|| ts
->expire_time
> current_time
)
1207 /* remove timer from the list before calling the callback */
1208 *ptimer_head
= ts
->next
;
1211 /* run the callback (the timer list can be modified) */
1216 int64_t qemu_get_clock(QEMUClock
*clock
)
1218 switch(clock
->type
) {
1219 case QEMU_TIMER_REALTIME
:
1220 return get_clock() / 1000000;
1222 case QEMU_TIMER_VIRTUAL
:
1224 return cpu_get_icount();
1226 return cpu_get_clock();
1231 static void init_timers(void)
1234 ticks_per_sec
= QEMU_TIMER_BASE
;
1235 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1236 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1240 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1242 uint64_t expire_time
;
1244 if (qemu_timer_pending(ts
)) {
1245 expire_time
= ts
->expire_time
;
1249 qemu_put_be64(f
, expire_time
);
1252 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1254 uint64_t expire_time
;
1256 expire_time
= qemu_get_be64(f
);
1257 if (expire_time
!= -1) {
1258 qemu_mod_timer(ts
, expire_time
);
1264 static void timer_save(QEMUFile
*f
, void *opaque
)
1266 if (cpu_ticks_enabled
) {
1267 hw_error("cannot save state if virtual timers are running");
1269 qemu_put_be64(f
, cpu_ticks_offset
);
1270 qemu_put_be64(f
, ticks_per_sec
);
1271 qemu_put_be64(f
, cpu_clock_offset
);
1274 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1276 if (version_id
!= 1 && version_id
!= 2)
1278 if (cpu_ticks_enabled
) {
1281 cpu_ticks_offset
=qemu_get_be64(f
);
1282 ticks_per_sec
=qemu_get_be64(f
);
1283 if (version_id
== 2) {
1284 cpu_clock_offset
=qemu_get_be64(f
);
1290 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1291 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1293 static void host_alarm_handler(int host_signum
)
1297 #define DISP_FREQ 1000
1299 static int64_t delta_min
= INT64_MAX
;
1300 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1302 ti
= qemu_get_clock(vm_clock
);
1303 if (last_clock
!= 0) {
1304 delta
= ti
- last_clock
;
1305 if (delta
< delta_min
)
1307 if (delta
> delta_max
)
1310 if (++count
== DISP_FREQ
) {
1311 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1312 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1313 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1314 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1315 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1317 delta_min
= INT64_MAX
;
1326 alarm_has_dynticks(alarm_timer
) ||
1328 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1329 qemu_get_clock(vm_clock
))) ||
1330 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1331 qemu_get_clock(rt_clock
))) {
1333 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1334 SetEvent(data
->host_alarm
);
1336 CPUState
*env
= next_cpu
;
1338 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1341 /* stop the currently executing cpu because a timer occured */
1342 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1344 if (env
->kqemu_enabled
) {
1345 kqemu_cpu_interrupt(env
);
1353 static int64_t qemu_next_deadline(void)
1357 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1358 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1359 qemu_get_clock(vm_clock
);
1361 /* To avoid problems with overflow limit this to 2^32. */
1371 static uint64_t qemu_next_deadline_dyntick(void)
1379 delta
= (qemu_next_deadline() + 999) / 1000;
1381 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1382 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1383 qemu_get_clock(rt_clock
))*1000;
1384 if (rtdelta
< delta
)
1388 if (delta
< MIN_TIMER_REARM_US
)
1389 delta
= MIN_TIMER_REARM_US
;
1396 #if defined(__linux__)
1398 #define RTC_FREQ 1024
1400 static void enable_sigio_timer(int fd
)
1402 struct sigaction act
;
1405 sigfillset(&act
.sa_mask
);
1407 act
.sa_handler
= host_alarm_handler
;
1409 sigaction(SIGIO
, &act
, NULL
);
1410 fcntl(fd
, F_SETFL
, O_ASYNC
);
1411 fcntl(fd
, F_SETOWN
, getpid());
1414 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1416 struct hpet_info info
;
1419 fd
= open("/dev/hpet", O_RDONLY
);
1424 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1426 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1427 "error, but for better emulation accuracy type:\n"
1428 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1432 /* Check capabilities */
1433 r
= ioctl(fd
, HPET_INFO
, &info
);
1437 /* Enable periodic mode */
1438 r
= ioctl(fd
, HPET_EPI
, 0);
1439 if (info
.hi_flags
&& (r
< 0))
1442 /* Enable interrupt */
1443 r
= ioctl(fd
, HPET_IE_ON
, 0);
1447 enable_sigio_timer(fd
);
1448 t
->priv
= (void *)(long)fd
;
1456 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1458 int fd
= (long)t
->priv
;
1463 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1466 unsigned long current_rtc_freq
= 0;
1468 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1471 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1472 if (current_rtc_freq
!= RTC_FREQ
&&
1473 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1474 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1475 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1476 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1479 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1485 enable_sigio_timer(rtc_fd
);
1487 t
->priv
= (void *)(long)rtc_fd
;
1492 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1494 int rtc_fd
= (long)t
->priv
;
1499 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1503 struct sigaction act
;
1505 sigfillset(&act
.sa_mask
);
1507 act
.sa_handler
= host_alarm_handler
;
1509 sigaction(SIGALRM
, &act
, NULL
);
1511 ev
.sigev_value
.sival_int
= 0;
1512 ev
.sigev_notify
= SIGEV_SIGNAL
;
1513 ev
.sigev_signo
= SIGALRM
;
1515 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1516 perror("timer_create");
1518 /* disable dynticks */
1519 fprintf(stderr
, "Dynamic Ticks disabled\n");
1524 t
->priv
= (void *)host_timer
;
1529 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1531 timer_t host_timer
= (timer_t
)t
->priv
;
1533 timer_delete(host_timer
);
1536 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1538 timer_t host_timer
= (timer_t
)t
->priv
;
1539 struct itimerspec timeout
;
1540 int64_t nearest_delta_us
= INT64_MAX
;
1543 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1544 !active_timers
[QEMU_TIMER_VIRTUAL
])
1547 nearest_delta_us
= qemu_next_deadline_dyntick();
1549 /* check whether a timer is already running */
1550 if (timer_gettime(host_timer
, &timeout
)) {
1552 fprintf(stderr
, "Internal timer error: aborting\n");
1555 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1556 if (current_us
&& current_us
<= nearest_delta_us
)
1559 timeout
.it_interval
.tv_sec
= 0;
1560 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1561 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1562 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1563 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1565 fprintf(stderr
, "Internal timer error: aborting\n");
1570 #endif /* defined(__linux__) */
1572 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1574 struct sigaction act
;
1575 struct itimerval itv
;
1579 sigfillset(&act
.sa_mask
);
1581 act
.sa_handler
= host_alarm_handler
;
1583 sigaction(SIGALRM
, &act
, NULL
);
1585 itv
.it_interval
.tv_sec
= 0;
1586 /* for i386 kernel 2.6 to get 1 ms */
1587 itv
.it_interval
.tv_usec
= 999;
1588 itv
.it_value
.tv_sec
= 0;
1589 itv
.it_value
.tv_usec
= 10 * 1000;
1591 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1598 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1600 struct itimerval itv
;
1602 memset(&itv
, 0, sizeof(itv
));
1603 setitimer(ITIMER_REAL
, &itv
, NULL
);
1606 #endif /* !defined(_WIN32) */
1610 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1613 struct qemu_alarm_win32
*data
= t
->priv
;
1616 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1617 if (!data
->host_alarm
) {
1618 perror("Failed CreateEvent");
1622 memset(&tc
, 0, sizeof(tc
));
1623 timeGetDevCaps(&tc
, sizeof(tc
));
1625 if (data
->period
< tc
.wPeriodMin
)
1626 data
->period
= tc
.wPeriodMin
;
1628 timeBeginPeriod(data
->period
);
1630 flags
= TIME_CALLBACK_FUNCTION
;
1631 if (alarm_has_dynticks(t
))
1632 flags
|= TIME_ONESHOT
;
1634 flags
|= TIME_PERIODIC
;
1636 data
->timerId
= timeSetEvent(1, // interval (ms)
1637 data
->period
, // resolution
1638 host_alarm_handler
, // function
1639 (DWORD
)t
, // parameter
1642 if (!data
->timerId
) {
1643 perror("Failed to initialize win32 alarm timer");
1645 timeEndPeriod(data
->period
);
1646 CloseHandle(data
->host_alarm
);
1650 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1655 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1657 struct qemu_alarm_win32
*data
= t
->priv
;
1659 timeKillEvent(data
->timerId
);
1660 timeEndPeriod(data
->period
);
1662 CloseHandle(data
->host_alarm
);
1665 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1667 struct qemu_alarm_win32
*data
= t
->priv
;
1668 uint64_t nearest_delta_us
;
1670 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1671 !active_timers
[QEMU_TIMER_VIRTUAL
])
1674 nearest_delta_us
= qemu_next_deadline_dyntick();
1675 nearest_delta_us
/= 1000;
1677 timeKillEvent(data
->timerId
);
1679 data
->timerId
= timeSetEvent(1,
1683 TIME_ONESHOT
| TIME_PERIODIC
);
1685 if (!data
->timerId
) {
1686 perror("Failed to re-arm win32 alarm timer");
1688 timeEndPeriod(data
->period
);
1689 CloseHandle(data
->host_alarm
);
1696 static void init_timer_alarm(void)
1698 struct qemu_alarm_timer
*t
;
1701 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1702 t
= &alarm_timers
[i
];
1710 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1711 fprintf(stderr
, "Terminating\n");
1718 static void quit_timers(void)
1720 alarm_timer
->stop(alarm_timer
);
1724 /***********************************************************/
1725 /* host time/date access */
1726 void qemu_get_timedate(struct tm
*tm
, int offset
)
1733 if (rtc_date_offset
== -1) {
1737 ret
= localtime(&ti
);
1739 ti
-= rtc_date_offset
;
1743 memcpy(tm
, ret
, sizeof(struct tm
));
1746 int qemu_timedate_diff(struct tm
*tm
)
1750 if (rtc_date_offset
== -1)
1752 seconds
= mktimegm(tm
);
1754 seconds
= mktime(tm
);
1756 seconds
= mktimegm(tm
) + rtc_date_offset
;
1758 return seconds
- time(NULL
);
1761 /***********************************************************/
1762 /* character device */
1764 static void qemu_chr_event(CharDriverState
*s
, int event
)
1768 s
->chr_event(s
->handler_opaque
, event
);
1771 static void qemu_chr_reset_bh(void *opaque
)
1773 CharDriverState
*s
= opaque
;
1774 qemu_chr_event(s
, CHR_EVENT_RESET
);
1775 qemu_bh_delete(s
->bh
);
1779 void qemu_chr_reset(CharDriverState
*s
)
1781 if (s
->bh
== NULL
) {
1782 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1783 qemu_bh_schedule(s
->bh
);
1787 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1789 return s
->chr_write(s
, buf
, len
);
1792 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1796 return s
->chr_ioctl(s
, cmd
, arg
);
1799 int qemu_chr_can_read(CharDriverState
*s
)
1801 if (!s
->chr_can_read
)
1803 return s
->chr_can_read(s
->handler_opaque
);
1806 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1808 s
->chr_read(s
->handler_opaque
, buf
, len
);
1811 void qemu_chr_accept_input(CharDriverState
*s
)
1813 if (s
->chr_accept_input
)
1814 s
->chr_accept_input(s
);
1817 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1822 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1823 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1827 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1829 if (s
->chr_send_event
)
1830 s
->chr_send_event(s
, event
);
1833 void qemu_chr_add_handlers(CharDriverState
*s
,
1834 IOCanRWHandler
*fd_can_read
,
1835 IOReadHandler
*fd_read
,
1836 IOEventHandler
*fd_event
,
1839 s
->chr_can_read
= fd_can_read
;
1840 s
->chr_read
= fd_read
;
1841 s
->chr_event
= fd_event
;
1842 s
->handler_opaque
= opaque
;
1843 if (s
->chr_update_read_handler
)
1844 s
->chr_update_read_handler(s
);
1847 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1852 static CharDriverState
*qemu_chr_open_null(void)
1854 CharDriverState
*chr
;
1856 chr
= qemu_mallocz(sizeof(CharDriverState
));
1859 chr
->chr_write
= null_chr_write
;
1863 /* MUX driver for serial I/O splitting */
1864 static int term_timestamps
;
1865 static int64_t term_timestamps_start
;
1867 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1868 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1870 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1871 IOReadHandler
*chr_read
[MAX_MUX
];
1872 IOEventHandler
*chr_event
[MAX_MUX
];
1873 void *ext_opaque
[MAX_MUX
];
1874 CharDriverState
*drv
;
1875 unsigned char buffer
[MUX_BUFFER_SIZE
];
1879 int term_got_escape
;
1884 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1886 MuxDriver
*d
= chr
->opaque
;
1888 if (!term_timestamps
) {
1889 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1894 for(i
= 0; i
< len
; i
++) {
1895 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1896 if (buf
[i
] == '\n') {
1902 if (term_timestamps_start
== -1)
1903 term_timestamps_start
= ti
;
1904 ti
-= term_timestamps_start
;
1905 secs
= ti
/ 1000000000;
1906 snprintf(buf1
, sizeof(buf1
),
1907 "[%02d:%02d:%02d.%03d] ",
1911 (int)((ti
/ 1000000) % 1000));
1912 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1919 static char *mux_help
[] = {
1920 "% h print this help\n\r",
1921 "% x exit emulator\n\r",
1922 "% s save disk data back to file (if -snapshot)\n\r",
1923 "% t toggle console timestamps\n\r"
1924 "% b send break (magic sysrq)\n\r",
1925 "% c switch between console and monitor\n\r",
1930 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1931 static void mux_print_help(CharDriverState
*chr
)
1934 char ebuf
[15] = "Escape-Char";
1935 char cbuf
[50] = "\n\r";
1937 if (term_escape_char
> 0 && term_escape_char
< 26) {
1938 sprintf(cbuf
,"\n\r");
1939 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1941 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1944 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1945 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1946 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1947 if (mux_help
[i
][j
] == '%')
1948 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1950 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1955 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1957 if (d
->term_got_escape
) {
1958 d
->term_got_escape
= 0;
1959 if (ch
== term_escape_char
)
1964 mux_print_help(chr
);
1968 char *term
= "QEMU: Terminated\n\r";
1969 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1976 for (i
= 0; i
< nb_drives
; i
++) {
1977 bdrv_commit(drives_table
[i
].bdrv
);
1982 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1985 /* Switch to the next registered device */
1987 if (chr
->focus
>= d
->mux_cnt
)
1991 term_timestamps
= !term_timestamps
;
1992 term_timestamps_start
= -1;
1995 } else if (ch
== term_escape_char
) {
1996 d
->term_got_escape
= 1;
2004 static void mux_chr_accept_input(CharDriverState
*chr
)
2007 MuxDriver
*d
= chr
->opaque
;
2009 while (d
->prod
!= d
->cons
&&
2010 d
->chr_can_read
[m
] &&
2011 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
2012 d
->chr_read
[m
](d
->ext_opaque
[m
],
2013 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2017 static int mux_chr_can_read(void *opaque
)
2019 CharDriverState
*chr
= opaque
;
2020 MuxDriver
*d
= chr
->opaque
;
2022 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2024 if (d
->chr_can_read
[chr
->focus
])
2025 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2029 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2031 CharDriverState
*chr
= opaque
;
2032 MuxDriver
*d
= chr
->opaque
;
2036 mux_chr_accept_input (opaque
);
2038 for(i
= 0; i
< size
; i
++)
2039 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2040 if (d
->prod
== d
->cons
&&
2041 d
->chr_can_read
[m
] &&
2042 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2043 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2045 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2049 static void mux_chr_event(void *opaque
, int event
)
2051 CharDriverState
*chr
= opaque
;
2052 MuxDriver
*d
= chr
->opaque
;
2055 /* Send the event to all registered listeners */
2056 for (i
= 0; i
< d
->mux_cnt
; i
++)
2057 if (d
->chr_event
[i
])
2058 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2061 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2063 MuxDriver
*d
= chr
->opaque
;
2065 if (d
->mux_cnt
>= MAX_MUX
) {
2066 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2069 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2070 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2071 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2072 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2073 /* Fix up the real driver with mux routines */
2074 if (d
->mux_cnt
== 0) {
2075 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2076 mux_chr_event
, chr
);
2078 chr
->focus
= d
->mux_cnt
;
2082 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2084 CharDriverState
*chr
;
2087 chr
= qemu_mallocz(sizeof(CharDriverState
));
2090 d
= qemu_mallocz(sizeof(MuxDriver
));
2099 chr
->chr_write
= mux_chr_write
;
2100 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2101 chr
->chr_accept_input
= mux_chr_accept_input
;
2108 static void socket_cleanup(void)
2113 static int socket_init(void)
2118 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2120 err
= WSAGetLastError();
2121 fprintf(stderr
, "WSAStartup: %d\n", err
);
2124 atexit(socket_cleanup
);
2128 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2134 ret
= send(fd
, buf
, len
, 0);
2137 errno
= WSAGetLastError();
2138 if (errno
!= WSAEWOULDBLOCK
) {
2141 } else if (ret
== 0) {
2151 void socket_set_nonblock(int fd
)
2153 unsigned long opt
= 1;
2154 ioctlsocket(fd
, FIONBIO
, &opt
);
2159 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2165 ret
= write(fd
, buf
, len
);
2167 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2169 } else if (ret
== 0) {
2179 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2181 return unix_write(fd
, buf
, len1
);
2184 void socket_set_nonblock(int fd
)
2187 f
= fcntl(fd
, F_GETFL
);
2188 fcntl(fd
, F_SETFL
, f
| O_NONBLOCK
);
2190 #endif /* !_WIN32 */
2199 #define STDIO_MAX_CLIENTS 1
2200 static int stdio_nb_clients
= 0;
2202 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2204 FDCharDriver
*s
= chr
->opaque
;
2205 return unix_write(s
->fd_out
, buf
, len
);
2208 static int fd_chr_read_poll(void *opaque
)
2210 CharDriverState
*chr
= opaque
;
2211 FDCharDriver
*s
= chr
->opaque
;
2213 s
->max_size
= qemu_chr_can_read(chr
);
2217 static void fd_chr_read(void *opaque
)
2219 CharDriverState
*chr
= opaque
;
2220 FDCharDriver
*s
= chr
->opaque
;
2225 if (len
> s
->max_size
)
2229 size
= read(s
->fd_in
, buf
, len
);
2231 /* FD has been closed. Remove it from the active list. */
2232 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2236 qemu_chr_read(chr
, buf
, size
);
2240 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2242 FDCharDriver
*s
= chr
->opaque
;
2244 if (s
->fd_in
>= 0) {
2245 if (nographic
&& s
->fd_in
== 0) {
2247 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2248 fd_chr_read
, NULL
, chr
);
2253 static void fd_chr_close(struct CharDriverState
*chr
)
2255 FDCharDriver
*s
= chr
->opaque
;
2257 if (s
->fd_in
>= 0) {
2258 if (nographic
&& s
->fd_in
== 0) {
2260 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2267 /* open a character device to a unix fd */
2268 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2270 CharDriverState
*chr
;
2273 chr
= qemu_mallocz(sizeof(CharDriverState
));
2276 s
= qemu_mallocz(sizeof(FDCharDriver
));
2284 chr
->chr_write
= fd_chr_write
;
2285 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2286 chr
->chr_close
= fd_chr_close
;
2288 qemu_chr_reset(chr
);
2293 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2297 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2300 return qemu_chr_open_fd(-1, fd_out
);
2303 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2306 char filename_in
[256], filename_out
[256];
2308 snprintf(filename_in
, 256, "%s.in", filename
);
2309 snprintf(filename_out
, 256, "%s.out", filename
);
2310 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2311 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2312 if (fd_in
< 0 || fd_out
< 0) {
2317 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2321 return qemu_chr_open_fd(fd_in
, fd_out
);
2325 /* for STDIO, we handle the case where several clients use it
2328 #define TERM_FIFO_MAX_SIZE 1
2330 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2331 static int term_fifo_size
;
2333 static int stdio_read_poll(void *opaque
)
2335 CharDriverState
*chr
= opaque
;
2337 /* try to flush the queue if needed */
2338 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2339 qemu_chr_read(chr
, term_fifo
, 1);
2342 /* see if we can absorb more chars */
2343 if (term_fifo_size
== 0)
2349 static void stdio_read(void *opaque
)
2353 CharDriverState
*chr
= opaque
;
2355 size
= read(0, buf
, 1);
2357 /* stdin has been closed. Remove it from the active list. */
2358 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2362 if (qemu_chr_can_read(chr
) > 0) {
2363 qemu_chr_read(chr
, buf
, 1);
2364 } else if (term_fifo_size
== 0) {
2365 term_fifo
[term_fifo_size
++] = buf
[0];
2370 /* init terminal so that we can grab keys */
2371 static struct termios oldtty
;
2372 static int old_fd0_flags
;
2373 static int term_atexit_done
;
2375 static void term_exit(void)
2377 tcsetattr (0, TCSANOW
, &oldtty
);
2378 fcntl(0, F_SETFL
, old_fd0_flags
);
2381 static void term_init(void)
2385 tcgetattr (0, &tty
);
2387 old_fd0_flags
= fcntl(0, F_GETFL
);
2389 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2390 |INLCR
|IGNCR
|ICRNL
|IXON
);
2391 tty
.c_oflag
|= OPOST
;
2392 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2393 /* if graphical mode, we allow Ctrl-C handling */
2395 tty
.c_lflag
&= ~ISIG
;
2396 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2399 tty
.c_cc
[VTIME
] = 0;
2401 tcsetattr (0, TCSANOW
, &tty
);
2403 if (!term_atexit_done
++)
2406 fcntl(0, F_SETFL
, O_NONBLOCK
);
2409 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2413 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2417 static CharDriverState
*qemu_chr_open_stdio(void)
2419 CharDriverState
*chr
;
2421 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2423 chr
= qemu_chr_open_fd(0, 1);
2424 chr
->chr_close
= qemu_chr_close_stdio
;
2425 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2433 /* Once Solaris has openpty(), this is going to be removed. */
2434 int openpty(int *amaster
, int *aslave
, char *name
,
2435 struct termios
*termp
, struct winsize
*winp
)
2438 int mfd
= -1, sfd
= -1;
2440 *amaster
= *aslave
= -1;
2442 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2446 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2449 if ((slave
= ptsname(mfd
)) == NULL
)
2452 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2455 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2456 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2464 ioctl(sfd
, TIOCSWINSZ
, winp
);
2475 void cfmakeraw (struct termios
*termios_p
)
2477 termios_p
->c_iflag
&=
2478 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2479 termios_p
->c_oflag
&= ~OPOST
;
2480 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2481 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2482 termios_p
->c_cflag
|= CS8
;
2484 termios_p
->c_cc
[VMIN
] = 0;
2485 termios_p
->c_cc
[VTIME
] = 0;
2489 #if defined(__linux__) || defined(__sun__)
2499 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2500 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2502 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2504 PtyCharDriver
*s
= chr
->opaque
;
2506 if (!s
->connected
) {
2507 /* guest sends data, check for (re-)connect */
2508 pty_chr_update_read_handler(chr
);
2511 return unix_write(s
->fd
, buf
, len
);
2514 static int pty_chr_read_poll(void *opaque
)
2516 CharDriverState
*chr
= opaque
;
2517 PtyCharDriver
*s
= chr
->opaque
;
2519 s
->read_bytes
= qemu_chr_can_read(chr
);
2520 return s
->read_bytes
;
2523 static void pty_chr_read(void *opaque
)
2525 CharDriverState
*chr
= opaque
;
2526 PtyCharDriver
*s
= chr
->opaque
;
2531 if (len
> s
->read_bytes
)
2532 len
= s
->read_bytes
;
2535 size
= read(s
->fd
, buf
, len
);
2536 if ((size
== -1 && errno
== EIO
) ||
2538 pty_chr_state(chr
, 0);
2542 pty_chr_state(chr
, 1);
2543 qemu_chr_read(chr
, buf
, size
);
2547 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2549 PtyCharDriver
*s
= chr
->opaque
;
2551 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2552 pty_chr_read
, NULL
, chr
);
2555 * Short timeout here: just need wait long enougth that qemu makes
2556 * it through the poll loop once. When reconnected we want a
2557 * short timeout so we notice it almost instantly. Otherwise
2558 * read() gives us -EIO instantly, making pty_chr_state() reset the
2559 * timeout to the normal (much longer) poll interval before the
2562 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2565 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2567 PtyCharDriver
*s
= chr
->opaque
;
2570 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2573 /* (re-)connect poll interval for idle guests: once per second.
2574 * We check more frequently in case the guests sends data to
2575 * the virtual device linked to our pty. */
2576 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2579 qemu_chr_reset(chr
);
2584 void pty_chr_timer(void *opaque
)
2586 struct CharDriverState
*chr
= opaque
;
2587 PtyCharDriver
*s
= chr
->opaque
;
2592 /* If we arrive here without polling being cleared due
2593 * read returning -EIO, then we are (re-)connected */
2594 pty_chr_state(chr
, 1);
2599 pty_chr_update_read_handler(chr
);
2602 static void pty_chr_close(struct CharDriverState
*chr
)
2604 PtyCharDriver
*s
= chr
->opaque
;
2606 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2611 static CharDriverState
*qemu_chr_open_pty(void)
2613 CharDriverState
*chr
;
2618 chr
= qemu_mallocz(sizeof(CharDriverState
));
2621 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2627 if (openpty(&s
->fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2631 /* Set raw attributes on the pty. */
2633 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2636 fprintf(stderr
, "char device redirected to %s\n", ptsname(s
->fd
));
2639 chr
->chr_write
= pty_chr_write
;
2640 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2641 chr
->chr_close
= pty_chr_close
;
2643 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2648 static void tty_serial_init(int fd
, int speed
,
2649 int parity
, int data_bits
, int stop_bits
)
2655 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2656 speed
, parity
, data_bits
, stop_bits
);
2658 tcgetattr (fd
, &tty
);
2661 if (speed
<= 50 * MARGIN
)
2663 else if (speed
<= 75 * MARGIN
)
2665 else if (speed
<= 300 * MARGIN
)
2667 else if (speed
<= 600 * MARGIN
)
2669 else if (speed
<= 1200 * MARGIN
)
2671 else if (speed
<= 2400 * MARGIN
)
2673 else if (speed
<= 4800 * MARGIN
)
2675 else if (speed
<= 9600 * MARGIN
)
2677 else if (speed
<= 19200 * MARGIN
)
2679 else if (speed
<= 38400 * MARGIN
)
2681 else if (speed
<= 57600 * MARGIN
)
2683 else if (speed
<= 115200 * MARGIN
)
2688 cfsetispeed(&tty
, spd
);
2689 cfsetospeed(&tty
, spd
);
2691 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2692 |INLCR
|IGNCR
|ICRNL
|IXON
);
2693 tty
.c_oflag
|= OPOST
;
2694 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2695 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2716 tty
.c_cflag
|= PARENB
;
2719 tty
.c_cflag
|= PARENB
| PARODD
;
2723 tty
.c_cflag
|= CSTOPB
;
2725 tcsetattr (fd
, TCSANOW
, &tty
);
2728 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2730 FDCharDriver
*s
= chr
->opaque
;
2733 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2735 QEMUSerialSetParams
*ssp
= arg
;
2736 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2737 ssp
->data_bits
, ssp
->stop_bits
);
2740 case CHR_IOCTL_SERIAL_SET_BREAK
:
2742 int enable
= *(int *)arg
;
2744 tcsendbreak(s
->fd_in
, 1);
2753 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2755 CharDriverState
*chr
;
2758 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2759 tty_serial_init(fd
, 115200, 'N', 8, 1);
2760 chr
= qemu_chr_open_fd(fd
, fd
);
2765 chr
->chr_ioctl
= tty_serial_ioctl
;
2766 qemu_chr_reset(chr
);
2769 #else /* ! __linux__ && ! __sun__ */
2770 static CharDriverState
*qemu_chr_open_pty(void)
2774 #endif /* __linux__ || __sun__ */
2776 #if defined(__linux__)
2780 } ParallelCharDriver
;
2782 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2784 if (s
->mode
!= mode
) {
2786 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2793 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2795 ParallelCharDriver
*drv
= chr
->opaque
;
2800 case CHR_IOCTL_PP_READ_DATA
:
2801 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2803 *(uint8_t *)arg
= b
;
2805 case CHR_IOCTL_PP_WRITE_DATA
:
2806 b
= *(uint8_t *)arg
;
2807 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2810 case CHR_IOCTL_PP_READ_CONTROL
:
2811 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2813 /* Linux gives only the lowest bits, and no way to know data
2814 direction! For better compatibility set the fixed upper
2816 *(uint8_t *)arg
= b
| 0xc0;
2818 case CHR_IOCTL_PP_WRITE_CONTROL
:
2819 b
= *(uint8_t *)arg
;
2820 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2823 case CHR_IOCTL_PP_READ_STATUS
:
2824 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2826 *(uint8_t *)arg
= b
;
2828 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2829 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2830 struct ParallelIOArg
*parg
= arg
;
2831 int n
= read(fd
, parg
->buffer
, parg
->count
);
2832 if (n
!= parg
->count
) {
2837 case CHR_IOCTL_PP_EPP_READ
:
2838 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2839 struct ParallelIOArg
*parg
= arg
;
2840 int n
= read(fd
, parg
->buffer
, parg
->count
);
2841 if (n
!= parg
->count
) {
2846 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2847 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2848 struct ParallelIOArg
*parg
= arg
;
2849 int n
= write(fd
, parg
->buffer
, parg
->count
);
2850 if (n
!= parg
->count
) {
2855 case CHR_IOCTL_PP_EPP_WRITE
:
2856 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2857 struct ParallelIOArg
*parg
= arg
;
2858 int n
= write(fd
, parg
->buffer
, parg
->count
);
2859 if (n
!= parg
->count
) {
2870 static void pp_close(CharDriverState
*chr
)
2872 ParallelCharDriver
*drv
= chr
->opaque
;
2875 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2876 ioctl(fd
, PPRELEASE
);
2881 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2883 CharDriverState
*chr
;
2884 ParallelCharDriver
*drv
;
2887 TFR(fd
= open(filename
, O_RDWR
));
2891 if (ioctl(fd
, PPCLAIM
) < 0) {
2896 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2902 drv
->mode
= IEEE1284_MODE_COMPAT
;
2904 chr
= qemu_mallocz(sizeof(CharDriverState
));
2910 chr
->chr_write
= null_chr_write
;
2911 chr
->chr_ioctl
= pp_ioctl
;
2912 chr
->chr_close
= pp_close
;
2915 qemu_chr_reset(chr
);
2919 #endif /* __linux__ */
2925 HANDLE hcom
, hrecv
, hsend
;
2926 OVERLAPPED orecv
, osend
;
2931 #define NSENDBUF 2048
2932 #define NRECVBUF 2048
2933 #define MAXCONNECT 1
2934 #define NTIMEOUT 5000
2936 static int win_chr_poll(void *opaque
);
2937 static int win_chr_pipe_poll(void *opaque
);
2939 static void win_chr_close(CharDriverState
*chr
)
2941 WinCharState
*s
= chr
->opaque
;
2944 CloseHandle(s
->hsend
);
2948 CloseHandle(s
->hrecv
);
2952 CloseHandle(s
->hcom
);
2956 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2958 qemu_del_polling_cb(win_chr_poll
, chr
);
2961 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2963 WinCharState
*s
= chr
->opaque
;
2965 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2970 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2972 fprintf(stderr
, "Failed CreateEvent\n");
2975 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2977 fprintf(stderr
, "Failed CreateEvent\n");
2981 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2982 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2983 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2984 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2989 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2990 fprintf(stderr
, "Failed SetupComm\n");
2994 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2995 size
= sizeof(COMMCONFIG
);
2996 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2997 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2998 CommConfigDialog(filename
, NULL
, &comcfg
);
3000 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3001 fprintf(stderr
, "Failed SetCommState\n");
3005 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3006 fprintf(stderr
, "Failed SetCommMask\n");
3010 cto
.ReadIntervalTimeout
= MAXDWORD
;
3011 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3012 fprintf(stderr
, "Failed SetCommTimeouts\n");
3016 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3017 fprintf(stderr
, "Failed ClearCommError\n");
3020 qemu_add_polling_cb(win_chr_poll
, chr
);
3028 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3030 WinCharState
*s
= chr
->opaque
;
3031 DWORD len
, ret
, size
, err
;
3034 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3035 s
->osend
.hEvent
= s
->hsend
;
3038 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3040 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3042 err
= GetLastError();
3043 if (err
== ERROR_IO_PENDING
) {
3044 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3062 static int win_chr_read_poll(CharDriverState
*chr
)
3064 WinCharState
*s
= chr
->opaque
;
3066 s
->max_size
= qemu_chr_can_read(chr
);
3070 static void win_chr_readfile(CharDriverState
*chr
)
3072 WinCharState
*s
= chr
->opaque
;
3077 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3078 s
->orecv
.hEvent
= s
->hrecv
;
3079 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3081 err
= GetLastError();
3082 if (err
== ERROR_IO_PENDING
) {
3083 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3088 qemu_chr_read(chr
, buf
, size
);
3092 static void win_chr_read(CharDriverState
*chr
)
3094 WinCharState
*s
= chr
->opaque
;
3096 if (s
->len
> s
->max_size
)
3097 s
->len
= s
->max_size
;
3101 win_chr_readfile(chr
);
3104 static int win_chr_poll(void *opaque
)
3106 CharDriverState
*chr
= opaque
;
3107 WinCharState
*s
= chr
->opaque
;
3111 ClearCommError(s
->hcom
, &comerr
, &status
);
3112 if (status
.cbInQue
> 0) {
3113 s
->len
= status
.cbInQue
;
3114 win_chr_read_poll(chr
);
3121 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3123 CharDriverState
*chr
;
3126 chr
= qemu_mallocz(sizeof(CharDriverState
));
3129 s
= qemu_mallocz(sizeof(WinCharState
));
3135 chr
->chr_write
= win_chr_write
;
3136 chr
->chr_close
= win_chr_close
;
3138 if (win_chr_init(chr
, filename
) < 0) {
3143 qemu_chr_reset(chr
);
3147 static int win_chr_pipe_poll(void *opaque
)
3149 CharDriverState
*chr
= opaque
;
3150 WinCharState
*s
= chr
->opaque
;
3153 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3156 win_chr_read_poll(chr
);
3163 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3165 WinCharState
*s
= chr
->opaque
;
3173 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3175 fprintf(stderr
, "Failed CreateEvent\n");
3178 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3180 fprintf(stderr
, "Failed CreateEvent\n");
3184 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3185 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3186 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3188 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3189 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3190 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3195 ZeroMemory(&ov
, sizeof(ov
));
3196 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3197 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3199 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3203 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3205 fprintf(stderr
, "Failed GetOverlappedResult\n");
3207 CloseHandle(ov
.hEvent
);
3214 CloseHandle(ov
.hEvent
);
3217 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3226 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3228 CharDriverState
*chr
;
3231 chr
= qemu_mallocz(sizeof(CharDriverState
));
3234 s
= qemu_mallocz(sizeof(WinCharState
));
3240 chr
->chr_write
= win_chr_write
;
3241 chr
->chr_close
= win_chr_close
;
3243 if (win_chr_pipe_init(chr
, filename
) < 0) {
3248 qemu_chr_reset(chr
);
3252 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3254 CharDriverState
*chr
;
3257 chr
= qemu_mallocz(sizeof(CharDriverState
));
3260 s
= qemu_mallocz(sizeof(WinCharState
));
3267 chr
->chr_write
= win_chr_write
;
3268 qemu_chr_reset(chr
);
3272 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3274 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3277 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3281 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3282 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3283 if (fd_out
== INVALID_HANDLE_VALUE
)
3286 return qemu_chr_open_win_file(fd_out
);
3288 #endif /* !_WIN32 */
3290 /***********************************************************/
3291 /* UDP Net console */
3295 struct sockaddr_in daddr
;
3302 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3304 NetCharDriver
*s
= chr
->opaque
;
3306 return sendto(s
->fd
, buf
, len
, 0,
3307 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3310 static int udp_chr_read_poll(void *opaque
)
3312 CharDriverState
*chr
= opaque
;
3313 NetCharDriver
*s
= chr
->opaque
;
3315 s
->max_size
= qemu_chr_can_read(chr
);
3317 /* If there were any stray characters in the queue process them
3320 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3321 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3323 s
->max_size
= qemu_chr_can_read(chr
);
3328 static void udp_chr_read(void *opaque
)
3330 CharDriverState
*chr
= opaque
;
3331 NetCharDriver
*s
= chr
->opaque
;
3333 if (s
->max_size
== 0)
3335 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3336 s
->bufptr
= s
->bufcnt
;
3341 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3342 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3344 s
->max_size
= qemu_chr_can_read(chr
);
3348 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3350 NetCharDriver
*s
= chr
->opaque
;
3353 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3354 udp_chr_read
, NULL
, chr
);
3359 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3361 int parse_host_src_port(struct sockaddr_in
*haddr
,
3362 struct sockaddr_in
*saddr
,
3365 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3367 CharDriverState
*chr
= NULL
;
3368 NetCharDriver
*s
= NULL
;
3370 struct sockaddr_in saddr
;
3372 chr
= qemu_mallocz(sizeof(CharDriverState
));
3375 s
= qemu_mallocz(sizeof(NetCharDriver
));
3379 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3381 perror("socket(PF_INET, SOCK_DGRAM)");
3385 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3386 printf("Could not parse: %s\n", def
);
3390 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3400 chr
->chr_write
= udp_chr_write
;
3401 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3414 /***********************************************************/
3415 /* TCP Net console */
3426 static void tcp_chr_accept(void *opaque
);
3428 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3430 TCPCharDriver
*s
= chr
->opaque
;
3432 return send_all(s
->fd
, buf
, len
);
3434 /* XXX: indicate an error ? */
3439 static int tcp_chr_read_poll(void *opaque
)
3441 CharDriverState
*chr
= opaque
;
3442 TCPCharDriver
*s
= chr
->opaque
;
3445 s
->max_size
= qemu_chr_can_read(chr
);
3450 #define IAC_BREAK 243
3451 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3453 uint8_t *buf
, int *size
)
3455 /* Handle any telnet client's basic IAC options to satisfy char by
3456 * char mode with no echo. All IAC options will be removed from
3457 * the buf and the do_telnetopt variable will be used to track the
3458 * state of the width of the IAC information.
3460 * IAC commands come in sets of 3 bytes with the exception of the
3461 * "IAC BREAK" command and the double IAC.
3467 for (i
= 0; i
< *size
; i
++) {
3468 if (s
->do_telnetopt
> 1) {
3469 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3470 /* Double IAC means send an IAC */
3474 s
->do_telnetopt
= 1;
3476 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3477 /* Handle IAC break commands by sending a serial break */
3478 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3483 if (s
->do_telnetopt
>= 4) {
3484 s
->do_telnetopt
= 1;
3487 if ((unsigned char)buf
[i
] == IAC
) {
3488 s
->do_telnetopt
= 2;
3499 static void tcp_chr_read(void *opaque
)
3501 CharDriverState
*chr
= opaque
;
3502 TCPCharDriver
*s
= chr
->opaque
;
3506 if (!s
->connected
|| s
->max_size
<= 0)
3509 if (len
> s
->max_size
)
3511 size
= recv(s
->fd
, buf
, len
, 0);
3513 /* connection closed */
3515 if (s
->listen_fd
>= 0) {
3516 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3518 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3521 } else if (size
> 0) {
3522 if (s
->do_telnetopt
)
3523 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3525 qemu_chr_read(chr
, buf
, size
);
3529 static void tcp_chr_connect(void *opaque
)
3531 CharDriverState
*chr
= opaque
;
3532 TCPCharDriver
*s
= chr
->opaque
;
3535 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3536 tcp_chr_read
, NULL
, chr
);
3537 qemu_chr_reset(chr
);
3540 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3541 static void tcp_chr_telnet_init(int fd
)
3544 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3545 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3546 send(fd
, (char *)buf
, 3, 0);
3547 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3548 send(fd
, (char *)buf
, 3, 0);
3549 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3550 send(fd
, (char *)buf
, 3, 0);
3551 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3552 send(fd
, (char *)buf
, 3, 0);
3555 static void socket_set_nodelay(int fd
)
3558 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3561 static void tcp_chr_accept(void *opaque
)
3563 CharDriverState
*chr
= opaque
;
3564 TCPCharDriver
*s
= chr
->opaque
;
3565 struct sockaddr_in saddr
;
3567 struct sockaddr_un uaddr
;
3569 struct sockaddr
*addr
;
3576 len
= sizeof(uaddr
);
3577 addr
= (struct sockaddr
*)&uaddr
;
3581 len
= sizeof(saddr
);
3582 addr
= (struct sockaddr
*)&saddr
;
3584 fd
= accept(s
->listen_fd
, addr
, &len
);
3585 if (fd
< 0 && errno
!= EINTR
) {
3587 } else if (fd
>= 0) {
3588 if (s
->do_telnetopt
)
3589 tcp_chr_telnet_init(fd
);
3593 socket_set_nonblock(fd
);
3595 socket_set_nodelay(fd
);
3597 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3598 tcp_chr_connect(chr
);
3601 static void tcp_chr_close(CharDriverState
*chr
)
3603 TCPCharDriver
*s
= chr
->opaque
;
3606 if (s
->listen_fd
>= 0)
3607 closesocket(s
->listen_fd
);
3611 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3615 CharDriverState
*chr
= NULL
;
3616 TCPCharDriver
*s
= NULL
;
3617 int fd
= -1, ret
, err
, val
;
3619 int is_waitconnect
= 1;
3622 struct sockaddr_in saddr
;
3624 struct sockaddr_un uaddr
;
3626 struct sockaddr
*addr
;
3631 addr
= (struct sockaddr
*)&uaddr
;
3632 addrlen
= sizeof(uaddr
);
3633 if (parse_unix_path(&uaddr
, host_str
) < 0)
3638 addr
= (struct sockaddr
*)&saddr
;
3639 addrlen
= sizeof(saddr
);
3640 if (parse_host_port(&saddr
, host_str
) < 0)
3645 while((ptr
= strchr(ptr
,','))) {
3647 if (!strncmp(ptr
,"server",6)) {
3649 } else if (!strncmp(ptr
,"nowait",6)) {
3651 } else if (!strncmp(ptr
,"nodelay",6)) {
3654 printf("Unknown option: %s\n", ptr
);
3661 chr
= qemu_mallocz(sizeof(CharDriverState
));
3664 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3670 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3673 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3678 if (!is_waitconnect
)
3679 socket_set_nonblock(fd
);
3684 s
->is_unix
= is_unix
;
3685 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3688 chr
->chr_write
= tcp_chr_write
;
3689 chr
->chr_close
= tcp_chr_close
;
3692 /* allow fast reuse */
3696 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3702 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3705 ret
= bind(fd
, addr
, addrlen
);
3709 ret
= listen(fd
, 0);
3714 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3716 s
->do_telnetopt
= 1;
3719 ret
= connect(fd
, addr
, addrlen
);
3721 err
= socket_error();
3722 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3723 } else if (err
== EINPROGRESS
) {
3726 } else if (err
== WSAEALREADY
) {
3738 socket_set_nodelay(fd
);
3740 tcp_chr_connect(chr
);
3742 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3745 if (is_listen
&& is_waitconnect
) {
3746 printf("QEMU waiting for connection on: %s\n", host_str
);
3747 tcp_chr_accept(chr
);
3748 socket_set_nonblock(s
->listen_fd
);
3760 CharDriverState
*qemu_chr_open(const char *filename
)
3764 if (!strcmp(filename
, "vc")) {
3765 return text_console_init(&display_state
, 0);
3766 } else if (strstart(filename
, "vc:", &p
)) {
3767 return text_console_init(&display_state
, p
);
3768 } else if (!strcmp(filename
, "null")) {
3769 return qemu_chr_open_null();
3771 if (strstart(filename
, "tcp:", &p
)) {
3772 return qemu_chr_open_tcp(p
, 0, 0);
3774 if (strstart(filename
, "telnet:", &p
)) {
3775 return qemu_chr_open_tcp(p
, 1, 0);
3777 if (strstart(filename
, "udp:", &p
)) {
3778 return qemu_chr_open_udp(p
);
3780 if (strstart(filename
, "mon:", &p
)) {
3781 CharDriverState
*drv
= qemu_chr_open(p
);
3783 drv
= qemu_chr_open_mux(drv
);
3784 monitor_init(drv
, !nographic
);
3787 printf("Unable to open driver: %s\n", p
);
3791 if (strstart(filename
, "unix:", &p
)) {
3792 return qemu_chr_open_tcp(p
, 0, 1);
3793 } else if (strstart(filename
, "file:", &p
)) {
3794 return qemu_chr_open_file_out(p
);
3795 } else if (strstart(filename
, "pipe:", &p
)) {
3796 return qemu_chr_open_pipe(p
);
3797 } else if (!strcmp(filename
, "pty")) {
3798 return qemu_chr_open_pty();
3799 } else if (!strcmp(filename
, "stdio")) {
3800 return qemu_chr_open_stdio();
3802 #if defined(__linux__)
3803 if (strstart(filename
, "/dev/parport", NULL
)) {
3804 return qemu_chr_open_pp(filename
);
3807 #if defined(__linux__) || defined(__sun__)
3808 if (strstart(filename
, "/dev/", NULL
)) {
3809 return qemu_chr_open_tty(filename
);
3813 if (strstart(filename
, "COM", NULL
)) {
3814 return qemu_chr_open_win(filename
);
3816 if (strstart(filename
, "pipe:", &p
)) {
3817 return qemu_chr_open_win_pipe(p
);
3819 if (strstart(filename
, "con:", NULL
)) {
3820 return qemu_chr_open_win_con(filename
);
3822 if (strstart(filename
, "file:", &p
)) {
3823 return qemu_chr_open_win_file_out(p
);
3826 #ifdef CONFIG_BRLAPI
3827 if (!strcmp(filename
, "braille")) {
3828 return chr_baum_init();
3836 void qemu_chr_close(CharDriverState
*chr
)
3839 chr
->chr_close(chr
);
3843 /***********************************************************/
3844 /* network device redirectors */
3846 __attribute__ (( unused
))
3847 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3851 for(i
=0;i
<size
;i
+=16) {
3855 fprintf(f
, "%08x ", i
);
3858 fprintf(f
, " %02x", buf
[i
+j
]);
3863 for(j
=0;j
<len
;j
++) {
3865 if (c
< ' ' || c
> '~')
3867 fprintf(f
, "%c", c
);
3873 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3880 offset
= strtol(p
, &last_char
, 0);
3881 if (0 == errno
&& '\0' == *last_char
&&
3882 offset
>= 0 && offset
<= 0xFFFFFF) {
3883 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3884 macaddr
[4] = (offset
& 0xFF00) >> 8;
3885 macaddr
[5] = offset
& 0xFF;
3888 for(i
= 0; i
< 6; i
++) {
3889 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3894 if (*p
!= ':' && *p
!= '-')
3905 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3910 p1
= strchr(p
, sep
);
3916 if (len
> buf_size
- 1)
3918 memcpy(buf
, p
, len
);
3925 int parse_host_src_port(struct sockaddr_in
*haddr
,
3926 struct sockaddr_in
*saddr
,
3927 const char *input_str
)
3929 char *str
= strdup(input_str
);
3930 char *host_str
= str
;
3935 * Chop off any extra arguments at the end of the string which
3936 * would start with a comma, then fill in the src port information
3937 * if it was provided else use the "any address" and "any port".
3939 if ((ptr
= strchr(str
,',')))
3942 if ((src_str
= strchr(input_str
,'@'))) {
3947 if (parse_host_port(haddr
, host_str
) < 0)
3950 if (!src_str
|| *src_str
== '\0')
3953 if (parse_host_port(saddr
, src_str
) < 0)
3964 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3972 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3974 saddr
->sin_family
= AF_INET
;
3975 if (buf
[0] == '\0') {
3976 saddr
->sin_addr
.s_addr
= 0;
3978 if (isdigit(buf
[0])) {
3979 if (!inet_aton(buf
, &saddr
->sin_addr
))
3982 if ((he
= gethostbyname(buf
)) == NULL
)
3984 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3987 port
= strtol(p
, (char **)&r
, 0);
3990 saddr
->sin_port
= htons(port
);
3995 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4000 len
= MIN(108, strlen(str
));
4001 p
= strchr(str
, ',');
4003 len
= MIN(len
, p
- str
);
4005 memset(uaddr
, 0, sizeof(*uaddr
));
4007 uaddr
->sun_family
= AF_UNIX
;
4008 memcpy(uaddr
->sun_path
, str
, len
);
4014 /* find or alloc a new VLAN */
4015 VLANState
*qemu_find_vlan(int id
)
4017 VLANState
**pvlan
, *vlan
;
4018 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4022 vlan
= qemu_mallocz(sizeof(VLANState
));
4027 pvlan
= &first_vlan
;
4028 while (*pvlan
!= NULL
)
4029 pvlan
= &(*pvlan
)->next
;
4034 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4035 IOReadHandler
*fd_read
,
4036 IOCanRWHandler
*fd_can_read
,
4039 VLANClientState
*vc
, **pvc
;
4040 vc
= qemu_mallocz(sizeof(VLANClientState
));
4043 vc
->fd_read
= fd_read
;
4044 vc
->fd_can_read
= fd_can_read
;
4045 vc
->opaque
= opaque
;
4049 pvc
= &vlan
->first_client
;
4050 while (*pvc
!= NULL
)
4051 pvc
= &(*pvc
)->next
;
4056 void qemu_del_vlan_client(VLANClientState
*vc
)
4058 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4060 while (*pvc
!= NULL
)
4066 pvc
= &(*pvc
)->next
;
4069 int qemu_can_send_packet(VLANClientState
*vc1
)
4071 VLANState
*vlan
= vc1
->vlan
;
4072 VLANClientState
*vc
;
4074 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4076 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4083 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4085 VLANState
*vlan
= vc1
->vlan
;
4086 VLANClientState
*vc
;
4090 printf("vlan %d send:\n", vlan
->id
);
4091 hex_dump(stdout
, buf
, size
);
4093 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4095 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
4096 vc
->fd_read(vc
->opaque
, buf
, size
);
4105 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
4112 for (i
= 0; i
< iovcnt
; i
++) {
4115 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
4116 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
4120 vc
->fd_read(vc
->opaque
, buffer
, offset
);
4125 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
4128 VLANState
*vlan
= vc1
->vlan
;
4129 VLANClientState
*vc
;
4130 ssize_t max_len
= 0;
4132 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4139 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
4140 else if (vc
->fd_read
)
4141 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
4143 max_len
= MAX(max_len
, len
);
4149 #if defined(CONFIG_SLIRP)
4151 /* slirp network adapter */
4153 static int slirp_inited
;
4154 static VLANClientState
*slirp_vc
;
4156 int slirp_can_output(void)
4158 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4161 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4164 printf("slirp output:\n");
4165 hex_dump(stdout
, pkt
, pkt_len
);
4169 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4172 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4175 printf("slirp input:\n");
4176 hex_dump(stdout
, buf
, size
);
4178 slirp_input(buf
, size
);
4181 static int net_slirp_init(VLANState
*vlan
)
4183 if (!slirp_inited
) {
4187 slirp_vc
= qemu_new_vlan_client(vlan
,
4188 slirp_receive
, NULL
, NULL
);
4189 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4193 static void net_slirp_redir(const char *redir_str
)
4198 struct in_addr guest_addr
;
4199 int host_port
, guest_port
;
4201 if (!slirp_inited
) {
4207 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4209 if (!strcmp(buf
, "tcp")) {
4211 } else if (!strcmp(buf
, "udp")) {
4217 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4219 host_port
= strtol(buf
, &r
, 0);
4223 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4225 if (buf
[0] == '\0') {
4226 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4228 if (!inet_aton(buf
, &guest_addr
))
4231 guest_port
= strtol(p
, &r
, 0);
4235 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4236 fprintf(stderr
, "qemu: could not set up redirection\n");
4241 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4249 static void erase_dir(char *dir_name
)
4253 char filename
[1024];
4255 /* erase all the files in the directory */
4256 if ((d
= opendir(dir_name
)) != 0) {
4261 if (strcmp(de
->d_name
, ".") != 0 &&
4262 strcmp(de
->d_name
, "..") != 0) {
4263 snprintf(filename
, sizeof(filename
), "%s/%s",
4264 smb_dir
, de
->d_name
);
4265 if (unlink(filename
) != 0) /* is it a directory? */
4266 erase_dir(filename
);
4274 /* automatic user mode samba server configuration */
4275 static void smb_exit(void)
4280 /* automatic user mode samba server configuration */
4281 static void net_slirp_smb(const char *exported_dir
)
4283 char smb_conf
[1024];
4284 char smb_cmdline
[1024];
4287 if (!slirp_inited
) {
4292 /* XXX: better tmp dir construction */
4293 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4294 if (mkdir(smb_dir
, 0700) < 0) {
4295 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4298 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4300 f
= fopen(smb_conf
, "w");
4302 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4309 "socket address=127.0.0.1\n"
4310 "pid directory=%s\n"
4311 "lock directory=%s\n"
4312 "log file=%s/log.smbd\n"
4313 "smb passwd file=%s/smbpasswd\n"
4314 "security = share\n"
4329 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4330 SMBD_COMMAND
, smb_conf
);
4332 slirp_add_exec(0, smb_cmdline
, 4, 139);
4335 #endif /* !defined(_WIN32) */
4336 void do_info_slirp(void)
4341 #endif /* CONFIG_SLIRP */
4345 int tap_has_vnet_hdr(void *opaque
)
4350 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4354 #else /* !defined(_WIN32) */
4356 #ifndef IFF_VNET_HDR
4357 #define TAP_BUFSIZE 4096
4359 #include <linux/virtio_net.h>
4361 #define ETH_DATA_LEN 1500
4362 #define MAX_PACKET_LEN (ETH_HLEN + ETH_DATA_LEN)
4363 #define MAX_SKB_FRAGS ((65536/TARGET_PAGE_SIZE) + 2)
4364 #define TAP_BUFSIZE (sizeof(struct virtio_net_hdr) + MAX_PACKET_LEN + (MAX_SKB_FRAGS*TARGET_PAGE_SIZE))
4367 typedef struct TAPState
{
4368 VLANClientState
*vc
;
4370 char down_script
[1024];
4371 char buf
[TAP_BUFSIZE
];
4373 unsigned int has_vnet_hdr
: 1;
4374 unsigned int using_vnet_hdr
: 1;
4377 static ssize_t
tap_writev(void *opaque
, const struct iovec
*iov
,
4380 TAPState
*s
= opaque
;
4384 len
= writev(s
->fd
, iov
, iovcnt
);
4385 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4390 static ssize_t
tap_receive_iov(void *opaque
, const struct iovec
*iov
,
4394 TAPState
*s
= opaque
;
4396 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4397 struct iovec
*iov_copy
;
4398 struct virtio_net_hdr hdr
= { 0, };
4400 iov_copy
= alloca(sizeof(struct iovec
) * (iovcnt
+ 1));
4402 iov_copy
[0].iov_base
= &hdr
;
4403 iov_copy
[0].iov_len
= sizeof(hdr
);
4405 memcpy(&iov_copy
[1], iov
, sizeof(struct iovec
) * iovcnt
);
4407 return tap_writev(opaque
, iov_copy
, iovcnt
+ 1);
4411 return tap_writev(opaque
, iov
, iovcnt
);
4414 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4416 struct iovec iov
[2];
4420 TAPState
*s
= opaque
;
4421 struct virtio_net_hdr hdr
= { 0, };
4423 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4424 iov
[i
].iov_base
= &hdr
;
4425 iov
[i
].iov_len
= sizeof(hdr
);
4430 iov
[i
].iov_base
= (char *) buf
;
4431 iov
[i
].iov_len
= size
;
4434 tap_writev(opaque
, iov
, i
);
4437 static int tap_can_send(void *opaque
)
4439 TAPState
*s
= opaque
;
4440 VLANClientState
*vc
;
4441 int can_receive
= 0;
4443 /* Check to see if any of our clients can receive a packet */
4444 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4445 /* Skip ourselves */
4449 if (!vc
->fd_can_read
) {
4450 /* no fd_can_read handler, they always can receive */
4453 can_receive
= vc
->fd_can_read(vc
->opaque
);
4455 /* Once someone can receive, we try to send a packet */
4463 static int tap_send_packet(TAPState
*s
)
4465 uint8_t *buf
= s
->buf
;
4469 if (s
->has_vnet_hdr
&& !s
->using_vnet_hdr
) {
4470 buf
+= sizeof(struct virtio_net_hdr
);
4471 size
-= sizeof(struct virtio_net_hdr
);
4475 return qemu_send_packet(s
->vc
, buf
, size
);
4478 static void tap_send(void *opaque
)
4480 TAPState
*s
= opaque
;
4482 /* First try to send any buffered packet */
4486 /* If noone can receive the packet, buffer it */
4487 err
= tap_send_packet(s
);
4492 /* Read packets until we hit EAGAIN */
4497 sbuf
.maxlen
= sizeof(s
->buf
);
4499 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4502 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4506 if (s
->size
== -1 && errno
== EINTR
)
4512 /* If noone can receive the packet, buffer it */
4513 err
= tap_send_packet(s
);
4517 } while (s
->size
> 0);
4520 int tap_has_vnet_hdr(void *opaque
)
4522 VLANClientState
*vc
= opaque
;
4523 TAPState
*s
= vc
->opaque
;
4525 return s
? s
->has_vnet_hdr
: 0;
4528 void tap_using_vnet_hdr(void *opaque
, int using_vnet_hdr
)
4530 VLANClientState
*vc
= opaque
;
4531 TAPState
*s
= vc
->opaque
;
4533 if (!s
|| !s
->has_vnet_hdr
)
4536 s
->using_vnet_hdr
= using_vnet_hdr
!= 0;
4539 #ifdef TUNSETOFFLOAD
4540 static void tap_set_offload(VLANClientState
*vc
, int csum
, int tso4
, int tso6
,
4543 TAPState
*s
= vc
->opaque
;
4544 unsigned int offload
= 0;
4547 offload
|= TUN_F_CSUM
;
4549 offload
|= TUN_F_TSO4
;
4551 offload
|= TUN_F_TSO6
;
4552 if ((tso4
|| tso6
) && ecn
)
4553 offload
|= TUN_F_TSO_ECN
;
4556 if (ioctl(s
->fd
, TUNSETOFFLOAD
, offload
) != 0)
4557 fprintf(stderr
, "TUNSETOFFLOAD ioctl() failed: %s\n",
4560 #endif /* TUNSETOFFLOAD */
4564 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
, int vnet_hdr
)
4568 s
= qemu_mallocz(sizeof(TAPState
));
4572 s
->has_vnet_hdr
= vnet_hdr
!= 0;
4573 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4574 s
->vc
->fd_readv
= tap_receive_iov
;
4575 #ifdef TUNSETOFFLOAD
4576 s
->vc
->set_offload
= tap_set_offload
;
4578 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4579 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4583 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4584 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4590 TFR(fd
= open("/dev/tap", O_RDWR
));
4592 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4597 dev
= devname(s
.st_rdev
, S_IFCHR
);
4598 pstrcpy(ifname
, ifname_size
, dev
);
4600 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4603 #elif defined(__sun__)
4604 #define TUNNEWPPA (('T'<<16) | 0x0001)
4606 * Allocate TAP device, returns opened fd.
4607 * Stores dev name in the first arg(must be large enough).
4609 int tap_alloc(char *dev
)
4611 int tap_fd
, if_fd
, ppa
= -1;
4612 static int ip_fd
= 0;
4615 static int arp_fd
= 0;
4616 int ip_muxid
, arp_muxid
;
4617 struct strioctl strioc_if
, strioc_ppa
;
4618 int link_type
= I_PLINK
;;
4620 char actual_name
[32] = "";
4622 memset(&ifr
, 0x0, sizeof(ifr
));
4626 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4630 /* Check if IP device was opened */
4634 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4636 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4640 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4642 syslog(LOG_ERR
, "Can't open /dev/tap");
4646 /* Assign a new PPA and get its unit number. */
4647 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4648 strioc_ppa
.ic_timout
= 0;
4649 strioc_ppa
.ic_len
= sizeof(ppa
);
4650 strioc_ppa
.ic_dp
= (char *)&ppa
;
4651 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4652 syslog (LOG_ERR
, "Can't assign new interface");
4654 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4656 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4659 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4660 syslog(LOG_ERR
, "Can't push IP module");
4664 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4665 syslog(LOG_ERR
, "Can't get flags\n");
4667 snprintf (actual_name
, 32, "tap%d", ppa
);
4668 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4671 /* Assign ppa according to the unit number returned by tun device */
4673 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4674 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4675 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4676 syslog (LOG_ERR
, "Can't get flags\n");
4677 /* Push arp module to if_fd */
4678 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4679 syslog (LOG_ERR
, "Can't push ARP module (2)");
4681 /* Push arp module to ip_fd */
4682 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4683 syslog (LOG_ERR
, "I_POP failed\n");
4684 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4685 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4687 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4689 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4691 /* Set ifname to arp */
4692 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4693 strioc_if
.ic_timout
= 0;
4694 strioc_if
.ic_len
= sizeof(ifr
);
4695 strioc_if
.ic_dp
= (char *)&ifr
;
4696 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4697 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4700 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4701 syslog(LOG_ERR
, "Can't link TAP device to IP");
4705 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4706 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4710 memset(&ifr
, 0x0, sizeof(ifr
));
4711 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4712 ifr
.lifr_ip_muxid
= ip_muxid
;
4713 ifr
.lifr_arp_muxid
= arp_muxid
;
4715 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4717 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4718 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4719 syslog (LOG_ERR
, "Can't set multiplexor id");
4722 sprintf(dev
, "tap%d", ppa
);
4726 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4730 if( (fd
= tap_alloc(dev
)) < 0 ){
4731 fprintf(stderr
, "Cannot allocate TAP device\n");
4734 pstrcpy(ifname
, ifname_size
, dev
);
4735 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4739 static int tap_open(char *ifname
, int ifname_size
, int *vnet_hdr
)
4744 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4746 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4749 memset(&ifr
, 0, sizeof(ifr
));
4750 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4752 #if defined(TUNGETFEATURES) && defined(IFF_VNET_HDR)
4754 unsigned int features
;
4756 if (ioctl(fd
, TUNGETFEATURES
, &features
) == 0 &&
4757 features
& IFF_VNET_HDR
) {
4759 ifr
.ifr_flags
|= IFF_VNET_HDR
;
4764 if (ifname
[0] != '\0')
4765 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4767 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4768 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4770 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4774 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4775 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4780 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4786 /* try to launch network script */
4790 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4791 for (i
= 0; i
< open_max
; i
++)
4792 if (i
!= STDIN_FILENO
&&
4793 i
!= STDOUT_FILENO
&&
4794 i
!= STDERR_FILENO
&&
4799 *parg
++ = (char *)setup_script
;
4800 *parg
++ = (char *)ifname
;
4802 execv(setup_script
, args
);
4805 while (waitpid(pid
, &status
, 0) != pid
);
4806 if (!WIFEXITED(status
) ||
4807 WEXITSTATUS(status
) != 0) {
4808 fprintf(stderr
, "%s: could not launch network script\n",
4816 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4817 const char *setup_script
, const char *down_script
)
4824 if (ifname1
!= NULL
)
4825 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4829 TFR(fd
= tap_open(ifname
, sizeof(ifname
), &vnet_hdr
));
4833 if (!setup_script
|| !strcmp(setup_script
, "no"))
4835 if (setup_script
[0] != '\0') {
4836 if (launch_script(setup_script
, ifname
, fd
))
4839 s
= net_tap_fd_init(vlan
, fd
, vnet_hdr
);
4843 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4844 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4845 if (down_script
&& strcmp(down_script
, "no"))
4846 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4850 #endif /* !_WIN32 */
4852 #if defined(CONFIG_VDE)
4853 typedef struct VDEState
{
4854 VLANClientState
*vc
;
4858 static void vde_to_qemu(void *opaque
)
4860 VDEState
*s
= opaque
;
4864 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4866 qemu_send_packet(s
->vc
, buf
, size
);
4870 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4872 VDEState
*s
= opaque
;
4875 ret
= vde_send(s
->vde
, buf
, size
, 0);
4876 if (ret
< 0 && errno
== EINTR
) {
4883 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4884 const char *group
, int mode
)
4887 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4888 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4890 struct vde_open_args args
= {
4892 .group
= init_group
,
4896 s
= qemu_mallocz(sizeof(VDEState
));
4899 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4904 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4905 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4906 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4907 sock
, vde_datafd(s
->vde
));
4912 /* network connection */
4913 typedef struct NetSocketState
{
4914 VLANClientState
*vc
;
4916 int state
; /* 0 = getting length, 1 = getting data */
4920 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4923 typedef struct NetSocketListenState
{
4926 } NetSocketListenState
;
4928 /* XXX: we consider we can send the whole packet without blocking */
4929 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4931 NetSocketState
*s
= opaque
;
4935 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4936 send_all(s
->fd
, buf
, size
);
4939 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4941 NetSocketState
*s
= opaque
;
4942 sendto(s
->fd
, buf
, size
, 0,
4943 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4946 static void net_socket_send(void *opaque
)
4948 NetSocketState
*s
= opaque
;
4953 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4955 err
= socket_error();
4956 if (err
!= EWOULDBLOCK
)
4958 } else if (size
== 0) {
4959 /* end of connection */
4961 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4967 /* reassemble a packet from the network */
4973 memcpy(s
->buf
+ s
->index
, buf
, l
);
4977 if (s
->index
== 4) {
4979 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4985 l
= s
->packet_len
- s
->index
;
4988 memcpy(s
->buf
+ s
->index
, buf
, l
);
4992 if (s
->index
>= s
->packet_len
) {
4993 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
5002 static void net_socket_send_dgram(void *opaque
)
5004 NetSocketState
*s
= opaque
;
5007 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
5011 /* end of connection */
5012 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
5015 qemu_send_packet(s
->vc
, s
->buf
, size
);
5018 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
5023 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
5024 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
5025 inet_ntoa(mcastaddr
->sin_addr
),
5026 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
5030 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
5032 perror("socket(PF_INET, SOCK_DGRAM)");
5037 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
5038 (const char *)&val
, sizeof(val
));
5040 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
5044 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
5050 /* Add host to multicast group */
5051 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
5052 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
5054 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
5055 (const char *)&imr
, sizeof(struct ip_mreq
));
5057 perror("setsockopt(IP_ADD_MEMBERSHIP)");
5061 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
5063 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
5064 (const char *)&val
, sizeof(val
));
5066 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
5070 socket_set_nonblock(fd
);
5078 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
5081 struct sockaddr_in saddr
;
5083 socklen_t saddr_len
;
5086 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
5087 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
5088 * by ONLY ONE process: we must "clone" this dgram socket --jjo
5092 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
5094 if (saddr
.sin_addr
.s_addr
==0) {
5095 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
5099 /* clone dgram socket */
5100 newfd
= net_socket_mcast_create(&saddr
);
5102 /* error already reported by net_socket_mcast_create() */
5106 /* clone newfd to fd, close newfd */
5111 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
5112 fd
, strerror(errno
));
5117 s
= qemu_mallocz(sizeof(NetSocketState
));
5122 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
5123 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
5125 /* mcast: save bound address as dst */
5126 if (is_connected
) s
->dgram_dst
=saddr
;
5128 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5129 "socket: fd=%d (%s mcast=%s:%d)",
5130 fd
, is_connected
? "cloned" : "",
5131 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5135 static void net_socket_connect(void *opaque
)
5137 NetSocketState
*s
= opaque
;
5138 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5141 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5145 s
= qemu_mallocz(sizeof(NetSocketState
));
5149 s
->vc
= qemu_new_vlan_client(vlan
,
5150 net_socket_receive
, NULL
, s
);
5151 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5152 "socket: fd=%d", fd
);
5154 net_socket_connect(s
);
5156 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5161 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5164 int so_type
=-1, optlen
=sizeof(so_type
);
5166 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5167 (socklen_t
*)&optlen
)< 0) {
5168 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5173 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5175 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5177 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5178 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5179 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5184 static void net_socket_accept(void *opaque
)
5186 NetSocketListenState
*s
= opaque
;
5188 struct sockaddr_in saddr
;
5193 len
= sizeof(saddr
);
5194 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5195 if (fd
< 0 && errno
!= EINTR
) {
5197 } else if (fd
>= 0) {
5201 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5205 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5206 "socket: connection from %s:%d",
5207 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5211 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5213 NetSocketListenState
*s
;
5215 struct sockaddr_in saddr
;
5217 if (parse_host_port(&saddr
, host_str
) < 0)
5220 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5224 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5229 socket_set_nonblock(fd
);
5231 /* allow fast reuse */
5233 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5235 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5240 ret
= listen(fd
, 0);
5247 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5251 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5254 int fd
, connected
, ret
, err
;
5255 struct sockaddr_in saddr
;
5257 if (parse_host_port(&saddr
, host_str
) < 0)
5260 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5265 socket_set_nonblock(fd
);
5269 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5271 err
= socket_error();
5272 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5273 } else if (err
== EINPROGRESS
) {
5276 } else if (err
== WSAEALREADY
) {
5289 s
= net_socket_fd_init(vlan
, fd
, connected
);
5292 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5293 "socket: connect to %s:%d",
5294 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5298 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5302 struct sockaddr_in saddr
;
5304 if (parse_host_port(&saddr
, host_str
) < 0)
5308 fd
= net_socket_mcast_create(&saddr
);
5312 s
= net_socket_fd_init(vlan
, fd
, 0);
5316 s
->dgram_dst
= saddr
;
5318 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5319 "socket: mcast=%s:%d",
5320 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5325 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5330 while (*p
!= '\0' && *p
!= '=') {
5331 if (q
&& (q
- buf
) < buf_size
- 1)
5341 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5346 while (*p
!= '\0') {
5348 if (*(p
+ 1) != ',')
5352 if (q
&& (q
- buf
) < buf_size
- 1)
5362 int get_param_value(char *buf
, int buf_size
,
5363 const char *tag
, const char *str
)
5370 p
= get_opt_name(option
, sizeof(option
), p
);
5374 if (!strcmp(tag
, option
)) {
5375 (void)get_opt_value(buf
, buf_size
, p
);
5378 p
= get_opt_value(NULL
, 0, p
);
5387 int check_params(char *buf
, int buf_size
,
5388 char **params
, const char *str
)
5395 p
= get_opt_name(buf
, buf_size
, p
);
5399 for(i
= 0; params
[i
] != NULL
; i
++)
5400 if (!strcmp(params
[i
], buf
))
5402 if (params
[i
] == NULL
)
5404 p
= get_opt_value(NULL
, 0, p
);
5412 static int nic_get_free_idx(void)
5416 for (index
= 0; index
< MAX_NICS
; index
++)
5417 if (!nd_table
[index
].used
)
5422 int net_client_init(const char *device
, const char *p
)
5429 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5430 vlan_id
= strtol(buf
, NULL
, 0);
5432 vlan
= qemu_find_vlan(vlan_id
);
5434 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5437 if (!strcmp(device
, "nic")) {
5440 int idx
= nic_get_free_idx();
5442 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5443 fprintf(stderr
, "Too Many NICs\n");
5446 nd
= &nd_table
[idx
];
5447 macaddr
= nd
->macaddr
;
5453 macaddr
[5] = 0x56 + idx
;
5455 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5456 if (parse_macaddr(macaddr
, buf
) < 0) {
5457 fprintf(stderr
, "invalid syntax for ethernet address\n");
5461 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5462 nd
->model
= strdup(buf
);
5467 vlan
->nb_guest_devs
++;
5470 if (!strcmp(device
, "none")) {
5471 /* does nothing. It is needed to signal that no network cards
5476 if (!strcmp(device
, "user")) {
5477 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5478 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5480 vlan
->nb_host_devs
++;
5481 ret
= net_slirp_init(vlan
);
5485 if (!strcmp(device
, "tap")) {
5487 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5488 fprintf(stderr
, "tap: no interface name\n");
5491 vlan
->nb_host_devs
++;
5492 ret
= tap_win32_init(vlan
, ifname
);
5495 if (!strcmp(device
, "tap")) {
5497 char setup_script
[1024], down_script
[1024];
5499 vlan
->nb_host_devs
++;
5500 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5501 fd
= strtol(buf
, NULL
, 0);
5502 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5504 if (net_tap_fd_init(vlan
, fd
, 0))
5507 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5510 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5511 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5513 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5514 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5516 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5520 if (!strcmp(device
, "socket")) {
5521 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5523 fd
= strtol(buf
, NULL
, 0);
5525 if (net_socket_fd_init(vlan
, fd
, 1))
5527 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5528 ret
= net_socket_listen_init(vlan
, buf
);
5529 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5530 ret
= net_socket_connect_init(vlan
, buf
);
5531 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5532 ret
= net_socket_mcast_init(vlan
, buf
);
5534 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5537 vlan
->nb_host_devs
++;
5540 if (!strcmp(device
, "vde")) {
5541 char vde_sock
[1024], vde_group
[512];
5542 int vde_port
, vde_mode
;
5543 vlan
->nb_host_devs
++;
5544 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5547 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5548 vde_port
= strtol(buf
, NULL
, 10);
5552 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5553 vde_group
[0] = '\0';
5555 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5556 vde_mode
= strtol(buf
, NULL
, 8);
5560 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5564 fprintf(stderr
, "Unknown network device: %s\n", device
);
5568 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5574 void net_client_uninit(NICInfo
*nd
)
5576 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5579 free((void *)nd
->model
);
5582 static int net_client_parse(const char *str
)
5590 while (*p
!= '\0' && *p
!= ',') {
5591 if ((q
- device
) < sizeof(device
) - 1)
5599 return net_client_init(device
, p
);
5602 void do_info_network(void)
5605 VLANClientState
*vc
;
5607 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5608 term_printf("VLAN %d devices:\n", vlan
->id
);
5609 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5610 term_printf(" %s\n", vc
->info_str
);
5614 #define HD_ALIAS "index=%d,media=disk"
5616 #define CDROM_ALIAS "index=1,media=cdrom"
5618 #define CDROM_ALIAS "index=2,media=cdrom"
5620 #define FD_ALIAS "index=%d,if=floppy"
5621 #define PFLASH_ALIAS "if=pflash"
5622 #define MTD_ALIAS "if=mtd"
5623 #define SD_ALIAS "index=0,if=sd"
5625 static int drive_opt_get_free_idx(void)
5629 for (index
= 0; index
< MAX_DRIVES
; index
++)
5630 if (!drives_opt
[index
].used
) {
5631 drives_opt
[index
].used
= 1;
5638 static int drive_get_free_idx(void)
5642 for (index
= 0; index
< MAX_DRIVES
; index
++)
5643 if (!drives_table
[index
].used
) {
5644 drives_table
[index
].used
= 1;
5651 int drive_add(const char *file
, const char *fmt
, ...)
5654 int index
= drive_opt_get_free_idx();
5656 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5657 fprintf(stderr
, "qemu: too many drives\n");
5661 drives_opt
[index
].file
= file
;
5663 vsnprintf(drives_opt
[index
].opt
,
5664 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5671 void drive_remove(int index
)
5673 drives_opt
[index
].used
= 0;
5677 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5681 /* seek interface, bus and unit */
5683 for (index
= 0; index
< MAX_DRIVES
; index
++)
5684 if (drives_table
[index
].type
== type
&&
5685 drives_table
[index
].bus
== bus
&&
5686 drives_table
[index
].unit
== unit
&&
5687 drives_table
[index
].used
)
5693 int drive_get_max_bus(BlockInterfaceType type
)
5699 for (index
= 0; index
< nb_drives
; index
++) {
5700 if(drives_table
[index
].type
== type
&&
5701 drives_table
[index
].bus
> max_bus
)
5702 max_bus
= drives_table
[index
].bus
;
5707 static void bdrv_format_print(void *opaque
, const char *name
)
5709 fprintf(stderr
, " %s", name
);
5712 void drive_uninit(BlockDriverState
*bdrv
)
5716 for (i
= 0; i
< MAX_DRIVES
; i
++)
5717 if (drives_table
[i
].bdrv
== bdrv
) {
5718 drives_table
[i
].bdrv
= NULL
;
5719 drives_table
[i
].used
= 0;
5720 drive_remove(drives_table
[i
].drive_opt_idx
);
5726 int drive_init(struct drive_opt
*arg
, int snapshot
,
5727 QEMUMachine
*machine
)
5732 const char *mediastr
= "";
5733 BlockInterfaceType type
;
5734 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5735 int bus_id
, unit_id
;
5736 int cyls
, heads
, secs
, translation
;
5737 BlockDriverState
*bdrv
;
5738 BlockDriver
*drv
= NULL
;
5743 int drives_table_idx
;
5744 char *str
= arg
->opt
;
5745 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5746 "secs", "trans", "media", "snapshot", "file",
5747 "cache", "format", "boot", NULL
};
5749 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5750 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5756 cyls
= heads
= secs
= 0;
5759 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5763 if (!strcmp(machine
->name
, "realview") ||
5764 !strcmp(machine
->name
, "SS-5") ||
5765 !strcmp(machine
->name
, "SS-10") ||
5766 !strcmp(machine
->name
, "SS-600MP") ||
5767 !strcmp(machine
->name
, "versatilepb") ||
5768 !strcmp(machine
->name
, "versatileab")) {
5770 max_devs
= MAX_SCSI_DEVS
;
5771 strcpy(devname
, "scsi");
5774 max_devs
= MAX_IDE_DEVS
;
5775 strcpy(devname
, "ide");
5779 /* extract parameters */
5781 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5782 bus_id
= strtol(buf
, NULL
, 0);
5784 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5789 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5790 unit_id
= strtol(buf
, NULL
, 0);
5792 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5797 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5798 pstrcpy(devname
, sizeof(devname
), buf
);
5799 if (!strcmp(buf
, "ide")) {
5801 max_devs
= MAX_IDE_DEVS
;
5802 } else if (!strcmp(buf
, "scsi")) {
5804 max_devs
= MAX_SCSI_DEVS
;
5805 } else if (!strcmp(buf
, "floppy")) {
5808 } else if (!strcmp(buf
, "pflash")) {
5811 } else if (!strcmp(buf
, "mtd")) {
5814 } else if (!strcmp(buf
, "sd")) {
5817 } else if (!strcmp(buf
, "virtio")) {
5821 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5826 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5827 index
= strtol(buf
, NULL
, 0);
5829 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5834 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5835 cyls
= strtol(buf
, NULL
, 0);
5838 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5839 heads
= strtol(buf
, NULL
, 0);
5842 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5843 secs
= strtol(buf
, NULL
, 0);
5846 if (cyls
|| heads
|| secs
) {
5847 if (cyls
< 1 || cyls
> 16383) {
5848 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5851 if (heads
< 1 || heads
> 16) {
5852 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5855 if (secs
< 1 || secs
> 63) {
5856 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5861 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5864 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5868 if (!strcmp(buf
, "none"))
5869 translation
= BIOS_ATA_TRANSLATION_NONE
;
5870 else if (!strcmp(buf
, "lba"))
5871 translation
= BIOS_ATA_TRANSLATION_LBA
;
5872 else if (!strcmp(buf
, "auto"))
5873 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5875 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5880 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5881 if (!strcmp(buf
, "disk")) {
5883 } else if (!strcmp(buf
, "cdrom")) {
5884 if (cyls
|| secs
|| heads
) {
5886 "qemu: '%s' invalid physical CHS format\n", str
);
5889 media
= MEDIA_CDROM
;
5891 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5896 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5897 if (!strcmp(buf
, "on"))
5899 else if (!strcmp(buf
, "off"))
5902 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5907 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5908 if (!strcmp(buf
, "off"))
5910 else if (!strcmp(buf
, "on"))
5913 fprintf(stderr
, "qemu: invalid cache option\n");
5918 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5919 if (strcmp(buf
, "?") == 0) {
5920 fprintf(stderr
, "qemu: Supported formats:");
5921 bdrv_iterate_format(bdrv_format_print
, NULL
);
5922 fprintf(stderr
, "\n");
5925 drv
= bdrv_find_format(buf
);
5927 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5932 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5933 if (!strcmp(buf
, "on")) {
5934 if (extboot_drive
!= -1) {
5935 fprintf(stderr
, "qemu: two bootable drives specified\n");
5938 extboot_drive
= nb_drives
;
5939 } else if (strcmp(buf
, "off")) {
5940 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5945 if (arg
->file
== NULL
)
5946 get_param_value(file
, sizeof(file
), "file", str
);
5948 pstrcpy(file
, sizeof(file
), arg
->file
);
5950 /* compute bus and unit according index */
5953 if (bus_id
!= 0 || unit_id
!= -1) {
5955 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5963 unit_id
= index
% max_devs
;
5964 bus_id
= index
/ max_devs
;
5968 /* if user doesn't specify a unit_id,
5969 * try to find the first free
5972 if (unit_id
== -1) {
5974 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5976 if (max_devs
&& unit_id
>= max_devs
) {
5977 unit_id
-= max_devs
;
5985 if (max_devs
&& unit_id
>= max_devs
) {
5986 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5987 str
, unit_id
, max_devs
- 1);
5992 * ignore multiple definitions
5995 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
6000 if (type
== IF_IDE
|| type
== IF_SCSI
)
6001 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
6003 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
6004 devname
, bus_id
, mediastr
, unit_id
);
6006 snprintf(buf
, sizeof(buf
), "%s%s%i",
6007 devname
, mediastr
, unit_id
);
6008 bdrv
= bdrv_new(buf
);
6009 drives_table_idx
= drive_get_free_idx();
6010 drives_table
[drives_table_idx
].bdrv
= bdrv
;
6011 drives_table
[drives_table_idx
].type
= type
;
6012 drives_table
[drives_table_idx
].bus
= bus_id
;
6013 drives_table
[drives_table_idx
].unit
= unit_id
;
6014 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
6023 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
6024 bdrv_set_translation_hint(bdrv
, translation
);
6028 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
6033 /* FIXME: This isn't really a floppy, but it's a reasonable
6036 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
6047 bdrv_flags
|= BDRV_O_SNAPSHOT
;
6049 bdrv_flags
|= BDRV_O_DIRECT
;
6050 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
6051 fprintf(stderr
, "qemu: could not open disk image %s\n",
6055 return drives_table_idx
;
6058 /***********************************************************/
6061 static USBPort
*used_usb_ports
;
6062 static USBPort
*free_usb_ports
;
6064 /* ??? Maybe change this to register a hub to keep track of the topology. */
6065 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
6066 usb_attachfn attach
)
6068 port
->opaque
= opaque
;
6069 port
->index
= index
;
6070 port
->attach
= attach
;
6071 port
->next
= free_usb_ports
;
6072 free_usb_ports
= port
;
6075 static int usb_device_add(const char *devname
)
6081 if (!free_usb_ports
)
6084 if (strstart(devname
, "host:", &p
)) {
6085 dev
= usb_host_device_open(p
);
6086 } else if (!strcmp(devname
, "mouse")) {
6087 dev
= usb_mouse_init();
6088 } else if (!strcmp(devname
, "tablet")) {
6089 dev
= usb_tablet_init();
6090 } else if (!strcmp(devname
, "keyboard")) {
6091 dev
= usb_keyboard_init();
6092 } else if (strstart(devname
, "disk:", &p
)) {
6093 dev
= usb_msd_init(p
);
6094 } else if (!strcmp(devname
, "wacom-tablet")) {
6095 dev
= usb_wacom_init();
6096 } else if (strstart(devname
, "serial:", &p
)) {
6097 dev
= usb_serial_init(p
);
6098 #ifdef CONFIG_BRLAPI
6099 } else if (!strcmp(devname
, "braille")) {
6100 dev
= usb_baum_init();
6102 } else if (strstart(devname
, "net:", &p
)) {
6105 if (net_client_init("nic", p
) < 0)
6107 nd_table
[nic
].model
= "usb";
6108 dev
= usb_net_init(&nd_table
[nic
]);
6115 /* Find a USB port to add the device to. */
6116 port
= free_usb_ports
;
6120 /* Create a new hub and chain it on. */
6121 free_usb_ports
= NULL
;
6122 port
->next
= used_usb_ports
;
6123 used_usb_ports
= port
;
6125 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
6126 usb_attach(port
, hub
);
6127 port
= free_usb_ports
;
6130 free_usb_ports
= port
->next
;
6131 port
->next
= used_usb_ports
;
6132 used_usb_ports
= port
;
6133 usb_attach(port
, dev
);
6137 static int usb_device_del(const char *devname
)
6145 if (!used_usb_ports
)
6148 p
= strchr(devname
, '.');
6151 bus_num
= strtoul(devname
, NULL
, 0);
6152 addr
= strtoul(p
+ 1, NULL
, 0);
6156 lastp
= &used_usb_ports
;
6157 port
= used_usb_ports
;
6158 while (port
&& port
->dev
->addr
!= addr
) {
6159 lastp
= &port
->next
;
6167 *lastp
= port
->next
;
6168 usb_attach(port
, NULL
);
6169 dev
->handle_destroy(dev
);
6170 port
->next
= free_usb_ports
;
6171 free_usb_ports
= port
;
6175 void do_usb_add(const char *devname
)
6178 ret
= usb_device_add(devname
);
6180 term_printf("Could not add USB device '%s'\n", devname
);
6183 void do_usb_del(const char *devname
)
6186 ret
= usb_device_del(devname
);
6188 term_printf("Could not remove USB device '%s'\n", devname
);
6195 const char *speed_str
;
6198 term_printf("USB support not enabled\n");
6202 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6206 switch(dev
->speed
) {
6210 case USB_SPEED_FULL
:
6213 case USB_SPEED_HIGH
:
6220 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6221 0, dev
->addr
, speed_str
, dev
->devname
);
6225 /***********************************************************/
6226 /* PCMCIA/Cardbus */
6228 static struct pcmcia_socket_entry_s
{
6229 struct pcmcia_socket_s
*socket
;
6230 struct pcmcia_socket_entry_s
*next
;
6231 } *pcmcia_sockets
= 0;
6233 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6235 struct pcmcia_socket_entry_s
*entry
;
6237 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6238 entry
->socket
= socket
;
6239 entry
->next
= pcmcia_sockets
;
6240 pcmcia_sockets
= entry
;
6243 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6245 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6247 ptr
= &pcmcia_sockets
;
6248 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6249 if (entry
->socket
== socket
) {
6255 void pcmcia_info(void)
6257 struct pcmcia_socket_entry_s
*iter
;
6258 if (!pcmcia_sockets
)
6259 term_printf("No PCMCIA sockets\n");
6261 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6262 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6263 iter
->socket
->attached
? iter
->socket
->card_string
:
6267 /***********************************************************/
6270 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6274 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6278 static void dumb_refresh(DisplayState
*ds
)
6280 #if defined(CONFIG_SDL)
6285 static void dumb_display_init(DisplayState
*ds
)
6290 ds
->dpy_update
= dumb_update
;
6291 ds
->dpy_resize
= dumb_resize
;
6292 ds
->dpy_refresh
= dumb_refresh
;
6295 /***********************************************************/
6298 #define MAX_IO_HANDLERS 64
6300 typedef struct IOHandlerRecord
{
6302 IOCanRWHandler
*fd_read_poll
;
6304 IOHandler
*fd_write
;
6307 /* temporary data */
6309 struct IOHandlerRecord
*next
;
6312 static IOHandlerRecord
*first_io_handler
;
6314 /* XXX: fd_read_poll should be suppressed, but an API change is
6315 necessary in the character devices to suppress fd_can_read(). */
6316 int qemu_set_fd_handler2(int fd
,
6317 IOCanRWHandler
*fd_read_poll
,
6319 IOHandler
*fd_write
,
6322 IOHandlerRecord
**pioh
, *ioh
;
6324 if (!fd_read
&& !fd_write
) {
6325 pioh
= &first_io_handler
;
6330 if (ioh
->fd
== fd
) {
6337 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6341 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6344 ioh
->next
= first_io_handler
;
6345 first_io_handler
= ioh
;
6348 ioh
->fd_read_poll
= fd_read_poll
;
6349 ioh
->fd_read
= fd_read
;
6350 ioh
->fd_write
= fd_write
;
6351 ioh
->opaque
= opaque
;
6358 int qemu_set_fd_handler(int fd
,
6360 IOHandler
*fd_write
,
6363 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6366 /***********************************************************/
6367 /* Polling handling */
6369 typedef struct PollingEntry
{
6372 struct PollingEntry
*next
;
6375 static PollingEntry
*first_polling_entry
;
6377 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6379 PollingEntry
**ppe
, *pe
;
6380 pe
= qemu_mallocz(sizeof(PollingEntry
));
6384 pe
->opaque
= opaque
;
6385 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6390 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6392 PollingEntry
**ppe
, *pe
;
6393 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6395 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6404 /***********************************************************/
6405 /* Wait objects support */
6406 typedef struct WaitObjects
{
6408 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6409 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6410 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6413 static WaitObjects wait_objects
= {0};
6415 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6417 WaitObjects
*w
= &wait_objects
;
6419 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6421 w
->events
[w
->num
] = handle
;
6422 w
->func
[w
->num
] = func
;
6423 w
->opaque
[w
->num
] = opaque
;
6428 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6431 WaitObjects
*w
= &wait_objects
;
6434 for (i
= 0; i
< w
->num
; i
++) {
6435 if (w
->events
[i
] == handle
)
6438 w
->events
[i
] = w
->events
[i
+ 1];
6439 w
->func
[i
] = w
->func
[i
+ 1];
6440 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6448 #define SELF_ANNOUNCE_ROUNDS 5
6449 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6450 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6451 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6453 static int announce_self_create(uint8_t *buf
,
6456 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6457 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6459 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6461 memset(buf
, 0xff, 6); /* h_dst */
6462 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6463 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6464 memcpy(buf
+ 14, &magic
, 4); /* magic */
6466 return 18; /* len */
6469 static void qemu_announce_self(void)
6473 VLANClientState
*vc
;
6476 for (i
= 0; i
< nb_nics
; i
++) {
6477 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6478 vlan
= nd_table
[i
].vlan
;
6479 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6480 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6481 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6482 vc
->fd_read(vc
->opaque
, buf
, len
);
6487 /***********************************************************/
6488 /* savevm/loadvm support */
6490 #define IO_BUF_SIZE 32768
6493 QEMUFilePutBufferFunc
*put_buffer
;
6494 QEMUFileGetBufferFunc
*get_buffer
;
6495 QEMUFileCloseFunc
*close
;
6498 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6501 int buf_size
; /* 0 when writing */
6502 uint8_t buf
[IO_BUF_SIZE
];
6505 typedef struct QEMUFileFD
6510 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6512 QEMUFileFD
*s
= opaque
;
6517 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6519 if (errno
== EINTR
|| errno
== EAGAIN
)
6526 QEMUFile
*qemu_fopen_fd(int fd
)
6528 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6530 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6533 typedef struct QEMUFileUnix
6538 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6540 QEMUFileUnix
*s
= opaque
;
6541 fseek(s
->outfile
, pos
, SEEK_SET
);
6542 fwrite(buf
, 1, size
, s
->outfile
);
6545 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6547 QEMUFileUnix
*s
= opaque
;
6548 fseek(s
->outfile
, pos
, SEEK_SET
);
6549 return fread(buf
, 1, size
, s
->outfile
);
6552 static void file_close(void *opaque
)
6554 QEMUFileUnix
*s
= opaque
;
6559 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6563 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6567 s
->outfile
= fopen(filename
, mode
);
6571 if (!strcmp(mode
, "wb"))
6572 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6573 else if (!strcmp(mode
, "rb"))
6574 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6583 typedef struct QEMUFileBdrv
6585 BlockDriverState
*bs
;
6586 int64_t base_offset
;
6589 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6591 QEMUFileBdrv
*s
= opaque
;
6592 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6595 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6597 QEMUFileBdrv
*s
= opaque
;
6598 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6601 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6605 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6610 s
->base_offset
= offset
;
6613 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6615 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6618 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6619 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6623 f
= qemu_mallocz(sizeof(QEMUFile
));
6628 f
->put_buffer
= put_buffer
;
6629 f
->get_buffer
= get_buffer
;
6635 void qemu_fflush(QEMUFile
*f
)
6640 if (f
->buf_index
> 0) {
6641 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6642 f
->buf_offset
+= f
->buf_index
;
6647 static void qemu_fill_buffer(QEMUFile
*f
)
6654 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6660 f
->buf_offset
+= len
;
6663 void qemu_fclose(QEMUFile
*f
)
6667 f
->close(f
->opaque
);
6671 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6675 l
= IO_BUF_SIZE
- f
->buf_index
;
6678 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6682 if (f
->buf_index
>= IO_BUF_SIZE
)
6687 void qemu_put_byte(QEMUFile
*f
, int v
)
6689 f
->buf
[f
->buf_index
++] = v
;
6690 if (f
->buf_index
>= IO_BUF_SIZE
)
6694 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6700 l
= f
->buf_size
- f
->buf_index
;
6702 qemu_fill_buffer(f
);
6703 l
= f
->buf_size
- f
->buf_index
;
6709 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6714 return size1
- size
;
6717 int qemu_get_byte(QEMUFile
*f
)
6719 if (f
->buf_index
>= f
->buf_size
) {
6720 qemu_fill_buffer(f
);
6721 if (f
->buf_index
>= f
->buf_size
)
6724 return f
->buf
[f
->buf_index
++];
6727 int64_t qemu_ftell(QEMUFile
*f
)
6729 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6732 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6734 if (whence
== SEEK_SET
) {
6736 } else if (whence
== SEEK_CUR
) {
6737 pos
+= qemu_ftell(f
);
6739 /* SEEK_END not supported */
6742 if (f
->put_buffer
) {
6744 f
->buf_offset
= pos
;
6746 f
->buf_offset
= pos
;
6753 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6755 qemu_put_byte(f
, v
>> 8);
6756 qemu_put_byte(f
, v
);
6759 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6761 qemu_put_byte(f
, v
>> 24);
6762 qemu_put_byte(f
, v
>> 16);
6763 qemu_put_byte(f
, v
>> 8);
6764 qemu_put_byte(f
, v
);
6767 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6769 qemu_put_be32(f
, v
>> 32);
6770 qemu_put_be32(f
, v
);
6773 unsigned int qemu_get_be16(QEMUFile
*f
)
6776 v
= qemu_get_byte(f
) << 8;
6777 v
|= qemu_get_byte(f
);
6781 unsigned int qemu_get_be32(QEMUFile
*f
)
6784 v
= qemu_get_byte(f
) << 24;
6785 v
|= qemu_get_byte(f
) << 16;
6786 v
|= qemu_get_byte(f
) << 8;
6787 v
|= qemu_get_byte(f
);
6791 uint64_t qemu_get_be64(QEMUFile
*f
)
6794 v
= (uint64_t)qemu_get_be32(f
) << 32;
6795 v
|= qemu_get_be32(f
);
6799 typedef struct SaveStateEntry
{
6803 SaveStateHandler
*save_state
;
6804 LoadStateHandler
*load_state
;
6806 struct SaveStateEntry
*next
;
6809 static SaveStateEntry
*first_se
;
6811 /* TODO: Individual devices generally have very little idea about the rest
6812 of the system, so instance_id should be removed/replaced.
6813 Meanwhile pass -1 as instance_id if you do not already have a clearly
6814 distinguishing id for all instances of your device class. */
6815 int register_savevm(const char *idstr
,
6818 SaveStateHandler
*save_state
,
6819 LoadStateHandler
*load_state
,
6822 SaveStateEntry
*se
, **pse
;
6824 se
= qemu_malloc(sizeof(SaveStateEntry
));
6827 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6828 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6829 se
->version_id
= version_id
;
6830 se
->save_state
= save_state
;
6831 se
->load_state
= load_state
;
6832 se
->opaque
= opaque
;
6835 /* add at the end of list */
6837 while (*pse
!= NULL
) {
6838 if (instance_id
== -1
6839 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6840 && se
->instance_id
<= (*pse
)->instance_id
)
6841 se
->instance_id
= (*pse
)->instance_id
+ 1;
6842 pse
= &(*pse
)->next
;
6848 #define QEMU_VM_FILE_MAGIC 0x5145564d
6849 #define QEMU_VM_FILE_VERSION 0x00000002
6851 static int qemu_savevm_state(QEMUFile
*f
)
6855 int64_t cur_pos
, len_pos
, total_len_pos
;
6857 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6858 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6859 total_len_pos
= qemu_ftell(f
);
6860 qemu_put_be64(f
, 0); /* total size */
6862 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6863 if (se
->save_state
== NULL
)
6864 /* this one has a loader only, for backwards compatibility */
6868 len
= strlen(se
->idstr
);
6869 qemu_put_byte(f
, len
);
6870 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6872 qemu_put_be32(f
, se
->instance_id
);
6873 qemu_put_be32(f
, se
->version_id
);
6875 /* record size: filled later */
6876 len_pos
= qemu_ftell(f
);
6877 qemu_put_be32(f
, 0);
6878 se
->save_state(f
, se
->opaque
);
6880 /* fill record size */
6881 cur_pos
= qemu_ftell(f
);
6882 len
= cur_pos
- len_pos
- 4;
6883 qemu_fseek(f
, len_pos
, SEEK_SET
);
6884 qemu_put_be32(f
, len
);
6885 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6887 cur_pos
= qemu_ftell(f
);
6888 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6889 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6890 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6896 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6900 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6901 if (!strcmp(se
->idstr
, idstr
) &&
6902 instance_id
== se
->instance_id
)
6908 static int qemu_loadvm_state(QEMUFile
*f
)
6911 int len
, ret
, instance_id
, record_len
, version_id
;
6912 int64_t total_len
, end_pos
, cur_pos
;
6916 v
= qemu_get_be32(f
);
6917 if (v
!= QEMU_VM_FILE_MAGIC
)
6919 v
= qemu_get_be32(f
);
6920 if (v
!= QEMU_VM_FILE_VERSION
) {
6925 total_len
= qemu_get_be64(f
);
6926 end_pos
= total_len
+ qemu_ftell(f
);
6928 if (qemu_ftell(f
) >= end_pos
)
6930 len
= qemu_get_byte(f
);
6931 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6933 instance_id
= qemu_get_be32(f
);
6934 version_id
= qemu_get_be32(f
);
6935 record_len
= qemu_get_be32(f
);
6937 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6938 idstr
, instance_id
, version_id
, record_len
);
6940 cur_pos
= qemu_ftell(f
);
6941 se
= find_se(idstr
, instance_id
);
6943 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6944 instance_id
, idstr
);
6946 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6948 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6949 instance_id
, idstr
);
6953 /* always seek to exact end of record */
6954 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6961 int qemu_live_savevm_state(QEMUFile
*f
)
6966 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6967 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6969 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6970 len
= strlen(se
->idstr
);
6972 qemu_put_byte(f
, len
);
6973 qemu_put_buffer(f
, se
->idstr
, len
);
6974 qemu_put_be32(f
, se
->instance_id
);
6975 qemu_put_be32(f
, se
->version_id
);
6977 se
->save_state(f
, se
->opaque
);
6980 qemu_put_byte(f
, 0);
6986 int qemu_live_loadvm_state(QEMUFile
*f
)
6989 int len
, ret
, instance_id
, version_id
;
6993 v
= qemu_get_be32(f
);
6994 if (v
!= QEMU_VM_FILE_MAGIC
)
6996 v
= qemu_get_be32(f
);
6997 if (v
!= QEMU_VM_FILE_VERSION
) {
7004 len
= qemu_get_byte(f
);
7007 qemu_get_buffer(f
, idstr
, len
);
7009 instance_id
= qemu_get_be32(f
);
7010 version_id
= qemu_get_be32(f
);
7011 se
= find_se(idstr
, instance_id
);
7013 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
7014 instance_id
, idstr
);
7016 if (version_id
> se
->version_id
) { /* src version > dst version */
7017 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
7018 idstr
, version_id
, se
->version_id
);
7022 ret
= se
->load_state(f
, se
->opaque
, version_id
);
7024 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
7025 instance_id
, idstr
);
7032 qemu_announce_self();
7038 /* device can contain snapshots */
7039 static int bdrv_can_snapshot(BlockDriverState
*bs
)
7042 !bdrv_is_removable(bs
) &&
7043 !bdrv_is_read_only(bs
));
7046 /* device must be snapshots in order to have a reliable snapshot */
7047 static int bdrv_has_snapshot(BlockDriverState
*bs
)
7050 !bdrv_is_removable(bs
) &&
7051 !bdrv_is_read_only(bs
));
7054 static BlockDriverState
*get_bs_snapshots(void)
7056 BlockDriverState
*bs
;
7060 return bs_snapshots
;
7061 for(i
= 0; i
<= nb_drives
; i
++) {
7062 bs
= drives_table
[i
].bdrv
;
7063 if (bdrv_can_snapshot(bs
))
7072 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
7075 QEMUSnapshotInfo
*sn_tab
, *sn
;
7079 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7082 for(i
= 0; i
< nb_sns
; i
++) {
7084 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
7094 void do_savevm(const char *name
)
7096 BlockDriverState
*bs
, *bs1
;
7097 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
7098 int must_delete
, ret
, i
;
7099 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7101 int saved_vm_running
;
7108 bs
= get_bs_snapshots();
7110 term_printf("No block device can accept snapshots\n");
7114 /* ??? Should this occur after vm_stop? */
7117 saved_vm_running
= vm_running
;
7122 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
7127 memset(sn
, 0, sizeof(*sn
));
7129 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
7130 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
7133 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
7136 /* fill auxiliary fields */
7139 sn
->date_sec
= tb
.time
;
7140 sn
->date_nsec
= tb
.millitm
* 1000000;
7142 gettimeofday(&tv
, NULL
);
7143 sn
->date_sec
= tv
.tv_sec
;
7144 sn
->date_nsec
= tv
.tv_usec
* 1000;
7146 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7148 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7149 term_printf("Device %s does not support VM state snapshots\n",
7150 bdrv_get_device_name(bs
));
7154 /* save the VM state */
7155 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7157 term_printf("Could not open VM state file\n");
7160 ret
= qemu_savevm_state(f
);
7161 sn
->vm_state_size
= qemu_ftell(f
);
7164 term_printf("Error %d while writing VM\n", ret
);
7168 /* create the snapshots */
7170 for(i
= 0; i
< nb_drives
; i
++) {
7171 bs1
= drives_table
[i
].bdrv
;
7172 if (bdrv_has_snapshot(bs1
)) {
7174 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7176 term_printf("Error while deleting snapshot on '%s'\n",
7177 bdrv_get_device_name(bs1
));
7180 ret
= bdrv_snapshot_create(bs1
, sn
);
7182 term_printf("Error while creating snapshot on '%s'\n",
7183 bdrv_get_device_name(bs1
));
7189 if (saved_vm_running
)
7193 void do_loadvm(const char *name
)
7195 BlockDriverState
*bs
, *bs1
;
7196 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7199 int saved_vm_running
;
7201 bs
= get_bs_snapshots();
7203 term_printf("No block device supports snapshots\n");
7207 /* Flush all IO requests so they don't interfere with the new state. */
7210 saved_vm_running
= vm_running
;
7213 for(i
= 0; i
<= nb_drives
; i
++) {
7214 bs1
= drives_table
[i
].bdrv
;
7215 if (bdrv_has_snapshot(bs1
)) {
7216 ret
= bdrv_snapshot_goto(bs1
, name
);
7219 term_printf("Warning: ");
7222 term_printf("Snapshots not supported on device '%s'\n",
7223 bdrv_get_device_name(bs1
));
7226 term_printf("Could not find snapshot '%s' on device '%s'\n",
7227 name
, bdrv_get_device_name(bs1
));
7230 term_printf("Error %d while activating snapshot on '%s'\n",
7231 ret
, bdrv_get_device_name(bs1
));
7234 /* fatal on snapshot block device */
7241 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7242 term_printf("Device %s does not support VM state snapshots\n",
7243 bdrv_get_device_name(bs
));
7247 /* restore the VM state */
7248 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7250 term_printf("Could not open VM state file\n");
7253 ret
= qemu_loadvm_state(f
);
7256 term_printf("Error %d while loading VM state\n", ret
);
7259 if (saved_vm_running
)
7263 void do_delvm(const char *name
)
7265 BlockDriverState
*bs
, *bs1
;
7268 bs
= get_bs_snapshots();
7270 term_printf("No block device supports snapshots\n");
7274 for(i
= 0; i
<= nb_drives
; i
++) {
7275 bs1
= drives_table
[i
].bdrv
;
7276 if (bdrv_has_snapshot(bs1
)) {
7277 ret
= bdrv_snapshot_delete(bs1
, name
);
7279 if (ret
== -ENOTSUP
)
7280 term_printf("Snapshots not supported on device '%s'\n",
7281 bdrv_get_device_name(bs1
));
7283 term_printf("Error %d while deleting snapshot on '%s'\n",
7284 ret
, bdrv_get_device_name(bs1
));
7290 void do_info_snapshots(void)
7292 BlockDriverState
*bs
, *bs1
;
7293 QEMUSnapshotInfo
*sn_tab
, *sn
;
7297 bs
= get_bs_snapshots();
7299 term_printf("No available block device supports snapshots\n");
7302 term_printf("Snapshot devices:");
7303 for(i
= 0; i
<= nb_drives
; i
++) {
7304 bs1
= drives_table
[i
].bdrv
;
7305 if (bdrv_has_snapshot(bs1
)) {
7307 term_printf(" %s", bdrv_get_device_name(bs1
));
7312 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7314 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7317 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7318 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7319 for(i
= 0; i
< nb_sns
; i
++) {
7321 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7326 /***********************************************************/
7327 /* ram save/restore */
7329 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7333 v
= qemu_get_byte(f
);
7336 if (qemu_get_buffer(f
, buf
, len
) != len
)
7340 v
= qemu_get_byte(f
);
7341 memset(buf
, v
, len
);
7349 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7354 if (qemu_get_be32(f
) != phys_ram_size
)
7356 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7357 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7359 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7366 #define BDRV_HASH_BLOCK_SIZE 1024
7367 #define IOBUF_SIZE 4096
7368 #define RAM_CBLOCK_MAGIC 0xfabe
7370 typedef struct RamCompressState
{
7373 uint8_t buf
[IOBUF_SIZE
];
7376 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7379 memset(s
, 0, sizeof(*s
));
7381 ret
= deflateInit2(&s
->zstream
, 1,
7383 9, Z_DEFAULT_STRATEGY
);
7386 s
->zstream
.avail_out
= IOBUF_SIZE
;
7387 s
->zstream
.next_out
= s
->buf
;
7391 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7393 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7394 qemu_put_be16(s
->f
, len
);
7395 qemu_put_buffer(s
->f
, buf
, len
);
7398 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7402 s
->zstream
.avail_in
= len
;
7403 s
->zstream
.next_in
= (uint8_t *)buf
;
7404 while (s
->zstream
.avail_in
> 0) {
7405 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7408 if (s
->zstream
.avail_out
== 0) {
7409 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7410 s
->zstream
.avail_out
= IOBUF_SIZE
;
7411 s
->zstream
.next_out
= s
->buf
;
7417 static void ram_compress_close(RamCompressState
*s
)
7421 /* compress last bytes */
7423 ret
= deflate(&s
->zstream
, Z_FINISH
);
7424 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7425 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7427 ram_put_cblock(s
, s
->buf
, len
);
7429 s
->zstream
.avail_out
= IOBUF_SIZE
;
7430 s
->zstream
.next_out
= s
->buf
;
7431 if (ret
== Z_STREAM_END
)
7438 deflateEnd(&s
->zstream
);
7441 typedef struct RamDecompressState
{
7444 uint8_t buf
[IOBUF_SIZE
];
7445 } RamDecompressState
;
7447 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7450 memset(s
, 0, sizeof(*s
));
7452 ret
= inflateInit(&s
->zstream
);
7458 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7462 s
->zstream
.avail_out
= len
;
7463 s
->zstream
.next_out
= buf
;
7464 while (s
->zstream
.avail_out
> 0) {
7465 if (s
->zstream
.avail_in
== 0) {
7466 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7468 clen
= qemu_get_be16(s
->f
);
7469 if (clen
> IOBUF_SIZE
)
7471 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7472 s
->zstream
.avail_in
= clen
;
7473 s
->zstream
.next_in
= s
->buf
;
7475 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7476 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7483 static void ram_decompress_close(RamDecompressState
*s
)
7485 inflateEnd(&s
->zstream
);
7488 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7492 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7493 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7495 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7496 qemu_put_be32(f
, addr
);
7497 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7500 qemu_put_be32(f
, 1);
7503 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7506 RamCompressState s1
, *s
= &s1
;
7509 qemu_put_be32(f
, phys_ram_size
);
7510 if (ram_compress_open(s
, f
) < 0)
7512 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7513 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7516 if (tight_savevm_enabled
) {
7520 /* find if the memory block is available on a virtual
7523 for(j
= 0; j
< nb_drives
; j
++) {
7524 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7526 BDRV_HASH_BLOCK_SIZE
);
7527 if (sector_num
>= 0)
7531 goto normal_compress
;
7534 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7535 ram_compress_buf(s
, buf
, 10);
7541 ram_compress_buf(s
, buf
, 1);
7542 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7545 ram_compress_close(s
);
7548 static void ram_save(QEMUFile
*f
, void *opaque
)
7550 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7552 qemu_put_byte(f
, in_migration
);
7555 ram_save_live(f
, opaque
);
7557 ram_save_static(f
, opaque
);
7560 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7565 addr
= qemu_get_be32(f
);
7569 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7575 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7577 RamDecompressState s1
, *s
= &s1
;
7581 if (qemu_get_be32(f
) != phys_ram_size
)
7583 if (ram_decompress_open(s
, f
) < 0)
7585 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7586 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7588 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7589 fprintf(stderr
, "Error while reading ram block header\n");
7593 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7594 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7603 ram_decompress_buf(s
, buf
+ 1, 9);
7605 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7606 if (bs_index
>= nb_drives
) {
7607 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7610 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7612 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7613 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7614 bs_index
, sector_num
);
7621 printf("Error block header\n");
7625 ram_decompress_close(s
);
7629 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7633 switch (version_id
) {
7635 ret
= ram_load_v1(f
, opaque
);
7638 if (qemu_get_byte(f
)) {
7639 ret
= ram_load_live(f
, opaque
);
7643 ret
= ram_load_static(f
, opaque
);
7653 /***********************************************************/
7654 /* bottom halves (can be seen as timers which expire ASAP) */
7663 static QEMUBH
*first_bh
= NULL
;
7665 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7668 bh
= qemu_mallocz(sizeof(QEMUBH
));
7672 bh
->opaque
= opaque
;
7676 int qemu_bh_poll(void)
7695 void qemu_bh_schedule(QEMUBH
*bh
)
7697 CPUState
*env
= cpu_single_env
;
7701 bh
->next
= first_bh
;
7704 /* stop the currently executing CPU to execute the BH ASAP */
7706 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7711 void qemu_bh_cancel(QEMUBH
*bh
)
7714 if (bh
->scheduled
) {
7717 pbh
= &(*pbh
)->next
;
7723 void qemu_bh_delete(QEMUBH
*bh
)
7729 /***********************************************************/
7730 /* machine registration */
7732 QEMUMachine
*first_machine
= NULL
;
7733 QEMUMachine
*current_machine
= NULL
;
7735 int qemu_register_machine(QEMUMachine
*m
)
7738 pm
= &first_machine
;
7746 static QEMUMachine
*find_machine(const char *name
)
7750 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7751 if (!strcmp(m
->name
, name
))
7757 /***********************************************************/
7758 /* main execution loop */
7760 static void gui_update(void *opaque
)
7762 DisplayState
*ds
= opaque
;
7763 ds
->dpy_refresh(ds
);
7764 qemu_mod_timer(ds
->gui_timer
,
7765 (ds
->gui_timer_interval
?
7766 ds
->gui_timer_interval
:
7767 GUI_REFRESH_INTERVAL
)
7768 + qemu_get_clock(rt_clock
));
7771 struct vm_change_state_entry
{
7772 VMChangeStateHandler
*cb
;
7774 LIST_ENTRY (vm_change_state_entry
) entries
;
7777 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7779 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7782 VMChangeStateEntry
*e
;
7784 e
= qemu_mallocz(sizeof (*e
));
7790 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7794 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7796 LIST_REMOVE (e
, entries
);
7800 static void vm_state_notify(int running
)
7802 VMChangeStateEntry
*e
;
7804 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7805 e
->cb(e
->opaque
, running
);
7809 /* XXX: support several handlers */
7810 static VMStopHandler
*vm_stop_cb
;
7811 static void *vm_stop_opaque
;
7813 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7816 vm_stop_opaque
= opaque
;
7820 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7831 qemu_rearm_alarm_timer(alarm_timer
);
7835 void vm_stop(int reason
)
7838 cpu_disable_ticks();
7842 vm_stop_cb(vm_stop_opaque
, reason
);
7849 /* reset/shutdown handler */
7851 typedef struct QEMUResetEntry
{
7852 QEMUResetHandler
*func
;
7854 struct QEMUResetEntry
*next
;
7857 static QEMUResetEntry
*first_reset_entry
;
7858 static int reset_requested
;
7859 static int shutdown_requested
;
7860 static int powerdown_requested
;
7862 int qemu_shutdown_requested(void)
7864 int r
= shutdown_requested
;
7865 shutdown_requested
= 0;
7869 int qemu_reset_requested(void)
7871 int r
= reset_requested
;
7872 reset_requested
= 0;
7876 int qemu_powerdown_requested(void)
7878 int r
= powerdown_requested
;
7879 powerdown_requested
= 0;
7883 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7885 QEMUResetEntry
**pre
, *re
;
7887 pre
= &first_reset_entry
;
7888 while (*pre
!= NULL
)
7889 pre
= &(*pre
)->next
;
7890 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7892 re
->opaque
= opaque
;
7897 void qemu_system_reset(void)
7901 /* reset all devices */
7902 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7903 re
->func(re
->opaque
);
7907 void qemu_system_reset_request(void)
7910 shutdown_requested
= 1;
7912 reset_requested
= 1;
7915 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7919 void qemu_system_shutdown_request(void)
7921 shutdown_requested
= 1;
7923 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7926 void qemu_system_powerdown_request(void)
7928 powerdown_requested
= 1;
7930 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7933 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
7938 /* KVM holds a mutex while QEMU code is running, we need hooks to
7939 release the mutex whenever QEMU code sleeps. */
7943 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
7950 void main_loop_wait(int timeout
)
7952 IOHandlerRecord
*ioh
;
7953 fd_set rfds
, wfds
, xfds
;
7962 /* XXX: need to suppress polling by better using win32 events */
7964 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7965 ret
|= pe
->func(pe
->opaque
);
7970 WaitObjects
*w
= &wait_objects
;
7972 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7973 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7974 if (w
->func
[ret
- WAIT_OBJECT_0
])
7975 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7977 /* Check for additional signaled events */
7978 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7980 /* Check if event is signaled */
7981 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7982 if(ret2
== WAIT_OBJECT_0
) {
7984 w
->func
[i
](w
->opaque
[i
]);
7985 } else if (ret2
== WAIT_TIMEOUT
) {
7987 err
= GetLastError();
7988 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7991 } else if (ret
== WAIT_TIMEOUT
) {
7993 err
= GetLastError();
7994 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7998 /* poll any events */
7999 /* XXX: separate device handlers from system ones */
8004 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8008 (!ioh
->fd_read_poll
||
8009 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
8010 FD_SET(ioh
->fd
, &rfds
);
8014 if (ioh
->fd_write
) {
8015 FD_SET(ioh
->fd
, &wfds
);
8025 tv
.tv_sec
= timeout
/ 1000;
8026 tv
.tv_usec
= (timeout
% 1000) * 1000;
8028 #if defined(CONFIG_SLIRP)
8030 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
8033 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
8035 IOHandlerRecord
**pioh
;
8037 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
8038 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
8039 ioh
->fd_read(ioh
->opaque
);
8040 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
8041 FD_CLR(ioh
->fd
, &rfds
);
8043 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
8044 ioh
->fd_write(ioh
->opaque
);
8048 /* remove deleted IO handlers */
8049 pioh
= &first_io_handler
;
8059 #if defined(CONFIG_SLIRP)
8066 slirp_select_poll(&rfds
, &wfds
, &xfds
);
8071 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
8072 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
8073 qemu_get_clock(vm_clock
));
8074 /* run dma transfers, if any */
8078 /* real time timers */
8079 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
8080 qemu_get_clock(rt_clock
));
8082 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
8083 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
8084 qemu_rearm_alarm_timer(alarm_timer
);
8087 /* Check bottom-halves last in case any of the earlier events triggered
8093 static int main_loop(void)
8096 #ifdef CONFIG_PROFILER
8102 if (kvm_enabled()) {
8104 cpu_disable_ticks();
8108 cur_cpu
= first_cpu
;
8109 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
8116 #ifdef CONFIG_PROFILER
8117 ti
= profile_getclock();
8122 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
8123 env
->icount_decr
.u16
.low
= 0;
8124 env
->icount_extra
= 0;
8125 count
= qemu_next_deadline();
8126 count
= (count
+ (1 << icount_time_shift
) - 1)
8127 >> icount_time_shift
;
8128 qemu_icount
+= count
;
8129 decr
= (count
> 0xffff) ? 0xffff : count
;
8131 env
->icount_decr
.u16
.low
= decr
;
8132 env
->icount_extra
= count
;
8134 ret
= cpu_exec(env
);
8135 #ifdef CONFIG_PROFILER
8136 qemu_time
+= profile_getclock() - ti
;
8139 /* Fold pending instructions back into the
8140 instruction counter, and clear the interrupt flag. */
8141 qemu_icount
-= (env
->icount_decr
.u16
.low
8142 + env
->icount_extra
);
8143 env
->icount_decr
.u32
= 0;
8144 env
->icount_extra
= 0;
8146 next_cpu
= env
->next_cpu
?: first_cpu
;
8147 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8148 ret
= EXCP_INTERRUPT
;
8152 if (ret
== EXCP_HLT
) {
8153 /* Give the next CPU a chance to run. */
8157 if (ret
!= EXCP_HALTED
)
8159 /* all CPUs are halted ? */
8165 if (shutdown_requested
) {
8166 ret
= EXCP_INTERRUPT
;
8174 if (reset_requested
) {
8175 reset_requested
= 0;
8176 qemu_system_reset();
8178 kvm_load_registers(env
);
8179 ret
= EXCP_INTERRUPT
;
8181 if (powerdown_requested
) {
8182 powerdown_requested
= 0;
8183 qemu_system_powerdown();
8184 ret
= EXCP_INTERRUPT
;
8186 if (unlikely(ret
== EXCP_DEBUG
)) {
8187 vm_stop(EXCP_DEBUG
);
8189 /* If all cpus are halted then wait until the next IRQ */
8190 /* XXX: use timeout computed from timers */
8191 if (ret
== EXCP_HALTED
) {
8195 /* Advance virtual time to the next event. */
8196 if (use_icount
== 1) {
8197 /* When not using an adaptive execution frequency
8198 we tend to get badly out of sync with real time,
8199 so just delay for a reasonable amount of time. */
8202 delta
= cpu_get_icount() - cpu_get_clock();
8205 /* If virtual time is ahead of real time then just
8207 timeout
= (delta
/ 1000000) + 1;
8209 /* Wait for either IO to occur or the next
8211 add
= qemu_next_deadline();
8212 /* We advance the timer before checking for IO.
8213 Limit the amount we advance so that early IO
8214 activity won't get the guest too far ahead. */
8218 add
= (add
+ (1 << icount_time_shift
) - 1)
8219 >> icount_time_shift
;
8221 timeout
= delta
/ 1000000;
8234 #ifdef CONFIG_PROFILER
8235 ti
= profile_getclock();
8237 main_loop_wait(timeout
);
8238 #ifdef CONFIG_PROFILER
8239 dev_time
+= profile_getclock() - ti
;
8242 cpu_disable_ticks();
8246 static void help(int exitcode
)
8248 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8249 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8250 "usage: %s [options] [disk_image]\n"
8252 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8254 "Standard options:\n"
8255 "-M machine select emulated machine (-M ? for list)\n"
8256 "-cpu cpu select CPU (-cpu ? for list)\n"
8257 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8258 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8259 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8260 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8261 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8262 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8263 " [,cache=on|off][,format=f][,boot=on|off]\n"
8264 " use 'file' as a drive image\n"
8265 "-mtdblock file use 'file' as on-board Flash memory image\n"
8266 "-sd file use 'file' as SecureDigital card image\n"
8267 "-pflash file use 'file' as a parallel flash image\n"
8268 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8269 "-snapshot write to temporary files instead of disk image files\n"
8271 "-no-frame open SDL window without a frame and window decorations\n"
8272 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8273 "-no-quit disable SDL window close capability\n"
8276 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8278 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8279 "-smp n set the number of CPUs to 'n' [default=1]\n"
8280 "-nographic disable graphical output and redirect serial I/Os to console\n"
8281 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8283 "-k language use keyboard layout (for example \"fr\" for French)\n"
8286 "-audio-help print list of audio drivers and their options\n"
8287 "-soundhw c1,... enable audio support\n"
8288 " and only specified sound cards (comma separated list)\n"
8289 " use -soundhw ? to get the list of supported cards\n"
8290 " use -soundhw all to enable all of them\n"
8292 "-localtime set the real time clock to local time [default=utc]\n"
8293 "-full-screen start in full screen\n"
8295 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8297 "-usb enable the USB driver (will be the default soon)\n"
8298 "-usbdevice name add the host or guest USB device 'name'\n"
8299 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8300 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8302 "-name string set the name of the guest\n"
8304 "Network options:\n"
8305 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8306 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8308 "-net user[,vlan=n][,hostname=host]\n"
8309 " connect the user mode network stack to VLAN 'n' and send\n"
8310 " hostname 'host' to DHCP clients\n"
8313 "-net tap[,vlan=n],ifname=name\n"
8314 " connect the host TAP network interface to VLAN 'n'\n"
8316 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8317 " connect the host TAP network interface to VLAN 'n' and use the\n"
8318 " network scripts 'file' (default=%s)\n"
8319 " and 'dfile' (default=%s);\n"
8320 " use '[down]script=no' to disable script execution;\n"
8321 " use 'fd=h' to connect to an already opened TAP interface\n"
8323 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8324 " connect the vlan 'n' to another VLAN using a socket connection\n"
8325 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8326 " connect the vlan 'n' to multicast maddr and port\n"
8328 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8329 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8330 " on host and listening for incoming connections on 'socketpath'.\n"
8331 " Use group 'groupname' and mode 'octalmode' to change default\n"
8332 " ownership and permissions for communication port.\n"
8334 "-net none use it alone to have zero network devices; if no -net option\n"
8335 " is provided, the default is '-net nic -net user'\n"
8338 "-tftp dir allow tftp access to files in dir [-net user]\n"
8339 "-bootp file advertise file in BOOTP replies\n"
8341 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8343 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8344 " redirect TCP or UDP connections from host to guest [-net user]\n"
8347 "Linux boot specific:\n"
8348 "-kernel bzImage use 'bzImage' as kernel image\n"
8349 "-append cmdline use 'cmdline' as kernel command line\n"
8350 "-initrd file use 'file' as initial ram disk\n"
8352 "Debug/Expert options:\n"
8353 "-monitor dev redirect the monitor to char device 'dev'\n"
8354 "-serial dev redirect the serial port to char device 'dev'\n"
8355 "-parallel dev redirect the parallel port to char device 'dev'\n"
8356 "-pidfile file Write PID to 'file'\n"
8357 "-S freeze CPU at startup (use 'c' to start execution)\n"
8358 "-s wait gdb connection to port\n"
8359 "-p port set gdb connection port [default=%s]\n"
8360 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8361 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8362 " translation (t=none or lba) (usually qemu can guess them)\n"
8363 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8365 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8366 "-no-kqemu disable KQEMU kernel module usage\n"
8369 #ifndef NO_CPU_EMULATION
8370 "-no-kvm disable KVM hardware virtualization\n"
8372 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8373 "-no-kvm-pit disable KVM kernel mode PIT\n"
8376 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8377 " (default is CL-GD5446 PCI VGA)\n"
8378 "-no-acpi disable ACPI\n"
8380 #ifdef CONFIG_CURSES
8381 "-curses use a curses/ncurses interface instead of SDL\n"
8383 "-no-reboot exit instead of rebooting\n"
8384 "-no-shutdown stop before shutdown\n"
8385 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8386 "-vnc display start a VNC server on display\n"
8388 "-daemonize daemonize QEMU after initializing\n"
8390 "-tdf inject timer interrupts that got lost\n"
8391 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8392 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8393 "-option-rom rom load a file, rom, into the option ROM space\n"
8395 "-prom-env variable=value set OpenBIOS nvram variables\n"
8397 "-clock force the use of the given methods for timer alarm.\n"
8398 " To see what timers are available use -clock ?\n"
8399 "-startdate select initial date of the clock\n"
8400 "-icount [N|auto]\n"
8401 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8403 "During emulation, the following keys are useful:\n"
8404 "ctrl-alt-f toggle full screen\n"
8405 "ctrl-alt-n switch to virtual console 'n'\n"
8406 "ctrl-alt toggle mouse and keyboard grab\n"
8408 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8413 DEFAULT_NETWORK_SCRIPT
,
8414 DEFAULT_NETWORK_DOWN_SCRIPT
,
8416 DEFAULT_GDBSTUB_PORT
,
8421 #define HAS_ARG 0x0001
8436 QEMU_OPTION_mtdblock
,
8440 QEMU_OPTION_snapshot
,
8442 QEMU_OPTION_no_fd_bootchk
,
8445 QEMU_OPTION_nographic
,
8446 QEMU_OPTION_portrait
,
8448 QEMU_OPTION_audio_help
,
8449 QEMU_OPTION_soundhw
,
8470 QEMU_OPTION_localtime
,
8471 QEMU_OPTION_cirrusvga
,
8474 QEMU_OPTION_std_vga
,
8476 QEMU_OPTION_monitor
,
8478 QEMU_OPTION_parallel
,
8480 QEMU_OPTION_full_screen
,
8481 QEMU_OPTION_no_frame
,
8482 QEMU_OPTION_alt_grab
,
8483 QEMU_OPTION_no_quit
,
8484 QEMU_OPTION_pidfile
,
8485 QEMU_OPTION_no_kqemu
,
8486 QEMU_OPTION_kernel_kqemu
,
8487 QEMU_OPTION_win2k_hack
,
8489 QEMU_OPTION_usbdevice
,
8492 QEMU_OPTION_no_acpi
,
8495 QEMU_OPTION_no_kvm_irqchip
,
8496 QEMU_OPTION_no_kvm_pit
,
8497 QEMU_OPTION_no_reboot
,
8498 QEMU_OPTION_no_shutdown
,
8499 QEMU_OPTION_show_cursor
,
8500 QEMU_OPTION_daemonize
,
8501 QEMU_OPTION_option_rom
,
8502 QEMU_OPTION_semihosting
,
8503 QEMU_OPTION_cpu_vendor
,
8505 QEMU_OPTION_prom_env
,
8506 QEMU_OPTION_old_param
,
8508 QEMU_OPTION_startdate
,
8509 QEMU_OPTION_tb_size
,
8511 QEMU_OPTION_incoming
,
8513 QEMU_OPTION_kvm_shadow_memory
,
8514 QEMU_OPTION_mempath
,
8517 typedef struct QEMUOption
{
8523 const QEMUOption qemu_options
[] = {
8524 { "h", 0, QEMU_OPTION_h
},
8525 { "help", 0, QEMU_OPTION_h
},
8527 { "M", HAS_ARG
, QEMU_OPTION_M
},
8528 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8529 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8530 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8531 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8532 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8533 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8534 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8535 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8536 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8537 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8538 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8539 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8540 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8541 { "snapshot", 0, QEMU_OPTION_snapshot
},
8543 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8545 { "m", HAS_ARG
, QEMU_OPTION_m
},
8546 { "nographic", 0, QEMU_OPTION_nographic
},
8547 { "portrait", 0, QEMU_OPTION_portrait
},
8548 { "k", HAS_ARG
, QEMU_OPTION_k
},
8550 { "audio-help", 0, QEMU_OPTION_audio_help
},
8551 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8554 { "net", HAS_ARG
, QEMU_OPTION_net
},
8556 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8557 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8559 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8561 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8564 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8565 { "append", HAS_ARG
, QEMU_OPTION_append
},
8566 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8568 { "S", 0, QEMU_OPTION_S
},
8569 { "s", 0, QEMU_OPTION_s
},
8570 { "p", HAS_ARG
, QEMU_OPTION_p
},
8571 { "d", HAS_ARG
, QEMU_OPTION_d
},
8572 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8573 { "L", HAS_ARG
, QEMU_OPTION_L
},
8574 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8576 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8577 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8580 #ifndef NO_CPU_EMULATION
8581 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8583 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8584 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8586 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8587 { "g", 1, QEMU_OPTION_g
},
8589 { "localtime", 0, QEMU_OPTION_localtime
},
8590 { "std-vga", 0, QEMU_OPTION_std_vga
},
8591 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8592 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8593 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8594 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8595 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8596 { "incoming", 1, QEMU_OPTION_incoming
},
8597 { "full-screen", 0, QEMU_OPTION_full_screen
},
8599 { "no-frame", 0, QEMU_OPTION_no_frame
},
8600 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8601 { "no-quit", 0, QEMU_OPTION_no_quit
},
8603 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8604 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8605 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8606 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8607 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8608 #ifdef CONFIG_CURSES
8609 { "curses", 0, QEMU_OPTION_curses
},
8612 /* temporary options */
8613 { "usb", 0, QEMU_OPTION_usb
},
8614 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8615 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8616 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8617 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8618 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8619 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8620 { "daemonize", 0, QEMU_OPTION_daemonize
},
8621 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8622 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8623 { "semihosting", 0, QEMU_OPTION_semihosting
},
8625 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8626 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8627 { "name", HAS_ARG
, QEMU_OPTION_name
},
8628 #if defined(TARGET_SPARC)
8629 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8631 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8632 #if defined(TARGET_ARM)
8633 { "old-param", 0, QEMU_OPTION_old_param
},
8635 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8636 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8637 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8638 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8639 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8643 /* password input */
8645 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8650 if (!bdrv_is_encrypted(bs
))
8653 term_printf("%s is encrypted.\n", name
);
8654 for(i
= 0; i
< 3; i
++) {
8655 monitor_readline("Password: ", 1, password
, sizeof(password
));
8656 if (bdrv_set_key(bs
, password
) == 0)
8658 term_printf("invalid password\n");
8663 static void read_passwords(void)
8665 BlockDriverState
*bs
;
8668 for(i
= 0; i
< nb_drives
; i
++) {
8669 bs
= drives_table
[i
].bdrv
;
8670 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8675 struct soundhw soundhw
[] = {
8676 #ifdef HAS_AUDIO_CHOICE
8677 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8683 { .init_isa
= pcspk_audio_init
}
8688 "Creative Sound Blaster 16",
8691 { .init_isa
= SB16_init
}
8694 #ifdef CONFIG_CS4231A
8700 { .init_isa
= cs4231a_init
}
8708 "Yamaha YMF262 (OPL3)",
8710 "Yamaha YM3812 (OPL2)",
8714 { .init_isa
= Adlib_init
}
8721 "Gravis Ultrasound GF1",
8724 { .init_isa
= GUS_init
}
8731 "Intel 82801AA AC97 Audio",
8734 { .init_pci
= ac97_init
}
8740 "ENSONIQ AudioPCI ES1370",
8743 { .init_pci
= es1370_init
}
8747 { NULL
, NULL
, 0, 0, { NULL
} }
8750 static void select_soundhw (const char *optarg
)
8754 if (*optarg
== '?') {
8757 printf ("Valid sound card names (comma separated):\n");
8758 for (c
= soundhw
; c
->name
; ++c
) {
8759 printf ("%-11s %s\n", c
->name
, c
->descr
);
8761 printf ("\n-soundhw all will enable all of the above\n");
8762 exit (*optarg
!= '?');
8770 if (!strcmp (optarg
, "all")) {
8771 for (c
= soundhw
; c
->name
; ++c
) {
8779 e
= strchr (p
, ',');
8780 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8782 for (c
= soundhw
; c
->name
; ++c
) {
8783 if (!strncmp (c
->name
, p
, l
)) {
8792 "Unknown sound card name (too big to show)\n");
8795 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8800 p
+= l
+ (e
!= NULL
);
8804 goto show_valid_cards
;
8810 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8812 exit(STATUS_CONTROL_C_EXIT
);
8817 #define MAX_NET_CLIENTS 32
8819 static int saved_argc
;
8820 static char **saved_argv
;
8822 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8826 *opt_daemonize
= daemonize
;
8827 *opt_incoming
= incoming
;
8831 static int gethugepagesize(void)
8835 char *needle
= "Hugepagesize:";
8837 unsigned long hugepagesize
;
8839 fd
= open("/proc/meminfo", O_RDONLY
);
8845 ret
= read(fd
, buf
, sizeof(buf
));
8851 size
= strstr(buf
, needle
);
8854 size
+= strlen(needle
);
8855 hugepagesize
= strtol(size
, NULL
, 0);
8856 return hugepagesize
;
8859 void *alloc_mem_area(unsigned long memory
, const char *path
)
8865 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8868 hpagesize
= gethugepagesize() * 1024;
8872 fd
= mkstemp(filename
);
8881 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8884 * ftruncate is not supported by hugetlbfs in older
8885 * hosts, so don't bother checking for errors.
8886 * If anything goes wrong with it under other filesystems,
8889 ftruncate(fd
, memory
);
8891 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8892 if (area
== MAP_FAILED
) {
8901 void *qemu_alloc_physram(unsigned long memory
)
8906 area
= alloc_mem_area(memory
, mem_path
);
8908 area
= qemu_vmalloc(memory
);
8913 int main(int argc
, char **argv
)
8915 #ifdef CONFIG_GDBSTUB
8917 const char *gdbstub_port
;
8919 uint32_t boot_devices_bitmap
= 0;
8921 int snapshot
, linux_boot
, net_boot
;
8922 const char *initrd_filename
;
8923 const char *kernel_filename
, *kernel_cmdline
;
8924 const char *boot_devices
= "";
8925 DisplayState
*ds
= &display_state
;
8926 int cyls
, heads
, secs
, translation
;
8927 const char *net_clients
[MAX_NET_CLIENTS
];
8931 const char *r
, *optarg
;
8932 CharDriverState
*monitor_hd
;
8934 const char *monitor_device
;
8935 const char *serial_devices
[MAX_SERIAL_PORTS
];
8936 int serial_device_index
;
8937 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8938 int parallel_device_index
;
8939 const char *loadvm
= NULL
;
8940 QEMUMachine
*machine
;
8941 const char *cpu_model
;
8942 const char *usb_devices
[MAX_USB_CMDLINE
];
8943 int usb_devices_index
;
8946 const char *pid_file
= NULL
;
8952 LIST_INIT (&vm_change_state_head
);
8955 struct sigaction act
;
8956 sigfillset(&act
.sa_mask
);
8958 act
.sa_handler
= SIG_IGN
;
8959 sigaction(SIGPIPE
, &act
, NULL
);
8962 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8963 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8964 QEMU to run on a single CPU */
8969 h
= GetCurrentProcess();
8970 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8971 for(i
= 0; i
< 32; i
++) {
8972 if (mask
& (1 << i
))
8977 SetProcessAffinityMask(h
, mask
);
8983 register_machines();
8984 machine
= first_machine
;
8986 initrd_filename
= NULL
;
8988 vga_ram_size
= VGA_RAM_SIZE
;
8989 #ifdef CONFIG_GDBSTUB
8991 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8996 kernel_filename
= NULL
;
8997 kernel_cmdline
= "";
8998 cyls
= heads
= secs
= 0;
8999 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9000 monitor_device
= "vc";
9002 serial_devices
[0] = "vc:80Cx24C";
9003 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
9004 serial_devices
[i
] = NULL
;
9005 serial_device_index
= 0;
9007 parallel_devices
[0] = "vc:640x480";
9008 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
9009 parallel_devices
[i
] = NULL
;
9010 parallel_device_index
= 0;
9012 usb_devices_index
= 0;
9029 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
9031 const QEMUOption
*popt
;
9034 /* Treat --foo the same as -foo. */
9037 popt
= qemu_options
;
9040 fprintf(stderr
, "%s: invalid option -- '%s'\n",
9044 if (!strcmp(popt
->name
, r
+ 1))
9048 if (popt
->flags
& HAS_ARG
) {
9049 if (optind
>= argc
) {
9050 fprintf(stderr
, "%s: option '%s' requires an argument\n",
9054 optarg
= argv
[optind
++];
9059 switch(popt
->index
) {
9061 machine
= find_machine(optarg
);
9064 printf("Supported machines are:\n");
9065 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
9066 printf("%-10s %s%s\n",
9068 m
== first_machine
? " (default)" : "");
9070 exit(*optarg
!= '?');
9073 case QEMU_OPTION_cpu
:
9074 /* hw initialization will check this */
9075 if (*optarg
== '?') {
9076 /* XXX: implement xxx_cpu_list for targets that still miss it */
9077 #if defined(cpu_list)
9078 cpu_list(stdout
, &fprintf
);
9085 case QEMU_OPTION_initrd
:
9086 initrd_filename
= optarg
;
9088 case QEMU_OPTION_hda
:
9090 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
9092 hda_index
= drive_add(optarg
, HD_ALIAS
9093 ",cyls=%d,heads=%d,secs=%d%s",
9094 0, cyls
, heads
, secs
,
9095 translation
== BIOS_ATA_TRANSLATION_LBA
?
9097 translation
== BIOS_ATA_TRANSLATION_NONE
?
9098 ",trans=none" : "");
9100 case QEMU_OPTION_hdb
:
9101 case QEMU_OPTION_hdc
:
9102 case QEMU_OPTION_hdd
:
9103 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
9105 case QEMU_OPTION_drive
:
9106 drive_add(NULL
, "%s", optarg
);
9108 case QEMU_OPTION_mtdblock
:
9109 drive_add(optarg
, MTD_ALIAS
);
9111 case QEMU_OPTION_sd
:
9112 drive_add(optarg
, SD_ALIAS
);
9114 case QEMU_OPTION_pflash
:
9115 drive_add(optarg
, PFLASH_ALIAS
);
9117 case QEMU_OPTION_snapshot
:
9120 case QEMU_OPTION_hdachs
:
9124 cyls
= strtol(p
, (char **)&p
, 0);
9125 if (cyls
< 1 || cyls
> 16383)
9130 heads
= strtol(p
, (char **)&p
, 0);
9131 if (heads
< 1 || heads
> 16)
9136 secs
= strtol(p
, (char **)&p
, 0);
9137 if (secs
< 1 || secs
> 63)
9141 if (!strcmp(p
, "none"))
9142 translation
= BIOS_ATA_TRANSLATION_NONE
;
9143 else if (!strcmp(p
, "lba"))
9144 translation
= BIOS_ATA_TRANSLATION_LBA
;
9145 else if (!strcmp(p
, "auto"))
9146 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9149 } else if (*p
!= '\0') {
9151 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9154 if (hda_index
!= -1)
9155 snprintf(drives_opt
[hda_index
].opt
,
9156 sizeof(drives_opt
[hda_index
].opt
),
9157 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9158 0, cyls
, heads
, secs
,
9159 translation
== BIOS_ATA_TRANSLATION_LBA
?
9161 translation
== BIOS_ATA_TRANSLATION_NONE
?
9162 ",trans=none" : "");
9165 case QEMU_OPTION_nographic
:
9168 #ifdef CONFIG_CURSES
9169 case QEMU_OPTION_curses
:
9173 case QEMU_OPTION_portrait
:
9176 case QEMU_OPTION_kernel
:
9177 kernel_filename
= optarg
;
9179 case QEMU_OPTION_append
:
9180 kernel_cmdline
= optarg
;
9182 case QEMU_OPTION_cdrom
:
9183 drive_add(optarg
, CDROM_ALIAS
);
9185 case QEMU_OPTION_boot
:
9186 boot_devices
= optarg
;
9187 /* We just do some generic consistency checks */
9189 /* Could easily be extended to 64 devices if needed */
9192 boot_devices_bitmap
= 0;
9193 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9194 /* Allowed boot devices are:
9195 * a b : floppy disk drives
9196 * c ... f : IDE disk drives
9197 * g ... m : machine implementation dependant drives
9198 * n ... p : network devices
9199 * It's up to each machine implementation to check
9200 * if the given boot devices match the actual hardware
9201 * implementation and firmware features.
9203 if (*p
< 'a' || *p
> 'q') {
9204 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9207 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9209 "Boot device '%c' was given twice\n",*p
);
9212 boot_devices_bitmap
|= 1 << (*p
- 'a');
9216 case QEMU_OPTION_fda
:
9217 case QEMU_OPTION_fdb
:
9218 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9221 case QEMU_OPTION_no_fd_bootchk
:
9225 case QEMU_OPTION_net
:
9226 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9227 fprintf(stderr
, "qemu: too many network clients\n");
9230 net_clients
[nb_net_clients
] = optarg
;
9234 case QEMU_OPTION_tftp
:
9235 tftp_prefix
= optarg
;
9237 case QEMU_OPTION_bootp
:
9238 bootp_filename
= optarg
;
9241 case QEMU_OPTION_smb
:
9242 net_slirp_smb(optarg
);
9245 case QEMU_OPTION_redir
:
9246 net_slirp_redir(optarg
);
9250 case QEMU_OPTION_audio_help
:
9254 case QEMU_OPTION_soundhw
:
9255 select_soundhw (optarg
);
9261 case QEMU_OPTION_m
: {
9265 value
= strtoul(optarg
, &ptr
, 10);
9267 case 0: case 'M': case 'm':
9274 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9278 /* On 32-bit hosts, QEMU is limited by virtual address space */
9279 if (value
> (2047 << 20)
9281 && HOST_LONG_BITS
== 32
9284 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9287 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9288 fprintf(stderr
, "qemu: ram size too large\n");
9299 mask
= cpu_str_to_log_mask(optarg
);
9301 printf("Log items (comma separated):\n");
9302 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9303 printf("%-10s %s\n", item
->name
, item
->help
);
9310 #ifdef CONFIG_GDBSTUB
9315 gdbstub_port
= optarg
;
9321 case QEMU_OPTION_bios
:
9328 keyboard_layout
= optarg
;
9330 case QEMU_OPTION_localtime
:
9333 case QEMU_OPTION_cirrusvga
:
9334 cirrus_vga_enabled
= 1;
9337 case QEMU_OPTION_vmsvga
:
9338 cirrus_vga_enabled
= 0;
9341 case QEMU_OPTION_std_vga
:
9342 cirrus_vga_enabled
= 0;
9350 w
= strtol(p
, (char **)&p
, 10);
9353 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9359 h
= strtol(p
, (char **)&p
, 10);
9364 depth
= strtol(p
, (char **)&p
, 10);
9365 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9366 depth
!= 24 && depth
!= 32)
9368 } else if (*p
== '\0') {
9369 depth
= graphic_depth
;
9376 graphic_depth
= depth
;
9379 case QEMU_OPTION_echr
:
9382 term_escape_char
= strtol(optarg
, &r
, 0);
9384 printf("Bad argument to echr\n");
9387 case QEMU_OPTION_monitor
:
9388 monitor_device
= optarg
;
9390 case QEMU_OPTION_serial
:
9391 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9392 fprintf(stderr
, "qemu: too many serial ports\n");
9395 serial_devices
[serial_device_index
] = optarg
;
9396 serial_device_index
++;
9398 case QEMU_OPTION_parallel
:
9399 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9400 fprintf(stderr
, "qemu: too many parallel ports\n");
9403 parallel_devices
[parallel_device_index
] = optarg
;
9404 parallel_device_index
++;
9406 case QEMU_OPTION_loadvm
:
9409 case QEMU_OPTION_incoming
:
9412 case QEMU_OPTION_full_screen
:
9416 case QEMU_OPTION_no_frame
:
9419 case QEMU_OPTION_alt_grab
:
9422 case QEMU_OPTION_no_quit
:
9426 case QEMU_OPTION_pidfile
:
9430 case QEMU_OPTION_win2k_hack
:
9431 win2k_install_hack
= 1;
9435 case QEMU_OPTION_no_kqemu
:
9438 case QEMU_OPTION_kernel_kqemu
:
9443 case QEMU_OPTION_no_kvm
:
9446 case QEMU_OPTION_no_kvm_irqchip
: {
9447 extern int kvm_irqchip
, kvm_pit
;
9452 case QEMU_OPTION_no_kvm_pit
: {
9458 case QEMU_OPTION_usb
:
9461 case QEMU_OPTION_usbdevice
:
9463 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9464 fprintf(stderr
, "Too many USB devices\n");
9467 usb_devices
[usb_devices_index
] = optarg
;
9468 usb_devices_index
++;
9470 case QEMU_OPTION_smp
:
9471 smp_cpus
= atoi(optarg
);
9472 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9473 fprintf(stderr
, "Invalid number of CPUs\n");
9477 case QEMU_OPTION_vnc
:
9478 vnc_display
= optarg
;
9480 case QEMU_OPTION_no_acpi
:
9483 case QEMU_OPTION_no_reboot
:
9486 case QEMU_OPTION_no_shutdown
:
9489 case QEMU_OPTION_show_cursor
:
9492 case QEMU_OPTION_daemonize
:
9495 case QEMU_OPTION_option_rom
:
9496 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9497 fprintf(stderr
, "Too many option ROMs\n");
9500 option_rom
[nb_option_roms
] = optarg
;
9503 case QEMU_OPTION_semihosting
:
9504 semihosting_enabled
= 1;
9506 case QEMU_OPTION_tdf
:
9509 case QEMU_OPTION_kvm_shadow_memory
:
9510 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9512 case QEMU_OPTION_mempath
:
9515 case QEMU_OPTION_name
:
9519 case QEMU_OPTION_prom_env
:
9520 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9521 fprintf(stderr
, "Too many prom variables\n");
9524 prom_envs
[nb_prom_envs
] = optarg
;
9528 case QEMU_OPTION_cpu_vendor
:
9529 cpu_vendor_string
= optarg
;
9532 case QEMU_OPTION_old_param
:
9536 case QEMU_OPTION_clock
:
9537 configure_alarms(optarg
);
9539 case QEMU_OPTION_startdate
:
9542 time_t rtc_start_date
;
9543 if (!strcmp(optarg
, "now")) {
9544 rtc_date_offset
= -1;
9546 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9554 } else if (sscanf(optarg
, "%d-%d-%d",
9557 &tm
.tm_mday
) == 3) {
9566 rtc_start_date
= mktimegm(&tm
);
9567 if (rtc_start_date
== -1) {
9569 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9570 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9573 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9577 case QEMU_OPTION_tb_size
:
9578 tb_size
= strtol(optarg
, NULL
, 0);
9582 case QEMU_OPTION_icount
:
9584 if (strcmp(optarg
, "auto") == 0) {
9585 icount_time_shift
= -1;
9587 icount_time_shift
= strtol(optarg
, NULL
, 0);
9595 if (serial_device_index
== 0)
9596 serial_devices
[0] = "stdio";
9597 if (parallel_device_index
== 0)
9598 parallel_devices
[0] = "null";
9599 if (strncmp(monitor_device
, "vc", 2) == 0)
9600 monitor_device
= "stdio";
9607 if (pipe(fds
) == -1)
9618 len
= read(fds
[0], &status
, 1);
9619 if (len
== -1 && (errno
== EINTR
))
9624 else if (status
== 1) {
9625 fprintf(stderr
, "Could not acquire pidfile\n");
9642 signal(SIGTSTP
, SIG_IGN
);
9643 signal(SIGTTOU
, SIG_IGN
);
9644 signal(SIGTTIN
, SIG_IGN
);
9649 if (kvm_enabled()) {
9650 if (kvm_qemu_init() < 0) {
9651 extern int kvm_allowed
;
9652 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9653 #ifdef NO_CPU_EMULATION
9654 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9662 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9665 write(fds
[1], &status
, 1);
9667 fprintf(stderr
, "Could not acquire pid file\n");
9675 linux_boot
= (kernel_filename
!= NULL
);
9676 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9678 /* XXX: this should not be: some embedded targets just have flash */
9679 if (!linux_boot
&& net_boot
== 0 &&
9683 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9684 fprintf(stderr
, "-append only allowed with -kernel option\n");
9688 if (!linux_boot
&& initrd_filename
!= NULL
) {
9689 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9693 /* boot to floppy or the default cd if no hard disk defined yet */
9694 if (!boot_devices
[0]) {
9695 boot_devices
= "cad";
9697 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9702 if (use_icount
&& icount_time_shift
< 0) {
9704 /* 125MIPS seems a reasonable initial guess at the guest speed.
9705 It will be corrected fairly quickly anyway. */
9706 icount_time_shift
= 3;
9707 init_icount_adjust();
9714 /* init network clients */
9715 if (nb_net_clients
== 0) {
9716 /* if no clients, we use a default config */
9717 net_clients
[0] = "nic";
9718 net_clients
[1] = "user";
9722 for(i
= 0;i
< nb_net_clients
; i
++) {
9723 if (net_client_parse(net_clients
[i
]) < 0)
9726 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9727 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9729 if (vlan
->nb_guest_devs
== 0)
9730 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9731 if (vlan
->nb_host_devs
== 0)
9733 "Warning: vlan %d is not connected to host network\n",
9738 /* XXX: this should be moved in the PC machine instantiation code */
9739 if (net_boot
!= 0) {
9741 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9742 const char *model
= nd_table
[i
].model
;
9744 if (net_boot
& (1 << i
)) {
9747 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9748 if (get_image_size(buf
) > 0) {
9749 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9750 fprintf(stderr
, "Too many option ROMs\n");
9753 option_rom
[nb_option_roms
] = strdup(buf
);
9760 fprintf(stderr
, "No valid PXE rom found for network device\n");
9766 /* init the memory */
9767 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9769 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9771 if (ram_size
< phys_ram_size
) {
9772 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9773 machine
->name
, (unsigned long long) phys_ram_size
);
9777 phys_ram_size
= ram_size
;
9779 ram_size
= phys_ram_size
;
9782 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9784 phys_ram_size
+= ram_size
;
9787 /* Initialize kvm */
9788 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9789 #define KVM_EXTRA_PAGES 3
9791 #define KVM_EXTRA_PAGES 0
9793 if (kvm_enabled()) {
9794 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9795 if (kvm_qemu_create_context() < 0) {
9796 fprintf(stderr
, "Could not create KVM context\n");
9799 #ifdef KVM_CAP_USER_MEMORY
9803 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9805 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9806 if (!phys_ram_base
) {
9807 fprintf(stderr
, "Could not allocate physical memory\n");
9814 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9815 if (!phys_ram_base
) {
9816 fprintf(stderr
, "Could not allocate physical memory\n");
9821 /* init the dynamic translator */
9822 cpu_exec_init_all(tb_size
* 1024 * 1024);
9826 /* we always create the cdrom drive, even if no disk is there */
9828 if (nb_drives_opt
< MAX_DRIVES
)
9829 drive_add(NULL
, CDROM_ALIAS
);
9831 /* we always create at least one floppy */
9833 if (nb_drives_opt
< MAX_DRIVES
)
9834 drive_add(NULL
, FD_ALIAS
, 0);
9836 /* we always create one sd slot, even if no card is in it */
9838 if (nb_drives_opt
< MAX_DRIVES
)
9839 drive_add(NULL
, SD_ALIAS
);
9841 /* open the virtual block devices
9842 * note that migration with device
9843 * hot add/remove is broken.
9845 for(i
= 0; i
< nb_drives_opt
; i
++)
9846 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9849 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9850 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9853 memset(&display_state
, 0, sizeof(display_state
));
9856 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9859 /* nearly nothing to do */
9860 dumb_display_init(ds
);
9861 } else if (vnc_display
!= NULL
) {
9862 vnc_display_init(ds
);
9863 if (vnc_display_open(ds
, vnc_display
) < 0)
9866 #if defined(CONFIG_CURSES)
9868 curses_display_init(ds
, full_screen
);
9872 #if defined(CONFIG_SDL)
9873 sdl_display_init(ds
, full_screen
, no_frame
);
9874 #elif defined(CONFIG_COCOA)
9875 cocoa_display_init(ds
, full_screen
);
9877 dumb_display_init(ds
);
9881 /* Maintain compatibility with multiple stdio monitors */
9884 if (!strcmp(monitor_device
,"stdio")) {
9885 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9886 const char *devname
= serial_devices
[i
];
9887 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9888 monitor_device
= NULL
;
9890 } else if (devname
&& !strcmp(devname
,"stdio")) {
9891 monitor_device
= NULL
;
9892 serial_devices
[i
] = "mon:stdio";
9898 if (monitor_device
) {
9899 monitor_hd
= qemu_chr_open(monitor_device
);
9901 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9904 monitor_init(monitor_hd
, !nographic
);
9908 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9909 const char *devname
= serial_devices
[i
];
9910 if (devname
&& strcmp(devname
, "none")) {
9911 serial_hds
[i
] = qemu_chr_open(devname
);
9912 if (!serial_hds
[i
]) {
9913 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9917 if (strstart(devname
, "vc", 0))
9918 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9922 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9923 const char *devname
= parallel_devices
[i
];
9924 if (devname
&& strcmp(devname
, "none")) {
9925 parallel_hds
[i
] = qemu_chr_open(devname
);
9926 if (!parallel_hds
[i
]) {
9927 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9931 if (strstart(devname
, "vc", 0))
9932 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9939 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9940 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9942 current_machine
= machine
;
9944 /* init USB devices */
9946 for(i
= 0; i
< usb_devices_index
; i
++) {
9947 if (usb_device_add(usb_devices
[i
]) < 0) {
9948 fprintf(stderr
, "Warning: could not add USB device %s\n",
9954 if (display_state
.dpy_refresh
) {
9955 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9956 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9959 #ifdef CONFIG_GDBSTUB
9961 /* XXX: use standard host:port notation and modify options
9963 if (gdbserver_start(gdbstub_port
) < 0) {
9964 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9974 monitor_start_input();
9982 rc
= migrate_incoming(incoming
);
9984 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
9990 /* XXX: simplify init */
10002 len
= write(fds
[1], &status
, 1);
10003 if (len
== -1 && (errno
== EINTR
))
10010 TFR(fd
= open("/dev/null", O_RDWR
));
10024 #if !defined(_WIN32)
10025 /* close network clients */
10026 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
10027 VLANClientState
*vc
;
10029 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
10030 if (vc
->fd_read
== tap_receive
) {
10032 TAPState
*s
= vc
->opaque
;
10034 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
10036 launch_script(s
->down_script
, ifname
, s
->fd
);
10038 #if defined(CONFIG_VDE)
10039 if (vc
->fd_read
== vde_from_qemu
) {
10040 VDEState
*s
= vc
->opaque
;