4 * Copyright (c) 2003-2007 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
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
78 #if defined(CONFIG_SLIRP)
84 #include <sys/timeb.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
90 #include "qemu_socket.h"
96 #endif /* CONFIG_SDL */
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
111 #define SMBD_COMMAND "/usr/sbin/smbd"
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
120 #define DEFAULT_RAM_SIZE 144
122 #define DEFAULT_RAM_SIZE 128
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
134 char phys_ram_file
[1024];
135 void *ioport_opaque
[MAX_IOPORTS
];
136 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
137 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState
*bs_table
[MAX_DISKS
+ 1], *fd_table
[MAX_FD
];
141 /* point to the block driver where the snapshots are managed */
142 BlockDriverState
*bs_snapshots
;
144 static DisplayState display_state
;
146 const char* keyboard_layout
= NULL
;
147 int64_t ticks_per_sec
;
148 int boot_device
= 'c';
150 int pit_min_timer_count
= 0;
152 NICInfo nd_table
[MAX_NICS
];
153 QEMUTimer
*gui_timer
;
156 int cirrus_vga_enabled
= 1;
157 int vmsvga_enabled
= 0;
159 int graphic_width
= 1024;
160 int graphic_height
= 768;
162 int graphic_width
= 800;
163 int graphic_height
= 600;
165 int graphic_depth
= 15;
169 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
170 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
172 int win2k_install_hack
= 0;
175 static VLANState
*first_vlan
;
177 const char *vnc_display
;
178 #if defined(TARGET_SPARC)
180 #elif defined(TARGET_I386)
185 int acpi_enabled
= 1;
189 const char *option_rom
[MAX_OPTION_ROMS
];
191 int semihosting_enabled
= 0;
193 const char *qemu_name
;
195 /***********************************************************/
196 /* x86 ISA bus support */
198 target_phys_addr_t isa_mem_base
= 0;
201 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
203 #ifdef DEBUG_UNUSED_IOPORT
204 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
209 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
211 #ifdef DEBUG_UNUSED_IOPORT
212 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
216 /* default is to make two byte accesses */
217 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
220 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
221 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
222 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
226 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
228 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
229 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
230 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
233 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
235 #ifdef DEBUG_UNUSED_IOPORT
236 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
241 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
243 #ifdef DEBUG_UNUSED_IOPORT
244 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
248 void init_ioports(void)
252 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
253 ioport_read_table
[0][i
] = default_ioport_readb
;
254 ioport_write_table
[0][i
] = default_ioport_writeb
;
255 ioport_read_table
[1][i
] = default_ioport_readw
;
256 ioport_write_table
[1][i
] = default_ioport_writew
;
257 ioport_read_table
[2][i
] = default_ioport_readl
;
258 ioport_write_table
[2][i
] = default_ioport_writel
;
262 /* size is the word size in byte */
263 int register_ioport_read(int start
, int length
, int size
,
264 IOPortReadFunc
*func
, void *opaque
)
270 } else if (size
== 2) {
272 } else if (size
== 4) {
275 hw_error("register_ioport_read: invalid size");
278 for(i
= start
; i
< start
+ length
; i
+= size
) {
279 ioport_read_table
[bsize
][i
] = func
;
280 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
281 hw_error("register_ioport_read: invalid opaque");
282 ioport_opaque
[i
] = opaque
;
287 /* size is the word size in byte */
288 int register_ioport_write(int start
, int length
, int size
,
289 IOPortWriteFunc
*func
, void *opaque
)
295 } else if (size
== 2) {
297 } else if (size
== 4) {
300 hw_error("register_ioport_write: invalid size");
303 for(i
= start
; i
< start
+ length
; i
+= size
) {
304 ioport_write_table
[bsize
][i
] = func
;
305 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
306 hw_error("register_ioport_write: invalid opaque");
307 ioport_opaque
[i
] = opaque
;
312 void isa_unassign_ioport(int start
, int length
)
316 for(i
= start
; i
< start
+ length
; i
++) {
317 ioport_read_table
[0][i
] = default_ioport_readb
;
318 ioport_read_table
[1][i
] = default_ioport_readw
;
319 ioport_read_table
[2][i
] = default_ioport_readl
;
321 ioport_write_table
[0][i
] = default_ioport_writeb
;
322 ioport_write_table
[1][i
] = default_ioport_writew
;
323 ioport_write_table
[2][i
] = default_ioport_writel
;
327 /***********************************************************/
329 void cpu_outb(CPUState
*env
, int addr
, int val
)
332 if (loglevel
& CPU_LOG_IOPORT
)
333 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
335 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
338 env
->last_io_time
= cpu_get_time_fast();
342 void cpu_outw(CPUState
*env
, int addr
, int val
)
345 if (loglevel
& CPU_LOG_IOPORT
)
346 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
348 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
351 env
->last_io_time
= cpu_get_time_fast();
355 void cpu_outl(CPUState
*env
, int addr
, int val
)
358 if (loglevel
& CPU_LOG_IOPORT
)
359 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
361 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
364 env
->last_io_time
= cpu_get_time_fast();
368 int cpu_inb(CPUState
*env
, int addr
)
371 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
373 if (loglevel
& CPU_LOG_IOPORT
)
374 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
378 env
->last_io_time
= cpu_get_time_fast();
383 int cpu_inw(CPUState
*env
, int addr
)
386 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
388 if (loglevel
& CPU_LOG_IOPORT
)
389 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
393 env
->last_io_time
= cpu_get_time_fast();
398 int cpu_inl(CPUState
*env
, int addr
)
401 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
403 if (loglevel
& CPU_LOG_IOPORT
)
404 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
408 env
->last_io_time
= cpu_get_time_fast();
413 /***********************************************************/
414 void hw_error(const char *fmt
, ...)
420 fprintf(stderr
, "qemu: hardware error: ");
421 vfprintf(stderr
, fmt
, ap
);
422 fprintf(stderr
, "\n");
423 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
424 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
426 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
428 cpu_dump_state(env
, stderr
, fprintf
, 0);
435 /***********************************************************/
438 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
439 static void *qemu_put_kbd_event_opaque
;
440 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
441 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
443 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
445 qemu_put_kbd_event_opaque
= opaque
;
446 qemu_put_kbd_event
= func
;
449 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
450 void *opaque
, int absolute
,
453 QEMUPutMouseEntry
*s
, *cursor
;
455 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
459 s
->qemu_put_mouse_event
= func
;
460 s
->qemu_put_mouse_event_opaque
= opaque
;
461 s
->qemu_put_mouse_event_absolute
= absolute
;
462 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
465 if (!qemu_put_mouse_event_head
) {
466 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
470 cursor
= qemu_put_mouse_event_head
;
471 while (cursor
->next
!= NULL
)
472 cursor
= cursor
->next
;
475 qemu_put_mouse_event_current
= s
;
480 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
482 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
484 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
487 cursor
= qemu_put_mouse_event_head
;
488 while (cursor
!= NULL
&& cursor
!= entry
) {
490 cursor
= cursor
->next
;
493 if (cursor
== NULL
) // does not exist or list empty
495 else if (prev
== NULL
) { // entry is head
496 qemu_put_mouse_event_head
= cursor
->next
;
497 if (qemu_put_mouse_event_current
== entry
)
498 qemu_put_mouse_event_current
= cursor
->next
;
499 qemu_free(entry
->qemu_put_mouse_event_name
);
504 prev
->next
= entry
->next
;
506 if (qemu_put_mouse_event_current
== entry
)
507 qemu_put_mouse_event_current
= prev
;
509 qemu_free(entry
->qemu_put_mouse_event_name
);
513 void kbd_put_keycode(int keycode
)
515 if (qemu_put_kbd_event
) {
516 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
520 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
522 QEMUPutMouseEvent
*mouse_event
;
523 void *mouse_event_opaque
;
525 if (!qemu_put_mouse_event_current
) {
530 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
532 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
535 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
539 int kbd_mouse_is_absolute(void)
541 if (!qemu_put_mouse_event_current
)
544 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
547 void (*kbd_mouse_set
)(int x
, int y
, int on
) = NULL
;
548 void (*kbd_cursor_define
)(int width
, int height
, int bpp
, int hot_x
, int hot_y
,
549 uint8_t *image
, uint8_t *mask
) = NULL
;
551 void do_info_mice(void)
553 QEMUPutMouseEntry
*cursor
;
556 if (!qemu_put_mouse_event_head
) {
557 term_printf("No mouse devices connected\n");
561 term_printf("Mouse devices available:\n");
562 cursor
= qemu_put_mouse_event_head
;
563 while (cursor
!= NULL
) {
564 term_printf("%c Mouse #%d: %s\n",
565 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
566 index
, cursor
->qemu_put_mouse_event_name
);
568 cursor
= cursor
->next
;
572 void do_mouse_set(int index
)
574 QEMUPutMouseEntry
*cursor
;
577 if (!qemu_put_mouse_event_head
) {
578 term_printf("No mouse devices connected\n");
582 cursor
= qemu_put_mouse_event_head
;
583 while (cursor
!= NULL
&& index
!= i
) {
585 cursor
= cursor
->next
;
589 qemu_put_mouse_event_current
= cursor
;
591 term_printf("Mouse at given index not found\n");
594 /* compute with 96 bit intermediate result: (a*b)/c */
595 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
600 #ifdef WORDS_BIGENDIAN
610 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
611 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
614 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
618 /***********************************************************/
619 /* real time host monotonic timer */
621 #define QEMU_TIMER_BASE 1000000000LL
625 static int64_t clock_freq
;
627 static void init_get_clock(void)
631 ret
= QueryPerformanceFrequency(&freq
);
633 fprintf(stderr
, "Could not calibrate ticks\n");
636 clock_freq
= freq
.QuadPart
;
639 static int64_t get_clock(void)
642 QueryPerformanceCounter(&ti
);
643 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
648 static int use_rt_clock
;
650 static void init_get_clock(void)
653 #if defined(__linux__)
656 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
663 static int64_t get_clock(void)
665 #if defined(__linux__)
668 clock_gettime(CLOCK_MONOTONIC
, &ts
);
669 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
673 /* XXX: using gettimeofday leads to problems if the date
674 changes, so it should be avoided. */
676 gettimeofday(&tv
, NULL
);
677 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
683 /***********************************************************/
684 /* guest cycle counter */
686 static int64_t cpu_ticks_prev
;
687 static int64_t cpu_ticks_offset
;
688 static int64_t cpu_clock_offset
;
689 static int cpu_ticks_enabled
;
691 /* return the host CPU cycle counter and handle stop/restart */
692 int64_t cpu_get_ticks(void)
694 if (!cpu_ticks_enabled
) {
695 return cpu_ticks_offset
;
698 ticks
= cpu_get_real_ticks();
699 if (cpu_ticks_prev
> ticks
) {
700 /* Note: non increasing ticks may happen if the host uses
702 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
704 cpu_ticks_prev
= ticks
;
705 return ticks
+ cpu_ticks_offset
;
709 /* return the host CPU monotonic timer and handle stop/restart */
710 static int64_t cpu_get_clock(void)
713 if (!cpu_ticks_enabled
) {
714 return cpu_clock_offset
;
717 return ti
+ cpu_clock_offset
;
721 /* enable cpu_get_ticks() */
722 void cpu_enable_ticks(void)
724 if (!cpu_ticks_enabled
) {
725 cpu_ticks_offset
-= cpu_get_real_ticks();
726 cpu_clock_offset
-= get_clock();
727 cpu_ticks_enabled
= 1;
731 /* disable cpu_get_ticks() : the clock is stopped. You must not call
732 cpu_get_ticks() after that. */
733 void cpu_disable_ticks(void)
735 if (cpu_ticks_enabled
) {
736 cpu_ticks_offset
= cpu_get_ticks();
737 cpu_clock_offset
= cpu_get_clock();
738 cpu_ticks_enabled
= 0;
742 /***********************************************************/
745 #define QEMU_TIMER_REALTIME 0
746 #define QEMU_TIMER_VIRTUAL 1
750 /* XXX: add frequency */
758 struct QEMUTimer
*next
;
764 static QEMUTimer
*active_timers
[2];
766 static MMRESULT timerID
;
767 static HANDLE host_alarm
= NULL
;
768 static unsigned int period
= 1;
770 /* frequency of the times() clock tick */
771 static int timer_freq
;
774 QEMUClock
*qemu_new_clock(int type
)
777 clock
= qemu_mallocz(sizeof(QEMUClock
));
784 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
788 ts
= qemu_mallocz(sizeof(QEMUTimer
));
795 void qemu_free_timer(QEMUTimer
*ts
)
800 /* stop a timer, but do not dealloc it */
801 void qemu_del_timer(QEMUTimer
*ts
)
805 /* NOTE: this code must be signal safe because
806 qemu_timer_expired() can be called from a signal. */
807 pt
= &active_timers
[ts
->clock
->type
];
820 /* modify the current timer so that it will be fired when current_time
821 >= expire_time. The corresponding callback will be called. */
822 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
828 /* add the timer in the sorted list */
829 /* NOTE: this code must be signal safe because
830 qemu_timer_expired() can be called from a signal. */
831 pt
= &active_timers
[ts
->clock
->type
];
836 if (t
->expire_time
> expire_time
)
840 ts
->expire_time
= expire_time
;
845 int qemu_timer_pending(QEMUTimer
*ts
)
848 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
855 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
859 return (timer_head
->expire_time
<= current_time
);
862 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
868 if (!ts
|| ts
->expire_time
> current_time
)
870 /* remove timer from the list before calling the callback */
871 *ptimer_head
= ts
->next
;
874 /* run the callback (the timer list can be modified) */
879 int64_t qemu_get_clock(QEMUClock
*clock
)
881 switch(clock
->type
) {
882 case QEMU_TIMER_REALTIME
:
883 return get_clock() / 1000000;
885 case QEMU_TIMER_VIRTUAL
:
886 return cpu_get_clock();
890 static void init_timers(void)
893 ticks_per_sec
= QEMU_TIMER_BASE
;
894 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
895 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
899 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
901 uint64_t expire_time
;
903 if (qemu_timer_pending(ts
)) {
904 expire_time
= ts
->expire_time
;
908 qemu_put_be64(f
, expire_time
);
911 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
913 uint64_t expire_time
;
915 expire_time
= qemu_get_be64(f
);
916 if (expire_time
!= -1) {
917 qemu_mod_timer(ts
, expire_time
);
923 static void timer_save(QEMUFile
*f
, void *opaque
)
925 if (cpu_ticks_enabled
) {
926 hw_error("cannot save state if virtual timers are running");
928 qemu_put_be64s(f
, &cpu_ticks_offset
);
929 qemu_put_be64s(f
, &ticks_per_sec
);
930 qemu_put_be64s(f
, &cpu_clock_offset
);
933 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
935 if (version_id
!= 1 && version_id
!= 2)
937 if (cpu_ticks_enabled
) {
940 qemu_get_be64s(f
, &cpu_ticks_offset
);
941 qemu_get_be64s(f
, &ticks_per_sec
);
942 if (version_id
== 2) {
943 qemu_get_be64s(f
, &cpu_clock_offset
);
949 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
950 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
952 static void host_alarm_handler(int host_signum
)
956 #define DISP_FREQ 1000
958 static int64_t delta_min
= INT64_MAX
;
959 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
961 ti
= qemu_get_clock(vm_clock
);
962 if (last_clock
!= 0) {
963 delta
= ti
- last_clock
;
964 if (delta
< delta_min
)
966 if (delta
> delta_max
)
969 if (++count
== DISP_FREQ
) {
970 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
971 muldiv64(delta_min
, 1000000, ticks_per_sec
),
972 muldiv64(delta_max
, 1000000, ticks_per_sec
),
973 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
974 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
976 delta_min
= INT64_MAX
;
984 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
985 qemu_get_clock(vm_clock
)) ||
986 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
987 qemu_get_clock(rt_clock
))) {
989 SetEvent(host_alarm
);
991 CPUState
*env
= cpu_single_env
;
993 /* stop the currently executing cpu because a timer occured */
994 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
996 if (env
->kqemu_enabled
) {
997 kqemu_cpu_interrupt(env
);
1006 #if defined(__linux__)
1008 #define RTC_FREQ 1024
1012 static int start_rtc_timer(void)
1014 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1017 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1018 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1019 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1020 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1023 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1028 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1034 static int start_rtc_timer(void)
1039 #endif /* !defined(__linux__) */
1041 #endif /* !defined(_WIN32) */
1043 static void init_timer_alarm(void)
1050 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1051 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1052 if (period
< tc
.wPeriodMin
)
1053 period
= tc
.wPeriodMin
;
1054 timeBeginPeriod(period
);
1055 timerID
= timeSetEvent(1, // interval (ms)
1056 period
, // resolution
1057 host_alarm_handler
, // function
1058 (DWORD
)&count
, // user parameter
1059 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1061 perror("failed timer alarm");
1064 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1066 perror("failed CreateEvent");
1069 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1071 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1074 struct sigaction act
;
1075 struct itimerval itv
;
1077 /* get times() syscall frequency */
1078 timer_freq
= sysconf(_SC_CLK_TCK
);
1081 sigfillset(&act
.sa_mask
);
1083 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1084 act
.sa_flags
|= SA_ONSTACK
;
1086 act
.sa_handler
= host_alarm_handler
;
1087 sigaction(SIGALRM
, &act
, NULL
);
1089 itv
.it_interval
.tv_sec
= 0;
1090 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1091 itv
.it_value
.tv_sec
= 0;
1092 itv
.it_value
.tv_usec
= 10 * 1000;
1093 setitimer(ITIMER_REAL
, &itv
, NULL
);
1094 /* we probe the tick duration of the kernel to inform the user if
1095 the emulated kernel requested a too high timer frequency */
1096 getitimer(ITIMER_REAL
, &itv
);
1098 #if defined(__linux__)
1099 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1100 have timers with 1 ms resolution. The correct solution will
1101 be to use the POSIX real time timers available in recent
1103 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1104 /* try to use /dev/rtc to have a faster timer */
1105 if (start_rtc_timer() < 0)
1107 /* disable itimer */
1108 itv
.it_interval
.tv_sec
= 0;
1109 itv
.it_interval
.tv_usec
= 0;
1110 itv
.it_value
.tv_sec
= 0;
1111 itv
.it_value
.tv_usec
= 0;
1112 setitimer(ITIMER_REAL
, &itv
, NULL
);
1115 sigaction(SIGIO
, &act
, NULL
);
1116 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1117 fcntl(rtc_fd
, F_SETOWN
, getpid());
1119 #endif /* defined(__linux__) */
1122 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1123 PIT_FREQ
) / 1000000;
1129 void quit_timers(void)
1132 timeKillEvent(timerID
);
1133 timeEndPeriod(period
);
1135 CloseHandle(host_alarm
);
1141 /***********************************************************/
1142 /* character device */
1144 static void qemu_chr_event(CharDriverState
*s
, int event
)
1148 s
->chr_event(s
->handler_opaque
, event
);
1151 static void qemu_chr_reset_bh(void *opaque
)
1153 CharDriverState
*s
= opaque
;
1154 qemu_chr_event(s
, CHR_EVENT_RESET
);
1155 qemu_bh_delete(s
->bh
);
1159 void qemu_chr_reset(CharDriverState
*s
)
1161 if (s
->bh
== NULL
) {
1162 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1163 qemu_bh_schedule(s
->bh
);
1167 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1169 return s
->chr_write(s
, buf
, len
);
1172 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1176 return s
->chr_ioctl(s
, cmd
, arg
);
1179 int qemu_chr_can_read(CharDriverState
*s
)
1181 if (!s
->chr_can_read
)
1183 return s
->chr_can_read(s
->handler_opaque
);
1186 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1188 s
->chr_read(s
->handler_opaque
, buf
, len
);
1192 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1197 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1198 qemu_chr_write(s
, buf
, strlen(buf
));
1202 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1204 if (s
->chr_send_event
)
1205 s
->chr_send_event(s
, event
);
1208 void qemu_chr_add_handlers(CharDriverState
*s
,
1209 IOCanRWHandler
*fd_can_read
,
1210 IOReadHandler
*fd_read
,
1211 IOEventHandler
*fd_event
,
1214 s
->chr_can_read
= fd_can_read
;
1215 s
->chr_read
= fd_read
;
1216 s
->chr_event
= fd_event
;
1217 s
->handler_opaque
= opaque
;
1218 if (s
->chr_update_read_handler
)
1219 s
->chr_update_read_handler(s
);
1222 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1227 static CharDriverState
*qemu_chr_open_null(void)
1229 CharDriverState
*chr
;
1231 chr
= qemu_mallocz(sizeof(CharDriverState
));
1234 chr
->chr_write
= null_chr_write
;
1238 /* MUX driver for serial I/O splitting */
1239 static int term_timestamps
;
1240 static int64_t term_timestamps_start
;
1243 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1244 IOReadHandler
*chr_read
[MAX_MUX
];
1245 IOEventHandler
*chr_event
[MAX_MUX
];
1246 void *ext_opaque
[MAX_MUX
];
1247 CharDriverState
*drv
;
1249 int term_got_escape
;
1254 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1256 MuxDriver
*d
= chr
->opaque
;
1258 if (!term_timestamps
) {
1259 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1264 for(i
= 0; i
< len
; i
++) {
1265 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1266 if (buf
[i
] == '\n') {
1272 if (term_timestamps_start
== -1)
1273 term_timestamps_start
= ti
;
1274 ti
-= term_timestamps_start
;
1275 secs
= ti
/ 1000000000;
1276 snprintf(buf1
, sizeof(buf1
),
1277 "[%02d:%02d:%02d.%03d] ",
1281 (int)((ti
/ 1000000) % 1000));
1282 d
->drv
->chr_write(d
->drv
, buf1
, strlen(buf1
));
1289 static char *mux_help
[] = {
1290 "% h print this help\n\r",
1291 "% x exit emulator\n\r",
1292 "% s save disk data back to file (if -snapshot)\n\r",
1293 "% t toggle console timestamps\n\r"
1294 "% b send break (magic sysrq)\n\r",
1295 "% c switch between console and monitor\n\r",
1300 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1301 static void mux_print_help(CharDriverState
*chr
)
1304 char ebuf
[15] = "Escape-Char";
1305 char cbuf
[50] = "\n\r";
1307 if (term_escape_char
> 0 && term_escape_char
< 26) {
1308 sprintf(cbuf
,"\n\r");
1309 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1311 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char
);
1313 chr
->chr_write(chr
, cbuf
, strlen(cbuf
));
1314 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1315 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1316 if (mux_help
[i
][j
] == '%')
1317 chr
->chr_write(chr
, ebuf
, strlen(ebuf
));
1319 chr
->chr_write(chr
, &mux_help
[i
][j
], 1);
1324 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1326 if (d
->term_got_escape
) {
1327 d
->term_got_escape
= 0;
1328 if (ch
== term_escape_char
)
1333 mux_print_help(chr
);
1337 char *term
= "QEMU: Terminated\n\r";
1338 chr
->chr_write(chr
,term
,strlen(term
));
1345 for (i
= 0; i
< MAX_DISKS
; i
++) {
1347 bdrv_commit(bs_table
[i
]);
1353 chr
->chr_event(chr
->opaque
, CHR_EVENT_BREAK
);
1356 /* Switch to the next registered device */
1358 if (chr
->focus
>= d
->mux_cnt
)
1362 term_timestamps
= !term_timestamps
;
1363 term_timestamps_start
= -1;
1366 } else if (ch
== term_escape_char
) {
1367 d
->term_got_escape
= 1;
1375 static int mux_chr_can_read(void *opaque
)
1377 CharDriverState
*chr
= opaque
;
1378 MuxDriver
*d
= chr
->opaque
;
1379 if (d
->chr_can_read
[chr
->focus
])
1380 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1384 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1386 CharDriverState
*chr
= opaque
;
1387 MuxDriver
*d
= chr
->opaque
;
1389 for(i
= 0; i
< size
; i
++)
1390 if (mux_proc_byte(chr
, d
, buf
[i
]))
1391 d
->chr_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
], &buf
[i
], 1);
1394 static void mux_chr_event(void *opaque
, int event
)
1396 CharDriverState
*chr
= opaque
;
1397 MuxDriver
*d
= chr
->opaque
;
1400 /* Send the event to all registered listeners */
1401 for (i
= 0; i
< d
->mux_cnt
; i
++)
1402 if (d
->chr_event
[i
])
1403 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1406 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1408 MuxDriver
*d
= chr
->opaque
;
1410 if (d
->mux_cnt
>= MAX_MUX
) {
1411 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1414 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1415 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1416 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1417 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1418 /* Fix up the real driver with mux routines */
1419 if (d
->mux_cnt
== 0) {
1420 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1421 mux_chr_event
, chr
);
1423 chr
->focus
= d
->mux_cnt
;
1427 CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1429 CharDriverState
*chr
;
1432 chr
= qemu_mallocz(sizeof(CharDriverState
));
1435 d
= qemu_mallocz(sizeof(MuxDriver
));
1444 chr
->chr_write
= mux_chr_write
;
1445 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1452 static void socket_cleanup(void)
1457 static int socket_init(void)
1462 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1464 err
= WSAGetLastError();
1465 fprintf(stderr
, "WSAStartup: %d\n", err
);
1468 atexit(socket_cleanup
);
1472 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1478 ret
= send(fd
, buf
, len
, 0);
1481 errno
= WSAGetLastError();
1482 if (errno
!= WSAEWOULDBLOCK
) {
1485 } else if (ret
== 0) {
1495 void socket_set_nonblock(int fd
)
1497 unsigned long opt
= 1;
1498 ioctlsocket(fd
, FIONBIO
, &opt
);
1503 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1509 ret
= write(fd
, buf
, len
);
1511 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1513 } else if (ret
== 0) {
1523 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1525 return unix_write(fd
, buf
, len1
);
1528 void socket_set_nonblock(int fd
)
1530 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1532 #endif /* !_WIN32 */
1541 #define STDIO_MAX_CLIENTS 1
1542 static int stdio_nb_clients
= 0;
1544 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1546 FDCharDriver
*s
= chr
->opaque
;
1547 return unix_write(s
->fd_out
, buf
, len
);
1550 static int fd_chr_read_poll(void *opaque
)
1552 CharDriverState
*chr
= opaque
;
1553 FDCharDriver
*s
= chr
->opaque
;
1555 s
->max_size
= qemu_chr_can_read(chr
);
1559 static void fd_chr_read(void *opaque
)
1561 CharDriverState
*chr
= opaque
;
1562 FDCharDriver
*s
= chr
->opaque
;
1567 if (len
> s
->max_size
)
1571 size
= read(s
->fd_in
, buf
, len
);
1573 /* FD has been closed. Remove it from the active list. */
1574 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1578 qemu_chr_read(chr
, buf
, size
);
1582 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1584 FDCharDriver
*s
= chr
->opaque
;
1586 if (s
->fd_in
>= 0) {
1587 if (nographic
&& s
->fd_in
== 0) {
1589 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1590 fd_chr_read
, NULL
, chr
);
1595 /* open a character device to a unix fd */
1596 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1598 CharDriverState
*chr
;
1601 chr
= qemu_mallocz(sizeof(CharDriverState
));
1604 s
= qemu_mallocz(sizeof(FDCharDriver
));
1612 chr
->chr_write
= fd_chr_write
;
1613 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1615 qemu_chr_reset(chr
);
1620 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1624 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1627 return qemu_chr_open_fd(-1, fd_out
);
1630 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1633 char filename_in
[256], filename_out
[256];
1635 snprintf(filename_in
, 256, "%s.in", filename
);
1636 snprintf(filename_out
, 256, "%s.out", filename
);
1637 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1638 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1639 if (fd_in
< 0 || fd_out
< 0) {
1644 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1648 return qemu_chr_open_fd(fd_in
, fd_out
);
1652 /* for STDIO, we handle the case where several clients use it
1655 #define TERM_FIFO_MAX_SIZE 1
1657 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1658 static int term_fifo_size
;
1660 static int stdio_read_poll(void *opaque
)
1662 CharDriverState
*chr
= opaque
;
1664 /* try to flush the queue if needed */
1665 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1666 qemu_chr_read(chr
, term_fifo
, 1);
1669 /* see if we can absorb more chars */
1670 if (term_fifo_size
== 0)
1676 static void stdio_read(void *opaque
)
1680 CharDriverState
*chr
= opaque
;
1682 size
= read(0, buf
, 1);
1684 /* stdin has been closed. Remove it from the active list. */
1685 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1689 if (qemu_chr_can_read(chr
) > 0) {
1690 qemu_chr_read(chr
, buf
, 1);
1691 } else if (term_fifo_size
== 0) {
1692 term_fifo
[term_fifo_size
++] = buf
[0];
1697 /* init terminal so that we can grab keys */
1698 static struct termios oldtty
;
1699 static int old_fd0_flags
;
1701 static void term_exit(void)
1703 tcsetattr (0, TCSANOW
, &oldtty
);
1704 fcntl(0, F_SETFL
, old_fd0_flags
);
1707 static void term_init(void)
1711 tcgetattr (0, &tty
);
1713 old_fd0_flags
= fcntl(0, F_GETFL
);
1715 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1716 |INLCR
|IGNCR
|ICRNL
|IXON
);
1717 tty
.c_oflag
|= OPOST
;
1718 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1719 /* if graphical mode, we allow Ctrl-C handling */
1721 tty
.c_lflag
&= ~ISIG
;
1722 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1725 tty
.c_cc
[VTIME
] = 0;
1727 tcsetattr (0, TCSANOW
, &tty
);
1731 fcntl(0, F_SETFL
, O_NONBLOCK
);
1734 static CharDriverState
*qemu_chr_open_stdio(void)
1736 CharDriverState
*chr
;
1738 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1740 chr
= qemu_chr_open_fd(0, 1);
1741 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
1748 #if defined(__linux__)
1749 static CharDriverState
*qemu_chr_open_pty(void)
1752 char slave_name
[1024];
1753 int master_fd
, slave_fd
;
1755 /* Not satisfying */
1756 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1760 /* Disabling local echo and line-buffered output */
1761 tcgetattr (master_fd
, &tty
);
1762 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1764 tty
.c_cc
[VTIME
] = 0;
1765 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1767 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1768 return qemu_chr_open_fd(master_fd
, master_fd
);
1771 static void tty_serial_init(int fd
, int speed
,
1772 int parity
, int data_bits
, int stop_bits
)
1778 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1779 speed
, parity
, data_bits
, stop_bits
);
1781 tcgetattr (fd
, &tty
);
1823 cfsetispeed(&tty
, spd
);
1824 cfsetospeed(&tty
, spd
);
1826 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1827 |INLCR
|IGNCR
|ICRNL
|IXON
);
1828 tty
.c_oflag
|= OPOST
;
1829 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1830 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1851 tty
.c_cflag
|= PARENB
;
1854 tty
.c_cflag
|= PARENB
| PARODD
;
1858 tty
.c_cflag
|= CSTOPB
;
1860 tcsetattr (fd
, TCSANOW
, &tty
);
1863 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1865 FDCharDriver
*s
= chr
->opaque
;
1868 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1870 QEMUSerialSetParams
*ssp
= arg
;
1871 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1872 ssp
->data_bits
, ssp
->stop_bits
);
1875 case CHR_IOCTL_SERIAL_SET_BREAK
:
1877 int enable
= *(int *)arg
;
1879 tcsendbreak(s
->fd_in
, 1);
1888 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1890 CharDriverState
*chr
;
1893 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1896 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1897 tty_serial_init(fd
, 115200, 'N', 8, 1);
1898 chr
= qemu_chr_open_fd(fd
, fd
);
1901 chr
->chr_ioctl
= tty_serial_ioctl
;
1902 qemu_chr_reset(chr
);
1909 } ParallelCharDriver
;
1911 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
1913 if (s
->mode
!= mode
) {
1915 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
1922 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1924 ParallelCharDriver
*drv
= chr
->opaque
;
1929 case CHR_IOCTL_PP_READ_DATA
:
1930 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1932 *(uint8_t *)arg
= b
;
1934 case CHR_IOCTL_PP_WRITE_DATA
:
1935 b
= *(uint8_t *)arg
;
1936 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1939 case CHR_IOCTL_PP_READ_CONTROL
:
1940 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1942 /* Linux gives only the lowest bits, and no way to know data
1943 direction! For better compatibility set the fixed upper
1945 *(uint8_t *)arg
= b
| 0xc0;
1947 case CHR_IOCTL_PP_WRITE_CONTROL
:
1948 b
= *(uint8_t *)arg
;
1949 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1952 case CHR_IOCTL_PP_READ_STATUS
:
1953 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1955 *(uint8_t *)arg
= b
;
1957 case CHR_IOCTL_PP_EPP_READ_ADDR
:
1958 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1959 struct ParallelIOArg
*parg
= arg
;
1960 int n
= read(fd
, parg
->buffer
, parg
->count
);
1961 if (n
!= parg
->count
) {
1966 case CHR_IOCTL_PP_EPP_READ
:
1967 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1968 struct ParallelIOArg
*parg
= arg
;
1969 int n
= read(fd
, parg
->buffer
, parg
->count
);
1970 if (n
!= parg
->count
) {
1975 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
1976 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1977 struct ParallelIOArg
*parg
= arg
;
1978 int n
= write(fd
, parg
->buffer
, parg
->count
);
1979 if (n
!= parg
->count
) {
1984 case CHR_IOCTL_PP_EPP_WRITE
:
1985 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1986 struct ParallelIOArg
*parg
= arg
;
1987 int n
= write(fd
, parg
->buffer
, parg
->count
);
1988 if (n
!= parg
->count
) {
1999 static void pp_close(CharDriverState
*chr
)
2001 ParallelCharDriver
*drv
= chr
->opaque
;
2004 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2005 ioctl(fd
, PPRELEASE
);
2010 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2012 CharDriverState
*chr
;
2013 ParallelCharDriver
*drv
;
2016 fd
= open(filename
, O_RDWR
);
2020 if (ioctl(fd
, PPCLAIM
) < 0) {
2025 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2031 drv
->mode
= IEEE1284_MODE_COMPAT
;
2033 chr
= qemu_mallocz(sizeof(CharDriverState
));
2039 chr
->chr_write
= null_chr_write
;
2040 chr
->chr_ioctl
= pp_ioctl
;
2041 chr
->chr_close
= pp_close
;
2044 qemu_chr_reset(chr
);
2050 static CharDriverState
*qemu_chr_open_pty(void)
2056 #endif /* !defined(_WIN32) */
2061 HANDLE hcom
, hrecv
, hsend
;
2062 OVERLAPPED orecv
, osend
;
2067 #define NSENDBUF 2048
2068 #define NRECVBUF 2048
2069 #define MAXCONNECT 1
2070 #define NTIMEOUT 5000
2072 static int win_chr_poll(void *opaque
);
2073 static int win_chr_pipe_poll(void *opaque
);
2075 static void win_chr_close(CharDriverState
*chr
)
2077 WinCharState
*s
= chr
->opaque
;
2080 CloseHandle(s
->hsend
);
2084 CloseHandle(s
->hrecv
);
2088 CloseHandle(s
->hcom
);
2092 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2094 qemu_del_polling_cb(win_chr_poll
, chr
);
2097 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2099 WinCharState
*s
= chr
->opaque
;
2101 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2106 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2108 fprintf(stderr
, "Failed CreateEvent\n");
2111 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2113 fprintf(stderr
, "Failed CreateEvent\n");
2117 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2118 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2119 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2120 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2125 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2126 fprintf(stderr
, "Failed SetupComm\n");
2130 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2131 size
= sizeof(COMMCONFIG
);
2132 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2133 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2134 CommConfigDialog(filename
, NULL
, &comcfg
);
2136 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2137 fprintf(stderr
, "Failed SetCommState\n");
2141 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2142 fprintf(stderr
, "Failed SetCommMask\n");
2146 cto
.ReadIntervalTimeout
= MAXDWORD
;
2147 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2148 fprintf(stderr
, "Failed SetCommTimeouts\n");
2152 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2153 fprintf(stderr
, "Failed ClearCommError\n");
2156 qemu_add_polling_cb(win_chr_poll
, chr
);
2164 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2166 WinCharState
*s
= chr
->opaque
;
2167 DWORD len
, ret
, size
, err
;
2170 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2171 s
->osend
.hEvent
= s
->hsend
;
2174 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2176 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2178 err
= GetLastError();
2179 if (err
== ERROR_IO_PENDING
) {
2180 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2198 static int win_chr_read_poll(CharDriverState
*chr
)
2200 WinCharState
*s
= chr
->opaque
;
2202 s
->max_size
= qemu_chr_can_read(chr
);
2206 static void win_chr_readfile(CharDriverState
*chr
)
2208 WinCharState
*s
= chr
->opaque
;
2213 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2214 s
->orecv
.hEvent
= s
->hrecv
;
2215 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2217 err
= GetLastError();
2218 if (err
== ERROR_IO_PENDING
) {
2219 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2224 qemu_chr_read(chr
, buf
, size
);
2228 static void win_chr_read(CharDriverState
*chr
)
2230 WinCharState
*s
= chr
->opaque
;
2232 if (s
->len
> s
->max_size
)
2233 s
->len
= s
->max_size
;
2237 win_chr_readfile(chr
);
2240 static int win_chr_poll(void *opaque
)
2242 CharDriverState
*chr
= opaque
;
2243 WinCharState
*s
= chr
->opaque
;
2247 ClearCommError(s
->hcom
, &comerr
, &status
);
2248 if (status
.cbInQue
> 0) {
2249 s
->len
= status
.cbInQue
;
2250 win_chr_read_poll(chr
);
2257 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2259 CharDriverState
*chr
;
2262 chr
= qemu_mallocz(sizeof(CharDriverState
));
2265 s
= qemu_mallocz(sizeof(WinCharState
));
2271 chr
->chr_write
= win_chr_write
;
2272 chr
->chr_close
= win_chr_close
;
2274 if (win_chr_init(chr
, filename
) < 0) {
2279 qemu_chr_reset(chr
);
2283 static int win_chr_pipe_poll(void *opaque
)
2285 CharDriverState
*chr
= opaque
;
2286 WinCharState
*s
= chr
->opaque
;
2289 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2292 win_chr_read_poll(chr
);
2299 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2301 WinCharState
*s
= chr
->opaque
;
2309 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2311 fprintf(stderr
, "Failed CreateEvent\n");
2314 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2316 fprintf(stderr
, "Failed CreateEvent\n");
2320 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2321 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2322 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2324 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2325 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2326 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2331 ZeroMemory(&ov
, sizeof(ov
));
2332 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2333 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2335 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2339 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2341 fprintf(stderr
, "Failed GetOverlappedResult\n");
2343 CloseHandle(ov
.hEvent
);
2350 CloseHandle(ov
.hEvent
);
2353 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2362 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2364 CharDriverState
*chr
;
2367 chr
= qemu_mallocz(sizeof(CharDriverState
));
2370 s
= qemu_mallocz(sizeof(WinCharState
));
2376 chr
->chr_write
= win_chr_write
;
2377 chr
->chr_close
= win_chr_close
;
2379 if (win_chr_pipe_init(chr
, filename
) < 0) {
2384 qemu_chr_reset(chr
);
2388 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2390 CharDriverState
*chr
;
2393 chr
= qemu_mallocz(sizeof(CharDriverState
));
2396 s
= qemu_mallocz(sizeof(WinCharState
));
2403 chr
->chr_write
= win_chr_write
;
2404 qemu_chr_reset(chr
);
2408 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2412 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2413 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2414 if (fd_out
== INVALID_HANDLE_VALUE
)
2417 return qemu_chr_open_win_file(fd_out
);
2421 /***********************************************************/
2422 /* UDP Net console */
2426 struct sockaddr_in daddr
;
2433 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2435 NetCharDriver
*s
= chr
->opaque
;
2437 return sendto(s
->fd
, buf
, len
, 0,
2438 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2441 static int udp_chr_read_poll(void *opaque
)
2443 CharDriverState
*chr
= opaque
;
2444 NetCharDriver
*s
= chr
->opaque
;
2446 s
->max_size
= qemu_chr_can_read(chr
);
2448 /* If there were any stray characters in the queue process them
2451 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2452 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2454 s
->max_size
= qemu_chr_can_read(chr
);
2459 static void udp_chr_read(void *opaque
)
2461 CharDriverState
*chr
= opaque
;
2462 NetCharDriver
*s
= chr
->opaque
;
2464 if (s
->max_size
== 0)
2466 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2467 s
->bufptr
= s
->bufcnt
;
2472 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2473 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2475 s
->max_size
= qemu_chr_can_read(chr
);
2479 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2481 NetCharDriver
*s
= chr
->opaque
;
2484 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2485 udp_chr_read
, NULL
, chr
);
2489 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2491 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2493 int parse_host_src_port(struct sockaddr_in
*haddr
,
2494 struct sockaddr_in
*saddr
,
2497 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2499 CharDriverState
*chr
= NULL
;
2500 NetCharDriver
*s
= NULL
;
2502 struct sockaddr_in saddr
;
2504 chr
= qemu_mallocz(sizeof(CharDriverState
));
2507 s
= qemu_mallocz(sizeof(NetCharDriver
));
2511 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2513 perror("socket(PF_INET, SOCK_DGRAM)");
2517 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2518 printf("Could not parse: %s\n", def
);
2522 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2532 chr
->chr_write
= udp_chr_write
;
2533 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2546 /***********************************************************/
2547 /* TCP Net console */
2558 static void tcp_chr_accept(void *opaque
);
2560 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2562 TCPCharDriver
*s
= chr
->opaque
;
2564 return send_all(s
->fd
, buf
, len
);
2566 /* XXX: indicate an error ? */
2571 static int tcp_chr_read_poll(void *opaque
)
2573 CharDriverState
*chr
= opaque
;
2574 TCPCharDriver
*s
= chr
->opaque
;
2577 s
->max_size
= qemu_chr_can_read(chr
);
2582 #define IAC_BREAK 243
2583 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2585 char *buf
, int *size
)
2587 /* Handle any telnet client's basic IAC options to satisfy char by
2588 * char mode with no echo. All IAC options will be removed from
2589 * the buf and the do_telnetopt variable will be used to track the
2590 * state of the width of the IAC information.
2592 * IAC commands come in sets of 3 bytes with the exception of the
2593 * "IAC BREAK" command and the double IAC.
2599 for (i
= 0; i
< *size
; i
++) {
2600 if (s
->do_telnetopt
> 1) {
2601 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2602 /* Double IAC means send an IAC */
2606 s
->do_telnetopt
= 1;
2608 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2609 /* Handle IAC break commands by sending a serial break */
2610 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2615 if (s
->do_telnetopt
>= 4) {
2616 s
->do_telnetopt
= 1;
2619 if ((unsigned char)buf
[i
] == IAC
) {
2620 s
->do_telnetopt
= 2;
2631 static void tcp_chr_read(void *opaque
)
2633 CharDriverState
*chr
= opaque
;
2634 TCPCharDriver
*s
= chr
->opaque
;
2638 if (!s
->connected
|| s
->max_size
<= 0)
2641 if (len
> s
->max_size
)
2643 size
= recv(s
->fd
, buf
, len
, 0);
2645 /* connection closed */
2647 if (s
->listen_fd
>= 0) {
2648 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2650 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2653 } else if (size
> 0) {
2654 if (s
->do_telnetopt
)
2655 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2657 qemu_chr_read(chr
, buf
, size
);
2661 static void tcp_chr_connect(void *opaque
)
2663 CharDriverState
*chr
= opaque
;
2664 TCPCharDriver
*s
= chr
->opaque
;
2667 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2668 tcp_chr_read
, NULL
, chr
);
2669 qemu_chr_reset(chr
);
2672 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2673 static void tcp_chr_telnet_init(int fd
)
2676 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2677 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2678 send(fd
, (char *)buf
, 3, 0);
2679 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2680 send(fd
, (char *)buf
, 3, 0);
2681 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2682 send(fd
, (char *)buf
, 3, 0);
2683 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2684 send(fd
, (char *)buf
, 3, 0);
2687 static void socket_set_nodelay(int fd
)
2690 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2693 static void tcp_chr_accept(void *opaque
)
2695 CharDriverState
*chr
= opaque
;
2696 TCPCharDriver
*s
= chr
->opaque
;
2697 struct sockaddr_in saddr
;
2699 struct sockaddr_un uaddr
;
2701 struct sockaddr
*addr
;
2708 len
= sizeof(uaddr
);
2709 addr
= (struct sockaddr
*)&uaddr
;
2713 len
= sizeof(saddr
);
2714 addr
= (struct sockaddr
*)&saddr
;
2716 fd
= accept(s
->listen_fd
, addr
, &len
);
2717 if (fd
< 0 && errno
!= EINTR
) {
2719 } else if (fd
>= 0) {
2720 if (s
->do_telnetopt
)
2721 tcp_chr_telnet_init(fd
);
2725 socket_set_nonblock(fd
);
2727 socket_set_nodelay(fd
);
2729 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2730 tcp_chr_connect(chr
);
2733 static void tcp_chr_close(CharDriverState
*chr
)
2735 TCPCharDriver
*s
= chr
->opaque
;
2738 if (s
->listen_fd
>= 0)
2739 closesocket(s
->listen_fd
);
2743 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2747 CharDriverState
*chr
= NULL
;
2748 TCPCharDriver
*s
= NULL
;
2749 int fd
= -1, ret
, err
, val
;
2751 int is_waitconnect
= 1;
2754 struct sockaddr_in saddr
;
2756 struct sockaddr_un uaddr
;
2758 struct sockaddr
*addr
;
2763 addr
= (struct sockaddr
*)&uaddr
;
2764 addrlen
= sizeof(uaddr
);
2765 if (parse_unix_path(&uaddr
, host_str
) < 0)
2770 addr
= (struct sockaddr
*)&saddr
;
2771 addrlen
= sizeof(saddr
);
2772 if (parse_host_port(&saddr
, host_str
) < 0)
2777 while((ptr
= strchr(ptr
,','))) {
2779 if (!strncmp(ptr
,"server",6)) {
2781 } else if (!strncmp(ptr
,"nowait",6)) {
2783 } else if (!strncmp(ptr
,"nodelay",6)) {
2786 printf("Unknown option: %s\n", ptr
);
2793 chr
= qemu_mallocz(sizeof(CharDriverState
));
2796 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2802 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2805 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2810 if (!is_waitconnect
)
2811 socket_set_nonblock(fd
);
2816 s
->is_unix
= is_unix
;
2817 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2820 chr
->chr_write
= tcp_chr_write
;
2821 chr
->chr_close
= tcp_chr_close
;
2824 /* allow fast reuse */
2828 strncpy(path
, uaddr
.sun_path
, 108);
2835 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2838 ret
= bind(fd
, addr
, addrlen
);
2842 ret
= listen(fd
, 0);
2847 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2849 s
->do_telnetopt
= 1;
2852 ret
= connect(fd
, addr
, addrlen
);
2854 err
= socket_error();
2855 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2856 } else if (err
== EINPROGRESS
) {
2859 } else if (err
== WSAEALREADY
) {
2871 socket_set_nodelay(fd
);
2873 tcp_chr_connect(chr
);
2875 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2878 if (is_listen
&& is_waitconnect
) {
2879 printf("QEMU waiting for connection on: %s\n", host_str
);
2880 tcp_chr_accept(chr
);
2881 socket_set_nonblock(s
->listen_fd
);
2893 CharDriverState
*qemu_chr_open(const char *filename
)
2897 if (!strcmp(filename
, "vc")) {
2898 return text_console_init(&display_state
);
2899 } else if (!strcmp(filename
, "null")) {
2900 return qemu_chr_open_null();
2902 if (strstart(filename
, "tcp:", &p
)) {
2903 return qemu_chr_open_tcp(p
, 0, 0);
2905 if (strstart(filename
, "telnet:", &p
)) {
2906 return qemu_chr_open_tcp(p
, 1, 0);
2908 if (strstart(filename
, "udp:", &p
)) {
2909 return qemu_chr_open_udp(p
);
2911 if (strstart(filename
, "mon:", &p
)) {
2912 CharDriverState
*drv
= qemu_chr_open(p
);
2914 drv
= qemu_chr_open_mux(drv
);
2915 monitor_init(drv
, !nographic
);
2918 printf("Unable to open driver: %s\n", p
);
2922 if (strstart(filename
, "unix:", &p
)) {
2923 return qemu_chr_open_tcp(p
, 0, 1);
2924 } else if (strstart(filename
, "file:", &p
)) {
2925 return qemu_chr_open_file_out(p
);
2926 } else if (strstart(filename
, "pipe:", &p
)) {
2927 return qemu_chr_open_pipe(p
);
2928 } else if (!strcmp(filename
, "pty")) {
2929 return qemu_chr_open_pty();
2930 } else if (!strcmp(filename
, "stdio")) {
2931 return qemu_chr_open_stdio();
2934 #if defined(__linux__)
2935 if (strstart(filename
, "/dev/parport", NULL
)) {
2936 return qemu_chr_open_pp(filename
);
2938 if (strstart(filename
, "/dev/", NULL
)) {
2939 return qemu_chr_open_tty(filename
);
2943 if (strstart(filename
, "COM", NULL
)) {
2944 return qemu_chr_open_win(filename
);
2946 if (strstart(filename
, "pipe:", &p
)) {
2947 return qemu_chr_open_win_pipe(p
);
2949 if (strstart(filename
, "file:", &p
)) {
2950 return qemu_chr_open_win_file_out(p
);
2958 void qemu_chr_close(CharDriverState
*chr
)
2961 chr
->chr_close(chr
);
2964 /***********************************************************/
2965 /* network device redirectors */
2967 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2971 for(i
=0;i
<size
;i
+=16) {
2975 fprintf(f
, "%08x ", i
);
2978 fprintf(f
, " %02x", buf
[i
+j
]);
2983 for(j
=0;j
<len
;j
++) {
2985 if (c
< ' ' || c
> '~')
2987 fprintf(f
, "%c", c
);
2993 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2996 for(i
= 0; i
< 6; i
++) {
2997 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3010 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3015 p1
= strchr(p
, sep
);
3021 if (len
> buf_size
- 1)
3023 memcpy(buf
, p
, len
);
3030 int parse_host_src_port(struct sockaddr_in
*haddr
,
3031 struct sockaddr_in
*saddr
,
3032 const char *input_str
)
3034 char *str
= strdup(input_str
);
3035 char *host_str
= str
;
3040 * Chop off any extra arguments at the end of the string which
3041 * would start with a comma, then fill in the src port information
3042 * if it was provided else use the "any address" and "any port".
3044 if ((ptr
= strchr(str
,',')))
3047 if ((src_str
= strchr(input_str
,'@'))) {
3052 if (parse_host_port(haddr
, host_str
) < 0)
3055 if (!src_str
|| *src_str
== '\0')
3058 if (parse_host_port(saddr
, src_str
) < 0)
3069 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3077 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3079 saddr
->sin_family
= AF_INET
;
3080 if (buf
[0] == '\0') {
3081 saddr
->sin_addr
.s_addr
= 0;
3083 if (isdigit(buf
[0])) {
3084 if (!inet_aton(buf
, &saddr
->sin_addr
))
3087 if ((he
= gethostbyname(buf
)) == NULL
)
3089 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3092 port
= strtol(p
, (char **)&r
, 0);
3095 saddr
->sin_port
= htons(port
);
3100 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3105 len
= MIN(108, strlen(str
));
3106 p
= strchr(str
, ',');
3108 len
= MIN(len
, p
- str
);
3110 memset(uaddr
, 0, sizeof(*uaddr
));
3112 uaddr
->sun_family
= AF_UNIX
;
3113 memcpy(uaddr
->sun_path
, str
, len
);
3119 /* find or alloc a new VLAN */
3120 VLANState
*qemu_find_vlan(int id
)
3122 VLANState
**pvlan
, *vlan
;
3123 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3127 vlan
= qemu_mallocz(sizeof(VLANState
));
3132 pvlan
= &first_vlan
;
3133 while (*pvlan
!= NULL
)
3134 pvlan
= &(*pvlan
)->next
;
3139 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3140 IOReadHandler
*fd_read
,
3141 IOCanRWHandler
*fd_can_read
,
3144 VLANClientState
*vc
, **pvc
;
3145 vc
= qemu_mallocz(sizeof(VLANClientState
));
3148 vc
->fd_read
= fd_read
;
3149 vc
->fd_can_read
= fd_can_read
;
3150 vc
->opaque
= opaque
;
3154 pvc
= &vlan
->first_client
;
3155 while (*pvc
!= NULL
)
3156 pvc
= &(*pvc
)->next
;
3161 int qemu_can_send_packet(VLANClientState
*vc1
)
3163 VLANState
*vlan
= vc1
->vlan
;
3164 VLANClientState
*vc
;
3166 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3168 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
3175 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3177 VLANState
*vlan
= vc1
->vlan
;
3178 VLANClientState
*vc
;
3181 printf("vlan %d send:\n", vlan
->id
);
3182 hex_dump(stdout
, buf
, size
);
3184 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3186 vc
->fd_read(vc
->opaque
, buf
, size
);
3191 #if defined(CONFIG_SLIRP)
3193 /* slirp network adapter */
3195 static int slirp_inited
;
3196 static VLANClientState
*slirp_vc
;
3198 int slirp_can_output(void)
3200 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3203 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3206 printf("slirp output:\n");
3207 hex_dump(stdout
, pkt
, pkt_len
);
3211 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3214 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3217 printf("slirp input:\n");
3218 hex_dump(stdout
, buf
, size
);
3220 slirp_input(buf
, size
);
3223 static int net_slirp_init(VLANState
*vlan
)
3225 if (!slirp_inited
) {
3229 slirp_vc
= qemu_new_vlan_client(vlan
,
3230 slirp_receive
, NULL
, NULL
);
3231 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3235 static void net_slirp_redir(const char *redir_str
)
3240 struct in_addr guest_addr
;
3241 int host_port
, guest_port
;
3243 if (!slirp_inited
) {
3249 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3251 if (!strcmp(buf
, "tcp")) {
3253 } else if (!strcmp(buf
, "udp")) {
3259 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3261 host_port
= strtol(buf
, &r
, 0);
3265 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3267 if (buf
[0] == '\0') {
3268 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3270 if (!inet_aton(buf
, &guest_addr
))
3273 guest_port
= strtol(p
, &r
, 0);
3277 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3278 fprintf(stderr
, "qemu: could not set up redirection\n");
3283 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3291 static void smb_exit(void)
3295 char filename
[1024];
3297 /* erase all the files in the directory */
3298 d
= opendir(smb_dir
);
3303 if (strcmp(de
->d_name
, ".") != 0 &&
3304 strcmp(de
->d_name
, "..") != 0) {
3305 snprintf(filename
, sizeof(filename
), "%s/%s",
3306 smb_dir
, de
->d_name
);
3314 /* automatic user mode samba server configuration */
3315 void net_slirp_smb(const char *exported_dir
)
3317 char smb_conf
[1024];
3318 char smb_cmdline
[1024];
3321 if (!slirp_inited
) {
3326 /* XXX: better tmp dir construction */
3327 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3328 if (mkdir(smb_dir
, 0700) < 0) {
3329 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3332 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3334 f
= fopen(smb_conf
, "w");
3336 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3343 "socket address=127.0.0.1\n"
3344 "pid directory=%s\n"
3345 "lock directory=%s\n"
3346 "log file=%s/log.smbd\n"
3347 "smb passwd file=%s/smbpasswd\n"
3348 "security = share\n"
3363 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3364 SMBD_COMMAND
, smb_conf
);
3366 slirp_add_exec(0, smb_cmdline
, 4, 139);
3369 #endif /* !defined(_WIN32) */
3371 #endif /* CONFIG_SLIRP */
3373 #if !defined(_WIN32)
3375 typedef struct TAPState
{
3376 VLANClientState
*vc
;
3380 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3382 TAPState
*s
= opaque
;
3385 ret
= write(s
->fd
, buf
, size
);
3386 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3393 static void tap_send(void *opaque
)
3395 TAPState
*s
= opaque
;
3402 sbuf
.maxlen
= sizeof(buf
);
3404 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3406 size
= read(s
->fd
, buf
, sizeof(buf
));
3409 qemu_send_packet(s
->vc
, buf
, size
);
3415 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3419 s
= qemu_mallocz(sizeof(TAPState
));
3423 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3424 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3425 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3430 static int tap_open(char *ifname
, int ifname_size
)
3436 fd
= open("/dev/tap", O_RDWR
);
3438 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3443 dev
= devname(s
.st_rdev
, S_IFCHR
);
3444 pstrcpy(ifname
, ifname_size
, dev
);
3446 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3449 #elif defined(__sun__)
3450 #define TUNNEWPPA (('T'<<16) | 0x0001)
3452 * Allocate TAP device, returns opened fd.
3453 * Stores dev name in the first arg(must be large enough).
3455 int tap_alloc(char *dev
)
3457 int tap_fd
, if_fd
, ppa
= -1;
3458 static int ip_fd
= 0;
3461 static int arp_fd
= 0;
3462 int ip_muxid
, arp_muxid
;
3463 struct strioctl strioc_if
, strioc_ppa
;
3464 int link_type
= I_PLINK
;;
3466 char actual_name
[32] = "";
3468 memset(&ifr
, 0x0, sizeof(ifr
));
3472 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
3476 /* Check if IP device was opened */
3480 if( (ip_fd
= open("/dev/udp", O_RDWR
, 0)) < 0){
3481 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
3485 if( (tap_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3486 syslog(LOG_ERR
, "Can't open /dev/tap");
3490 /* Assign a new PPA and get its unit number. */
3491 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
3492 strioc_ppa
.ic_timout
= 0;
3493 strioc_ppa
.ic_len
= sizeof(ppa
);
3494 strioc_ppa
.ic_dp
= (char *)&ppa
;
3495 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
3496 syslog (LOG_ERR
, "Can't assign new interface");
3498 if( (if_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3499 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
3502 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
3503 syslog(LOG_ERR
, "Can't push IP module");
3507 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
3508 syslog(LOG_ERR
, "Can't get flags\n");
3510 snprintf (actual_name
, 32, "tap%d", ppa
);
3511 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3514 /* Assign ppa according to the unit number returned by tun device */
3516 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
3517 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
3518 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
3519 syslog (LOG_ERR
, "Can't get flags\n");
3520 /* Push arp module to if_fd */
3521 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
3522 syslog (LOG_ERR
, "Can't push ARP module (2)");
3524 /* Push arp module to ip_fd */
3525 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
3526 syslog (LOG_ERR
, "I_POP failed\n");
3527 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
3528 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
3530 if ((arp_fd
= open ("/dev/tap", O_RDWR
, 0)) < 0)
3531 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
3533 /* Set ifname to arp */
3534 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
3535 strioc_if
.ic_timout
= 0;
3536 strioc_if
.ic_len
= sizeof(ifr
);
3537 strioc_if
.ic_dp
= (char *)&ifr
;
3538 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
3539 syslog (LOG_ERR
, "Can't set ifname to arp\n");
3542 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
3543 syslog(LOG_ERR
, "Can't link TAP device to IP");
3547 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
3548 syslog (LOG_ERR
, "Can't link TAP device to ARP");
3552 memset(&ifr
, 0x0, sizeof(ifr
));
3553 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3554 ifr
.lifr_ip_muxid
= ip_muxid
;
3555 ifr
.lifr_arp_muxid
= arp_muxid
;
3557 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
3559 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
3560 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
3561 syslog (LOG_ERR
, "Can't set multiplexor id");
3564 sprintf(dev
, "tap%d", ppa
);
3568 static int tap_open(char *ifname
, int ifname_size
)
3572 if( (fd
= tap_alloc(dev
)) < 0 ){
3573 fprintf(stderr
, "Cannot allocate TAP device\n");
3576 pstrcpy(ifname
, ifname_size
, dev
);
3577 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3581 static int tap_open(char *ifname
, int ifname_size
)
3586 fd
= open("/dev/net/tun", O_RDWR
);
3588 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3591 memset(&ifr
, 0, sizeof(ifr
));
3592 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3593 if (ifname
[0] != '\0')
3594 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3596 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3597 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3599 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3603 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3604 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3609 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3610 const char *setup_script
)
3613 int pid
, status
, fd
;
3618 if (ifname1
!= NULL
)
3619 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3622 fd
= tap_open(ifname
, sizeof(ifname
));
3626 if (!setup_script
|| !strcmp(setup_script
, "no"))
3628 if (setup_script
[0] != '\0') {
3629 /* try to launch network init script */
3633 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
3634 for (i
= 0; i
< open_max
; i
++)
3635 if (i
!= STDIN_FILENO
&&
3636 i
!= STDOUT_FILENO
&&
3637 i
!= STDERR_FILENO
&&
3642 *parg
++ = (char *)setup_script
;
3645 execv(setup_script
, args
);
3648 while (waitpid(pid
, &status
, 0) != pid
);
3649 if (!WIFEXITED(status
) ||
3650 WEXITSTATUS(status
) != 0) {
3651 fprintf(stderr
, "%s: could not launch network script\n",
3657 s
= net_tap_fd_init(vlan
, fd
);
3660 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3661 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3665 #endif /* !_WIN32 */
3667 /* network connection */
3668 typedef struct NetSocketState
{
3669 VLANClientState
*vc
;
3671 int state
; /* 0 = getting length, 1 = getting data */
3675 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3678 typedef struct NetSocketListenState
{
3681 } NetSocketListenState
;
3683 /* XXX: we consider we can send the whole packet without blocking */
3684 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3686 NetSocketState
*s
= opaque
;
3690 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3691 send_all(s
->fd
, buf
, size
);
3694 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3696 NetSocketState
*s
= opaque
;
3697 sendto(s
->fd
, buf
, size
, 0,
3698 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3701 static void net_socket_send(void *opaque
)
3703 NetSocketState
*s
= opaque
;
3708 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3710 err
= socket_error();
3711 if (err
!= EWOULDBLOCK
)
3713 } else if (size
== 0) {
3714 /* end of connection */
3716 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3722 /* reassemble a packet from the network */
3728 memcpy(s
->buf
+ s
->index
, buf
, l
);
3732 if (s
->index
== 4) {
3734 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3740 l
= s
->packet_len
- s
->index
;
3743 memcpy(s
->buf
+ s
->index
, buf
, l
);
3747 if (s
->index
>= s
->packet_len
) {
3748 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3757 static void net_socket_send_dgram(void *opaque
)
3759 NetSocketState
*s
= opaque
;
3762 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3766 /* end of connection */
3767 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3770 qemu_send_packet(s
->vc
, s
->buf
, size
);
3773 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3778 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3779 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3780 inet_ntoa(mcastaddr
->sin_addr
),
3781 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3785 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3787 perror("socket(PF_INET, SOCK_DGRAM)");
3792 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3793 (const char *)&val
, sizeof(val
));
3795 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3799 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3805 /* Add host to multicast group */
3806 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3807 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3809 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3810 (const char *)&imr
, sizeof(struct ip_mreq
));
3812 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3816 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3818 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3819 (const char *)&val
, sizeof(val
));
3821 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3825 socket_set_nonblock(fd
);
3833 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3836 struct sockaddr_in saddr
;
3838 socklen_t saddr_len
;
3841 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3842 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3843 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3847 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3849 if (saddr
.sin_addr
.s_addr
==0) {
3850 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3854 /* clone dgram socket */
3855 newfd
= net_socket_mcast_create(&saddr
);
3857 /* error already reported by net_socket_mcast_create() */
3861 /* clone newfd to fd, close newfd */
3866 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3867 fd
, strerror(errno
));
3872 s
= qemu_mallocz(sizeof(NetSocketState
));
3877 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3878 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3880 /* mcast: save bound address as dst */
3881 if (is_connected
) s
->dgram_dst
=saddr
;
3883 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3884 "socket: fd=%d (%s mcast=%s:%d)",
3885 fd
, is_connected
? "cloned" : "",
3886 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3890 static void net_socket_connect(void *opaque
)
3892 NetSocketState
*s
= opaque
;
3893 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3896 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3900 s
= qemu_mallocz(sizeof(NetSocketState
));
3904 s
->vc
= qemu_new_vlan_client(vlan
,
3905 net_socket_receive
, NULL
, s
);
3906 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3907 "socket: fd=%d", fd
);
3909 net_socket_connect(s
);
3911 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3916 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3919 int so_type
=-1, optlen
=sizeof(so_type
);
3921 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3922 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3927 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3929 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3931 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3932 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3933 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3938 static void net_socket_accept(void *opaque
)
3940 NetSocketListenState
*s
= opaque
;
3942 struct sockaddr_in saddr
;
3947 len
= sizeof(saddr
);
3948 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3949 if (fd
< 0 && errno
!= EINTR
) {
3951 } else if (fd
>= 0) {
3955 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3959 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3960 "socket: connection from %s:%d",
3961 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3965 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3967 NetSocketListenState
*s
;
3969 struct sockaddr_in saddr
;
3971 if (parse_host_port(&saddr
, host_str
) < 0)
3974 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3978 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3983 socket_set_nonblock(fd
);
3985 /* allow fast reuse */
3987 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3989 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3994 ret
= listen(fd
, 0);
4001 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4005 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4008 int fd
, connected
, ret
, err
;
4009 struct sockaddr_in saddr
;
4011 if (parse_host_port(&saddr
, host_str
) < 0)
4014 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4019 socket_set_nonblock(fd
);
4023 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4025 err
= socket_error();
4026 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4027 } else if (err
== EINPROGRESS
) {
4030 } else if (err
== WSAEALREADY
) {
4043 s
= net_socket_fd_init(vlan
, fd
, connected
);
4046 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4047 "socket: connect to %s:%d",
4048 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4052 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4056 struct sockaddr_in saddr
;
4058 if (parse_host_port(&saddr
, host_str
) < 0)
4062 fd
= net_socket_mcast_create(&saddr
);
4066 s
= net_socket_fd_init(vlan
, fd
, 0);
4070 s
->dgram_dst
= saddr
;
4072 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4073 "socket: mcast=%s:%d",
4074 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4079 static int get_param_value(char *buf
, int buf_size
,
4080 const char *tag
, const char *str
)
4089 while (*p
!= '\0' && *p
!= '=') {
4090 if ((q
- option
) < sizeof(option
) - 1)
4098 if (!strcmp(tag
, option
)) {
4100 while (*p
!= '\0' && *p
!= ',') {
4101 if ((q
- buf
) < buf_size
- 1)
4108 while (*p
!= '\0' && *p
!= ',') {
4119 static int net_client_init(const char *str
)
4130 while (*p
!= '\0' && *p
!= ',') {
4131 if ((q
- device
) < sizeof(device
) - 1)
4139 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4140 vlan_id
= strtol(buf
, NULL
, 0);
4142 vlan
= qemu_find_vlan(vlan_id
);
4144 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4147 if (!strcmp(device
, "nic")) {
4151 if (nb_nics
>= MAX_NICS
) {
4152 fprintf(stderr
, "Too Many NICs\n");
4155 nd
= &nd_table
[nb_nics
];
4156 macaddr
= nd
->macaddr
;
4162 macaddr
[5] = 0x56 + nb_nics
;
4164 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4165 if (parse_macaddr(macaddr
, buf
) < 0) {
4166 fprintf(stderr
, "invalid syntax for ethernet address\n");
4170 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4171 nd
->model
= strdup(buf
);
4177 if (!strcmp(device
, "none")) {
4178 /* does nothing. It is needed to signal that no network cards
4183 if (!strcmp(device
, "user")) {
4184 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4185 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4187 ret
= net_slirp_init(vlan
);
4191 if (!strcmp(device
, "tap")) {
4193 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4194 fprintf(stderr
, "tap: no interface name\n");
4197 ret
= tap_win32_init(vlan
, ifname
);
4200 if (!strcmp(device
, "tap")) {
4202 char setup_script
[1024];
4204 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4205 fd
= strtol(buf
, NULL
, 0);
4207 if (net_tap_fd_init(vlan
, fd
))
4210 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4213 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4214 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4216 ret
= net_tap_init(vlan
, ifname
, setup_script
);
4220 if (!strcmp(device
, "socket")) {
4221 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4223 fd
= strtol(buf
, NULL
, 0);
4225 if (net_socket_fd_init(vlan
, fd
, 1))
4227 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4228 ret
= net_socket_listen_init(vlan
, buf
);
4229 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4230 ret
= net_socket_connect_init(vlan
, buf
);
4231 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4232 ret
= net_socket_mcast_init(vlan
, buf
);
4234 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4239 fprintf(stderr
, "Unknown network device: %s\n", device
);
4243 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4249 void do_info_network(void)
4252 VLANClientState
*vc
;
4254 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4255 term_printf("VLAN %d devices:\n", vlan
->id
);
4256 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4257 term_printf(" %s\n", vc
->info_str
);
4261 /***********************************************************/
4264 static USBPort
*used_usb_ports
;
4265 static USBPort
*free_usb_ports
;
4267 /* ??? Maybe change this to register a hub to keep track of the topology. */
4268 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
4269 usb_attachfn attach
)
4271 port
->opaque
= opaque
;
4272 port
->index
= index
;
4273 port
->attach
= attach
;
4274 port
->next
= free_usb_ports
;
4275 free_usb_ports
= port
;
4278 static int usb_device_add(const char *devname
)
4284 if (!free_usb_ports
)
4287 if (strstart(devname
, "host:", &p
)) {
4288 dev
= usb_host_device_open(p
);
4289 } else if (!strcmp(devname
, "mouse")) {
4290 dev
= usb_mouse_init();
4291 } else if (!strcmp(devname
, "tablet")) {
4292 dev
= usb_tablet_init();
4293 } else if (strstart(devname
, "disk:", &p
)) {
4294 dev
= usb_msd_init(p
);
4301 /* Find a USB port to add the device to. */
4302 port
= free_usb_ports
;
4306 /* Create a new hub and chain it on. */
4307 free_usb_ports
= NULL
;
4308 port
->next
= used_usb_ports
;
4309 used_usb_ports
= port
;
4311 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
4312 usb_attach(port
, hub
);
4313 port
= free_usb_ports
;
4316 free_usb_ports
= port
->next
;
4317 port
->next
= used_usb_ports
;
4318 used_usb_ports
= port
;
4319 usb_attach(port
, dev
);
4323 static int usb_device_del(const char *devname
)
4331 if (!used_usb_ports
)
4334 p
= strchr(devname
, '.');
4337 bus_num
= strtoul(devname
, NULL
, 0);
4338 addr
= strtoul(p
+ 1, NULL
, 0);
4342 lastp
= &used_usb_ports
;
4343 port
= used_usb_ports
;
4344 while (port
&& port
->dev
->addr
!= addr
) {
4345 lastp
= &port
->next
;
4353 *lastp
= port
->next
;
4354 usb_attach(port
, NULL
);
4355 dev
->handle_destroy(dev
);
4356 port
->next
= free_usb_ports
;
4357 free_usb_ports
= port
;
4361 void do_usb_add(const char *devname
)
4364 ret
= usb_device_add(devname
);
4366 term_printf("Could not add USB device '%s'\n", devname
);
4369 void do_usb_del(const char *devname
)
4372 ret
= usb_device_del(devname
);
4374 term_printf("Could not remove USB device '%s'\n", devname
);
4381 const char *speed_str
;
4384 term_printf("USB support not enabled\n");
4388 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4392 switch(dev
->speed
) {
4396 case USB_SPEED_FULL
:
4399 case USB_SPEED_HIGH
:
4406 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4407 0, dev
->addr
, speed_str
, dev
->devname
);
4411 /***********************************************************/
4414 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4418 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4422 static void dumb_refresh(DisplayState
*ds
)
4427 void dumb_display_init(DisplayState
*ds
)
4432 ds
->dpy_update
= dumb_update
;
4433 ds
->dpy_resize
= dumb_resize
;
4434 ds
->dpy_refresh
= dumb_refresh
;
4437 /***********************************************************/
4440 #define MAX_IO_HANDLERS 64
4442 typedef struct IOHandlerRecord
{
4444 IOCanRWHandler
*fd_read_poll
;
4446 IOHandler
*fd_write
;
4449 /* temporary data */
4451 struct IOHandlerRecord
*next
;
4454 static IOHandlerRecord
*first_io_handler
;
4456 /* XXX: fd_read_poll should be suppressed, but an API change is
4457 necessary in the character devices to suppress fd_can_read(). */
4458 int qemu_set_fd_handler2(int fd
,
4459 IOCanRWHandler
*fd_read_poll
,
4461 IOHandler
*fd_write
,
4464 IOHandlerRecord
**pioh
, *ioh
;
4466 if (!fd_read
&& !fd_write
) {
4467 pioh
= &first_io_handler
;
4472 if (ioh
->fd
== fd
) {
4479 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4483 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4486 ioh
->next
= first_io_handler
;
4487 first_io_handler
= ioh
;
4490 ioh
->fd_read_poll
= fd_read_poll
;
4491 ioh
->fd_read
= fd_read
;
4492 ioh
->fd_write
= fd_write
;
4493 ioh
->opaque
= opaque
;
4499 int qemu_set_fd_handler(int fd
,
4501 IOHandler
*fd_write
,
4504 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4507 /***********************************************************/
4508 /* Polling handling */
4510 typedef struct PollingEntry
{
4513 struct PollingEntry
*next
;
4516 static PollingEntry
*first_polling_entry
;
4518 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4520 PollingEntry
**ppe
, *pe
;
4521 pe
= qemu_mallocz(sizeof(PollingEntry
));
4525 pe
->opaque
= opaque
;
4526 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4531 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4533 PollingEntry
**ppe
, *pe
;
4534 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4536 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4545 /***********************************************************/
4546 /* Wait objects support */
4547 typedef struct WaitObjects
{
4549 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4550 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4551 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4554 static WaitObjects wait_objects
= {0};
4556 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4558 WaitObjects
*w
= &wait_objects
;
4560 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4562 w
->events
[w
->num
] = handle
;
4563 w
->func
[w
->num
] = func
;
4564 w
->opaque
[w
->num
] = opaque
;
4569 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4572 WaitObjects
*w
= &wait_objects
;
4575 for (i
= 0; i
< w
->num
; i
++) {
4576 if (w
->events
[i
] == handle
)
4579 w
->events
[i
] = w
->events
[i
+ 1];
4580 w
->func
[i
] = w
->func
[i
+ 1];
4581 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4589 /***********************************************************/
4590 /* savevm/loadvm support */
4592 #define IO_BUF_SIZE 32768
4596 BlockDriverState
*bs
;
4599 int64_t base_offset
;
4600 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4603 int buf_size
; /* 0 when writing */
4604 uint8_t buf
[IO_BUF_SIZE
];
4607 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4611 f
= qemu_mallocz(sizeof(QEMUFile
));
4614 if (!strcmp(mode
, "wb")) {
4616 } else if (!strcmp(mode
, "rb")) {
4621 f
->outfile
= fopen(filename
, mode
);
4633 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4637 f
= qemu_mallocz(sizeof(QEMUFile
));
4642 f
->is_writable
= is_writable
;
4643 f
->base_offset
= offset
;
4647 void qemu_fflush(QEMUFile
*f
)
4649 if (!f
->is_writable
)
4651 if (f
->buf_index
> 0) {
4653 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4654 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4656 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4657 f
->buf
, f
->buf_index
);
4659 f
->buf_offset
+= f
->buf_index
;
4664 static void qemu_fill_buffer(QEMUFile
*f
)
4671 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4672 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4676 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4677 f
->buf
, IO_BUF_SIZE
);
4683 f
->buf_offset
+= len
;
4686 void qemu_fclose(QEMUFile
*f
)
4696 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4700 l
= IO_BUF_SIZE
- f
->buf_index
;
4703 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4707 if (f
->buf_index
>= IO_BUF_SIZE
)
4712 void qemu_put_byte(QEMUFile
*f
, int v
)
4714 f
->buf
[f
->buf_index
++] = v
;
4715 if (f
->buf_index
>= IO_BUF_SIZE
)
4719 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4725 l
= f
->buf_size
- f
->buf_index
;
4727 qemu_fill_buffer(f
);
4728 l
= f
->buf_size
- f
->buf_index
;
4734 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4739 return size1
- size
;
4742 int qemu_get_byte(QEMUFile
*f
)
4744 if (f
->buf_index
>= f
->buf_size
) {
4745 qemu_fill_buffer(f
);
4746 if (f
->buf_index
>= f
->buf_size
)
4749 return f
->buf
[f
->buf_index
++];
4752 int64_t qemu_ftell(QEMUFile
*f
)
4754 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4757 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4759 if (whence
== SEEK_SET
) {
4761 } else if (whence
== SEEK_CUR
) {
4762 pos
+= qemu_ftell(f
);
4764 /* SEEK_END not supported */
4767 if (f
->is_writable
) {
4769 f
->buf_offset
= pos
;
4771 f
->buf_offset
= pos
;
4778 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4780 qemu_put_byte(f
, v
>> 8);
4781 qemu_put_byte(f
, v
);
4784 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4786 qemu_put_byte(f
, v
>> 24);
4787 qemu_put_byte(f
, v
>> 16);
4788 qemu_put_byte(f
, v
>> 8);
4789 qemu_put_byte(f
, v
);
4792 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4794 qemu_put_be32(f
, v
>> 32);
4795 qemu_put_be32(f
, v
);
4798 unsigned int qemu_get_be16(QEMUFile
*f
)
4801 v
= qemu_get_byte(f
) << 8;
4802 v
|= qemu_get_byte(f
);
4806 unsigned int qemu_get_be32(QEMUFile
*f
)
4809 v
= qemu_get_byte(f
) << 24;
4810 v
|= qemu_get_byte(f
) << 16;
4811 v
|= qemu_get_byte(f
) << 8;
4812 v
|= qemu_get_byte(f
);
4816 uint64_t qemu_get_be64(QEMUFile
*f
)
4819 v
= (uint64_t)qemu_get_be32(f
) << 32;
4820 v
|= qemu_get_be32(f
);
4824 typedef struct SaveStateEntry
{
4828 SaveStateHandler
*save_state
;
4829 LoadStateHandler
*load_state
;
4831 struct SaveStateEntry
*next
;
4834 static SaveStateEntry
*first_se
;
4836 int register_savevm(const char *idstr
,
4839 SaveStateHandler
*save_state
,
4840 LoadStateHandler
*load_state
,
4843 SaveStateEntry
*se
, **pse
;
4845 se
= qemu_malloc(sizeof(SaveStateEntry
));
4848 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4849 se
->instance_id
= instance_id
;
4850 se
->version_id
= version_id
;
4851 se
->save_state
= save_state
;
4852 se
->load_state
= load_state
;
4853 se
->opaque
= opaque
;
4856 /* add at the end of list */
4858 while (*pse
!= NULL
)
4859 pse
= &(*pse
)->next
;
4864 #define QEMU_VM_FILE_MAGIC 0x5145564d
4865 #define QEMU_VM_FILE_VERSION 0x00000002
4867 int qemu_savevm_state(QEMUFile
*f
)
4871 int64_t cur_pos
, len_pos
, total_len_pos
;
4873 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4874 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4875 total_len_pos
= qemu_ftell(f
);
4876 qemu_put_be64(f
, 0); /* total size */
4878 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4880 len
= strlen(se
->idstr
);
4881 qemu_put_byte(f
, len
);
4882 qemu_put_buffer(f
, se
->idstr
, len
);
4884 qemu_put_be32(f
, se
->instance_id
);
4885 qemu_put_be32(f
, se
->version_id
);
4887 /* record size: filled later */
4888 len_pos
= qemu_ftell(f
);
4889 qemu_put_be32(f
, 0);
4891 se
->save_state(f
, se
->opaque
);
4893 /* fill record size */
4894 cur_pos
= qemu_ftell(f
);
4895 len
= cur_pos
- len_pos
- 4;
4896 qemu_fseek(f
, len_pos
, SEEK_SET
);
4897 qemu_put_be32(f
, len
);
4898 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4900 cur_pos
= qemu_ftell(f
);
4901 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4902 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4903 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4909 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4913 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4914 if (!strcmp(se
->idstr
, idstr
) &&
4915 instance_id
== se
->instance_id
)
4921 int qemu_loadvm_state(QEMUFile
*f
)
4924 int len
, ret
, instance_id
, record_len
, version_id
;
4925 int64_t total_len
, end_pos
, cur_pos
;
4929 v
= qemu_get_be32(f
);
4930 if (v
!= QEMU_VM_FILE_MAGIC
)
4932 v
= qemu_get_be32(f
);
4933 if (v
!= QEMU_VM_FILE_VERSION
) {
4938 total_len
= qemu_get_be64(f
);
4939 end_pos
= total_len
+ qemu_ftell(f
);
4941 if (qemu_ftell(f
) >= end_pos
)
4943 len
= qemu_get_byte(f
);
4944 qemu_get_buffer(f
, idstr
, len
);
4946 instance_id
= qemu_get_be32(f
);
4947 version_id
= qemu_get_be32(f
);
4948 record_len
= qemu_get_be32(f
);
4950 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4951 idstr
, instance_id
, version_id
, record_len
);
4953 cur_pos
= qemu_ftell(f
);
4954 se
= find_se(idstr
, instance_id
);
4956 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4957 instance_id
, idstr
);
4959 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4961 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4962 instance_id
, idstr
);
4965 /* always seek to exact end of record */
4966 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4973 /* device can contain snapshots */
4974 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4977 !bdrv_is_removable(bs
) &&
4978 !bdrv_is_read_only(bs
));
4981 /* device must be snapshots in order to have a reliable snapshot */
4982 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4985 !bdrv_is_removable(bs
) &&
4986 !bdrv_is_read_only(bs
));
4989 static BlockDriverState
*get_bs_snapshots(void)
4991 BlockDriverState
*bs
;
4995 return bs_snapshots
;
4996 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4998 if (bdrv_can_snapshot(bs
))
5007 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5010 QEMUSnapshotInfo
*sn_tab
, *sn
;
5014 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5017 for(i
= 0; i
< nb_sns
; i
++) {
5019 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5029 void do_savevm(const char *name
)
5031 BlockDriverState
*bs
, *bs1
;
5032 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5033 int must_delete
, ret
, i
;
5034 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5036 int saved_vm_running
;
5043 bs
= get_bs_snapshots();
5045 term_printf("No block device can accept snapshots\n");
5049 /* ??? Should this occur after vm_stop? */
5052 saved_vm_running
= vm_running
;
5057 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5062 memset(sn
, 0, sizeof(*sn
));
5064 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5065 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5068 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5071 /* fill auxiliary fields */
5074 sn
->date_sec
= tb
.time
;
5075 sn
->date_nsec
= tb
.millitm
* 1000000;
5077 gettimeofday(&tv
, NULL
);
5078 sn
->date_sec
= tv
.tv_sec
;
5079 sn
->date_nsec
= tv
.tv_usec
* 1000;
5081 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
5083 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5084 term_printf("Device %s does not support VM state snapshots\n",
5085 bdrv_get_device_name(bs
));
5089 /* save the VM state */
5090 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
5092 term_printf("Could not open VM state file\n");
5095 ret
= qemu_savevm_state(f
);
5096 sn
->vm_state_size
= qemu_ftell(f
);
5099 term_printf("Error %d while writing VM\n", ret
);
5103 /* create the snapshots */
5105 for(i
= 0; i
< MAX_DISKS
; i
++) {
5107 if (bdrv_has_snapshot(bs1
)) {
5109 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5111 term_printf("Error while deleting snapshot on '%s'\n",
5112 bdrv_get_device_name(bs1
));
5115 ret
= bdrv_snapshot_create(bs1
, sn
);
5117 term_printf("Error while creating snapshot on '%s'\n",
5118 bdrv_get_device_name(bs1
));
5124 if (saved_vm_running
)
5128 void do_loadvm(const char *name
)
5130 BlockDriverState
*bs
, *bs1
;
5131 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5134 int saved_vm_running
;
5136 bs
= get_bs_snapshots();
5138 term_printf("No block device supports snapshots\n");
5142 /* Flush all IO requests so they don't interfere with the new state. */
5145 saved_vm_running
= vm_running
;
5148 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5150 if (bdrv_has_snapshot(bs1
)) {
5151 ret
= bdrv_snapshot_goto(bs1
, name
);
5154 term_printf("Warning: ");
5157 term_printf("Snapshots not supported on device '%s'\n",
5158 bdrv_get_device_name(bs1
));
5161 term_printf("Could not find snapshot '%s' on device '%s'\n",
5162 name
, bdrv_get_device_name(bs1
));
5165 term_printf("Error %d while activating snapshot on '%s'\n",
5166 ret
, bdrv_get_device_name(bs1
));
5169 /* fatal on snapshot block device */
5176 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5177 term_printf("Device %s does not support VM state snapshots\n",
5178 bdrv_get_device_name(bs
));
5182 /* restore the VM state */
5183 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5185 term_printf("Could not open VM state file\n");
5188 ret
= qemu_loadvm_state(f
);
5191 term_printf("Error %d while loading VM state\n", ret
);
5194 if (saved_vm_running
)
5198 void do_delvm(const char *name
)
5200 BlockDriverState
*bs
, *bs1
;
5203 bs
= get_bs_snapshots();
5205 term_printf("No block device supports snapshots\n");
5209 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5211 if (bdrv_has_snapshot(bs1
)) {
5212 ret
= bdrv_snapshot_delete(bs1
, name
);
5214 if (ret
== -ENOTSUP
)
5215 term_printf("Snapshots not supported on device '%s'\n",
5216 bdrv_get_device_name(bs1
));
5218 term_printf("Error %d while deleting snapshot on '%s'\n",
5219 ret
, bdrv_get_device_name(bs1
));
5225 void do_info_snapshots(void)
5227 BlockDriverState
*bs
, *bs1
;
5228 QEMUSnapshotInfo
*sn_tab
, *sn
;
5232 bs
= get_bs_snapshots();
5234 term_printf("No available block device supports snapshots\n");
5237 term_printf("Snapshot devices:");
5238 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5240 if (bdrv_has_snapshot(bs1
)) {
5242 term_printf(" %s", bdrv_get_device_name(bs1
));
5247 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5249 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5252 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5253 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5254 for(i
= 0; i
< nb_sns
; i
++) {
5256 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5261 /***********************************************************/
5262 /* cpu save/restore */
5264 #if defined(TARGET_I386)
5266 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5268 qemu_put_be32(f
, dt
->selector
);
5269 qemu_put_betl(f
, dt
->base
);
5270 qemu_put_be32(f
, dt
->limit
);
5271 qemu_put_be32(f
, dt
->flags
);
5274 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5276 dt
->selector
= qemu_get_be32(f
);
5277 dt
->base
= qemu_get_betl(f
);
5278 dt
->limit
= qemu_get_be32(f
);
5279 dt
->flags
= qemu_get_be32(f
);
5282 void cpu_save(QEMUFile
*f
, void *opaque
)
5284 CPUState
*env
= opaque
;
5285 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5289 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5290 qemu_put_betls(f
, &env
->regs
[i
]);
5291 qemu_put_betls(f
, &env
->eip
);
5292 qemu_put_betls(f
, &env
->eflags
);
5293 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5294 qemu_put_be32s(f
, &hflags
);
5298 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5300 for(i
= 0; i
< 8; i
++) {
5301 fptag
|= ((!env
->fptags
[i
]) << i
);
5304 qemu_put_be16s(f
, &fpuc
);
5305 qemu_put_be16s(f
, &fpus
);
5306 qemu_put_be16s(f
, &fptag
);
5308 #ifdef USE_X86LDOUBLE
5313 qemu_put_be16s(f
, &fpregs_format
);
5315 for(i
= 0; i
< 8; i
++) {
5316 #ifdef USE_X86LDOUBLE
5320 /* we save the real CPU data (in case of MMX usage only 'mant'
5321 contains the MMX register */
5322 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5323 qemu_put_be64(f
, mant
);
5324 qemu_put_be16(f
, exp
);
5327 /* if we use doubles for float emulation, we save the doubles to
5328 avoid losing information in case of MMX usage. It can give
5329 problems if the image is restored on a CPU where long
5330 doubles are used instead. */
5331 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5335 for(i
= 0; i
< 6; i
++)
5336 cpu_put_seg(f
, &env
->segs
[i
]);
5337 cpu_put_seg(f
, &env
->ldt
);
5338 cpu_put_seg(f
, &env
->tr
);
5339 cpu_put_seg(f
, &env
->gdt
);
5340 cpu_put_seg(f
, &env
->idt
);
5342 qemu_put_be32s(f
, &env
->sysenter_cs
);
5343 qemu_put_be32s(f
, &env
->sysenter_esp
);
5344 qemu_put_be32s(f
, &env
->sysenter_eip
);
5346 qemu_put_betls(f
, &env
->cr
[0]);
5347 qemu_put_betls(f
, &env
->cr
[2]);
5348 qemu_put_betls(f
, &env
->cr
[3]);
5349 qemu_put_betls(f
, &env
->cr
[4]);
5351 for(i
= 0; i
< 8; i
++)
5352 qemu_put_betls(f
, &env
->dr
[i
]);
5355 qemu_put_be32s(f
, &env
->a20_mask
);
5358 qemu_put_be32s(f
, &env
->mxcsr
);
5359 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5360 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5361 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5364 #ifdef TARGET_X86_64
5365 qemu_put_be64s(f
, &env
->efer
);
5366 qemu_put_be64s(f
, &env
->star
);
5367 qemu_put_be64s(f
, &env
->lstar
);
5368 qemu_put_be64s(f
, &env
->cstar
);
5369 qemu_put_be64s(f
, &env
->fmask
);
5370 qemu_put_be64s(f
, &env
->kernelgsbase
);
5372 qemu_put_be32s(f
, &env
->smbase
);
5375 #ifdef USE_X86LDOUBLE
5376 /* XXX: add that in a FPU generic layer */
5377 union x86_longdouble
{
5382 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5383 #define EXPBIAS1 1023
5384 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5385 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5387 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5391 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5392 /* exponent + sign */
5393 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5394 e
|= SIGND1(temp
) >> 16;
5399 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5401 CPUState
*env
= opaque
;
5404 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5406 if (version_id
!= 3 && version_id
!= 4)
5408 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5409 qemu_get_betls(f
, &env
->regs
[i
]);
5410 qemu_get_betls(f
, &env
->eip
);
5411 qemu_get_betls(f
, &env
->eflags
);
5412 qemu_get_be32s(f
, &hflags
);
5414 qemu_get_be16s(f
, &fpuc
);
5415 qemu_get_be16s(f
, &fpus
);
5416 qemu_get_be16s(f
, &fptag
);
5417 qemu_get_be16s(f
, &fpregs_format
);
5419 /* NOTE: we cannot always restore the FPU state if the image come
5420 from a host with a different 'USE_X86LDOUBLE' define. We guess
5421 if we are in an MMX state to restore correctly in that case. */
5422 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5423 for(i
= 0; i
< 8; i
++) {
5427 switch(fpregs_format
) {
5429 mant
= qemu_get_be64(f
);
5430 exp
= qemu_get_be16(f
);
5431 #ifdef USE_X86LDOUBLE
5432 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5434 /* difficult case */
5436 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5438 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5442 mant
= qemu_get_be64(f
);
5443 #ifdef USE_X86LDOUBLE
5445 union x86_longdouble
*p
;
5446 /* difficult case */
5447 p
= (void *)&env
->fpregs
[i
];
5452 fp64_to_fp80(p
, mant
);
5456 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5465 /* XXX: restore FPU round state */
5466 env
->fpstt
= (fpus
>> 11) & 7;
5467 env
->fpus
= fpus
& ~0x3800;
5469 for(i
= 0; i
< 8; i
++) {
5470 env
->fptags
[i
] = (fptag
>> i
) & 1;
5473 for(i
= 0; i
< 6; i
++)
5474 cpu_get_seg(f
, &env
->segs
[i
]);
5475 cpu_get_seg(f
, &env
->ldt
);
5476 cpu_get_seg(f
, &env
->tr
);
5477 cpu_get_seg(f
, &env
->gdt
);
5478 cpu_get_seg(f
, &env
->idt
);
5480 qemu_get_be32s(f
, &env
->sysenter_cs
);
5481 qemu_get_be32s(f
, &env
->sysenter_esp
);
5482 qemu_get_be32s(f
, &env
->sysenter_eip
);
5484 qemu_get_betls(f
, &env
->cr
[0]);
5485 qemu_get_betls(f
, &env
->cr
[2]);
5486 qemu_get_betls(f
, &env
->cr
[3]);
5487 qemu_get_betls(f
, &env
->cr
[4]);
5489 for(i
= 0; i
< 8; i
++)
5490 qemu_get_betls(f
, &env
->dr
[i
]);
5493 qemu_get_be32s(f
, &env
->a20_mask
);
5495 qemu_get_be32s(f
, &env
->mxcsr
);
5496 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5497 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5498 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5501 #ifdef TARGET_X86_64
5502 qemu_get_be64s(f
, &env
->efer
);
5503 qemu_get_be64s(f
, &env
->star
);
5504 qemu_get_be64s(f
, &env
->lstar
);
5505 qemu_get_be64s(f
, &env
->cstar
);
5506 qemu_get_be64s(f
, &env
->fmask
);
5507 qemu_get_be64s(f
, &env
->kernelgsbase
);
5509 if (version_id
>= 4)
5510 qemu_get_be32s(f
, &env
->smbase
);
5512 /* XXX: compute hflags from scratch, except for CPL and IIF */
5513 env
->hflags
= hflags
;
5518 #elif defined(TARGET_PPC)
5519 void cpu_save(QEMUFile
*f
, void *opaque
)
5523 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5528 #elif defined(TARGET_MIPS)
5529 void cpu_save(QEMUFile
*f
, void *opaque
)
5533 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5538 #elif defined(TARGET_SPARC)
5539 void cpu_save(QEMUFile
*f
, void *opaque
)
5541 CPUState
*env
= opaque
;
5545 for(i
= 0; i
< 8; i
++)
5546 qemu_put_betls(f
, &env
->gregs
[i
]);
5547 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5548 qemu_put_betls(f
, &env
->regbase
[i
]);
5551 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5557 qemu_put_be32(f
, u
.i
);
5560 qemu_put_betls(f
, &env
->pc
);
5561 qemu_put_betls(f
, &env
->npc
);
5562 qemu_put_betls(f
, &env
->y
);
5564 qemu_put_be32(f
, tmp
);
5565 qemu_put_betls(f
, &env
->fsr
);
5566 qemu_put_betls(f
, &env
->tbr
);
5567 #ifndef TARGET_SPARC64
5568 qemu_put_be32s(f
, &env
->wim
);
5570 for(i
= 0; i
< 16; i
++)
5571 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5575 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5577 CPUState
*env
= opaque
;
5581 for(i
= 0; i
< 8; i
++)
5582 qemu_get_betls(f
, &env
->gregs
[i
]);
5583 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5584 qemu_get_betls(f
, &env
->regbase
[i
]);
5587 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5592 u
.i
= qemu_get_be32(f
);
5596 qemu_get_betls(f
, &env
->pc
);
5597 qemu_get_betls(f
, &env
->npc
);
5598 qemu_get_betls(f
, &env
->y
);
5599 tmp
= qemu_get_be32(f
);
5600 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5601 correctly updated */
5603 qemu_get_betls(f
, &env
->fsr
);
5604 qemu_get_betls(f
, &env
->tbr
);
5605 #ifndef TARGET_SPARC64
5606 qemu_get_be32s(f
, &env
->wim
);
5608 for(i
= 0; i
< 16; i
++)
5609 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5615 #elif defined(TARGET_ARM)
5617 /* ??? Need to implement these. */
5618 void cpu_save(QEMUFile
*f
, void *opaque
)
5622 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5629 #warning No CPU save/restore functions
5633 /***********************************************************/
5634 /* ram save/restore */
5636 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5640 v
= qemu_get_byte(f
);
5643 if (qemu_get_buffer(f
, buf
, len
) != len
)
5647 v
= qemu_get_byte(f
);
5648 memset(buf
, v
, len
);
5656 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5660 if (qemu_get_be32(f
) != phys_ram_size
)
5662 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5663 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5670 #define BDRV_HASH_BLOCK_SIZE 1024
5671 #define IOBUF_SIZE 4096
5672 #define RAM_CBLOCK_MAGIC 0xfabe
5674 typedef struct RamCompressState
{
5677 uint8_t buf
[IOBUF_SIZE
];
5680 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5683 memset(s
, 0, sizeof(*s
));
5685 ret
= deflateInit2(&s
->zstream
, 1,
5687 9, Z_DEFAULT_STRATEGY
);
5690 s
->zstream
.avail_out
= IOBUF_SIZE
;
5691 s
->zstream
.next_out
= s
->buf
;
5695 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5697 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5698 qemu_put_be16(s
->f
, len
);
5699 qemu_put_buffer(s
->f
, buf
, len
);
5702 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5706 s
->zstream
.avail_in
= len
;
5707 s
->zstream
.next_in
= (uint8_t *)buf
;
5708 while (s
->zstream
.avail_in
> 0) {
5709 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5712 if (s
->zstream
.avail_out
== 0) {
5713 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5714 s
->zstream
.avail_out
= IOBUF_SIZE
;
5715 s
->zstream
.next_out
= s
->buf
;
5721 static void ram_compress_close(RamCompressState
*s
)
5725 /* compress last bytes */
5727 ret
= deflate(&s
->zstream
, Z_FINISH
);
5728 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5729 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5731 ram_put_cblock(s
, s
->buf
, len
);
5733 s
->zstream
.avail_out
= IOBUF_SIZE
;
5734 s
->zstream
.next_out
= s
->buf
;
5735 if (ret
== Z_STREAM_END
)
5742 deflateEnd(&s
->zstream
);
5745 typedef struct RamDecompressState
{
5748 uint8_t buf
[IOBUF_SIZE
];
5749 } RamDecompressState
;
5751 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5754 memset(s
, 0, sizeof(*s
));
5756 ret
= inflateInit(&s
->zstream
);
5762 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5766 s
->zstream
.avail_out
= len
;
5767 s
->zstream
.next_out
= buf
;
5768 while (s
->zstream
.avail_out
> 0) {
5769 if (s
->zstream
.avail_in
== 0) {
5770 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5772 clen
= qemu_get_be16(s
->f
);
5773 if (clen
> IOBUF_SIZE
)
5775 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5776 s
->zstream
.avail_in
= clen
;
5777 s
->zstream
.next_in
= s
->buf
;
5779 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5780 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5787 static void ram_decompress_close(RamDecompressState
*s
)
5789 inflateEnd(&s
->zstream
);
5792 static void ram_save(QEMUFile
*f
, void *opaque
)
5795 RamCompressState s1
, *s
= &s1
;
5798 qemu_put_be32(f
, phys_ram_size
);
5799 if (ram_compress_open(s
, f
) < 0)
5801 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5803 if (tight_savevm_enabled
) {
5807 /* find if the memory block is available on a virtual
5810 for(j
= 0; j
< MAX_DISKS
; j
++) {
5812 sector_num
= bdrv_hash_find(bs_table
[j
],
5813 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5814 if (sector_num
>= 0)
5819 goto normal_compress
;
5822 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5823 ram_compress_buf(s
, buf
, 10);
5829 ram_compress_buf(s
, buf
, 1);
5830 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5833 ram_compress_close(s
);
5836 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5838 RamDecompressState s1
, *s
= &s1
;
5842 if (version_id
== 1)
5843 return ram_load_v1(f
, opaque
);
5844 if (version_id
!= 2)
5846 if (qemu_get_be32(f
) != phys_ram_size
)
5848 if (ram_decompress_open(s
, f
) < 0)
5850 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5851 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5852 fprintf(stderr
, "Error while reading ram block header\n");
5856 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5857 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5866 ram_decompress_buf(s
, buf
+ 1, 9);
5868 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5869 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5870 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5873 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5874 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5875 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5876 bs_index
, sector_num
);
5883 printf("Error block header\n");
5887 ram_decompress_close(s
);
5891 /***********************************************************/
5892 /* bottom halves (can be seen as timers which expire ASAP) */
5901 static QEMUBH
*first_bh
= NULL
;
5903 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5906 bh
= qemu_mallocz(sizeof(QEMUBH
));
5910 bh
->opaque
= opaque
;
5914 int qemu_bh_poll(void)
5933 void qemu_bh_schedule(QEMUBH
*bh
)
5935 CPUState
*env
= cpu_single_env
;
5939 bh
->next
= first_bh
;
5942 /* stop the currently executing CPU to execute the BH ASAP */
5944 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5948 void qemu_bh_cancel(QEMUBH
*bh
)
5951 if (bh
->scheduled
) {
5954 pbh
= &(*pbh
)->next
;
5960 void qemu_bh_delete(QEMUBH
*bh
)
5966 /***********************************************************/
5967 /* machine registration */
5969 QEMUMachine
*first_machine
= NULL
;
5971 int qemu_register_machine(QEMUMachine
*m
)
5974 pm
= &first_machine
;
5982 QEMUMachine
*find_machine(const char *name
)
5986 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5987 if (!strcmp(m
->name
, name
))
5993 /***********************************************************/
5994 /* main execution loop */
5996 void gui_update(void *opaque
)
5998 display_state
.dpy_refresh(&display_state
);
5999 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6002 struct vm_change_state_entry
{
6003 VMChangeStateHandler
*cb
;
6005 LIST_ENTRY (vm_change_state_entry
) entries
;
6008 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6010 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6013 VMChangeStateEntry
*e
;
6015 e
= qemu_mallocz(sizeof (*e
));
6021 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6025 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6027 LIST_REMOVE (e
, entries
);
6031 static void vm_state_notify(int running
)
6033 VMChangeStateEntry
*e
;
6035 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6036 e
->cb(e
->opaque
, running
);
6040 /* XXX: support several handlers */
6041 static VMStopHandler
*vm_stop_cb
;
6042 static void *vm_stop_opaque
;
6044 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6047 vm_stop_opaque
= opaque
;
6051 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6065 void vm_stop(int reason
)
6068 cpu_disable_ticks();
6072 vm_stop_cb(vm_stop_opaque
, reason
);
6079 /* reset/shutdown handler */
6081 typedef struct QEMUResetEntry
{
6082 QEMUResetHandler
*func
;
6084 struct QEMUResetEntry
*next
;
6087 static QEMUResetEntry
*first_reset_entry
;
6088 static int reset_requested
;
6089 static int shutdown_requested
;
6090 static int powerdown_requested
;
6092 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6094 QEMUResetEntry
**pre
, *re
;
6096 pre
= &first_reset_entry
;
6097 while (*pre
!= NULL
)
6098 pre
= &(*pre
)->next
;
6099 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6101 re
->opaque
= opaque
;
6106 static void qemu_system_reset(void)
6110 /* reset all devices */
6111 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6112 re
->func(re
->opaque
);
6116 void qemu_system_reset_request(void)
6119 shutdown_requested
= 1;
6121 reset_requested
= 1;
6124 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6127 void qemu_system_shutdown_request(void)
6129 shutdown_requested
= 1;
6131 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6134 void qemu_system_powerdown_request(void)
6136 powerdown_requested
= 1;
6138 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6141 void main_loop_wait(int timeout
)
6143 IOHandlerRecord
*ioh
;
6144 fd_set rfds
, wfds
, xfds
;
6150 /* XXX: need to suppress polling by better using win32 events */
6152 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6153 ret
|= pe
->func(pe
->opaque
);
6156 if (ret
== 0 && timeout
> 0) {
6158 WaitObjects
*w
= &wait_objects
;
6160 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6161 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6162 if (w
->func
[ret
- WAIT_OBJECT_0
])
6163 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6164 } else if (ret
== WAIT_TIMEOUT
) {
6166 err
= GetLastError();
6167 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6171 /* poll any events */
6172 /* XXX: separate device handlers from system ones */
6177 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6181 (!ioh
->fd_read_poll
||
6182 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6183 FD_SET(ioh
->fd
, &rfds
);
6187 if (ioh
->fd_write
) {
6188 FD_SET(ioh
->fd
, &wfds
);
6198 tv
.tv_usec
= timeout
* 1000;
6200 #if defined(CONFIG_SLIRP)
6202 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6205 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6207 IOHandlerRecord
**pioh
;
6209 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6212 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6213 ioh
->fd_read(ioh
->opaque
);
6215 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6216 ioh
->fd_write(ioh
->opaque
);
6220 /* remove deleted IO handlers */
6221 pioh
= &first_io_handler
;
6231 #if defined(CONFIG_SLIRP)
6238 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6245 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6246 qemu_get_clock(vm_clock
));
6247 /* run dma transfers, if any */
6251 /* real time timers */
6252 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6253 qemu_get_clock(rt_clock
));
6256 static CPUState
*cur_cpu
;
6261 #ifdef CONFIG_PROFILER
6266 cur_cpu
= first_cpu
;
6273 env
= env
->next_cpu
;
6276 #ifdef CONFIG_PROFILER
6277 ti
= profile_getclock();
6279 ret
= cpu_exec(env
);
6280 #ifdef CONFIG_PROFILER
6281 qemu_time
+= profile_getclock() - ti
;
6283 if (ret
== EXCP_HLT
) {
6284 /* Give the next CPU a chance to run. */
6288 if (ret
!= EXCP_HALTED
)
6290 /* all CPUs are halted ? */
6296 if (shutdown_requested
) {
6297 ret
= EXCP_INTERRUPT
;
6300 if (reset_requested
) {
6301 reset_requested
= 0;
6302 qemu_system_reset();
6303 ret
= EXCP_INTERRUPT
;
6305 if (powerdown_requested
) {
6306 powerdown_requested
= 0;
6307 qemu_system_powerdown();
6308 ret
= EXCP_INTERRUPT
;
6310 if (ret
== EXCP_DEBUG
) {
6311 vm_stop(EXCP_DEBUG
);
6313 /* If all cpus are halted then wait until the next IRQ */
6314 /* XXX: use timeout computed from timers */
6315 if (ret
== EXCP_HALTED
)
6322 #ifdef CONFIG_PROFILER
6323 ti
= profile_getclock();
6325 main_loop_wait(timeout
);
6326 #ifdef CONFIG_PROFILER
6327 dev_time
+= profile_getclock() - ti
;
6330 cpu_disable_ticks();
6336 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6337 "usage: %s [options] [disk_image]\n"
6339 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6341 "Standard options:\n"
6342 "-M machine select emulated machine (-M ? for list)\n"
6343 "-cpu cpu select CPU (-cpu ? for list)\n"
6344 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6345 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6346 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6347 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6348 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6349 "-snapshot write to temporary files instead of disk image files\n"
6351 "-no-frame open SDL window without a frame and window decorations\n"
6352 "-no-quit disable SDL window close capability\n"
6355 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6357 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6358 "-smp n set the number of CPUs to 'n' [default=1]\n"
6359 "-nographic disable graphical output and redirect serial I/Os to console\n"
6361 "-k language use keyboard layout (for example \"fr\" for French)\n"
6364 "-audio-help print list of audio drivers and their options\n"
6365 "-soundhw c1,... enable audio support\n"
6366 " and only specified sound cards (comma separated list)\n"
6367 " use -soundhw ? to get the list of supported cards\n"
6368 " use -soundhw all to enable all of them\n"
6370 "-localtime set the real time clock to local time [default=utc]\n"
6371 "-full-screen start in full screen\n"
6373 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6375 "-usb enable the USB driver (will be the default soon)\n"
6376 "-usbdevice name add the host or guest USB device 'name'\n"
6377 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6378 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6380 "-name string set the name of the guest\n"
6382 "Network options:\n"
6383 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6384 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6386 "-net user[,vlan=n][,hostname=host]\n"
6387 " connect the user mode network stack to VLAN 'n' and send\n"
6388 " hostname 'host' to DHCP clients\n"
6391 "-net tap[,vlan=n],ifname=name\n"
6392 " connect the host TAP network interface to VLAN 'n'\n"
6394 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6395 " connect the host TAP network interface to VLAN 'n' and use\n"
6396 " the network script 'file' (default=%s);\n"
6397 " use 'script=no' to disable script execution;\n"
6398 " use 'fd=h' to connect to an already opened TAP interface\n"
6400 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6401 " connect the vlan 'n' to another VLAN using a socket connection\n"
6402 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6403 " connect the vlan 'n' to multicast maddr and port\n"
6404 "-net none use it alone to have zero network devices; if no -net option\n"
6405 " is provided, the default is '-net nic -net user'\n"
6408 "-tftp dir allow tftp access to files in dir [-net user]\n"
6409 "-bootp file advertise file in BOOTP replies\n"
6411 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6413 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6414 " redirect TCP or UDP connections from host to guest [-net user]\n"
6417 "Linux boot specific:\n"
6418 "-kernel bzImage use 'bzImage' as kernel image\n"
6419 "-append cmdline use 'cmdline' as kernel command line\n"
6420 "-initrd file use 'file' as initial ram disk\n"
6422 "Debug/Expert options:\n"
6423 "-monitor dev redirect the monitor to char device 'dev'\n"
6424 "-serial dev redirect the serial port to char device 'dev'\n"
6425 "-parallel dev redirect the parallel port to char device 'dev'\n"
6426 "-pidfile file Write PID to 'file'\n"
6427 "-S freeze CPU at startup (use 'c' to start execution)\n"
6428 "-s wait gdb connection to port\n"
6429 "-p port set gdb connection port [default=%s]\n"
6430 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6431 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6432 " translation (t=none or lba) (usually qemu can guess them)\n"
6433 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6435 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6436 "-no-kqemu disable KQEMU kernel module usage\n"
6438 #ifdef USE_CODE_COPY
6439 "-no-code-copy disable code copy acceleration\n"
6442 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6443 " (default is CL-GD5446 PCI VGA)\n"
6444 "-no-acpi disable ACPI\n"
6446 "-no-reboot exit instead of rebooting\n"
6447 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6448 "-vnc display start a VNC server on display\n"
6450 "-daemonize daemonize QEMU after initializing\n"
6452 "-option-rom rom load a file, rom, into the option ROM space\n"
6454 "During emulation, the following keys are useful:\n"
6455 "ctrl-alt-f toggle full screen\n"
6456 "ctrl-alt-n switch to virtual console 'n'\n"
6457 "ctrl-alt toggle mouse and keyboard grab\n"
6459 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6464 DEFAULT_NETWORK_SCRIPT
,
6466 DEFAULT_GDBSTUB_PORT
,
6471 #define HAS_ARG 0x0001
6486 QEMU_OPTION_snapshot
,
6488 QEMU_OPTION_no_fd_bootchk
,
6491 QEMU_OPTION_nographic
,
6493 QEMU_OPTION_audio_help
,
6494 QEMU_OPTION_soundhw
,
6513 QEMU_OPTION_no_code_copy
,
6515 QEMU_OPTION_localtime
,
6516 QEMU_OPTION_cirrusvga
,
6519 QEMU_OPTION_std_vga
,
6521 QEMU_OPTION_monitor
,
6523 QEMU_OPTION_parallel
,
6525 QEMU_OPTION_full_screen
,
6526 QEMU_OPTION_no_frame
,
6527 QEMU_OPTION_no_quit
,
6528 QEMU_OPTION_pidfile
,
6529 QEMU_OPTION_no_kqemu
,
6530 QEMU_OPTION_kernel_kqemu
,
6531 QEMU_OPTION_win2k_hack
,
6533 QEMU_OPTION_usbdevice
,
6536 QEMU_OPTION_no_acpi
,
6537 QEMU_OPTION_no_reboot
,
6538 QEMU_OPTION_daemonize
,
6539 QEMU_OPTION_option_rom
,
6540 QEMU_OPTION_semihosting
,
6544 typedef struct QEMUOption
{
6550 const QEMUOption qemu_options
[] = {
6551 { "h", 0, QEMU_OPTION_h
},
6552 { "help", 0, QEMU_OPTION_h
},
6554 { "M", HAS_ARG
, QEMU_OPTION_M
},
6555 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
6556 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6557 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6558 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6559 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6560 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6561 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6562 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6563 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6564 { "snapshot", 0, QEMU_OPTION_snapshot
},
6566 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6568 { "m", HAS_ARG
, QEMU_OPTION_m
},
6569 { "nographic", 0, QEMU_OPTION_nographic
},
6570 { "k", HAS_ARG
, QEMU_OPTION_k
},
6572 { "audio-help", 0, QEMU_OPTION_audio_help
},
6573 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6576 { "net", HAS_ARG
, QEMU_OPTION_net
},
6578 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6579 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
6581 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6583 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6586 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6587 { "append", HAS_ARG
, QEMU_OPTION_append
},
6588 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6590 { "S", 0, QEMU_OPTION_S
},
6591 { "s", 0, QEMU_OPTION_s
},
6592 { "p", HAS_ARG
, QEMU_OPTION_p
},
6593 { "d", HAS_ARG
, QEMU_OPTION_d
},
6594 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6595 { "L", HAS_ARG
, QEMU_OPTION_L
},
6596 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6598 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6599 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6601 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6602 { "g", 1, QEMU_OPTION_g
},
6604 { "localtime", 0, QEMU_OPTION_localtime
},
6605 { "std-vga", 0, QEMU_OPTION_std_vga
},
6606 { "echr", 1, QEMU_OPTION_echr
},
6607 { "monitor", 1, QEMU_OPTION_monitor
},
6608 { "serial", 1, QEMU_OPTION_serial
},
6609 { "parallel", 1, QEMU_OPTION_parallel
},
6610 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6611 { "full-screen", 0, QEMU_OPTION_full_screen
},
6613 { "no-frame", 0, QEMU_OPTION_no_frame
},
6614 { "no-quit", 0, QEMU_OPTION_no_quit
},
6616 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6617 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6618 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6619 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6620 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6622 /* temporary options */
6623 { "usb", 0, QEMU_OPTION_usb
},
6624 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6625 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
6626 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6627 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6628 { "daemonize", 0, QEMU_OPTION_daemonize
},
6629 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6630 #if defined(TARGET_ARM)
6631 { "semihosting", 0, QEMU_OPTION_semihosting
},
6633 { "name", HAS_ARG
, QEMU_OPTION_name
},
6637 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6639 /* this stack is only used during signal handling */
6640 #define SIGNAL_STACK_SIZE 32768
6642 static uint8_t *signal_stack
;
6646 /* password input */
6648 static BlockDriverState
*get_bdrv(int index
)
6650 BlockDriverState
*bs
;
6653 bs
= bs_table
[index
];
6654 } else if (index
< 6) {
6655 bs
= fd_table
[index
- 4];
6662 static void read_passwords(void)
6664 BlockDriverState
*bs
;
6668 for(i
= 0; i
< 6; i
++) {
6670 if (bs
&& bdrv_is_encrypted(bs
)) {
6671 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6672 for(j
= 0; j
< 3; j
++) {
6673 monitor_readline("Password: ",
6674 1, password
, sizeof(password
));
6675 if (bdrv_set_key(bs
, password
) == 0)
6677 term_printf("invalid password\n");
6683 /* XXX: currently we cannot use simultaneously different CPUs */
6684 void register_machines(void)
6686 #if defined(TARGET_I386)
6687 qemu_register_machine(&pc_machine
);
6688 qemu_register_machine(&isapc_machine
);
6689 #elif defined(TARGET_PPC)
6690 qemu_register_machine(&heathrow_machine
);
6691 qemu_register_machine(&core99_machine
);
6692 qemu_register_machine(&prep_machine
);
6693 #elif defined(TARGET_MIPS)
6694 qemu_register_machine(&mips_machine
);
6695 qemu_register_machine(&mips_malta_machine
);
6696 #elif defined(TARGET_SPARC)
6697 #ifdef TARGET_SPARC64
6698 qemu_register_machine(&sun4u_machine
);
6700 qemu_register_machine(&ss5_machine
);
6701 qemu_register_machine(&ss10_machine
);
6703 #elif defined(TARGET_ARM)
6704 qemu_register_machine(&integratorcp_machine
);
6705 qemu_register_machine(&versatilepb_machine
);
6706 qemu_register_machine(&versatileab_machine
);
6707 qemu_register_machine(&realview_machine
);
6708 #elif defined(TARGET_SH4)
6709 qemu_register_machine(&shix_machine
);
6710 #elif defined(TARGET_ALPHA)
6713 #error unsupported CPU
6718 struct soundhw soundhw
[] = {
6725 { .init_isa
= pcspk_audio_init
}
6730 "Creative Sound Blaster 16",
6733 { .init_isa
= SB16_init
}
6740 "Yamaha YMF262 (OPL3)",
6742 "Yamaha YM3812 (OPL2)",
6746 { .init_isa
= Adlib_init
}
6753 "Gravis Ultrasound GF1",
6756 { .init_isa
= GUS_init
}
6762 "ENSONIQ AudioPCI ES1370",
6765 { .init_pci
= es1370_init
}
6768 { NULL
, NULL
, 0, 0, { NULL
} }
6771 static void select_soundhw (const char *optarg
)
6775 if (*optarg
== '?') {
6778 printf ("Valid sound card names (comma separated):\n");
6779 for (c
= soundhw
; c
->name
; ++c
) {
6780 printf ("%-11s %s\n", c
->name
, c
->descr
);
6782 printf ("\n-soundhw all will enable all of the above\n");
6783 exit (*optarg
!= '?');
6791 if (!strcmp (optarg
, "all")) {
6792 for (c
= soundhw
; c
->name
; ++c
) {
6800 e
= strchr (p
, ',');
6801 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6803 for (c
= soundhw
; c
->name
; ++c
) {
6804 if (!strncmp (c
->name
, p
, l
)) {
6813 "Unknown sound card name (too big to show)\n");
6816 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6821 p
+= l
+ (e
!= NULL
);
6825 goto show_valid_cards
;
6831 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6833 exit(STATUS_CONTROL_C_EXIT
);
6838 #define MAX_NET_CLIENTS 32
6840 int main(int argc
, char **argv
)
6842 #ifdef CONFIG_GDBSTUB
6844 const char *gdbstub_port
;
6847 int snapshot
, linux_boot
;
6848 const char *initrd_filename
;
6849 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6850 const char *kernel_filename
, *kernel_cmdline
;
6851 DisplayState
*ds
= &display_state
;
6852 int cyls
, heads
, secs
, translation
;
6853 char net_clients
[MAX_NET_CLIENTS
][256];
6856 const char *r
, *optarg
;
6857 CharDriverState
*monitor_hd
;
6858 char monitor_device
[128];
6859 char serial_devices
[MAX_SERIAL_PORTS
][128];
6860 int serial_device_index
;
6861 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6862 int parallel_device_index
;
6863 const char *loadvm
= NULL
;
6864 QEMUMachine
*machine
;
6865 const char *cpu_model
;
6866 char usb_devices
[MAX_USB_CMDLINE
][128];
6867 int usb_devices_index
;
6869 const char *pid_file
= NULL
;
6871 LIST_INIT (&vm_change_state_head
);
6874 struct sigaction act
;
6875 sigfillset(&act
.sa_mask
);
6877 act
.sa_handler
= SIG_IGN
;
6878 sigaction(SIGPIPE
, &act
, NULL
);
6881 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6882 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6883 QEMU to run on a single CPU */
6888 h
= GetCurrentProcess();
6889 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6890 for(i
= 0; i
< 32; i
++) {
6891 if (mask
& (1 << i
))
6896 SetProcessAffinityMask(h
, mask
);
6902 register_machines();
6903 machine
= first_machine
;
6905 initrd_filename
= NULL
;
6906 for(i
= 0; i
< MAX_FD
; i
++)
6907 fd_filename
[i
] = NULL
;
6908 for(i
= 0; i
< MAX_DISKS
; i
++)
6909 hd_filename
[i
] = NULL
;
6910 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6911 vga_ram_size
= VGA_RAM_SIZE
;
6912 #ifdef CONFIG_GDBSTUB
6914 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6918 kernel_filename
= NULL
;
6919 kernel_cmdline
= "";
6925 cyls
= heads
= secs
= 0;
6926 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6927 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6929 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6930 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6931 serial_devices
[i
][0] = '\0';
6932 serial_device_index
= 0;
6934 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6935 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6936 parallel_devices
[i
][0] = '\0';
6937 parallel_device_index
= 0;
6939 usb_devices_index
= 0;
6944 /* default mac address of the first network interface */
6952 hd_filename
[0] = argv
[optind
++];
6954 const QEMUOption
*popt
;
6957 /* Treat --foo the same as -foo. */
6960 popt
= qemu_options
;
6963 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6967 if (!strcmp(popt
->name
, r
+ 1))
6971 if (popt
->flags
& HAS_ARG
) {
6972 if (optind
>= argc
) {
6973 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6977 optarg
= argv
[optind
++];
6982 switch(popt
->index
) {
6984 machine
= find_machine(optarg
);
6987 printf("Supported machines are:\n");
6988 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6989 printf("%-10s %s%s\n",
6991 m
== first_machine
? " (default)" : "");
6996 case QEMU_OPTION_cpu
:
6997 /* hw initialization will check this */
6998 if (optarg
[0] == '?') {
6999 #if defined(TARGET_PPC)
7000 ppc_cpu_list(stdout
, &fprintf
);
7001 #elif defined(TARGET_ARM)
7003 #elif defined(TARGET_MIPS)
7004 mips_cpu_list(stdout
, &fprintf
);
7005 #elif defined(TARGET_SPARC)
7006 sparc_cpu_list(stdout
, &fprintf
);
7013 case QEMU_OPTION_initrd
:
7014 initrd_filename
= optarg
;
7016 case QEMU_OPTION_hda
:
7017 case QEMU_OPTION_hdb
:
7018 case QEMU_OPTION_hdc
:
7019 case QEMU_OPTION_hdd
:
7022 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7023 hd_filename
[hd_index
] = optarg
;
7024 if (hd_index
== cdrom_index
)
7028 case QEMU_OPTION_snapshot
:
7031 case QEMU_OPTION_hdachs
:
7035 cyls
= strtol(p
, (char **)&p
, 0);
7036 if (cyls
< 1 || cyls
> 16383)
7041 heads
= strtol(p
, (char **)&p
, 0);
7042 if (heads
< 1 || heads
> 16)
7047 secs
= strtol(p
, (char **)&p
, 0);
7048 if (secs
< 1 || secs
> 63)
7052 if (!strcmp(p
, "none"))
7053 translation
= BIOS_ATA_TRANSLATION_NONE
;
7054 else if (!strcmp(p
, "lba"))
7055 translation
= BIOS_ATA_TRANSLATION_LBA
;
7056 else if (!strcmp(p
, "auto"))
7057 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7060 } else if (*p
!= '\0') {
7062 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7067 case QEMU_OPTION_nographic
:
7068 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7069 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "null");
7070 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7073 case QEMU_OPTION_kernel
:
7074 kernel_filename
= optarg
;
7076 case QEMU_OPTION_append
:
7077 kernel_cmdline
= optarg
;
7079 case QEMU_OPTION_cdrom
:
7080 if (cdrom_index
>= 0) {
7081 hd_filename
[cdrom_index
] = optarg
;
7084 case QEMU_OPTION_boot
:
7085 boot_device
= optarg
[0];
7086 if (boot_device
!= 'a' &&
7087 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7089 boot_device
!= 'n' &&
7091 boot_device
!= 'c' && boot_device
!= 'd') {
7092 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7096 case QEMU_OPTION_fda
:
7097 fd_filename
[0] = optarg
;
7099 case QEMU_OPTION_fdb
:
7100 fd_filename
[1] = optarg
;
7103 case QEMU_OPTION_no_fd_bootchk
:
7107 case QEMU_OPTION_no_code_copy
:
7108 code_copy_enabled
= 0;
7110 case QEMU_OPTION_net
:
7111 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7112 fprintf(stderr
, "qemu: too many network clients\n");
7115 pstrcpy(net_clients
[nb_net_clients
],
7116 sizeof(net_clients
[0]),
7121 case QEMU_OPTION_tftp
:
7122 tftp_prefix
= optarg
;
7124 case QEMU_OPTION_bootp
:
7125 bootp_filename
= optarg
;
7128 case QEMU_OPTION_smb
:
7129 net_slirp_smb(optarg
);
7132 case QEMU_OPTION_redir
:
7133 net_slirp_redir(optarg
);
7137 case QEMU_OPTION_audio_help
:
7141 case QEMU_OPTION_soundhw
:
7142 select_soundhw (optarg
);
7149 ram_size
= atoi(optarg
) * 1024 * 1024;
7152 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7153 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7154 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7163 mask
= cpu_str_to_log_mask(optarg
);
7165 printf("Log items (comma separated):\n");
7166 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7167 printf("%-10s %s\n", item
->name
, item
->help
);
7174 #ifdef CONFIG_GDBSTUB
7179 gdbstub_port
= optarg
;
7189 keyboard_layout
= optarg
;
7191 case QEMU_OPTION_localtime
:
7194 case QEMU_OPTION_cirrusvga
:
7195 cirrus_vga_enabled
= 1;
7198 case QEMU_OPTION_vmsvga
:
7199 cirrus_vga_enabled
= 0;
7202 case QEMU_OPTION_std_vga
:
7203 cirrus_vga_enabled
= 0;
7211 w
= strtol(p
, (char **)&p
, 10);
7214 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7220 h
= strtol(p
, (char **)&p
, 10);
7225 depth
= strtol(p
, (char **)&p
, 10);
7226 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7227 depth
!= 24 && depth
!= 32)
7229 } else if (*p
== '\0') {
7230 depth
= graphic_depth
;
7237 graphic_depth
= depth
;
7240 case QEMU_OPTION_echr
:
7243 term_escape_char
= strtol(optarg
, &r
, 0);
7245 printf("Bad argument to echr\n");
7248 case QEMU_OPTION_monitor
:
7249 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7251 case QEMU_OPTION_serial
:
7252 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7253 fprintf(stderr
, "qemu: too many serial ports\n");
7256 pstrcpy(serial_devices
[serial_device_index
],
7257 sizeof(serial_devices
[0]), optarg
);
7258 serial_device_index
++;
7260 case QEMU_OPTION_parallel
:
7261 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7262 fprintf(stderr
, "qemu: too many parallel ports\n");
7265 pstrcpy(parallel_devices
[parallel_device_index
],
7266 sizeof(parallel_devices
[0]), optarg
);
7267 parallel_device_index
++;
7269 case QEMU_OPTION_loadvm
:
7272 case QEMU_OPTION_full_screen
:
7276 case QEMU_OPTION_no_frame
:
7279 case QEMU_OPTION_no_quit
:
7283 case QEMU_OPTION_pidfile
:
7287 case QEMU_OPTION_win2k_hack
:
7288 win2k_install_hack
= 1;
7292 case QEMU_OPTION_no_kqemu
:
7295 case QEMU_OPTION_kernel_kqemu
:
7299 case QEMU_OPTION_usb
:
7302 case QEMU_OPTION_usbdevice
:
7304 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7305 fprintf(stderr
, "Too many USB devices\n");
7308 pstrcpy(usb_devices
[usb_devices_index
],
7309 sizeof(usb_devices
[usb_devices_index
]),
7311 usb_devices_index
++;
7313 case QEMU_OPTION_smp
:
7314 smp_cpus
= atoi(optarg
);
7315 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7316 fprintf(stderr
, "Invalid number of CPUs\n");
7320 case QEMU_OPTION_vnc
:
7321 vnc_display
= optarg
;
7323 case QEMU_OPTION_no_acpi
:
7326 case QEMU_OPTION_no_reboot
:
7329 case QEMU_OPTION_daemonize
:
7332 case QEMU_OPTION_option_rom
:
7333 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7334 fprintf(stderr
, "Too many option ROMs\n");
7337 option_rom
[nb_option_roms
] = optarg
;
7340 case QEMU_OPTION_semihosting
:
7341 semihosting_enabled
= 1;
7343 case QEMU_OPTION_name
:
7351 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7352 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7359 if (pipe(fds
) == -1)
7370 len
= read(fds
[0], &status
, 1);
7371 if (len
== -1 && (errno
== EINTR
))
7376 else if (status
== 1) {
7377 fprintf(stderr
, "Could not acquire pidfile\n");
7395 signal(SIGTSTP
, SIG_IGN
);
7396 signal(SIGTTOU
, SIG_IGN
);
7397 signal(SIGTTIN
, SIG_IGN
);
7401 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
7404 write(fds
[1], &status
, 1);
7406 fprintf(stderr
, "Could not acquire pid file\n");
7414 linux_boot
= (kernel_filename
!= NULL
);
7417 boot_device
!= 'n' &&
7418 hd_filename
[0] == '\0' &&
7419 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7420 fd_filename
[0] == '\0')
7423 /* boot to floppy or the default cd if no hard disk defined yet */
7424 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7425 if (fd_filename
[0] != '\0')
7431 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7441 /* init network clients */
7442 if (nb_net_clients
== 0) {
7443 /* if no clients, we use a default config */
7444 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7446 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7451 for(i
= 0;i
< nb_net_clients
; i
++) {
7452 if (net_client_init(net_clients
[i
]) < 0)
7457 if (boot_device
== 'n') {
7458 for (i
= 0; i
< nb_nics
; i
++) {
7459 const char *model
= nd_table
[i
].model
;
7463 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7464 if (get_image_size(buf
) > 0) {
7465 option_rom
[nb_option_roms
] = strdup(buf
);
7471 fprintf(stderr
, "No valid PXE rom found for network device\n");
7474 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7478 /* init the memory */
7479 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
7481 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7482 if (!phys_ram_base
) {
7483 fprintf(stderr
, "Could not allocate physical memory\n");
7487 /* we always create the cdrom drive, even if no disk is there */
7489 if (cdrom_index
>= 0) {
7490 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7491 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7494 /* open the virtual block devices */
7495 for(i
= 0; i
< MAX_DISKS
; i
++) {
7496 if (hd_filename
[i
]) {
7499 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7500 bs_table
[i
] = bdrv_new(buf
);
7502 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7503 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7507 if (i
== 0 && cyls
!= 0) {
7508 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7509 bdrv_set_translation_hint(bs_table
[i
], translation
);
7514 /* we always create at least one floppy disk */
7515 fd_table
[0] = bdrv_new("fda");
7516 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7518 for(i
= 0; i
< MAX_FD
; i
++) {
7519 if (fd_filename
[i
]) {
7522 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7523 fd_table
[i
] = bdrv_new(buf
);
7524 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7526 if (fd_filename
[i
] != '\0') {
7527 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7528 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7529 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7537 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7538 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7544 dumb_display_init(ds
);
7545 } else if (vnc_display
!= NULL
) {
7546 vnc_display_init(ds
, vnc_display
);
7548 #if defined(CONFIG_SDL)
7549 sdl_display_init(ds
, full_screen
, no_frame
);
7550 #elif defined(CONFIG_COCOA)
7551 cocoa_display_init(ds
, full_screen
);
7553 dumb_display_init(ds
);
7557 /* Maintain compatibility with multiple stdio monitors */
7558 if (!strcmp(monitor_device
,"stdio")) {
7559 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7560 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
7561 monitor_device
[0] = '\0';
7563 } else if (!strcmp(serial_devices
[i
],"stdio")) {
7564 monitor_device
[0] = '\0';
7565 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
7570 if (monitor_device
[0] != '\0') {
7571 monitor_hd
= qemu_chr_open(monitor_device
);
7573 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7576 monitor_init(monitor_hd
, !nographic
);
7579 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7580 const char *devname
= serial_devices
[i
];
7581 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7582 serial_hds
[i
] = qemu_chr_open(devname
);
7583 if (!serial_hds
[i
]) {
7584 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7588 if (!strcmp(devname
, "vc"))
7589 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7593 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7594 const char *devname
= parallel_devices
[i
];
7595 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7596 parallel_hds
[i
] = qemu_chr_open(devname
);
7597 if (!parallel_hds
[i
]) {
7598 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7602 if (!strcmp(devname
, "vc"))
7603 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7607 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7608 ds
, fd_filename
, snapshot
,
7609 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
7611 /* init USB devices */
7613 for(i
= 0; i
< usb_devices_index
; i
++) {
7614 if (usb_device_add(usb_devices
[i
]) < 0) {
7615 fprintf(stderr
, "Warning: could not add USB device %s\n",
7621 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7622 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7624 #ifdef CONFIG_GDBSTUB
7626 /* XXX: use standard host:port notation and modify options
7628 if (gdbserver_start(gdbstub_port
) < 0) {
7629 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
7639 /* XXX: simplify init */
7652 len
= write(fds
[1], &status
, 1);
7653 if (len
== -1 && (errno
== EINTR
))
7659 fd
= open("/dev/null", O_RDWR
);