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 */
4343 #if !defined(_WIN32)
4345 typedef struct TAPState
{
4346 VLANClientState
*vc
;
4348 char down_script
[1024];
4353 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4355 TAPState
*s
= opaque
;
4358 ret
= write(s
->fd
, buf
, size
);
4359 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4366 static ssize_t
tap_readv(void *opaque
, const struct iovec
*iov
,
4369 TAPState
*s
= opaque
;
4373 len
= writev(s
->fd
, iov
, iovcnt
);
4374 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4379 static int tap_can_send(void *opaque
)
4381 TAPState
*s
= opaque
;
4382 VLANClientState
*vc
;
4383 int can_receive
= 0;
4385 /* Check to see if any of our clients can receive a packet */
4386 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4387 /* Skip ourselves */
4391 if (!vc
->fd_can_read
) {
4392 /* no fd_can_read handler, they always can receive */
4395 can_receive
= vc
->fd_can_read(vc
->opaque
);
4397 /* Once someone can receive, we try to send a packet */
4405 static void tap_send(void *opaque
)
4407 TAPState
*s
= opaque
;
4409 /* First try to send any buffered packet */
4413 /* If noone can receive the packet, buffer it */
4414 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4419 /* Read packets until we hit EAGAIN */
4424 sbuf
.maxlen
= sizeof(s
->buf
);
4426 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4428 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4431 if (s
->size
== -1 && errno
== EINTR
)
4437 /* If noone can receive the packet, buffer it */
4438 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4442 } while (s
->size
> 0);
4447 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4451 s
= qemu_mallocz(sizeof(TAPState
));
4455 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4456 s
->vc
->fd_readv
= tap_readv
;
4457 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4458 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4462 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4463 static int tap_open(char *ifname
, int ifname_size
)
4469 TFR(fd
= open("/dev/tap", O_RDWR
));
4471 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4476 dev
= devname(s
.st_rdev
, S_IFCHR
);
4477 pstrcpy(ifname
, ifname_size
, dev
);
4479 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4482 #elif defined(__sun__)
4483 #define TUNNEWPPA (('T'<<16) | 0x0001)
4485 * Allocate TAP device, returns opened fd.
4486 * Stores dev name in the first arg(must be large enough).
4488 int tap_alloc(char *dev
)
4490 int tap_fd
, if_fd
, ppa
= -1;
4491 static int ip_fd
= 0;
4494 static int arp_fd
= 0;
4495 int ip_muxid
, arp_muxid
;
4496 struct strioctl strioc_if
, strioc_ppa
;
4497 int link_type
= I_PLINK
;;
4499 char actual_name
[32] = "";
4501 memset(&ifr
, 0x0, sizeof(ifr
));
4505 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4509 /* Check if IP device was opened */
4513 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4515 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4519 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4521 syslog(LOG_ERR
, "Can't open /dev/tap");
4525 /* Assign a new PPA and get its unit number. */
4526 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4527 strioc_ppa
.ic_timout
= 0;
4528 strioc_ppa
.ic_len
= sizeof(ppa
);
4529 strioc_ppa
.ic_dp
= (char *)&ppa
;
4530 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4531 syslog (LOG_ERR
, "Can't assign new interface");
4533 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4535 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4538 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4539 syslog(LOG_ERR
, "Can't push IP module");
4543 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4544 syslog(LOG_ERR
, "Can't get flags\n");
4546 snprintf (actual_name
, 32, "tap%d", ppa
);
4547 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4550 /* Assign ppa according to the unit number returned by tun device */
4552 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4553 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4554 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4555 syslog (LOG_ERR
, "Can't get flags\n");
4556 /* Push arp module to if_fd */
4557 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4558 syslog (LOG_ERR
, "Can't push ARP module (2)");
4560 /* Push arp module to ip_fd */
4561 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4562 syslog (LOG_ERR
, "I_POP failed\n");
4563 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4564 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4566 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4568 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4570 /* Set ifname to arp */
4571 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4572 strioc_if
.ic_timout
= 0;
4573 strioc_if
.ic_len
= sizeof(ifr
);
4574 strioc_if
.ic_dp
= (char *)&ifr
;
4575 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4576 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4579 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4580 syslog(LOG_ERR
, "Can't link TAP device to IP");
4584 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4585 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4589 memset(&ifr
, 0x0, sizeof(ifr
));
4590 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4591 ifr
.lifr_ip_muxid
= ip_muxid
;
4592 ifr
.lifr_arp_muxid
= arp_muxid
;
4594 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4596 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4597 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4598 syslog (LOG_ERR
, "Can't set multiplexor id");
4601 sprintf(dev
, "tap%d", ppa
);
4605 static int tap_open(char *ifname
, int ifname_size
)
4609 if( (fd
= tap_alloc(dev
)) < 0 ){
4610 fprintf(stderr
, "Cannot allocate TAP device\n");
4613 pstrcpy(ifname
, ifname_size
, dev
);
4614 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4618 static int tap_open(char *ifname
, int ifname_size
)
4623 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4625 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4628 memset(&ifr
, 0, sizeof(ifr
));
4629 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4630 if (ifname
[0] != '\0')
4631 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4633 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4634 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4636 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4640 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4641 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4646 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4652 /* try to launch network script */
4656 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4657 for (i
= 0; i
< open_max
; i
++)
4658 if (i
!= STDIN_FILENO
&&
4659 i
!= STDOUT_FILENO
&&
4660 i
!= STDERR_FILENO
&&
4665 *parg
++ = (char *)setup_script
;
4666 *parg
++ = (char *)ifname
;
4668 execv(setup_script
, args
);
4671 while (waitpid(pid
, &status
, 0) != pid
);
4672 if (!WIFEXITED(status
) ||
4673 WEXITSTATUS(status
) != 0) {
4674 fprintf(stderr
, "%s: could not launch network script\n",
4682 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4683 const char *setup_script
, const char *down_script
)
4689 if (ifname1
!= NULL
)
4690 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4693 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4697 if (!setup_script
|| !strcmp(setup_script
, "no"))
4699 if (setup_script
[0] != '\0') {
4700 if (launch_script(setup_script
, ifname
, fd
))
4703 s
= net_tap_fd_init(vlan
, fd
);
4706 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4707 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4708 if (down_script
&& strcmp(down_script
, "no"))
4709 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4713 #endif /* !_WIN32 */
4715 #if defined(CONFIG_VDE)
4716 typedef struct VDEState
{
4717 VLANClientState
*vc
;
4721 static void vde_to_qemu(void *opaque
)
4723 VDEState
*s
= opaque
;
4727 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4729 qemu_send_packet(s
->vc
, buf
, size
);
4733 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4735 VDEState
*s
= opaque
;
4738 ret
= vde_send(s
->vde
, buf
, size
, 0);
4739 if (ret
< 0 && errno
== EINTR
) {
4746 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4747 const char *group
, int mode
)
4750 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4751 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4753 struct vde_open_args args
= {
4755 .group
= init_group
,
4759 s
= qemu_mallocz(sizeof(VDEState
));
4762 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4767 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4768 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4769 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4770 sock
, vde_datafd(s
->vde
));
4775 /* network connection */
4776 typedef struct NetSocketState
{
4777 VLANClientState
*vc
;
4779 int state
; /* 0 = getting length, 1 = getting data */
4783 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4786 typedef struct NetSocketListenState
{
4789 } NetSocketListenState
;
4791 /* XXX: we consider we can send the whole packet without blocking */
4792 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4794 NetSocketState
*s
= opaque
;
4798 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4799 send_all(s
->fd
, buf
, size
);
4802 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4804 NetSocketState
*s
= opaque
;
4805 sendto(s
->fd
, buf
, size
, 0,
4806 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4809 static void net_socket_send(void *opaque
)
4811 NetSocketState
*s
= opaque
;
4816 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4818 err
= socket_error();
4819 if (err
!= EWOULDBLOCK
)
4821 } else if (size
== 0) {
4822 /* end of connection */
4824 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4830 /* reassemble a packet from the network */
4836 memcpy(s
->buf
+ s
->index
, buf
, l
);
4840 if (s
->index
== 4) {
4842 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4848 l
= s
->packet_len
- s
->index
;
4851 memcpy(s
->buf
+ s
->index
, buf
, l
);
4855 if (s
->index
>= s
->packet_len
) {
4856 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4865 static void net_socket_send_dgram(void *opaque
)
4867 NetSocketState
*s
= opaque
;
4870 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4874 /* end of connection */
4875 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4878 qemu_send_packet(s
->vc
, s
->buf
, size
);
4881 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4886 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4887 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4888 inet_ntoa(mcastaddr
->sin_addr
),
4889 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4893 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4895 perror("socket(PF_INET, SOCK_DGRAM)");
4900 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4901 (const char *)&val
, sizeof(val
));
4903 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4907 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4913 /* Add host to multicast group */
4914 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4915 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4917 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4918 (const char *)&imr
, sizeof(struct ip_mreq
));
4920 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4924 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4926 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4927 (const char *)&val
, sizeof(val
));
4929 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4933 socket_set_nonblock(fd
);
4941 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4944 struct sockaddr_in saddr
;
4946 socklen_t saddr_len
;
4949 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4950 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4951 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4955 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4957 if (saddr
.sin_addr
.s_addr
==0) {
4958 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4962 /* clone dgram socket */
4963 newfd
= net_socket_mcast_create(&saddr
);
4965 /* error already reported by net_socket_mcast_create() */
4969 /* clone newfd to fd, close newfd */
4974 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4975 fd
, strerror(errno
));
4980 s
= qemu_mallocz(sizeof(NetSocketState
));
4985 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4986 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4988 /* mcast: save bound address as dst */
4989 if (is_connected
) s
->dgram_dst
=saddr
;
4991 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4992 "socket: fd=%d (%s mcast=%s:%d)",
4993 fd
, is_connected
? "cloned" : "",
4994 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4998 static void net_socket_connect(void *opaque
)
5000 NetSocketState
*s
= opaque
;
5001 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
5004 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
5008 s
= qemu_mallocz(sizeof(NetSocketState
));
5012 s
->vc
= qemu_new_vlan_client(vlan
,
5013 net_socket_receive
, NULL
, s
);
5014 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5015 "socket: fd=%d", fd
);
5017 net_socket_connect(s
);
5019 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
5024 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
5027 int so_type
=-1, optlen
=sizeof(so_type
);
5029 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
5030 (socklen_t
*)&optlen
)< 0) {
5031 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
5036 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
5038 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5040 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
5041 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
5042 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
5047 static void net_socket_accept(void *opaque
)
5049 NetSocketListenState
*s
= opaque
;
5051 struct sockaddr_in saddr
;
5056 len
= sizeof(saddr
);
5057 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
5058 if (fd
< 0 && errno
!= EINTR
) {
5060 } else if (fd
>= 0) {
5064 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
5068 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
5069 "socket: connection from %s:%d",
5070 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5074 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
5076 NetSocketListenState
*s
;
5078 struct sockaddr_in saddr
;
5080 if (parse_host_port(&saddr
, host_str
) < 0)
5083 s
= qemu_mallocz(sizeof(NetSocketListenState
));
5087 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5092 socket_set_nonblock(fd
);
5094 /* allow fast reuse */
5096 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5098 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5103 ret
= listen(fd
, 0);
5110 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5114 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5117 int fd
, connected
, ret
, err
;
5118 struct sockaddr_in saddr
;
5120 if (parse_host_port(&saddr
, host_str
) < 0)
5123 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5128 socket_set_nonblock(fd
);
5132 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5134 err
= socket_error();
5135 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5136 } else if (err
== EINPROGRESS
) {
5139 } else if (err
== WSAEALREADY
) {
5152 s
= net_socket_fd_init(vlan
, fd
, connected
);
5155 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5156 "socket: connect to %s:%d",
5157 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5161 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5165 struct sockaddr_in saddr
;
5167 if (parse_host_port(&saddr
, host_str
) < 0)
5171 fd
= net_socket_mcast_create(&saddr
);
5175 s
= net_socket_fd_init(vlan
, fd
, 0);
5179 s
->dgram_dst
= saddr
;
5181 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5182 "socket: mcast=%s:%d",
5183 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5188 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5193 while (*p
!= '\0' && *p
!= '=') {
5194 if (q
&& (q
- buf
) < buf_size
- 1)
5204 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5209 while (*p
!= '\0') {
5211 if (*(p
+ 1) != ',')
5215 if (q
&& (q
- buf
) < buf_size
- 1)
5225 int get_param_value(char *buf
, int buf_size
,
5226 const char *tag
, const char *str
)
5233 p
= get_opt_name(option
, sizeof(option
), p
);
5237 if (!strcmp(tag
, option
)) {
5238 (void)get_opt_value(buf
, buf_size
, p
);
5241 p
= get_opt_value(NULL
, 0, p
);
5250 int check_params(char *buf
, int buf_size
,
5251 char **params
, const char *str
)
5258 p
= get_opt_name(buf
, buf_size
, p
);
5262 for(i
= 0; params
[i
] != NULL
; i
++)
5263 if (!strcmp(params
[i
], buf
))
5265 if (params
[i
] == NULL
)
5267 p
= get_opt_value(NULL
, 0, p
);
5275 static int nic_get_free_idx(void)
5279 for (index
= 0; index
< MAX_NICS
; index
++)
5280 if (!nd_table
[index
].used
)
5285 int net_client_init(const char *device
, const char *p
)
5292 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5293 vlan_id
= strtol(buf
, NULL
, 0);
5295 vlan
= qemu_find_vlan(vlan_id
);
5297 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5300 if (!strcmp(device
, "nic")) {
5303 int idx
= nic_get_free_idx();
5305 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
5306 fprintf(stderr
, "Too Many NICs\n");
5309 nd
= &nd_table
[idx
];
5310 macaddr
= nd
->macaddr
;
5316 macaddr
[5] = 0x56 + idx
;
5318 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5319 if (parse_macaddr(macaddr
, buf
) < 0) {
5320 fprintf(stderr
, "invalid syntax for ethernet address\n");
5324 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5325 nd
->model
= strdup(buf
);
5330 vlan
->nb_guest_devs
++;
5333 if (!strcmp(device
, "none")) {
5334 /* does nothing. It is needed to signal that no network cards
5339 if (!strcmp(device
, "user")) {
5340 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5341 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5343 vlan
->nb_host_devs
++;
5344 ret
= net_slirp_init(vlan
);
5348 if (!strcmp(device
, "tap")) {
5350 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5351 fprintf(stderr
, "tap: no interface name\n");
5354 vlan
->nb_host_devs
++;
5355 ret
= tap_win32_init(vlan
, ifname
);
5358 if (!strcmp(device
, "tap")) {
5360 char setup_script
[1024], down_script
[1024];
5362 vlan
->nb_host_devs
++;
5363 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5364 fd
= strtol(buf
, NULL
, 0);
5365 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5367 if (net_tap_fd_init(vlan
, fd
))
5370 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5373 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5374 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5376 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5377 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5379 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5383 if (!strcmp(device
, "socket")) {
5384 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5386 fd
= strtol(buf
, NULL
, 0);
5388 if (net_socket_fd_init(vlan
, fd
, 1))
5390 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5391 ret
= net_socket_listen_init(vlan
, buf
);
5392 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5393 ret
= net_socket_connect_init(vlan
, buf
);
5394 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5395 ret
= net_socket_mcast_init(vlan
, buf
);
5397 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5400 vlan
->nb_host_devs
++;
5403 if (!strcmp(device
, "vde")) {
5404 char vde_sock
[1024], vde_group
[512];
5405 int vde_port
, vde_mode
;
5406 vlan
->nb_host_devs
++;
5407 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5410 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5411 vde_port
= strtol(buf
, NULL
, 10);
5415 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5416 vde_group
[0] = '\0';
5418 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5419 vde_mode
= strtol(buf
, NULL
, 8);
5423 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5427 fprintf(stderr
, "Unknown network device: %s\n", device
);
5431 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5437 void net_client_uninit(NICInfo
*nd
)
5439 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5442 free((void *)nd
->model
);
5445 static int net_client_parse(const char *str
)
5453 while (*p
!= '\0' && *p
!= ',') {
5454 if ((q
- device
) < sizeof(device
) - 1)
5462 return net_client_init(device
, p
);
5465 void do_info_network(void)
5468 VLANClientState
*vc
;
5470 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5471 term_printf("VLAN %d devices:\n", vlan
->id
);
5472 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5473 term_printf(" %s\n", vc
->info_str
);
5477 #define HD_ALIAS "index=%d,media=disk"
5479 #define CDROM_ALIAS "index=1,media=cdrom"
5481 #define CDROM_ALIAS "index=2,media=cdrom"
5483 #define FD_ALIAS "index=%d,if=floppy"
5484 #define PFLASH_ALIAS "if=pflash"
5485 #define MTD_ALIAS "if=mtd"
5486 #define SD_ALIAS "index=0,if=sd"
5488 static int drive_opt_get_free_idx(void)
5492 for (index
= 0; index
< MAX_DRIVES
; index
++)
5493 if (!drives_opt
[index
].used
) {
5494 drives_opt
[index
].used
= 1;
5501 static int drive_get_free_idx(void)
5505 for (index
= 0; index
< MAX_DRIVES
; index
++)
5506 if (!drives_table
[index
].used
) {
5507 drives_table
[index
].used
= 1;
5514 int drive_add(const char *file
, const char *fmt
, ...)
5517 int index
= drive_opt_get_free_idx();
5519 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5520 fprintf(stderr
, "qemu: too many drives\n");
5524 drives_opt
[index
].file
= file
;
5526 vsnprintf(drives_opt
[index
].opt
,
5527 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5534 void drive_remove(int index
)
5536 drives_opt
[index
].used
= 0;
5540 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5544 /* seek interface, bus and unit */
5546 for (index
= 0; index
< MAX_DRIVES
; index
++)
5547 if (drives_table
[index
].type
== type
&&
5548 drives_table
[index
].bus
== bus
&&
5549 drives_table
[index
].unit
== unit
&&
5550 drives_table
[index
].used
)
5556 int drive_get_max_bus(BlockInterfaceType type
)
5562 for (index
= 0; index
< nb_drives
; index
++) {
5563 if(drives_table
[index
].type
== type
&&
5564 drives_table
[index
].bus
> max_bus
)
5565 max_bus
= drives_table
[index
].bus
;
5570 static void bdrv_format_print(void *opaque
, const char *name
)
5572 fprintf(stderr
, " %s", name
);
5575 void drive_uninit(BlockDriverState
*bdrv
)
5579 for (i
= 0; i
< MAX_DRIVES
; i
++)
5580 if (drives_table
[i
].bdrv
== bdrv
) {
5581 drives_table
[i
].bdrv
= NULL
;
5582 drives_table
[i
].used
= 0;
5583 drive_remove(drives_table
[i
].drive_opt_idx
);
5589 int drive_init(struct drive_opt
*arg
, int snapshot
,
5590 QEMUMachine
*machine
)
5595 const char *mediastr
= "";
5596 BlockInterfaceType type
;
5597 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5598 int bus_id
, unit_id
;
5599 int cyls
, heads
, secs
, translation
;
5600 BlockDriverState
*bdrv
;
5601 BlockDriver
*drv
= NULL
;
5606 int drives_table_idx
;
5607 char *str
= arg
->opt
;
5608 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5609 "secs", "trans", "media", "snapshot", "file",
5610 "cache", "format", "boot", NULL
};
5612 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5613 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5619 cyls
= heads
= secs
= 0;
5622 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5626 if (!strcmp(machine
->name
, "realview") ||
5627 !strcmp(machine
->name
, "SS-5") ||
5628 !strcmp(machine
->name
, "SS-10") ||
5629 !strcmp(machine
->name
, "SS-600MP") ||
5630 !strcmp(machine
->name
, "versatilepb") ||
5631 !strcmp(machine
->name
, "versatileab")) {
5633 max_devs
= MAX_SCSI_DEVS
;
5634 strcpy(devname
, "scsi");
5637 max_devs
= MAX_IDE_DEVS
;
5638 strcpy(devname
, "ide");
5642 /* extract parameters */
5644 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5645 bus_id
= strtol(buf
, NULL
, 0);
5647 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5652 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5653 unit_id
= strtol(buf
, NULL
, 0);
5655 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5660 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5661 pstrcpy(devname
, sizeof(devname
), buf
);
5662 if (!strcmp(buf
, "ide")) {
5664 max_devs
= MAX_IDE_DEVS
;
5665 } else if (!strcmp(buf
, "scsi")) {
5667 max_devs
= MAX_SCSI_DEVS
;
5668 } else if (!strcmp(buf
, "floppy")) {
5671 } else if (!strcmp(buf
, "pflash")) {
5674 } else if (!strcmp(buf
, "mtd")) {
5677 } else if (!strcmp(buf
, "sd")) {
5680 } else if (!strcmp(buf
, "virtio")) {
5684 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5689 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5690 index
= strtol(buf
, NULL
, 0);
5692 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5697 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5698 cyls
= strtol(buf
, NULL
, 0);
5701 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5702 heads
= strtol(buf
, NULL
, 0);
5705 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5706 secs
= strtol(buf
, NULL
, 0);
5709 if (cyls
|| heads
|| secs
) {
5710 if (cyls
< 1 || cyls
> 16383) {
5711 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5714 if (heads
< 1 || heads
> 16) {
5715 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5718 if (secs
< 1 || secs
> 63) {
5719 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5724 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5727 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5731 if (!strcmp(buf
, "none"))
5732 translation
= BIOS_ATA_TRANSLATION_NONE
;
5733 else if (!strcmp(buf
, "lba"))
5734 translation
= BIOS_ATA_TRANSLATION_LBA
;
5735 else if (!strcmp(buf
, "auto"))
5736 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5738 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5743 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5744 if (!strcmp(buf
, "disk")) {
5746 } else if (!strcmp(buf
, "cdrom")) {
5747 if (cyls
|| secs
|| heads
) {
5749 "qemu: '%s' invalid physical CHS format\n", str
);
5752 media
= MEDIA_CDROM
;
5754 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5759 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5760 if (!strcmp(buf
, "on"))
5762 else if (!strcmp(buf
, "off"))
5765 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5770 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5771 if (!strcmp(buf
, "off"))
5773 else if (!strcmp(buf
, "on"))
5776 fprintf(stderr
, "qemu: invalid cache option\n");
5781 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5782 if (strcmp(buf
, "?") == 0) {
5783 fprintf(stderr
, "qemu: Supported formats:");
5784 bdrv_iterate_format(bdrv_format_print
, NULL
);
5785 fprintf(stderr
, "\n");
5788 drv
= bdrv_find_format(buf
);
5790 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5795 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5796 if (!strcmp(buf
, "on")) {
5797 if (extboot_drive
!= -1) {
5798 fprintf(stderr
, "qemu: two bootable drives specified\n");
5801 extboot_drive
= nb_drives
;
5802 } else if (strcmp(buf
, "off")) {
5803 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5808 if (arg
->file
== NULL
)
5809 get_param_value(file
, sizeof(file
), "file", str
);
5811 pstrcpy(file
, sizeof(file
), arg
->file
);
5813 /* compute bus and unit according index */
5816 if (bus_id
!= 0 || unit_id
!= -1) {
5818 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5826 unit_id
= index
% max_devs
;
5827 bus_id
= index
/ max_devs
;
5831 /* if user doesn't specify a unit_id,
5832 * try to find the first free
5835 if (unit_id
== -1) {
5837 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5839 if (max_devs
&& unit_id
>= max_devs
) {
5840 unit_id
-= max_devs
;
5848 if (max_devs
&& unit_id
>= max_devs
) {
5849 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5850 str
, unit_id
, max_devs
- 1);
5855 * ignore multiple definitions
5858 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5863 if (type
== IF_IDE
|| type
== IF_SCSI
)
5864 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5866 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5867 devname
, bus_id
, mediastr
, unit_id
);
5869 snprintf(buf
, sizeof(buf
), "%s%s%i",
5870 devname
, mediastr
, unit_id
);
5871 bdrv
= bdrv_new(buf
);
5872 drives_table_idx
= drive_get_free_idx();
5873 drives_table
[drives_table_idx
].bdrv
= bdrv
;
5874 drives_table
[drives_table_idx
].type
= type
;
5875 drives_table
[drives_table_idx
].bus
= bus_id
;
5876 drives_table
[drives_table_idx
].unit
= unit_id
;
5877 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
5886 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5887 bdrv_set_translation_hint(bdrv
, translation
);
5891 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5896 /* FIXME: This isn't really a floppy, but it's a reasonable
5899 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5910 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5912 bdrv_flags
|= BDRV_O_DIRECT
;
5913 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0) {
5914 fprintf(stderr
, "qemu: could not open disk image %s\n",
5918 return drives_table_idx
;
5921 /***********************************************************/
5924 static USBPort
*used_usb_ports
;
5925 static USBPort
*free_usb_ports
;
5927 /* ??? Maybe change this to register a hub to keep track of the topology. */
5928 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5929 usb_attachfn attach
)
5931 port
->opaque
= opaque
;
5932 port
->index
= index
;
5933 port
->attach
= attach
;
5934 port
->next
= free_usb_ports
;
5935 free_usb_ports
= port
;
5938 static int usb_device_add(const char *devname
)
5944 if (!free_usb_ports
)
5947 if (strstart(devname
, "host:", &p
)) {
5948 dev
= usb_host_device_open(p
);
5949 } else if (!strcmp(devname
, "mouse")) {
5950 dev
= usb_mouse_init();
5951 } else if (!strcmp(devname
, "tablet")) {
5952 dev
= usb_tablet_init();
5953 } else if (!strcmp(devname
, "keyboard")) {
5954 dev
= usb_keyboard_init();
5955 } else if (strstart(devname
, "disk:", &p
)) {
5956 dev
= usb_msd_init(p
);
5957 } else if (!strcmp(devname
, "wacom-tablet")) {
5958 dev
= usb_wacom_init();
5959 } else if (strstart(devname
, "serial:", &p
)) {
5960 dev
= usb_serial_init(p
);
5961 #ifdef CONFIG_BRLAPI
5962 } else if (!strcmp(devname
, "braille")) {
5963 dev
= usb_baum_init();
5965 } else if (strstart(devname
, "net:", &p
)) {
5968 if (net_client_init("nic", p
) < 0)
5970 nd_table
[nic
].model
= "usb";
5971 dev
= usb_net_init(&nd_table
[nic
]);
5978 /* Find a USB port to add the device to. */
5979 port
= free_usb_ports
;
5983 /* Create a new hub and chain it on. */
5984 free_usb_ports
= NULL
;
5985 port
->next
= used_usb_ports
;
5986 used_usb_ports
= port
;
5988 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5989 usb_attach(port
, hub
);
5990 port
= free_usb_ports
;
5993 free_usb_ports
= port
->next
;
5994 port
->next
= used_usb_ports
;
5995 used_usb_ports
= port
;
5996 usb_attach(port
, dev
);
6000 static int usb_device_del(const char *devname
)
6008 if (!used_usb_ports
)
6011 p
= strchr(devname
, '.');
6014 bus_num
= strtoul(devname
, NULL
, 0);
6015 addr
= strtoul(p
+ 1, NULL
, 0);
6019 lastp
= &used_usb_ports
;
6020 port
= used_usb_ports
;
6021 while (port
&& port
->dev
->addr
!= addr
) {
6022 lastp
= &port
->next
;
6030 *lastp
= port
->next
;
6031 usb_attach(port
, NULL
);
6032 dev
->handle_destroy(dev
);
6033 port
->next
= free_usb_ports
;
6034 free_usb_ports
= port
;
6038 void do_usb_add(const char *devname
)
6041 ret
= usb_device_add(devname
);
6043 term_printf("Could not add USB device '%s'\n", devname
);
6046 void do_usb_del(const char *devname
)
6049 ret
= usb_device_del(devname
);
6051 term_printf("Could not remove USB device '%s'\n", devname
);
6058 const char *speed_str
;
6061 term_printf("USB support not enabled\n");
6065 for (port
= used_usb_ports
; port
; port
= port
->next
) {
6069 switch(dev
->speed
) {
6073 case USB_SPEED_FULL
:
6076 case USB_SPEED_HIGH
:
6083 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
6084 0, dev
->addr
, speed_str
, dev
->devname
);
6088 /***********************************************************/
6089 /* PCMCIA/Cardbus */
6091 static struct pcmcia_socket_entry_s
{
6092 struct pcmcia_socket_s
*socket
;
6093 struct pcmcia_socket_entry_s
*next
;
6094 } *pcmcia_sockets
= 0;
6096 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
6098 struct pcmcia_socket_entry_s
*entry
;
6100 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
6101 entry
->socket
= socket
;
6102 entry
->next
= pcmcia_sockets
;
6103 pcmcia_sockets
= entry
;
6106 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
6108 struct pcmcia_socket_entry_s
*entry
, **ptr
;
6110 ptr
= &pcmcia_sockets
;
6111 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
6112 if (entry
->socket
== socket
) {
6118 void pcmcia_info(void)
6120 struct pcmcia_socket_entry_s
*iter
;
6121 if (!pcmcia_sockets
)
6122 term_printf("No PCMCIA sockets\n");
6124 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
6125 term_printf("%s: %s\n", iter
->socket
->slot_string
,
6126 iter
->socket
->attached
? iter
->socket
->card_string
:
6130 /***********************************************************/
6133 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
6137 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
6141 static void dumb_refresh(DisplayState
*ds
)
6143 #if defined(CONFIG_SDL)
6148 static void dumb_display_init(DisplayState
*ds
)
6153 ds
->dpy_update
= dumb_update
;
6154 ds
->dpy_resize
= dumb_resize
;
6155 ds
->dpy_refresh
= dumb_refresh
;
6158 /***********************************************************/
6161 #define MAX_IO_HANDLERS 64
6163 typedef struct IOHandlerRecord
{
6165 IOCanRWHandler
*fd_read_poll
;
6167 IOHandler
*fd_write
;
6170 /* temporary data */
6172 struct IOHandlerRecord
*next
;
6175 static IOHandlerRecord
*first_io_handler
;
6177 /* XXX: fd_read_poll should be suppressed, but an API change is
6178 necessary in the character devices to suppress fd_can_read(). */
6179 int qemu_set_fd_handler2(int fd
,
6180 IOCanRWHandler
*fd_read_poll
,
6182 IOHandler
*fd_write
,
6185 IOHandlerRecord
**pioh
, *ioh
;
6187 if (!fd_read
&& !fd_write
) {
6188 pioh
= &first_io_handler
;
6193 if (ioh
->fd
== fd
) {
6200 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6204 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6207 ioh
->next
= first_io_handler
;
6208 first_io_handler
= ioh
;
6211 ioh
->fd_read_poll
= fd_read_poll
;
6212 ioh
->fd_read
= fd_read
;
6213 ioh
->fd_write
= fd_write
;
6214 ioh
->opaque
= opaque
;
6221 int qemu_set_fd_handler(int fd
,
6223 IOHandler
*fd_write
,
6226 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6229 /***********************************************************/
6230 /* Polling handling */
6232 typedef struct PollingEntry
{
6235 struct PollingEntry
*next
;
6238 static PollingEntry
*first_polling_entry
;
6240 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6242 PollingEntry
**ppe
, *pe
;
6243 pe
= qemu_mallocz(sizeof(PollingEntry
));
6247 pe
->opaque
= opaque
;
6248 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6253 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6255 PollingEntry
**ppe
, *pe
;
6256 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6258 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6267 /***********************************************************/
6268 /* Wait objects support */
6269 typedef struct WaitObjects
{
6271 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6272 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6273 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6276 static WaitObjects wait_objects
= {0};
6278 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6280 WaitObjects
*w
= &wait_objects
;
6282 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6284 w
->events
[w
->num
] = handle
;
6285 w
->func
[w
->num
] = func
;
6286 w
->opaque
[w
->num
] = opaque
;
6291 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6294 WaitObjects
*w
= &wait_objects
;
6297 for (i
= 0; i
< w
->num
; i
++) {
6298 if (w
->events
[i
] == handle
)
6301 w
->events
[i
] = w
->events
[i
+ 1];
6302 w
->func
[i
] = w
->func
[i
+ 1];
6303 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6311 #define SELF_ANNOUNCE_ROUNDS 5
6312 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
6313 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
6314 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
6316 static int announce_self_create(uint8_t *buf
,
6319 uint32_t magic
= EXPERIMENTAL_MAGIC
;
6320 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
6322 /* FIXME: should we send a different packet (arp/rarp/ping)? */
6324 memset(buf
, 0xff, 6); /* h_dst */
6325 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
6326 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
6327 memcpy(buf
+ 14, &magic
, 4); /* magic */
6329 return 18; /* len */
6332 static void qemu_announce_self(void)
6336 VLANClientState
*vc
;
6339 for (i
= 0; i
< nb_nics
; i
++) {
6340 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
6341 vlan
= nd_table
[i
].vlan
;
6342 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
6343 if (vc
->fd_read
== tap_receive
) /* send only if tap */
6344 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
6345 vc
->fd_read(vc
->opaque
, buf
, len
);
6350 /***********************************************************/
6351 /* savevm/loadvm support */
6353 #define IO_BUF_SIZE 32768
6356 QEMUFilePutBufferFunc
*put_buffer
;
6357 QEMUFileGetBufferFunc
*get_buffer
;
6358 QEMUFileCloseFunc
*close
;
6361 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6364 int buf_size
; /* 0 when writing */
6365 uint8_t buf
[IO_BUF_SIZE
];
6368 typedef struct QEMUFileFD
6373 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6375 QEMUFileFD
*s
= opaque
;
6380 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6382 if (errno
== EINTR
|| errno
== EAGAIN
)
6389 QEMUFile
*qemu_fopen_fd(int fd
)
6391 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6393 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6396 typedef struct QEMUFileUnix
6401 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6403 QEMUFileUnix
*s
= opaque
;
6404 fseek(s
->outfile
, pos
, SEEK_SET
);
6405 fwrite(buf
, 1, size
, s
->outfile
);
6408 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6410 QEMUFileUnix
*s
= opaque
;
6411 fseek(s
->outfile
, pos
, SEEK_SET
);
6412 return fread(buf
, 1, size
, s
->outfile
);
6415 static void file_close(void *opaque
)
6417 QEMUFileUnix
*s
= opaque
;
6422 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6426 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6430 s
->outfile
= fopen(filename
, mode
);
6434 if (!strcmp(mode
, "wb"))
6435 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6436 else if (!strcmp(mode
, "rb"))
6437 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6446 typedef struct QEMUFileBdrv
6448 BlockDriverState
*bs
;
6449 int64_t base_offset
;
6452 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6454 QEMUFileBdrv
*s
= opaque
;
6455 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6458 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6460 QEMUFileBdrv
*s
= opaque
;
6461 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6464 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6468 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6473 s
->base_offset
= offset
;
6476 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6478 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6481 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6482 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6486 f
= qemu_mallocz(sizeof(QEMUFile
));
6491 f
->put_buffer
= put_buffer
;
6492 f
->get_buffer
= get_buffer
;
6498 void qemu_fflush(QEMUFile
*f
)
6503 if (f
->buf_index
> 0) {
6504 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6505 f
->buf_offset
+= f
->buf_index
;
6510 static void qemu_fill_buffer(QEMUFile
*f
)
6517 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6523 f
->buf_offset
+= len
;
6526 void qemu_fclose(QEMUFile
*f
)
6530 f
->close(f
->opaque
);
6534 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6538 l
= IO_BUF_SIZE
- f
->buf_index
;
6541 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6545 if (f
->buf_index
>= IO_BUF_SIZE
)
6550 void qemu_put_byte(QEMUFile
*f
, int v
)
6552 f
->buf
[f
->buf_index
++] = v
;
6553 if (f
->buf_index
>= IO_BUF_SIZE
)
6557 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6563 l
= f
->buf_size
- f
->buf_index
;
6565 qemu_fill_buffer(f
);
6566 l
= f
->buf_size
- f
->buf_index
;
6572 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6577 return size1
- size
;
6580 int qemu_get_byte(QEMUFile
*f
)
6582 if (f
->buf_index
>= f
->buf_size
) {
6583 qemu_fill_buffer(f
);
6584 if (f
->buf_index
>= f
->buf_size
)
6587 return f
->buf
[f
->buf_index
++];
6590 int64_t qemu_ftell(QEMUFile
*f
)
6592 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6595 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6597 if (whence
== SEEK_SET
) {
6599 } else if (whence
== SEEK_CUR
) {
6600 pos
+= qemu_ftell(f
);
6602 /* SEEK_END not supported */
6605 if (f
->put_buffer
) {
6607 f
->buf_offset
= pos
;
6609 f
->buf_offset
= pos
;
6616 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6618 qemu_put_byte(f
, v
>> 8);
6619 qemu_put_byte(f
, v
);
6622 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6624 qemu_put_byte(f
, v
>> 24);
6625 qemu_put_byte(f
, v
>> 16);
6626 qemu_put_byte(f
, v
>> 8);
6627 qemu_put_byte(f
, v
);
6630 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6632 qemu_put_be32(f
, v
>> 32);
6633 qemu_put_be32(f
, v
);
6636 unsigned int qemu_get_be16(QEMUFile
*f
)
6639 v
= qemu_get_byte(f
) << 8;
6640 v
|= qemu_get_byte(f
);
6644 unsigned int qemu_get_be32(QEMUFile
*f
)
6647 v
= qemu_get_byte(f
) << 24;
6648 v
|= qemu_get_byte(f
) << 16;
6649 v
|= qemu_get_byte(f
) << 8;
6650 v
|= qemu_get_byte(f
);
6654 uint64_t qemu_get_be64(QEMUFile
*f
)
6657 v
= (uint64_t)qemu_get_be32(f
) << 32;
6658 v
|= qemu_get_be32(f
);
6662 typedef struct SaveStateEntry
{
6666 SaveStateHandler
*save_state
;
6667 LoadStateHandler
*load_state
;
6669 struct SaveStateEntry
*next
;
6672 static SaveStateEntry
*first_se
;
6674 /* TODO: Individual devices generally have very little idea about the rest
6675 of the system, so instance_id should be removed/replaced.
6676 Meanwhile pass -1 as instance_id if you do not already have a clearly
6677 distinguishing id for all instances of your device class. */
6678 int register_savevm(const char *idstr
,
6681 SaveStateHandler
*save_state
,
6682 LoadStateHandler
*load_state
,
6685 SaveStateEntry
*se
, **pse
;
6687 se
= qemu_malloc(sizeof(SaveStateEntry
));
6690 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6691 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6692 se
->version_id
= version_id
;
6693 se
->save_state
= save_state
;
6694 se
->load_state
= load_state
;
6695 se
->opaque
= opaque
;
6698 /* add at the end of list */
6700 while (*pse
!= NULL
) {
6701 if (instance_id
== -1
6702 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6703 && se
->instance_id
<= (*pse
)->instance_id
)
6704 se
->instance_id
= (*pse
)->instance_id
+ 1;
6705 pse
= &(*pse
)->next
;
6711 #define QEMU_VM_FILE_MAGIC 0x5145564d
6712 #define QEMU_VM_FILE_VERSION 0x00000002
6714 static int qemu_savevm_state(QEMUFile
*f
)
6718 int64_t cur_pos
, len_pos
, total_len_pos
;
6720 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6721 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6722 total_len_pos
= qemu_ftell(f
);
6723 qemu_put_be64(f
, 0); /* total size */
6725 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6726 if (se
->save_state
== NULL
)
6727 /* this one has a loader only, for backwards compatibility */
6731 len
= strlen(se
->idstr
);
6732 qemu_put_byte(f
, len
);
6733 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6735 qemu_put_be32(f
, se
->instance_id
);
6736 qemu_put_be32(f
, se
->version_id
);
6738 /* record size: filled later */
6739 len_pos
= qemu_ftell(f
);
6740 qemu_put_be32(f
, 0);
6741 se
->save_state(f
, se
->opaque
);
6743 /* fill record size */
6744 cur_pos
= qemu_ftell(f
);
6745 len
= cur_pos
- len_pos
- 4;
6746 qemu_fseek(f
, len_pos
, SEEK_SET
);
6747 qemu_put_be32(f
, len
);
6748 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6750 cur_pos
= qemu_ftell(f
);
6751 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6752 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6753 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6759 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6763 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6764 if (!strcmp(se
->idstr
, idstr
) &&
6765 instance_id
== se
->instance_id
)
6771 static int qemu_loadvm_state(QEMUFile
*f
)
6774 int len
, ret
, instance_id
, record_len
, version_id
;
6775 int64_t total_len
, end_pos
, cur_pos
;
6779 v
= qemu_get_be32(f
);
6780 if (v
!= QEMU_VM_FILE_MAGIC
)
6782 v
= qemu_get_be32(f
);
6783 if (v
!= QEMU_VM_FILE_VERSION
) {
6788 total_len
= qemu_get_be64(f
);
6789 end_pos
= total_len
+ qemu_ftell(f
);
6791 if (qemu_ftell(f
) >= end_pos
)
6793 len
= qemu_get_byte(f
);
6794 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6796 instance_id
= qemu_get_be32(f
);
6797 version_id
= qemu_get_be32(f
);
6798 record_len
= qemu_get_be32(f
);
6800 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6801 idstr
, instance_id
, version_id
, record_len
);
6803 cur_pos
= qemu_ftell(f
);
6804 se
= find_se(idstr
, instance_id
);
6806 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6807 instance_id
, idstr
);
6809 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6811 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6812 instance_id
, idstr
);
6816 /* always seek to exact end of record */
6817 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6824 int qemu_live_savevm_state(QEMUFile
*f
)
6829 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6830 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6832 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6833 len
= strlen(se
->idstr
);
6835 qemu_put_byte(f
, len
);
6836 qemu_put_buffer(f
, se
->idstr
, len
);
6837 qemu_put_be32(f
, se
->instance_id
);
6838 qemu_put_be32(f
, se
->version_id
);
6840 se
->save_state(f
, se
->opaque
);
6843 qemu_put_byte(f
, 0);
6849 int qemu_live_loadvm_state(QEMUFile
*f
)
6852 int len
, ret
, instance_id
, version_id
;
6856 v
= qemu_get_be32(f
);
6857 if (v
!= QEMU_VM_FILE_MAGIC
)
6859 v
= qemu_get_be32(f
);
6860 if (v
!= QEMU_VM_FILE_VERSION
) {
6867 len
= qemu_get_byte(f
);
6870 qemu_get_buffer(f
, idstr
, len
);
6872 instance_id
= qemu_get_be32(f
);
6873 version_id
= qemu_get_be32(f
);
6874 se
= find_se(idstr
, instance_id
);
6876 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6877 instance_id
, idstr
);
6879 if (version_id
> se
->version_id
) { /* src version > dst version */
6880 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6881 idstr
, version_id
, se
->version_id
);
6885 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6887 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6888 instance_id
, idstr
);
6895 qemu_announce_self();
6901 /* device can contain snapshots */
6902 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6905 !bdrv_is_removable(bs
) &&
6906 !bdrv_is_read_only(bs
));
6909 /* device must be snapshots in order to have a reliable snapshot */
6910 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6913 !bdrv_is_removable(bs
) &&
6914 !bdrv_is_read_only(bs
));
6917 static BlockDriverState
*get_bs_snapshots(void)
6919 BlockDriverState
*bs
;
6923 return bs_snapshots
;
6924 for(i
= 0; i
<= nb_drives
; i
++) {
6925 bs
= drives_table
[i
].bdrv
;
6926 if (bdrv_can_snapshot(bs
))
6935 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6938 QEMUSnapshotInfo
*sn_tab
, *sn
;
6942 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6945 for(i
= 0; i
< nb_sns
; i
++) {
6947 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6957 void do_savevm(const char *name
)
6959 BlockDriverState
*bs
, *bs1
;
6960 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6961 int must_delete
, ret
, i
;
6962 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6964 int saved_vm_running
;
6971 bs
= get_bs_snapshots();
6973 term_printf("No block device can accept snapshots\n");
6977 /* ??? Should this occur after vm_stop? */
6980 saved_vm_running
= vm_running
;
6985 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6990 memset(sn
, 0, sizeof(*sn
));
6992 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6993 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6996 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6999 /* fill auxiliary fields */
7002 sn
->date_sec
= tb
.time
;
7003 sn
->date_nsec
= tb
.millitm
* 1000000;
7005 gettimeofday(&tv
, NULL
);
7006 sn
->date_sec
= tv
.tv_sec
;
7007 sn
->date_nsec
= tv
.tv_usec
* 1000;
7009 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
7011 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7012 term_printf("Device %s does not support VM state snapshots\n",
7013 bdrv_get_device_name(bs
));
7017 /* save the VM state */
7018 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
7020 term_printf("Could not open VM state file\n");
7023 ret
= qemu_savevm_state(f
);
7024 sn
->vm_state_size
= qemu_ftell(f
);
7027 term_printf("Error %d while writing VM\n", ret
);
7031 /* create the snapshots */
7033 for(i
= 0; i
< nb_drives
; i
++) {
7034 bs1
= drives_table
[i
].bdrv
;
7035 if (bdrv_has_snapshot(bs1
)) {
7037 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
7039 term_printf("Error while deleting snapshot on '%s'\n",
7040 bdrv_get_device_name(bs1
));
7043 ret
= bdrv_snapshot_create(bs1
, sn
);
7045 term_printf("Error while creating snapshot on '%s'\n",
7046 bdrv_get_device_name(bs1
));
7052 if (saved_vm_running
)
7056 void do_loadvm(const char *name
)
7058 BlockDriverState
*bs
, *bs1
;
7059 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
7062 int saved_vm_running
;
7064 bs
= get_bs_snapshots();
7066 term_printf("No block device supports snapshots\n");
7070 /* Flush all IO requests so they don't interfere with the new state. */
7073 saved_vm_running
= vm_running
;
7076 for(i
= 0; i
<= nb_drives
; i
++) {
7077 bs1
= drives_table
[i
].bdrv
;
7078 if (bdrv_has_snapshot(bs1
)) {
7079 ret
= bdrv_snapshot_goto(bs1
, name
);
7082 term_printf("Warning: ");
7085 term_printf("Snapshots not supported on device '%s'\n",
7086 bdrv_get_device_name(bs1
));
7089 term_printf("Could not find snapshot '%s' on device '%s'\n",
7090 name
, bdrv_get_device_name(bs1
));
7093 term_printf("Error %d while activating snapshot on '%s'\n",
7094 ret
, bdrv_get_device_name(bs1
));
7097 /* fatal on snapshot block device */
7104 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
7105 term_printf("Device %s does not support VM state snapshots\n",
7106 bdrv_get_device_name(bs
));
7110 /* restore the VM state */
7111 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
7113 term_printf("Could not open VM state file\n");
7116 ret
= qemu_loadvm_state(f
);
7119 term_printf("Error %d while loading VM state\n", ret
);
7122 if (saved_vm_running
)
7126 void do_delvm(const char *name
)
7128 BlockDriverState
*bs
, *bs1
;
7131 bs
= get_bs_snapshots();
7133 term_printf("No block device supports snapshots\n");
7137 for(i
= 0; i
<= nb_drives
; i
++) {
7138 bs1
= drives_table
[i
].bdrv
;
7139 if (bdrv_has_snapshot(bs1
)) {
7140 ret
= bdrv_snapshot_delete(bs1
, name
);
7142 if (ret
== -ENOTSUP
)
7143 term_printf("Snapshots not supported on device '%s'\n",
7144 bdrv_get_device_name(bs1
));
7146 term_printf("Error %d while deleting snapshot on '%s'\n",
7147 ret
, bdrv_get_device_name(bs1
));
7153 void do_info_snapshots(void)
7155 BlockDriverState
*bs
, *bs1
;
7156 QEMUSnapshotInfo
*sn_tab
, *sn
;
7160 bs
= get_bs_snapshots();
7162 term_printf("No available block device supports snapshots\n");
7165 term_printf("Snapshot devices:");
7166 for(i
= 0; i
<= nb_drives
; i
++) {
7167 bs1
= drives_table
[i
].bdrv
;
7168 if (bdrv_has_snapshot(bs1
)) {
7170 term_printf(" %s", bdrv_get_device_name(bs1
));
7175 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
7177 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
7180 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
7181 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
7182 for(i
= 0; i
< nb_sns
; i
++) {
7184 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
7189 /***********************************************************/
7190 /* ram save/restore */
7192 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
7196 v
= qemu_get_byte(f
);
7199 if (qemu_get_buffer(f
, buf
, len
) != len
)
7203 v
= qemu_get_byte(f
);
7204 memset(buf
, v
, len
);
7212 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
7217 if (qemu_get_be32(f
) != phys_ram_size
)
7219 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
7220 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7222 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
7229 #define BDRV_HASH_BLOCK_SIZE 1024
7230 #define IOBUF_SIZE 4096
7231 #define RAM_CBLOCK_MAGIC 0xfabe
7233 typedef struct RamCompressState
{
7236 uint8_t buf
[IOBUF_SIZE
];
7239 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
7242 memset(s
, 0, sizeof(*s
));
7244 ret
= deflateInit2(&s
->zstream
, 1,
7246 9, Z_DEFAULT_STRATEGY
);
7249 s
->zstream
.avail_out
= IOBUF_SIZE
;
7250 s
->zstream
.next_out
= s
->buf
;
7254 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
7256 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
7257 qemu_put_be16(s
->f
, len
);
7258 qemu_put_buffer(s
->f
, buf
, len
);
7261 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
7265 s
->zstream
.avail_in
= len
;
7266 s
->zstream
.next_in
= (uint8_t *)buf
;
7267 while (s
->zstream
.avail_in
> 0) {
7268 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
7271 if (s
->zstream
.avail_out
== 0) {
7272 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
7273 s
->zstream
.avail_out
= IOBUF_SIZE
;
7274 s
->zstream
.next_out
= s
->buf
;
7280 static void ram_compress_close(RamCompressState
*s
)
7284 /* compress last bytes */
7286 ret
= deflate(&s
->zstream
, Z_FINISH
);
7287 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
7288 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
7290 ram_put_cblock(s
, s
->buf
, len
);
7292 s
->zstream
.avail_out
= IOBUF_SIZE
;
7293 s
->zstream
.next_out
= s
->buf
;
7294 if (ret
== Z_STREAM_END
)
7301 deflateEnd(&s
->zstream
);
7304 typedef struct RamDecompressState
{
7307 uint8_t buf
[IOBUF_SIZE
];
7308 } RamDecompressState
;
7310 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
7313 memset(s
, 0, sizeof(*s
));
7315 ret
= inflateInit(&s
->zstream
);
7321 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
7325 s
->zstream
.avail_out
= len
;
7326 s
->zstream
.next_out
= buf
;
7327 while (s
->zstream
.avail_out
> 0) {
7328 if (s
->zstream
.avail_in
== 0) {
7329 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7331 clen
= qemu_get_be16(s
->f
);
7332 if (clen
> IOBUF_SIZE
)
7334 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7335 s
->zstream
.avail_in
= clen
;
7336 s
->zstream
.next_in
= s
->buf
;
7338 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7339 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7346 static void ram_decompress_close(RamDecompressState
*s
)
7348 inflateEnd(&s
->zstream
);
7351 static void ram_save_live(QEMUFile
*f
, void *opaque
)
7355 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
7356 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
7358 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
7359 qemu_put_be32(f
, addr
);
7360 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7363 qemu_put_be32(f
, 1);
7366 static void ram_save_static(QEMUFile
*f
, void *opaque
)
7369 RamCompressState s1
, *s
= &s1
;
7372 qemu_put_be32(f
, phys_ram_size
);
7373 if (ram_compress_open(s
, f
) < 0)
7375 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7376 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7379 if (tight_savevm_enabled
) {
7383 /* find if the memory block is available on a virtual
7386 for(j
= 0; j
< nb_drives
; j
++) {
7387 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7389 BDRV_HASH_BLOCK_SIZE
);
7390 if (sector_num
>= 0)
7394 goto normal_compress
;
7397 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7398 ram_compress_buf(s
, buf
, 10);
7404 ram_compress_buf(s
, buf
, 1);
7405 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7408 ram_compress_close(s
);
7411 static void ram_save(QEMUFile
*f
, void *opaque
)
7413 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7415 qemu_put_byte(f
, in_migration
);
7418 ram_save_live(f
, opaque
);
7420 ram_save_static(f
, opaque
);
7423 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7428 addr
= qemu_get_be32(f
);
7432 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7438 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7440 RamDecompressState s1
, *s
= &s1
;
7444 if (qemu_get_be32(f
) != phys_ram_size
)
7446 if (ram_decompress_open(s
, f
) < 0)
7448 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7449 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7451 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7452 fprintf(stderr
, "Error while reading ram block header\n");
7456 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7457 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7466 ram_decompress_buf(s
, buf
+ 1, 9);
7468 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7469 if (bs_index
>= nb_drives
) {
7470 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7473 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7475 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7476 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7477 bs_index
, sector_num
);
7484 printf("Error block header\n");
7488 ram_decompress_close(s
);
7492 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7496 switch (version_id
) {
7498 ret
= ram_load_v1(f
, opaque
);
7501 if (qemu_get_byte(f
)) {
7502 ret
= ram_load_live(f
, opaque
);
7506 ret
= ram_load_static(f
, opaque
);
7516 /***********************************************************/
7517 /* bottom halves (can be seen as timers which expire ASAP) */
7526 static QEMUBH
*first_bh
= NULL
;
7528 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7531 bh
= qemu_mallocz(sizeof(QEMUBH
));
7535 bh
->opaque
= opaque
;
7539 int qemu_bh_poll(void)
7558 void qemu_bh_schedule(QEMUBH
*bh
)
7560 CPUState
*env
= cpu_single_env
;
7564 bh
->next
= first_bh
;
7567 /* stop the currently executing CPU to execute the BH ASAP */
7569 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7574 void qemu_bh_cancel(QEMUBH
*bh
)
7577 if (bh
->scheduled
) {
7580 pbh
= &(*pbh
)->next
;
7586 void qemu_bh_delete(QEMUBH
*bh
)
7592 /***********************************************************/
7593 /* machine registration */
7595 QEMUMachine
*first_machine
= NULL
;
7596 QEMUMachine
*current_machine
= NULL
;
7598 int qemu_register_machine(QEMUMachine
*m
)
7601 pm
= &first_machine
;
7609 static QEMUMachine
*find_machine(const char *name
)
7613 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7614 if (!strcmp(m
->name
, name
))
7620 /***********************************************************/
7621 /* main execution loop */
7623 static void gui_update(void *opaque
)
7625 DisplayState
*ds
= opaque
;
7626 ds
->dpy_refresh(ds
);
7627 qemu_mod_timer(ds
->gui_timer
,
7628 (ds
->gui_timer_interval
?
7629 ds
->gui_timer_interval
:
7630 GUI_REFRESH_INTERVAL
)
7631 + qemu_get_clock(rt_clock
));
7634 struct vm_change_state_entry
{
7635 VMChangeStateHandler
*cb
;
7637 LIST_ENTRY (vm_change_state_entry
) entries
;
7640 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7642 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7645 VMChangeStateEntry
*e
;
7647 e
= qemu_mallocz(sizeof (*e
));
7653 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7657 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7659 LIST_REMOVE (e
, entries
);
7663 static void vm_state_notify(int running
)
7665 VMChangeStateEntry
*e
;
7667 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7668 e
->cb(e
->opaque
, running
);
7672 /* XXX: support several handlers */
7673 static VMStopHandler
*vm_stop_cb
;
7674 static void *vm_stop_opaque
;
7676 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7679 vm_stop_opaque
= opaque
;
7683 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7694 qemu_rearm_alarm_timer(alarm_timer
);
7698 void vm_stop(int reason
)
7701 cpu_disable_ticks();
7705 vm_stop_cb(vm_stop_opaque
, reason
);
7712 /* reset/shutdown handler */
7714 typedef struct QEMUResetEntry
{
7715 QEMUResetHandler
*func
;
7717 struct QEMUResetEntry
*next
;
7720 static QEMUResetEntry
*first_reset_entry
;
7721 static int reset_requested
;
7722 static int shutdown_requested
;
7723 static int powerdown_requested
;
7725 int qemu_shutdown_requested(void)
7727 int r
= shutdown_requested
;
7728 shutdown_requested
= 0;
7732 int qemu_reset_requested(void)
7734 int r
= reset_requested
;
7735 reset_requested
= 0;
7739 int qemu_powerdown_requested(void)
7741 int r
= powerdown_requested
;
7742 powerdown_requested
= 0;
7746 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7748 QEMUResetEntry
**pre
, *re
;
7750 pre
= &first_reset_entry
;
7751 while (*pre
!= NULL
)
7752 pre
= &(*pre
)->next
;
7753 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7755 re
->opaque
= opaque
;
7760 void qemu_system_reset(void)
7764 /* reset all devices */
7765 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7766 re
->func(re
->opaque
);
7770 void qemu_system_reset_request(void)
7773 shutdown_requested
= 1;
7775 reset_requested
= 1;
7778 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7782 void qemu_system_shutdown_request(void)
7784 shutdown_requested
= 1;
7786 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7789 void qemu_system_powerdown_request(void)
7791 powerdown_requested
= 1;
7793 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7796 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
7801 /* KVM holds a mutex while QEMU code is running, we need hooks to
7802 release the mutex whenever QEMU code sleeps. */
7806 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
7813 void main_loop_wait(int timeout
)
7815 IOHandlerRecord
*ioh
;
7816 fd_set rfds
, wfds
, xfds
;
7825 /* XXX: need to suppress polling by better using win32 events */
7827 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7828 ret
|= pe
->func(pe
->opaque
);
7833 WaitObjects
*w
= &wait_objects
;
7835 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7836 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7837 if (w
->func
[ret
- WAIT_OBJECT_0
])
7838 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7840 /* Check for additional signaled events */
7841 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7843 /* Check if event is signaled */
7844 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7845 if(ret2
== WAIT_OBJECT_0
) {
7847 w
->func
[i
](w
->opaque
[i
]);
7848 } else if (ret2
== WAIT_TIMEOUT
) {
7850 err
= GetLastError();
7851 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7854 } else if (ret
== WAIT_TIMEOUT
) {
7856 err
= GetLastError();
7857 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7861 /* poll any events */
7862 /* XXX: separate device handlers from system ones */
7867 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7871 (!ioh
->fd_read_poll
||
7872 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7873 FD_SET(ioh
->fd
, &rfds
);
7877 if (ioh
->fd_write
) {
7878 FD_SET(ioh
->fd
, &wfds
);
7888 tv
.tv_sec
= timeout
/ 1000;
7889 tv
.tv_usec
= (timeout
% 1000) * 1000;
7891 #if defined(CONFIG_SLIRP)
7893 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7896 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7898 IOHandlerRecord
**pioh
;
7900 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7901 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7902 ioh
->fd_read(ioh
->opaque
);
7903 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
7904 FD_CLR(ioh
->fd
, &rfds
);
7906 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7907 ioh
->fd_write(ioh
->opaque
);
7911 /* remove deleted IO handlers */
7912 pioh
= &first_io_handler
;
7922 #if defined(CONFIG_SLIRP)
7929 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7934 if (likely(!cur_cpu
|| !(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7935 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7936 qemu_get_clock(vm_clock
));
7937 /* run dma transfers, if any */
7941 /* real time timers */
7942 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7943 qemu_get_clock(rt_clock
));
7945 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7946 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7947 qemu_rearm_alarm_timer(alarm_timer
);
7950 /* Check bottom-halves last in case any of the earlier events triggered
7956 static int main_loop(void)
7959 #ifdef CONFIG_PROFILER
7965 if (kvm_enabled()) {
7967 cpu_disable_ticks();
7971 cur_cpu
= first_cpu
;
7972 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7979 #ifdef CONFIG_PROFILER
7980 ti
= profile_getclock();
7985 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7986 env
->icount_decr
.u16
.low
= 0;
7987 env
->icount_extra
= 0;
7988 count
= qemu_next_deadline();
7989 count
= (count
+ (1 << icount_time_shift
) - 1)
7990 >> icount_time_shift
;
7991 qemu_icount
+= count
;
7992 decr
= (count
> 0xffff) ? 0xffff : count
;
7994 env
->icount_decr
.u16
.low
= decr
;
7995 env
->icount_extra
= count
;
7997 ret
= cpu_exec(env
);
7998 #ifdef CONFIG_PROFILER
7999 qemu_time
+= profile_getclock() - ti
;
8002 /* Fold pending instructions back into the
8003 instruction counter, and clear the interrupt flag. */
8004 qemu_icount
-= (env
->icount_decr
.u16
.low
8005 + env
->icount_extra
);
8006 env
->icount_decr
.u32
= 0;
8007 env
->icount_extra
= 0;
8009 next_cpu
= env
->next_cpu
?: first_cpu
;
8010 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
8011 ret
= EXCP_INTERRUPT
;
8015 if (ret
== EXCP_HLT
) {
8016 /* Give the next CPU a chance to run. */
8020 if (ret
!= EXCP_HALTED
)
8022 /* all CPUs are halted ? */
8028 if (shutdown_requested
) {
8029 ret
= EXCP_INTERRUPT
;
8037 if (reset_requested
) {
8038 reset_requested
= 0;
8039 qemu_system_reset();
8041 kvm_load_registers(env
);
8042 ret
= EXCP_INTERRUPT
;
8044 if (powerdown_requested
) {
8045 powerdown_requested
= 0;
8046 qemu_system_powerdown();
8047 ret
= EXCP_INTERRUPT
;
8049 if (unlikely(ret
== EXCP_DEBUG
)) {
8050 vm_stop(EXCP_DEBUG
);
8052 /* If all cpus are halted then wait until the next IRQ */
8053 /* XXX: use timeout computed from timers */
8054 if (ret
== EXCP_HALTED
) {
8058 /* Advance virtual time to the next event. */
8059 if (use_icount
== 1) {
8060 /* When not using an adaptive execution frequency
8061 we tend to get badly out of sync with real time,
8062 so just delay for a reasonable amount of time. */
8065 delta
= cpu_get_icount() - cpu_get_clock();
8068 /* If virtual time is ahead of real time then just
8070 timeout
= (delta
/ 1000000) + 1;
8072 /* Wait for either IO to occur or the next
8074 add
= qemu_next_deadline();
8075 /* We advance the timer before checking for IO.
8076 Limit the amount we advance so that early IO
8077 activity won't get the guest too far ahead. */
8081 add
= (add
+ (1 << icount_time_shift
) - 1)
8082 >> icount_time_shift
;
8084 timeout
= delta
/ 1000000;
8097 #ifdef CONFIG_PROFILER
8098 ti
= profile_getclock();
8100 main_loop_wait(timeout
);
8101 #ifdef CONFIG_PROFILER
8102 dev_time
+= profile_getclock() - ti
;
8105 cpu_disable_ticks();
8109 static void help(int exitcode
)
8111 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
8112 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
8113 "usage: %s [options] [disk_image]\n"
8115 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
8117 "Standard options:\n"
8118 "-M machine select emulated machine (-M ? for list)\n"
8119 "-cpu cpu select CPU (-cpu ? for list)\n"
8120 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
8121 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
8122 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
8123 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
8124 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
8125 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
8126 " [,cache=on|off][,format=f][,boot=on|off]\n"
8127 " use 'file' as a drive image\n"
8128 "-mtdblock file use 'file' as on-board Flash memory image\n"
8129 "-sd file use 'file' as SecureDigital card image\n"
8130 "-pflash file use 'file' as a parallel flash image\n"
8131 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
8132 "-snapshot write to temporary files instead of disk image files\n"
8134 "-no-frame open SDL window without a frame and window decorations\n"
8135 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
8136 "-no-quit disable SDL window close capability\n"
8139 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
8141 "-m megs set virtual RAM size to megs MB [default=%d]\n"
8142 "-smp n set the number of CPUs to 'n' [default=1]\n"
8143 "-nographic disable graphical output and redirect serial I/Os to console\n"
8144 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
8146 "-k language use keyboard layout (for example \"fr\" for French)\n"
8149 "-audio-help print list of audio drivers and their options\n"
8150 "-soundhw c1,... enable audio support\n"
8151 " and only specified sound cards (comma separated list)\n"
8152 " use -soundhw ? to get the list of supported cards\n"
8153 " use -soundhw all to enable all of them\n"
8155 "-localtime set the real time clock to local time [default=utc]\n"
8156 "-full-screen start in full screen\n"
8158 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
8160 "-usb enable the USB driver (will be the default soon)\n"
8161 "-usbdevice name add the host or guest USB device 'name'\n"
8162 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8163 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
8165 "-name string set the name of the guest\n"
8167 "Network options:\n"
8168 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
8169 " create a new Network Interface Card and connect it to VLAN 'n'\n"
8171 "-net user[,vlan=n][,hostname=host]\n"
8172 " connect the user mode network stack to VLAN 'n' and send\n"
8173 " hostname 'host' to DHCP clients\n"
8176 "-net tap[,vlan=n],ifname=name\n"
8177 " connect the host TAP network interface to VLAN 'n'\n"
8179 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
8180 " connect the host TAP network interface to VLAN 'n' and use the\n"
8181 " network scripts 'file' (default=%s)\n"
8182 " and 'dfile' (default=%s);\n"
8183 " use '[down]script=no' to disable script execution;\n"
8184 " use 'fd=h' to connect to an already opened TAP interface\n"
8186 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
8187 " connect the vlan 'n' to another VLAN using a socket connection\n"
8188 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
8189 " connect the vlan 'n' to multicast maddr and port\n"
8191 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
8192 " connect the vlan 'n' to port 'n' of a vde switch running\n"
8193 " on host and listening for incoming connections on 'socketpath'.\n"
8194 " Use group 'groupname' and mode 'octalmode' to change default\n"
8195 " ownership and permissions for communication port.\n"
8197 "-net none use it alone to have zero network devices; if no -net option\n"
8198 " is provided, the default is '-net nic -net user'\n"
8201 "-tftp dir allow tftp access to files in dir [-net user]\n"
8202 "-bootp file advertise file in BOOTP replies\n"
8204 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
8206 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
8207 " redirect TCP or UDP connections from host to guest [-net user]\n"
8210 "Linux boot specific:\n"
8211 "-kernel bzImage use 'bzImage' as kernel image\n"
8212 "-append cmdline use 'cmdline' as kernel command line\n"
8213 "-initrd file use 'file' as initial ram disk\n"
8215 "Debug/Expert options:\n"
8216 "-monitor dev redirect the monitor to char device 'dev'\n"
8217 "-serial dev redirect the serial port to char device 'dev'\n"
8218 "-parallel dev redirect the parallel port to char device 'dev'\n"
8219 "-pidfile file Write PID to 'file'\n"
8220 "-S freeze CPU at startup (use 'c' to start execution)\n"
8221 "-s wait gdb connection to port\n"
8222 "-p port set gdb connection port [default=%s]\n"
8223 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
8224 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
8225 " translation (t=none or lba) (usually qemu can guess them)\n"
8226 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
8228 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
8229 "-no-kqemu disable KQEMU kernel module usage\n"
8232 #ifndef NO_CPU_EMULATION
8233 "-no-kvm disable KVM hardware virtualization\n"
8235 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
8236 "-no-kvm-pit disable KVM kernel mode PIT\n"
8239 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
8240 " (default is CL-GD5446 PCI VGA)\n"
8241 "-no-acpi disable ACPI\n"
8243 #ifdef CONFIG_CURSES
8244 "-curses use a curses/ncurses interface instead of SDL\n"
8246 "-no-reboot exit instead of rebooting\n"
8247 "-no-shutdown stop before shutdown\n"
8248 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
8249 "-vnc display start a VNC server on display\n"
8251 "-daemonize daemonize QEMU after initializing\n"
8253 "-tdf inject timer interrupts that got lost\n"
8254 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
8255 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
8256 "-option-rom rom load a file, rom, into the option ROM space\n"
8258 "-prom-env variable=value set OpenBIOS nvram variables\n"
8260 "-clock force the use of the given methods for timer alarm.\n"
8261 " To see what timers are available use -clock ?\n"
8262 "-startdate select initial date of the clock\n"
8263 "-icount [N|auto]\n"
8264 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
8266 "During emulation, the following keys are useful:\n"
8267 "ctrl-alt-f toggle full screen\n"
8268 "ctrl-alt-n switch to virtual console 'n'\n"
8269 "ctrl-alt toggle mouse and keyboard grab\n"
8271 "When using -nographic, press 'ctrl-a h' to get some help.\n"
8276 DEFAULT_NETWORK_SCRIPT
,
8277 DEFAULT_NETWORK_DOWN_SCRIPT
,
8279 DEFAULT_GDBSTUB_PORT
,
8284 #define HAS_ARG 0x0001
8299 QEMU_OPTION_mtdblock
,
8303 QEMU_OPTION_snapshot
,
8305 QEMU_OPTION_no_fd_bootchk
,
8308 QEMU_OPTION_nographic
,
8309 QEMU_OPTION_portrait
,
8311 QEMU_OPTION_audio_help
,
8312 QEMU_OPTION_soundhw
,
8333 QEMU_OPTION_localtime
,
8334 QEMU_OPTION_cirrusvga
,
8337 QEMU_OPTION_std_vga
,
8339 QEMU_OPTION_monitor
,
8341 QEMU_OPTION_parallel
,
8343 QEMU_OPTION_full_screen
,
8344 QEMU_OPTION_no_frame
,
8345 QEMU_OPTION_alt_grab
,
8346 QEMU_OPTION_no_quit
,
8347 QEMU_OPTION_pidfile
,
8348 QEMU_OPTION_no_kqemu
,
8349 QEMU_OPTION_kernel_kqemu
,
8350 QEMU_OPTION_win2k_hack
,
8352 QEMU_OPTION_usbdevice
,
8355 QEMU_OPTION_no_acpi
,
8358 QEMU_OPTION_no_kvm_irqchip
,
8359 QEMU_OPTION_no_kvm_pit
,
8360 QEMU_OPTION_no_reboot
,
8361 QEMU_OPTION_no_shutdown
,
8362 QEMU_OPTION_show_cursor
,
8363 QEMU_OPTION_daemonize
,
8364 QEMU_OPTION_option_rom
,
8365 QEMU_OPTION_semihosting
,
8366 QEMU_OPTION_cpu_vendor
,
8368 QEMU_OPTION_prom_env
,
8369 QEMU_OPTION_old_param
,
8371 QEMU_OPTION_startdate
,
8372 QEMU_OPTION_tb_size
,
8374 QEMU_OPTION_incoming
,
8376 QEMU_OPTION_kvm_shadow_memory
,
8377 QEMU_OPTION_mempath
,
8380 typedef struct QEMUOption
{
8386 const QEMUOption qemu_options
[] = {
8387 { "h", 0, QEMU_OPTION_h
},
8388 { "help", 0, QEMU_OPTION_h
},
8390 { "M", HAS_ARG
, QEMU_OPTION_M
},
8391 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
8392 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
8393 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
8394 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
8395 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
8396 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
8397 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
8398 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
8399 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
8400 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
8401 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
8402 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
8403 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
8404 { "snapshot", 0, QEMU_OPTION_snapshot
},
8406 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
8408 { "m", HAS_ARG
, QEMU_OPTION_m
},
8409 { "nographic", 0, QEMU_OPTION_nographic
},
8410 { "portrait", 0, QEMU_OPTION_portrait
},
8411 { "k", HAS_ARG
, QEMU_OPTION_k
},
8413 { "audio-help", 0, QEMU_OPTION_audio_help
},
8414 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
8417 { "net", HAS_ARG
, QEMU_OPTION_net
},
8419 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
8420 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
8422 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
8424 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
8427 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
8428 { "append", HAS_ARG
, QEMU_OPTION_append
},
8429 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
8431 { "S", 0, QEMU_OPTION_S
},
8432 { "s", 0, QEMU_OPTION_s
},
8433 { "p", HAS_ARG
, QEMU_OPTION_p
},
8434 { "d", HAS_ARG
, QEMU_OPTION_d
},
8435 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
8436 { "L", HAS_ARG
, QEMU_OPTION_L
},
8437 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
8439 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
8440 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8443 #ifndef NO_CPU_EMULATION
8444 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8446 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8447 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8449 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8450 { "g", 1, QEMU_OPTION_g
},
8452 { "localtime", 0, QEMU_OPTION_localtime
},
8453 { "std-vga", 0, QEMU_OPTION_std_vga
},
8454 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8455 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8456 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8457 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8458 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8459 { "incoming", 1, QEMU_OPTION_incoming
},
8460 { "full-screen", 0, QEMU_OPTION_full_screen
},
8462 { "no-frame", 0, QEMU_OPTION_no_frame
},
8463 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8464 { "no-quit", 0, QEMU_OPTION_no_quit
},
8466 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8467 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8468 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8469 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8470 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8471 #ifdef CONFIG_CURSES
8472 { "curses", 0, QEMU_OPTION_curses
},
8475 /* temporary options */
8476 { "usb", 0, QEMU_OPTION_usb
},
8477 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8478 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8479 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8480 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8481 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8482 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8483 { "daemonize", 0, QEMU_OPTION_daemonize
},
8484 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8485 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8486 { "semihosting", 0, QEMU_OPTION_semihosting
},
8488 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8489 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8490 { "name", HAS_ARG
, QEMU_OPTION_name
},
8491 #if defined(TARGET_SPARC)
8492 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8494 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8495 #if defined(TARGET_ARM)
8496 { "old-param", 0, QEMU_OPTION_old_param
},
8498 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8499 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8500 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8501 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8502 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8506 /* password input */
8508 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8513 if (!bdrv_is_encrypted(bs
))
8516 term_printf("%s is encrypted.\n", name
);
8517 for(i
= 0; i
< 3; i
++) {
8518 monitor_readline("Password: ", 1, password
, sizeof(password
));
8519 if (bdrv_set_key(bs
, password
) == 0)
8521 term_printf("invalid password\n");
8526 static void read_passwords(void)
8528 BlockDriverState
*bs
;
8531 for(i
= 0; i
< nb_drives
; i
++) {
8532 bs
= drives_table
[i
].bdrv
;
8533 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8538 struct soundhw soundhw
[] = {
8539 #ifdef HAS_AUDIO_CHOICE
8540 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8546 { .init_isa
= pcspk_audio_init
}
8551 "Creative Sound Blaster 16",
8554 { .init_isa
= SB16_init
}
8557 #ifdef CONFIG_CS4231A
8563 { .init_isa
= cs4231a_init
}
8571 "Yamaha YMF262 (OPL3)",
8573 "Yamaha YM3812 (OPL2)",
8577 { .init_isa
= Adlib_init
}
8584 "Gravis Ultrasound GF1",
8587 { .init_isa
= GUS_init
}
8594 "Intel 82801AA AC97 Audio",
8597 { .init_pci
= ac97_init
}
8603 "ENSONIQ AudioPCI ES1370",
8606 { .init_pci
= es1370_init
}
8610 { NULL
, NULL
, 0, 0, { NULL
} }
8613 static void select_soundhw (const char *optarg
)
8617 if (*optarg
== '?') {
8620 printf ("Valid sound card names (comma separated):\n");
8621 for (c
= soundhw
; c
->name
; ++c
) {
8622 printf ("%-11s %s\n", c
->name
, c
->descr
);
8624 printf ("\n-soundhw all will enable all of the above\n");
8625 exit (*optarg
!= '?');
8633 if (!strcmp (optarg
, "all")) {
8634 for (c
= soundhw
; c
->name
; ++c
) {
8642 e
= strchr (p
, ',');
8643 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8645 for (c
= soundhw
; c
->name
; ++c
) {
8646 if (!strncmp (c
->name
, p
, l
)) {
8655 "Unknown sound card name (too big to show)\n");
8658 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8663 p
+= l
+ (e
!= NULL
);
8667 goto show_valid_cards
;
8673 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8675 exit(STATUS_CONTROL_C_EXIT
);
8680 #define MAX_NET_CLIENTS 32
8682 static int saved_argc
;
8683 static char **saved_argv
;
8685 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8689 *opt_daemonize
= daemonize
;
8690 *opt_incoming
= incoming
;
8694 static int gethugepagesize(void)
8698 char *needle
= "Hugepagesize:";
8700 unsigned long hugepagesize
;
8702 fd
= open("/proc/meminfo", O_RDONLY
);
8708 ret
= read(fd
, buf
, sizeof(buf
));
8714 size
= strstr(buf
, needle
);
8717 size
+= strlen(needle
);
8718 hugepagesize
= strtol(size
, NULL
, 0);
8719 return hugepagesize
;
8722 void *alloc_mem_area(unsigned long memory
, const char *path
)
8728 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8731 hpagesize
= gethugepagesize() * 1024;
8735 fd
= mkstemp(filename
);
8744 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8747 * ftruncate is not supported by hugetlbfs in older
8748 * hosts, so don't bother checking for errors.
8749 * If anything goes wrong with it under other filesystems,
8752 ftruncate(fd
, memory
);
8754 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8755 if (area
== MAP_FAILED
) {
8764 void *qemu_alloc_physram(unsigned long memory
)
8769 area
= alloc_mem_area(memory
, mem_path
);
8771 area
= qemu_vmalloc(memory
);
8776 int main(int argc
, char **argv
)
8778 #ifdef CONFIG_GDBSTUB
8780 const char *gdbstub_port
;
8782 uint32_t boot_devices_bitmap
= 0;
8784 int snapshot
, linux_boot
, net_boot
;
8785 const char *initrd_filename
;
8786 const char *kernel_filename
, *kernel_cmdline
;
8787 const char *boot_devices
= "";
8788 DisplayState
*ds
= &display_state
;
8789 int cyls
, heads
, secs
, translation
;
8790 const char *net_clients
[MAX_NET_CLIENTS
];
8794 const char *r
, *optarg
;
8795 CharDriverState
*monitor_hd
;
8797 const char *monitor_device
;
8798 const char *serial_devices
[MAX_SERIAL_PORTS
];
8799 int serial_device_index
;
8800 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8801 int parallel_device_index
;
8802 const char *loadvm
= NULL
;
8803 QEMUMachine
*machine
;
8804 const char *cpu_model
;
8805 const char *usb_devices
[MAX_USB_CMDLINE
];
8806 int usb_devices_index
;
8809 const char *pid_file
= NULL
;
8815 LIST_INIT (&vm_change_state_head
);
8818 struct sigaction act
;
8819 sigfillset(&act
.sa_mask
);
8821 act
.sa_handler
= SIG_IGN
;
8822 sigaction(SIGPIPE
, &act
, NULL
);
8825 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8826 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8827 QEMU to run on a single CPU */
8832 h
= GetCurrentProcess();
8833 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8834 for(i
= 0; i
< 32; i
++) {
8835 if (mask
& (1 << i
))
8840 SetProcessAffinityMask(h
, mask
);
8846 register_machines();
8847 machine
= first_machine
;
8849 initrd_filename
= NULL
;
8851 vga_ram_size
= VGA_RAM_SIZE
;
8852 #ifdef CONFIG_GDBSTUB
8854 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8859 kernel_filename
= NULL
;
8860 kernel_cmdline
= "";
8861 cyls
= heads
= secs
= 0;
8862 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8863 monitor_device
= "vc";
8865 serial_devices
[0] = "vc:80Cx24C";
8866 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8867 serial_devices
[i
] = NULL
;
8868 serial_device_index
= 0;
8870 parallel_devices
[0] = "vc:640x480";
8871 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8872 parallel_devices
[i
] = NULL
;
8873 parallel_device_index
= 0;
8875 usb_devices_index
= 0;
8892 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8894 const QEMUOption
*popt
;
8897 /* Treat --foo the same as -foo. */
8900 popt
= qemu_options
;
8903 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8907 if (!strcmp(popt
->name
, r
+ 1))
8911 if (popt
->flags
& HAS_ARG
) {
8912 if (optind
>= argc
) {
8913 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8917 optarg
= argv
[optind
++];
8922 switch(popt
->index
) {
8924 machine
= find_machine(optarg
);
8927 printf("Supported machines are:\n");
8928 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8929 printf("%-10s %s%s\n",
8931 m
== first_machine
? " (default)" : "");
8933 exit(*optarg
!= '?');
8936 case QEMU_OPTION_cpu
:
8937 /* hw initialization will check this */
8938 if (*optarg
== '?') {
8939 /* XXX: implement xxx_cpu_list for targets that still miss it */
8940 #if defined(cpu_list)
8941 cpu_list(stdout
, &fprintf
);
8948 case QEMU_OPTION_initrd
:
8949 initrd_filename
= optarg
;
8951 case QEMU_OPTION_hda
:
8953 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8955 hda_index
= drive_add(optarg
, HD_ALIAS
8956 ",cyls=%d,heads=%d,secs=%d%s",
8957 0, cyls
, heads
, secs
,
8958 translation
== BIOS_ATA_TRANSLATION_LBA
?
8960 translation
== BIOS_ATA_TRANSLATION_NONE
?
8961 ",trans=none" : "");
8963 case QEMU_OPTION_hdb
:
8964 case QEMU_OPTION_hdc
:
8965 case QEMU_OPTION_hdd
:
8966 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8968 case QEMU_OPTION_drive
:
8969 drive_add(NULL
, "%s", optarg
);
8971 case QEMU_OPTION_mtdblock
:
8972 drive_add(optarg
, MTD_ALIAS
);
8974 case QEMU_OPTION_sd
:
8975 drive_add(optarg
, SD_ALIAS
);
8977 case QEMU_OPTION_pflash
:
8978 drive_add(optarg
, PFLASH_ALIAS
);
8980 case QEMU_OPTION_snapshot
:
8983 case QEMU_OPTION_hdachs
:
8987 cyls
= strtol(p
, (char **)&p
, 0);
8988 if (cyls
< 1 || cyls
> 16383)
8993 heads
= strtol(p
, (char **)&p
, 0);
8994 if (heads
< 1 || heads
> 16)
8999 secs
= strtol(p
, (char **)&p
, 0);
9000 if (secs
< 1 || secs
> 63)
9004 if (!strcmp(p
, "none"))
9005 translation
= BIOS_ATA_TRANSLATION_NONE
;
9006 else if (!strcmp(p
, "lba"))
9007 translation
= BIOS_ATA_TRANSLATION_LBA
;
9008 else if (!strcmp(p
, "auto"))
9009 translation
= BIOS_ATA_TRANSLATION_AUTO
;
9012 } else if (*p
!= '\0') {
9014 fprintf(stderr
, "qemu: invalid physical CHS format\n");
9017 if (hda_index
!= -1)
9018 snprintf(drives_opt
[hda_index
].opt
,
9019 sizeof(drives_opt
[hda_index
].opt
),
9020 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
9021 0, cyls
, heads
, secs
,
9022 translation
== BIOS_ATA_TRANSLATION_LBA
?
9024 translation
== BIOS_ATA_TRANSLATION_NONE
?
9025 ",trans=none" : "");
9028 case QEMU_OPTION_nographic
:
9031 #ifdef CONFIG_CURSES
9032 case QEMU_OPTION_curses
:
9036 case QEMU_OPTION_portrait
:
9039 case QEMU_OPTION_kernel
:
9040 kernel_filename
= optarg
;
9042 case QEMU_OPTION_append
:
9043 kernel_cmdline
= optarg
;
9045 case QEMU_OPTION_cdrom
:
9046 drive_add(optarg
, CDROM_ALIAS
);
9048 case QEMU_OPTION_boot
:
9049 boot_devices
= optarg
;
9050 /* We just do some generic consistency checks */
9052 /* Could easily be extended to 64 devices if needed */
9055 boot_devices_bitmap
= 0;
9056 for (p
= boot_devices
; *p
!= '\0'; p
++) {
9057 /* Allowed boot devices are:
9058 * a b : floppy disk drives
9059 * c ... f : IDE disk drives
9060 * g ... m : machine implementation dependant drives
9061 * n ... p : network devices
9062 * It's up to each machine implementation to check
9063 * if the given boot devices match the actual hardware
9064 * implementation and firmware features.
9066 if (*p
< 'a' || *p
> 'q') {
9067 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
9070 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
9072 "Boot device '%c' was given twice\n",*p
);
9075 boot_devices_bitmap
|= 1 << (*p
- 'a');
9079 case QEMU_OPTION_fda
:
9080 case QEMU_OPTION_fdb
:
9081 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
9084 case QEMU_OPTION_no_fd_bootchk
:
9088 case QEMU_OPTION_net
:
9089 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
9090 fprintf(stderr
, "qemu: too many network clients\n");
9093 net_clients
[nb_net_clients
] = optarg
;
9097 case QEMU_OPTION_tftp
:
9098 tftp_prefix
= optarg
;
9100 case QEMU_OPTION_bootp
:
9101 bootp_filename
= optarg
;
9104 case QEMU_OPTION_smb
:
9105 net_slirp_smb(optarg
);
9108 case QEMU_OPTION_redir
:
9109 net_slirp_redir(optarg
);
9113 case QEMU_OPTION_audio_help
:
9117 case QEMU_OPTION_soundhw
:
9118 select_soundhw (optarg
);
9124 case QEMU_OPTION_m
: {
9128 value
= strtoul(optarg
, &ptr
, 10);
9130 case 0: case 'M': case 'm':
9137 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
9141 /* On 32-bit hosts, QEMU is limited by virtual address space */
9142 if (value
> (2047 << 20)
9144 && HOST_LONG_BITS
== 32
9147 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
9150 if (value
!= (uint64_t)(ram_addr_t
)value
) {
9151 fprintf(stderr
, "qemu: ram size too large\n");
9162 mask
= cpu_str_to_log_mask(optarg
);
9164 printf("Log items (comma separated):\n");
9165 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
9166 printf("%-10s %s\n", item
->name
, item
->help
);
9173 #ifdef CONFIG_GDBSTUB
9178 gdbstub_port
= optarg
;
9184 case QEMU_OPTION_bios
:
9191 keyboard_layout
= optarg
;
9193 case QEMU_OPTION_localtime
:
9196 case QEMU_OPTION_cirrusvga
:
9197 cirrus_vga_enabled
= 1;
9200 case QEMU_OPTION_vmsvga
:
9201 cirrus_vga_enabled
= 0;
9204 case QEMU_OPTION_std_vga
:
9205 cirrus_vga_enabled
= 0;
9213 w
= strtol(p
, (char **)&p
, 10);
9216 fprintf(stderr
, "qemu: invalid resolution or depth\n");
9222 h
= strtol(p
, (char **)&p
, 10);
9227 depth
= strtol(p
, (char **)&p
, 10);
9228 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
9229 depth
!= 24 && depth
!= 32)
9231 } else if (*p
== '\0') {
9232 depth
= graphic_depth
;
9239 graphic_depth
= depth
;
9242 case QEMU_OPTION_echr
:
9245 term_escape_char
= strtol(optarg
, &r
, 0);
9247 printf("Bad argument to echr\n");
9250 case QEMU_OPTION_monitor
:
9251 monitor_device
= optarg
;
9253 case QEMU_OPTION_serial
:
9254 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
9255 fprintf(stderr
, "qemu: too many serial ports\n");
9258 serial_devices
[serial_device_index
] = optarg
;
9259 serial_device_index
++;
9261 case QEMU_OPTION_parallel
:
9262 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
9263 fprintf(stderr
, "qemu: too many parallel ports\n");
9266 parallel_devices
[parallel_device_index
] = optarg
;
9267 parallel_device_index
++;
9269 case QEMU_OPTION_loadvm
:
9272 case QEMU_OPTION_incoming
:
9275 case QEMU_OPTION_full_screen
:
9279 case QEMU_OPTION_no_frame
:
9282 case QEMU_OPTION_alt_grab
:
9285 case QEMU_OPTION_no_quit
:
9289 case QEMU_OPTION_pidfile
:
9293 case QEMU_OPTION_win2k_hack
:
9294 win2k_install_hack
= 1;
9298 case QEMU_OPTION_no_kqemu
:
9301 case QEMU_OPTION_kernel_kqemu
:
9306 case QEMU_OPTION_no_kvm
:
9309 case QEMU_OPTION_no_kvm_irqchip
: {
9310 extern int kvm_irqchip
, kvm_pit
;
9315 case QEMU_OPTION_no_kvm_pit
: {
9321 case QEMU_OPTION_usb
:
9324 case QEMU_OPTION_usbdevice
:
9326 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
9327 fprintf(stderr
, "Too many USB devices\n");
9330 usb_devices
[usb_devices_index
] = optarg
;
9331 usb_devices_index
++;
9333 case QEMU_OPTION_smp
:
9334 smp_cpus
= atoi(optarg
);
9335 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
9336 fprintf(stderr
, "Invalid number of CPUs\n");
9340 case QEMU_OPTION_vnc
:
9341 vnc_display
= optarg
;
9343 case QEMU_OPTION_no_acpi
:
9346 case QEMU_OPTION_no_reboot
:
9349 case QEMU_OPTION_no_shutdown
:
9352 case QEMU_OPTION_show_cursor
:
9355 case QEMU_OPTION_daemonize
:
9358 case QEMU_OPTION_option_rom
:
9359 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9360 fprintf(stderr
, "Too many option ROMs\n");
9363 option_rom
[nb_option_roms
] = optarg
;
9366 case QEMU_OPTION_semihosting
:
9367 semihosting_enabled
= 1;
9369 case QEMU_OPTION_tdf
:
9372 case QEMU_OPTION_kvm_shadow_memory
:
9373 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
9375 case QEMU_OPTION_mempath
:
9378 case QEMU_OPTION_name
:
9382 case QEMU_OPTION_prom_env
:
9383 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
9384 fprintf(stderr
, "Too many prom variables\n");
9387 prom_envs
[nb_prom_envs
] = optarg
;
9391 case QEMU_OPTION_cpu_vendor
:
9392 cpu_vendor_string
= optarg
;
9395 case QEMU_OPTION_old_param
:
9399 case QEMU_OPTION_clock
:
9400 configure_alarms(optarg
);
9402 case QEMU_OPTION_startdate
:
9405 time_t rtc_start_date
;
9406 if (!strcmp(optarg
, "now")) {
9407 rtc_date_offset
= -1;
9409 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9417 } else if (sscanf(optarg
, "%d-%d-%d",
9420 &tm
.tm_mday
) == 3) {
9429 rtc_start_date
= mktimegm(&tm
);
9430 if (rtc_start_date
== -1) {
9432 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9433 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9436 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9440 case QEMU_OPTION_tb_size
:
9441 tb_size
= strtol(optarg
, NULL
, 0);
9445 case QEMU_OPTION_icount
:
9447 if (strcmp(optarg
, "auto") == 0) {
9448 icount_time_shift
= -1;
9450 icount_time_shift
= strtol(optarg
, NULL
, 0);
9458 if (serial_device_index
== 0)
9459 serial_devices
[0] = "stdio";
9460 if (parallel_device_index
== 0)
9461 parallel_devices
[0] = "null";
9462 if (strncmp(monitor_device
, "vc", 2) == 0)
9463 monitor_device
= "stdio";
9470 if (pipe(fds
) == -1)
9481 len
= read(fds
[0], &status
, 1);
9482 if (len
== -1 && (errno
== EINTR
))
9487 else if (status
== 1) {
9488 fprintf(stderr
, "Could not acquire pidfile\n");
9505 signal(SIGTSTP
, SIG_IGN
);
9506 signal(SIGTTOU
, SIG_IGN
);
9507 signal(SIGTTIN
, SIG_IGN
);
9512 if (kvm_enabled()) {
9513 if (kvm_qemu_init() < 0) {
9514 extern int kvm_allowed
;
9515 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9516 #ifdef NO_CPU_EMULATION
9517 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9525 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9528 write(fds
[1], &status
, 1);
9530 fprintf(stderr
, "Could not acquire pid file\n");
9538 linux_boot
= (kernel_filename
!= NULL
);
9539 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9541 /* XXX: this should not be: some embedded targets just have flash */
9542 if (!linux_boot
&& net_boot
== 0 &&
9546 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
9547 fprintf(stderr
, "-append only allowed with -kernel option\n");
9551 if (!linux_boot
&& initrd_filename
!= NULL
) {
9552 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
9556 /* boot to floppy or the default cd if no hard disk defined yet */
9557 if (!boot_devices
[0]) {
9558 boot_devices
= "cad";
9560 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9565 if (use_icount
&& icount_time_shift
< 0) {
9567 /* 125MIPS seems a reasonable initial guess at the guest speed.
9568 It will be corrected fairly quickly anyway. */
9569 icount_time_shift
= 3;
9570 init_icount_adjust();
9577 /* init network clients */
9578 if (nb_net_clients
== 0) {
9579 /* if no clients, we use a default config */
9580 net_clients
[0] = "nic";
9581 net_clients
[1] = "user";
9585 for(i
= 0;i
< nb_net_clients
; i
++) {
9586 if (net_client_parse(net_clients
[i
]) < 0)
9589 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9590 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9592 if (vlan
->nb_guest_devs
== 0)
9593 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9594 if (vlan
->nb_host_devs
== 0)
9596 "Warning: vlan %d is not connected to host network\n",
9601 /* XXX: this should be moved in the PC machine instantiation code */
9602 if (net_boot
!= 0) {
9604 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9605 const char *model
= nd_table
[i
].model
;
9607 if (net_boot
& (1 << i
)) {
9610 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9611 if (get_image_size(buf
) > 0) {
9612 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9613 fprintf(stderr
, "Too many option ROMs\n");
9616 option_rom
[nb_option_roms
] = strdup(buf
);
9623 fprintf(stderr
, "No valid PXE rom found for network device\n");
9629 /* init the memory */
9630 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9632 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9634 if (ram_size
< phys_ram_size
) {
9635 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9636 machine
->name
, (unsigned long long) phys_ram_size
);
9640 phys_ram_size
= ram_size
;
9642 ram_size
= phys_ram_size
;
9645 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9647 phys_ram_size
+= ram_size
;
9650 /* Initialize kvm */
9651 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9652 #define KVM_EXTRA_PAGES 3
9654 #define KVM_EXTRA_PAGES 0
9656 if (kvm_enabled()) {
9657 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9658 if (kvm_qemu_create_context() < 0) {
9659 fprintf(stderr
, "Could not create KVM context\n");
9662 #ifdef KVM_CAP_USER_MEMORY
9666 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9668 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9669 if (!phys_ram_base
) {
9670 fprintf(stderr
, "Could not allocate physical memory\n");
9677 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9678 if (!phys_ram_base
) {
9679 fprintf(stderr
, "Could not allocate physical memory\n");
9684 /* init the dynamic translator */
9685 cpu_exec_init_all(tb_size
* 1024 * 1024);
9689 /* we always create the cdrom drive, even if no disk is there */
9691 if (nb_drives_opt
< MAX_DRIVES
)
9692 drive_add(NULL
, CDROM_ALIAS
);
9694 /* we always create at least one floppy */
9696 if (nb_drives_opt
< MAX_DRIVES
)
9697 drive_add(NULL
, FD_ALIAS
, 0);
9699 /* we always create one sd slot, even if no card is in it */
9701 if (nb_drives_opt
< MAX_DRIVES
)
9702 drive_add(NULL
, SD_ALIAS
);
9704 /* open the virtual block devices
9705 * note that migration with device
9706 * hot add/remove is broken.
9708 for(i
= 0; i
< nb_drives_opt
; i
++)
9709 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9712 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9713 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9716 memset(&display_state
, 0, sizeof(display_state
));
9719 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9722 /* nearly nothing to do */
9723 dumb_display_init(ds
);
9724 } else if (vnc_display
!= NULL
) {
9725 vnc_display_init(ds
);
9726 if (vnc_display_open(ds
, vnc_display
) < 0)
9729 #if defined(CONFIG_CURSES)
9731 curses_display_init(ds
, full_screen
);
9735 #if defined(CONFIG_SDL)
9736 sdl_display_init(ds
, full_screen
, no_frame
);
9737 #elif defined(CONFIG_COCOA)
9738 cocoa_display_init(ds
, full_screen
);
9740 dumb_display_init(ds
);
9744 /* Maintain compatibility with multiple stdio monitors */
9747 if (!strcmp(monitor_device
,"stdio")) {
9748 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9749 const char *devname
= serial_devices
[i
];
9750 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9751 monitor_device
= NULL
;
9753 } else if (devname
&& !strcmp(devname
,"stdio")) {
9754 monitor_device
= NULL
;
9755 serial_devices
[i
] = "mon:stdio";
9761 if (monitor_device
) {
9762 monitor_hd
= qemu_chr_open(monitor_device
);
9764 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9767 monitor_init(monitor_hd
, !nographic
);
9771 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9772 const char *devname
= serial_devices
[i
];
9773 if (devname
&& strcmp(devname
, "none")) {
9774 serial_hds
[i
] = qemu_chr_open(devname
);
9775 if (!serial_hds
[i
]) {
9776 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9780 if (strstart(devname
, "vc", 0))
9781 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9785 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9786 const char *devname
= parallel_devices
[i
];
9787 if (devname
&& strcmp(devname
, "none")) {
9788 parallel_hds
[i
] = qemu_chr_open(devname
);
9789 if (!parallel_hds
[i
]) {
9790 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9794 if (strstart(devname
, "vc", 0))
9795 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9802 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9803 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9805 current_machine
= machine
;
9807 /* init USB devices */
9809 for(i
= 0; i
< usb_devices_index
; i
++) {
9810 if (usb_device_add(usb_devices
[i
]) < 0) {
9811 fprintf(stderr
, "Warning: could not add USB device %s\n",
9817 if (display_state
.dpy_refresh
) {
9818 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9819 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9822 #ifdef CONFIG_GDBSTUB
9824 /* XXX: use standard host:port notation and modify options
9826 if (gdbserver_start(gdbstub_port
) < 0) {
9827 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9837 monitor_start_input();
9845 rc
= migrate_incoming(incoming
);
9847 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
9853 /* XXX: simplify init */
9865 len
= write(fds
[1], &status
, 1);
9866 if (len
== -1 && (errno
== EINTR
))
9873 TFR(fd
= open("/dev/null", O_RDWR
));
9887 #if !defined(_WIN32)
9888 /* close network clients */
9889 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9890 VLANClientState
*vc
;
9892 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9893 if (vc
->fd_read
== tap_receive
) {
9895 TAPState
*s
= vc
->opaque
;
9897 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9899 launch_script(s
->down_script
, ifname
, s
->fd
);
9901 #if defined(CONFIG_VDE)
9902 if (vc
->fd_read
== vde_from_qemu
) {
9903 VDEState
*s
= vc
->opaque
;