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;
158 int graphic_width
= 1024;
159 int graphic_height
= 768;
161 int graphic_width
= 800;
162 int graphic_height
= 600;
164 int graphic_depth
= 15;
168 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
169 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
171 int win2k_install_hack
= 0;
174 static VLANState
*first_vlan
;
176 const char *vnc_display
;
177 #if defined(TARGET_SPARC)
179 #elif defined(TARGET_I386)
184 int acpi_enabled
= 1;
188 const char *option_rom
[MAX_OPTION_ROMS
];
190 int semihosting_enabled
= 0;
193 /***********************************************************/
194 /* x86 ISA bus support */
196 target_phys_addr_t isa_mem_base
= 0;
199 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
201 #ifdef DEBUG_UNUSED_IOPORT
202 fprintf(stderr
, "inb: port=0x%04x\n", address
);
207 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
209 #ifdef DEBUG_UNUSED_IOPORT
210 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
214 /* default is to make two byte accesses */
215 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
218 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
219 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
220 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
224 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
226 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
227 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
228 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
231 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
233 #ifdef DEBUG_UNUSED_IOPORT
234 fprintf(stderr
, "inl: port=0x%04x\n", address
);
239 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
241 #ifdef DEBUG_UNUSED_IOPORT
242 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
246 void init_ioports(void)
250 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
251 ioport_read_table
[0][i
] = default_ioport_readb
;
252 ioport_write_table
[0][i
] = default_ioport_writeb
;
253 ioport_read_table
[1][i
] = default_ioport_readw
;
254 ioport_write_table
[1][i
] = default_ioport_writew
;
255 ioport_read_table
[2][i
] = default_ioport_readl
;
256 ioport_write_table
[2][i
] = default_ioport_writel
;
260 /* size is the word size in byte */
261 int register_ioport_read(int start
, int length
, int size
,
262 IOPortReadFunc
*func
, void *opaque
)
268 } else if (size
== 2) {
270 } else if (size
== 4) {
273 hw_error("register_ioport_read: invalid size");
276 for(i
= start
; i
< start
+ length
; i
+= size
) {
277 ioport_read_table
[bsize
][i
] = func
;
278 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
279 hw_error("register_ioport_read: invalid opaque");
280 ioport_opaque
[i
] = opaque
;
285 /* size is the word size in byte */
286 int register_ioport_write(int start
, int length
, int size
,
287 IOPortWriteFunc
*func
, void *opaque
)
293 } else if (size
== 2) {
295 } else if (size
== 4) {
298 hw_error("register_ioport_write: invalid size");
301 for(i
= start
; i
< start
+ length
; i
+= size
) {
302 ioport_write_table
[bsize
][i
] = func
;
303 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
304 hw_error("register_ioport_write: invalid opaque");
305 ioport_opaque
[i
] = opaque
;
310 void isa_unassign_ioport(int start
, int length
)
314 for(i
= start
; i
< start
+ length
; i
++) {
315 ioport_read_table
[0][i
] = default_ioport_readb
;
316 ioport_read_table
[1][i
] = default_ioport_readw
;
317 ioport_read_table
[2][i
] = default_ioport_readl
;
319 ioport_write_table
[0][i
] = default_ioport_writeb
;
320 ioport_write_table
[1][i
] = default_ioport_writew
;
321 ioport_write_table
[2][i
] = default_ioport_writel
;
325 /***********************************************************/
327 void cpu_outb(CPUState
*env
, int addr
, int val
)
330 if (loglevel
& CPU_LOG_IOPORT
)
331 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
333 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
336 env
->last_io_time
= cpu_get_time_fast();
340 void cpu_outw(CPUState
*env
, int addr
, int val
)
343 if (loglevel
& CPU_LOG_IOPORT
)
344 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
346 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
349 env
->last_io_time
= cpu_get_time_fast();
353 void cpu_outl(CPUState
*env
, int addr
, int val
)
356 if (loglevel
& CPU_LOG_IOPORT
)
357 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
359 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
362 env
->last_io_time
= cpu_get_time_fast();
366 int cpu_inb(CPUState
*env
, int addr
)
369 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
371 if (loglevel
& CPU_LOG_IOPORT
)
372 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
376 env
->last_io_time
= cpu_get_time_fast();
381 int cpu_inw(CPUState
*env
, int addr
)
384 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
386 if (loglevel
& CPU_LOG_IOPORT
)
387 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
391 env
->last_io_time
= cpu_get_time_fast();
396 int cpu_inl(CPUState
*env
, int addr
)
399 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
401 if (loglevel
& CPU_LOG_IOPORT
)
402 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
406 env
->last_io_time
= cpu_get_time_fast();
411 /***********************************************************/
412 void hw_error(const char *fmt
, ...)
418 fprintf(stderr
, "qemu: hardware error: ");
419 vfprintf(stderr
, fmt
, ap
);
420 fprintf(stderr
, "\n");
421 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
422 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
424 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
426 cpu_dump_state(env
, stderr
, fprintf
, 0);
433 /***********************************************************/
436 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
437 static void *qemu_put_kbd_event_opaque
;
438 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
439 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
441 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
443 qemu_put_kbd_event_opaque
= opaque
;
444 qemu_put_kbd_event
= func
;
447 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
448 void *opaque
, int absolute
,
451 QEMUPutMouseEntry
*s
, *cursor
;
453 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
457 s
->qemu_put_mouse_event
= func
;
458 s
->qemu_put_mouse_event_opaque
= opaque
;
459 s
->qemu_put_mouse_event_absolute
= absolute
;
460 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
463 if (!qemu_put_mouse_event_head
) {
464 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
468 cursor
= qemu_put_mouse_event_head
;
469 while (cursor
->next
!= NULL
)
470 cursor
= cursor
->next
;
473 qemu_put_mouse_event_current
= s
;
478 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
480 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
482 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
485 cursor
= qemu_put_mouse_event_head
;
486 while (cursor
!= NULL
&& cursor
!= entry
) {
488 cursor
= cursor
->next
;
491 if (cursor
== NULL
) // does not exist or list empty
493 else if (prev
== NULL
) { // entry is head
494 qemu_put_mouse_event_head
= cursor
->next
;
495 if (qemu_put_mouse_event_current
== entry
)
496 qemu_put_mouse_event_current
= cursor
->next
;
497 qemu_free(entry
->qemu_put_mouse_event_name
);
502 prev
->next
= entry
->next
;
504 if (qemu_put_mouse_event_current
== entry
)
505 qemu_put_mouse_event_current
= prev
;
507 qemu_free(entry
->qemu_put_mouse_event_name
);
511 void kbd_put_keycode(int keycode
)
513 if (qemu_put_kbd_event
) {
514 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
518 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
520 QEMUPutMouseEvent
*mouse_event
;
521 void *mouse_event_opaque
;
523 if (!qemu_put_mouse_event_current
) {
528 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
530 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
533 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
537 int kbd_mouse_is_absolute(void)
539 if (!qemu_put_mouse_event_current
)
542 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
545 void do_info_mice(void)
547 QEMUPutMouseEntry
*cursor
;
550 if (!qemu_put_mouse_event_head
) {
551 term_printf("No mouse devices connected\n");
555 term_printf("Mouse devices available:\n");
556 cursor
= qemu_put_mouse_event_head
;
557 while (cursor
!= NULL
) {
558 term_printf("%c Mouse #%d: %s\n",
559 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
560 index
, cursor
->qemu_put_mouse_event_name
);
562 cursor
= cursor
->next
;
566 void do_mouse_set(int index
)
568 QEMUPutMouseEntry
*cursor
;
571 if (!qemu_put_mouse_event_head
) {
572 term_printf("No mouse devices connected\n");
576 cursor
= qemu_put_mouse_event_head
;
577 while (cursor
!= NULL
&& index
!= i
) {
579 cursor
= cursor
->next
;
583 qemu_put_mouse_event_current
= cursor
;
585 term_printf("Mouse at given index not found\n");
588 /* compute with 96 bit intermediate result: (a*b)/c */
589 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
594 #ifdef WORDS_BIGENDIAN
604 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
605 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
608 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
612 /***********************************************************/
613 /* real time host monotonic timer */
615 #define QEMU_TIMER_BASE 1000000000LL
619 static int64_t clock_freq
;
621 static void init_get_clock(void)
625 ret
= QueryPerformanceFrequency(&freq
);
627 fprintf(stderr
, "Could not calibrate ticks\n");
630 clock_freq
= freq
.QuadPart
;
633 static int64_t get_clock(void)
636 QueryPerformanceCounter(&ti
);
637 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
642 static int use_rt_clock
;
644 static void init_get_clock(void)
647 #if defined(__linux__)
650 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
657 static int64_t get_clock(void)
659 #if defined(__linux__)
662 clock_gettime(CLOCK_MONOTONIC
, &ts
);
663 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
667 /* XXX: using gettimeofday leads to problems if the date
668 changes, so it should be avoided. */
670 gettimeofday(&tv
, NULL
);
671 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
677 /***********************************************************/
678 /* guest cycle counter */
680 static int64_t cpu_ticks_prev
;
681 static int64_t cpu_ticks_offset
;
682 static int64_t cpu_clock_offset
;
683 static int cpu_ticks_enabled
;
685 /* return the host CPU cycle counter and handle stop/restart */
686 int64_t cpu_get_ticks(void)
688 if (!cpu_ticks_enabled
) {
689 return cpu_ticks_offset
;
692 ticks
= cpu_get_real_ticks();
693 if (cpu_ticks_prev
> ticks
) {
694 /* Note: non increasing ticks may happen if the host uses
696 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
698 cpu_ticks_prev
= ticks
;
699 return ticks
+ cpu_ticks_offset
;
703 /* return the host CPU monotonic timer and handle stop/restart */
704 static int64_t cpu_get_clock(void)
707 if (!cpu_ticks_enabled
) {
708 return cpu_clock_offset
;
711 return ti
+ cpu_clock_offset
;
715 /* enable cpu_get_ticks() */
716 void cpu_enable_ticks(void)
718 if (!cpu_ticks_enabled
) {
719 cpu_ticks_offset
-= cpu_get_real_ticks();
720 cpu_clock_offset
-= get_clock();
721 cpu_ticks_enabled
= 1;
725 /* disable cpu_get_ticks() : the clock is stopped. You must not call
726 cpu_get_ticks() after that. */
727 void cpu_disable_ticks(void)
729 if (cpu_ticks_enabled
) {
730 cpu_ticks_offset
= cpu_get_ticks();
731 cpu_clock_offset
= cpu_get_clock();
732 cpu_ticks_enabled
= 0;
736 /***********************************************************/
739 #define QEMU_TIMER_REALTIME 0
740 #define QEMU_TIMER_VIRTUAL 1
744 /* XXX: add frequency */
752 struct QEMUTimer
*next
;
758 static QEMUTimer
*active_timers
[2];
760 static MMRESULT timerID
;
761 static HANDLE host_alarm
= NULL
;
762 static unsigned int period
= 1;
764 /* frequency of the times() clock tick */
765 static int timer_freq
;
768 QEMUClock
*qemu_new_clock(int type
)
771 clock
= qemu_mallocz(sizeof(QEMUClock
));
778 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
782 ts
= qemu_mallocz(sizeof(QEMUTimer
));
789 void qemu_free_timer(QEMUTimer
*ts
)
794 /* stop a timer, but do not dealloc it */
795 void qemu_del_timer(QEMUTimer
*ts
)
799 /* NOTE: this code must be signal safe because
800 qemu_timer_expired() can be called from a signal. */
801 pt
= &active_timers
[ts
->clock
->type
];
814 /* modify the current timer so that it will be fired when current_time
815 >= expire_time. The corresponding callback will be called. */
816 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
822 /* add the timer in the sorted list */
823 /* NOTE: this code must be signal safe because
824 qemu_timer_expired() can be called from a signal. */
825 pt
= &active_timers
[ts
->clock
->type
];
830 if (t
->expire_time
> expire_time
)
834 ts
->expire_time
= expire_time
;
839 int qemu_timer_pending(QEMUTimer
*ts
)
842 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
849 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
853 return (timer_head
->expire_time
<= current_time
);
856 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
862 if (!ts
|| ts
->expire_time
> current_time
)
864 /* remove timer from the list before calling the callback */
865 *ptimer_head
= ts
->next
;
868 /* run the callback (the timer list can be modified) */
873 int64_t qemu_get_clock(QEMUClock
*clock
)
875 switch(clock
->type
) {
876 case QEMU_TIMER_REALTIME
:
877 return get_clock() / 1000000;
879 case QEMU_TIMER_VIRTUAL
:
880 return cpu_get_clock();
884 static void init_timers(void)
887 ticks_per_sec
= QEMU_TIMER_BASE
;
888 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
889 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
893 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
895 uint64_t expire_time
;
897 if (qemu_timer_pending(ts
)) {
898 expire_time
= ts
->expire_time
;
902 qemu_put_be64(f
, expire_time
);
905 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
907 uint64_t expire_time
;
909 expire_time
= qemu_get_be64(f
);
910 if (expire_time
!= -1) {
911 qemu_mod_timer(ts
, expire_time
);
917 static void timer_save(QEMUFile
*f
, void *opaque
)
919 if (cpu_ticks_enabled
) {
920 hw_error("cannot save state if virtual timers are running");
922 qemu_put_be64s(f
, &cpu_ticks_offset
);
923 qemu_put_be64s(f
, &ticks_per_sec
);
924 qemu_put_be64s(f
, &cpu_clock_offset
);
927 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
929 if (version_id
!= 1 && version_id
!= 2)
931 if (cpu_ticks_enabled
) {
934 qemu_get_be64s(f
, &cpu_ticks_offset
);
935 qemu_get_be64s(f
, &ticks_per_sec
);
936 if (version_id
== 2) {
937 qemu_get_be64s(f
, &cpu_clock_offset
);
943 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
944 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
946 static void host_alarm_handler(int host_signum
)
950 #define DISP_FREQ 1000
952 static int64_t delta_min
= INT64_MAX
;
953 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
955 ti
= qemu_get_clock(vm_clock
);
956 if (last_clock
!= 0) {
957 delta
= ti
- last_clock
;
958 if (delta
< delta_min
)
960 if (delta
> delta_max
)
963 if (++count
== DISP_FREQ
) {
964 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
965 muldiv64(delta_min
, 1000000, ticks_per_sec
),
966 muldiv64(delta_max
, 1000000, ticks_per_sec
),
967 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
968 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
970 delta_min
= INT64_MAX
;
978 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
979 qemu_get_clock(vm_clock
)) ||
980 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
981 qemu_get_clock(rt_clock
))) {
983 SetEvent(host_alarm
);
985 CPUState
*env
= cpu_single_env
;
987 /* stop the currently executing cpu because a timer occured */
988 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
990 if (env
->kqemu_enabled
) {
991 kqemu_cpu_interrupt(env
);
1000 #if defined(__linux__)
1002 #define RTC_FREQ 1024
1006 static int start_rtc_timer(void)
1008 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1011 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1012 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1013 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1014 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1017 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1022 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1028 static int start_rtc_timer(void)
1033 #endif /* !defined(__linux__) */
1035 #endif /* !defined(_WIN32) */
1037 static void init_timer_alarm(void)
1044 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1045 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1046 if (period
< tc
.wPeriodMin
)
1047 period
= tc
.wPeriodMin
;
1048 timeBeginPeriod(period
);
1049 timerID
= timeSetEvent(1, // interval (ms)
1050 period
, // resolution
1051 host_alarm_handler
, // function
1052 (DWORD
)&count
, // user parameter
1053 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1055 perror("failed timer alarm");
1058 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1060 perror("failed CreateEvent");
1063 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1065 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1068 struct sigaction act
;
1069 struct itimerval itv
;
1071 /* get times() syscall frequency */
1072 timer_freq
= sysconf(_SC_CLK_TCK
);
1075 sigfillset(&act
.sa_mask
);
1077 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1078 act
.sa_flags
|= SA_ONSTACK
;
1080 act
.sa_handler
= host_alarm_handler
;
1081 sigaction(SIGALRM
, &act
, NULL
);
1083 itv
.it_interval
.tv_sec
= 0;
1084 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1085 itv
.it_value
.tv_sec
= 0;
1086 itv
.it_value
.tv_usec
= 10 * 1000;
1087 setitimer(ITIMER_REAL
, &itv
, NULL
);
1088 /* we probe the tick duration of the kernel to inform the user if
1089 the emulated kernel requested a too high timer frequency */
1090 getitimer(ITIMER_REAL
, &itv
);
1092 #if defined(__linux__)
1093 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1094 have timers with 1 ms resolution. The correct solution will
1095 be to use the POSIX real time timers available in recent
1097 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1098 /* try to use /dev/rtc to have a faster timer */
1099 if (start_rtc_timer() < 0)
1101 /* disable itimer */
1102 itv
.it_interval
.tv_sec
= 0;
1103 itv
.it_interval
.tv_usec
= 0;
1104 itv
.it_value
.tv_sec
= 0;
1105 itv
.it_value
.tv_usec
= 0;
1106 setitimer(ITIMER_REAL
, &itv
, NULL
);
1109 sigaction(SIGIO
, &act
, NULL
);
1110 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1111 fcntl(rtc_fd
, F_SETOWN
, getpid());
1113 #endif /* defined(__linux__) */
1116 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1117 PIT_FREQ
) / 1000000;
1123 void quit_timers(void)
1126 timeKillEvent(timerID
);
1127 timeEndPeriod(period
);
1129 CloseHandle(host_alarm
);
1135 /***********************************************************/
1136 /* character device */
1138 static void qemu_chr_event(CharDriverState
*s
, int event
)
1142 s
->chr_event(s
->handler_opaque
, event
);
1145 static void qemu_chr_reset_bh(void *opaque
)
1147 CharDriverState
*s
= opaque
;
1148 qemu_chr_event(s
, CHR_EVENT_RESET
);
1149 qemu_bh_delete(s
->bh
);
1153 void qemu_chr_reset(CharDriverState
*s
)
1155 if (s
->bh
== NULL
) {
1156 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1157 qemu_bh_schedule(s
->bh
);
1161 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1163 return s
->chr_write(s
, buf
, len
);
1166 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1170 return s
->chr_ioctl(s
, cmd
, arg
);
1173 int qemu_chr_can_read(CharDriverState
*s
)
1175 if (!s
->chr_can_read
)
1177 return s
->chr_can_read(s
->handler_opaque
);
1180 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1182 s
->chr_read(s
->handler_opaque
, buf
, len
);
1186 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1191 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1192 qemu_chr_write(s
, buf
, strlen(buf
));
1196 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1198 if (s
->chr_send_event
)
1199 s
->chr_send_event(s
, event
);
1202 void qemu_chr_add_handlers(CharDriverState
*s
,
1203 IOCanRWHandler
*fd_can_read
,
1204 IOReadHandler
*fd_read
,
1205 IOEventHandler
*fd_event
,
1208 s
->chr_can_read
= fd_can_read
;
1209 s
->chr_read
= fd_read
;
1210 s
->chr_event
= fd_event
;
1211 s
->handler_opaque
= opaque
;
1212 if (s
->chr_update_read_handler
)
1213 s
->chr_update_read_handler(s
);
1216 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1221 static CharDriverState
*qemu_chr_open_null(void)
1223 CharDriverState
*chr
;
1225 chr
= qemu_mallocz(sizeof(CharDriverState
));
1228 chr
->chr_write
= null_chr_write
;
1232 /* MUX driver for serial I/O splitting */
1233 static int term_timestamps
;
1234 static int64_t term_timestamps_start
;
1237 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1238 IOReadHandler
*chr_read
[MAX_MUX
];
1239 IOEventHandler
*chr_event
[MAX_MUX
];
1240 void *ext_opaque
[MAX_MUX
];
1241 CharDriverState
*drv
;
1243 int term_got_escape
;
1248 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1250 MuxDriver
*d
= chr
->opaque
;
1252 if (!term_timestamps
) {
1253 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1258 for(i
= 0; i
< len
; i
++) {
1259 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1260 if (buf
[i
] == '\n') {
1266 if (term_timestamps_start
== -1)
1267 term_timestamps_start
= ti
;
1268 ti
-= term_timestamps_start
;
1269 secs
= ti
/ 1000000000;
1270 snprintf(buf1
, sizeof(buf1
),
1271 "[%02d:%02d:%02d.%03d] ",
1275 (int)((ti
/ 1000000) % 1000));
1276 d
->drv
->chr_write(d
->drv
, buf1
, strlen(buf1
));
1283 static char *mux_help
[] = {
1284 "% h print this help\n\r",
1285 "% x exit emulator\n\r",
1286 "% s save disk data back to file (if -snapshot)\n\r",
1287 "% t toggle console timestamps\n\r"
1288 "% b send break (magic sysrq)\n\r",
1289 "% c switch between console and monitor\n\r",
1294 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1295 static void mux_print_help(CharDriverState
*chr
)
1298 char ebuf
[15] = "Escape-Char";
1299 char cbuf
[50] = "\n\r";
1301 if (term_escape_char
> 0 && term_escape_char
< 26) {
1302 sprintf(cbuf
,"\n\r");
1303 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1305 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char
);
1307 chr
->chr_write(chr
, cbuf
, strlen(cbuf
));
1308 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1309 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1310 if (mux_help
[i
][j
] == '%')
1311 chr
->chr_write(chr
, ebuf
, strlen(ebuf
));
1313 chr
->chr_write(chr
, &mux_help
[i
][j
], 1);
1318 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1320 if (d
->term_got_escape
) {
1321 d
->term_got_escape
= 0;
1322 if (ch
== term_escape_char
)
1327 mux_print_help(chr
);
1331 char *term
= "QEMU: Terminated\n\r";
1332 chr
->chr_write(chr
,term
,strlen(term
));
1339 for (i
= 0; i
< MAX_DISKS
; i
++) {
1341 bdrv_commit(bs_table
[i
]);
1347 chr
->chr_event(chr
->opaque
, CHR_EVENT_BREAK
);
1350 /* Switch to the next registered device */
1352 if (chr
->focus
>= d
->mux_cnt
)
1356 term_timestamps
= !term_timestamps
;
1357 term_timestamps_start
= -1;
1360 } else if (ch
== term_escape_char
) {
1361 d
->term_got_escape
= 1;
1369 static int mux_chr_can_read(void *opaque
)
1371 CharDriverState
*chr
= opaque
;
1372 MuxDriver
*d
= chr
->opaque
;
1373 if (d
->chr_can_read
[chr
->focus
])
1374 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1378 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1380 CharDriverState
*chr
= opaque
;
1381 MuxDriver
*d
= chr
->opaque
;
1383 for(i
= 0; i
< size
; i
++)
1384 if (mux_proc_byte(chr
, d
, buf
[i
]))
1385 d
->chr_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
], &buf
[i
], 1);
1388 static void mux_chr_event(void *opaque
, int event
)
1390 CharDriverState
*chr
= opaque
;
1391 MuxDriver
*d
= chr
->opaque
;
1394 /* Send the event to all registered listeners */
1395 for (i
= 0; i
< d
->mux_cnt
; i
++)
1396 if (d
->chr_event
[i
])
1397 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1400 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1402 MuxDriver
*d
= chr
->opaque
;
1404 if (d
->mux_cnt
>= MAX_MUX
) {
1405 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1408 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1409 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1410 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1411 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1412 /* Fix up the real driver with mux routines */
1413 if (d
->mux_cnt
== 0) {
1414 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1415 mux_chr_event
, chr
);
1417 chr
->focus
= d
->mux_cnt
;
1421 CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1423 CharDriverState
*chr
;
1426 chr
= qemu_mallocz(sizeof(CharDriverState
));
1429 d
= qemu_mallocz(sizeof(MuxDriver
));
1438 chr
->chr_write
= mux_chr_write
;
1439 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1446 static void socket_cleanup(void)
1451 static int socket_init(void)
1456 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1458 err
= WSAGetLastError();
1459 fprintf(stderr
, "WSAStartup: %d\n", err
);
1462 atexit(socket_cleanup
);
1466 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1472 ret
= send(fd
, buf
, len
, 0);
1475 errno
= WSAGetLastError();
1476 if (errno
!= WSAEWOULDBLOCK
) {
1479 } else if (ret
== 0) {
1489 void socket_set_nonblock(int fd
)
1491 unsigned long opt
= 1;
1492 ioctlsocket(fd
, FIONBIO
, &opt
);
1497 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1503 ret
= write(fd
, buf
, len
);
1505 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1507 } else if (ret
== 0) {
1517 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1519 return unix_write(fd
, buf
, len1
);
1522 void socket_set_nonblock(int fd
)
1524 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1526 #endif /* !_WIN32 */
1535 #define STDIO_MAX_CLIENTS 1
1536 static int stdio_nb_clients
= 0;
1538 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1540 FDCharDriver
*s
= chr
->opaque
;
1541 return unix_write(s
->fd_out
, buf
, len
);
1544 static int fd_chr_read_poll(void *opaque
)
1546 CharDriverState
*chr
= opaque
;
1547 FDCharDriver
*s
= chr
->opaque
;
1549 s
->max_size
= qemu_chr_can_read(chr
);
1553 static void fd_chr_read(void *opaque
)
1555 CharDriverState
*chr
= opaque
;
1556 FDCharDriver
*s
= chr
->opaque
;
1561 if (len
> s
->max_size
)
1565 size
= read(s
->fd_in
, buf
, len
);
1567 /* FD has been closed. Remove it from the active list. */
1568 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1572 qemu_chr_read(chr
, buf
, size
);
1576 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1578 FDCharDriver
*s
= chr
->opaque
;
1580 if (s
->fd_in
>= 0) {
1581 if (nographic
&& s
->fd_in
== 0) {
1583 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1584 fd_chr_read
, NULL
, chr
);
1589 /* open a character device to a unix fd */
1590 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1592 CharDriverState
*chr
;
1595 chr
= qemu_mallocz(sizeof(CharDriverState
));
1598 s
= qemu_mallocz(sizeof(FDCharDriver
));
1606 chr
->chr_write
= fd_chr_write
;
1607 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1609 qemu_chr_reset(chr
);
1614 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1618 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1621 return qemu_chr_open_fd(-1, fd_out
);
1624 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1627 char filename_in
[256], filename_out
[256];
1629 snprintf(filename_in
, 256, "%s.in", filename
);
1630 snprintf(filename_out
, 256, "%s.out", filename
);
1631 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1632 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1633 if (fd_in
< 0 || fd_out
< 0) {
1638 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1642 return qemu_chr_open_fd(fd_in
, fd_out
);
1646 /* for STDIO, we handle the case where several clients use it
1649 #define TERM_FIFO_MAX_SIZE 1
1651 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1652 static int term_fifo_size
;
1654 static int stdio_read_poll(void *opaque
)
1656 CharDriverState
*chr
= opaque
;
1658 /* try to flush the queue if needed */
1659 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1660 qemu_chr_read(chr
, term_fifo
, 1);
1663 /* see if we can absorb more chars */
1664 if (term_fifo_size
== 0)
1670 static void stdio_read(void *opaque
)
1674 CharDriverState
*chr
= opaque
;
1676 size
= read(0, buf
, 1);
1678 /* stdin has been closed. Remove it from the active list. */
1679 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1683 if (qemu_chr_can_read(chr
) > 0) {
1684 qemu_chr_read(chr
, buf
, 1);
1685 } else if (term_fifo_size
== 0) {
1686 term_fifo
[term_fifo_size
++] = buf
[0];
1691 /* init terminal so that we can grab keys */
1692 static struct termios oldtty
;
1693 static int old_fd0_flags
;
1695 static void term_exit(void)
1697 tcsetattr (0, TCSANOW
, &oldtty
);
1698 fcntl(0, F_SETFL
, old_fd0_flags
);
1701 static void term_init(void)
1705 tcgetattr (0, &tty
);
1707 old_fd0_flags
= fcntl(0, F_GETFL
);
1709 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1710 |INLCR
|IGNCR
|ICRNL
|IXON
);
1711 tty
.c_oflag
|= OPOST
;
1712 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1713 /* if graphical mode, we allow Ctrl-C handling */
1715 tty
.c_lflag
&= ~ISIG
;
1716 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1719 tty
.c_cc
[VTIME
] = 0;
1721 tcsetattr (0, TCSANOW
, &tty
);
1725 fcntl(0, F_SETFL
, O_NONBLOCK
);
1728 static CharDriverState
*qemu_chr_open_stdio(void)
1730 CharDriverState
*chr
;
1732 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1734 chr
= qemu_chr_open_fd(0, 1);
1735 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
1742 #if defined(__linux__)
1743 static CharDriverState
*qemu_chr_open_pty(void)
1746 char slave_name
[1024];
1747 int master_fd
, slave_fd
;
1749 /* Not satisfying */
1750 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1754 /* Disabling local echo and line-buffered output */
1755 tcgetattr (master_fd
, &tty
);
1756 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1758 tty
.c_cc
[VTIME
] = 0;
1759 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1761 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1762 return qemu_chr_open_fd(master_fd
, master_fd
);
1765 static void tty_serial_init(int fd
, int speed
,
1766 int parity
, int data_bits
, int stop_bits
)
1772 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1773 speed
, parity
, data_bits
, stop_bits
);
1775 tcgetattr (fd
, &tty
);
1817 cfsetispeed(&tty
, spd
);
1818 cfsetospeed(&tty
, spd
);
1820 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1821 |INLCR
|IGNCR
|ICRNL
|IXON
);
1822 tty
.c_oflag
|= OPOST
;
1823 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1824 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1845 tty
.c_cflag
|= PARENB
;
1848 tty
.c_cflag
|= PARENB
| PARODD
;
1852 tty
.c_cflag
|= CSTOPB
;
1854 tcsetattr (fd
, TCSANOW
, &tty
);
1857 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1859 FDCharDriver
*s
= chr
->opaque
;
1862 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1864 QEMUSerialSetParams
*ssp
= arg
;
1865 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1866 ssp
->data_bits
, ssp
->stop_bits
);
1869 case CHR_IOCTL_SERIAL_SET_BREAK
:
1871 int enable
= *(int *)arg
;
1873 tcsendbreak(s
->fd_in
, 1);
1882 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1884 CharDriverState
*chr
;
1887 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1890 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1891 tty_serial_init(fd
, 115200, 'N', 8, 1);
1892 chr
= qemu_chr_open_fd(fd
, fd
);
1895 chr
->chr_ioctl
= tty_serial_ioctl
;
1896 qemu_chr_reset(chr
);
1903 } ParallelCharDriver
;
1905 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
1907 if (s
->mode
!= mode
) {
1909 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
1916 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1918 ParallelCharDriver
*drv
= chr
->opaque
;
1923 case CHR_IOCTL_PP_READ_DATA
:
1924 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1926 *(uint8_t *)arg
= b
;
1928 case CHR_IOCTL_PP_WRITE_DATA
:
1929 b
= *(uint8_t *)arg
;
1930 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1933 case CHR_IOCTL_PP_READ_CONTROL
:
1934 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1936 /* Linux gives only the lowest bits, and no way to know data
1937 direction! For better compatibility set the fixed upper
1939 *(uint8_t *)arg
= b
| 0xc0;
1941 case CHR_IOCTL_PP_WRITE_CONTROL
:
1942 b
= *(uint8_t *)arg
;
1943 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1946 case CHR_IOCTL_PP_READ_STATUS
:
1947 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1949 *(uint8_t *)arg
= b
;
1951 case CHR_IOCTL_PP_EPP_READ_ADDR
:
1952 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1953 struct ParallelIOArg
*parg
= arg
;
1954 int n
= read(fd
, parg
->buffer
, parg
->count
);
1955 if (n
!= parg
->count
) {
1960 case CHR_IOCTL_PP_EPP_READ
:
1961 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1962 struct ParallelIOArg
*parg
= arg
;
1963 int n
= read(fd
, parg
->buffer
, parg
->count
);
1964 if (n
!= parg
->count
) {
1969 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
1970 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1971 struct ParallelIOArg
*parg
= arg
;
1972 int n
= write(fd
, parg
->buffer
, parg
->count
);
1973 if (n
!= parg
->count
) {
1978 case CHR_IOCTL_PP_EPP_WRITE
:
1979 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1980 struct ParallelIOArg
*parg
= arg
;
1981 int n
= write(fd
, parg
->buffer
, parg
->count
);
1982 if (n
!= parg
->count
) {
1993 static void pp_close(CharDriverState
*chr
)
1995 ParallelCharDriver
*drv
= chr
->opaque
;
1998 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
1999 ioctl(fd
, PPRELEASE
);
2004 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2006 CharDriverState
*chr
;
2007 ParallelCharDriver
*drv
;
2010 fd
= open(filename
, O_RDWR
);
2014 if (ioctl(fd
, PPCLAIM
) < 0) {
2019 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2025 drv
->mode
= IEEE1284_MODE_COMPAT
;
2027 chr
= qemu_mallocz(sizeof(CharDriverState
));
2033 chr
->chr_write
= null_chr_write
;
2034 chr
->chr_ioctl
= pp_ioctl
;
2035 chr
->chr_close
= pp_close
;
2038 qemu_chr_reset(chr
);
2044 static CharDriverState
*qemu_chr_open_pty(void)
2050 #endif /* !defined(_WIN32) */
2055 HANDLE hcom
, hrecv
, hsend
;
2056 OVERLAPPED orecv
, osend
;
2061 #define NSENDBUF 2048
2062 #define NRECVBUF 2048
2063 #define MAXCONNECT 1
2064 #define NTIMEOUT 5000
2066 static int win_chr_poll(void *opaque
);
2067 static int win_chr_pipe_poll(void *opaque
);
2069 static void win_chr_close(CharDriverState
*chr
)
2071 WinCharState
*s
= chr
->opaque
;
2074 CloseHandle(s
->hsend
);
2078 CloseHandle(s
->hrecv
);
2082 CloseHandle(s
->hcom
);
2086 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2088 qemu_del_polling_cb(win_chr_poll
, chr
);
2091 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2093 WinCharState
*s
= chr
->opaque
;
2095 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2100 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2102 fprintf(stderr
, "Failed CreateEvent\n");
2105 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2107 fprintf(stderr
, "Failed CreateEvent\n");
2111 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2112 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2113 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2114 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2119 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2120 fprintf(stderr
, "Failed SetupComm\n");
2124 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2125 size
= sizeof(COMMCONFIG
);
2126 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2127 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2128 CommConfigDialog(filename
, NULL
, &comcfg
);
2130 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2131 fprintf(stderr
, "Failed SetCommState\n");
2135 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2136 fprintf(stderr
, "Failed SetCommMask\n");
2140 cto
.ReadIntervalTimeout
= MAXDWORD
;
2141 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2142 fprintf(stderr
, "Failed SetCommTimeouts\n");
2146 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2147 fprintf(stderr
, "Failed ClearCommError\n");
2150 qemu_add_polling_cb(win_chr_poll
, chr
);
2158 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2160 WinCharState
*s
= chr
->opaque
;
2161 DWORD len
, ret
, size
, err
;
2164 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2165 s
->osend
.hEvent
= s
->hsend
;
2168 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2170 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2172 err
= GetLastError();
2173 if (err
== ERROR_IO_PENDING
) {
2174 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2192 static int win_chr_read_poll(CharDriverState
*chr
)
2194 WinCharState
*s
= chr
->opaque
;
2196 s
->max_size
= qemu_chr_can_read(chr
);
2200 static void win_chr_readfile(CharDriverState
*chr
)
2202 WinCharState
*s
= chr
->opaque
;
2207 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2208 s
->orecv
.hEvent
= s
->hrecv
;
2209 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2211 err
= GetLastError();
2212 if (err
== ERROR_IO_PENDING
) {
2213 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2218 qemu_chr_read(chr
, buf
, size
);
2222 static void win_chr_read(CharDriverState
*chr
)
2224 WinCharState
*s
= chr
->opaque
;
2226 if (s
->len
> s
->max_size
)
2227 s
->len
= s
->max_size
;
2231 win_chr_readfile(chr
);
2234 static int win_chr_poll(void *opaque
)
2236 CharDriverState
*chr
= opaque
;
2237 WinCharState
*s
= chr
->opaque
;
2241 ClearCommError(s
->hcom
, &comerr
, &status
);
2242 if (status
.cbInQue
> 0) {
2243 s
->len
= status
.cbInQue
;
2244 win_chr_read_poll(chr
);
2251 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2253 CharDriverState
*chr
;
2256 chr
= qemu_mallocz(sizeof(CharDriverState
));
2259 s
= qemu_mallocz(sizeof(WinCharState
));
2265 chr
->chr_write
= win_chr_write
;
2266 chr
->chr_close
= win_chr_close
;
2268 if (win_chr_init(chr
, filename
) < 0) {
2273 qemu_chr_reset(chr
);
2277 static int win_chr_pipe_poll(void *opaque
)
2279 CharDriverState
*chr
= opaque
;
2280 WinCharState
*s
= chr
->opaque
;
2283 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2286 win_chr_read_poll(chr
);
2293 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2295 WinCharState
*s
= chr
->opaque
;
2303 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2305 fprintf(stderr
, "Failed CreateEvent\n");
2308 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2310 fprintf(stderr
, "Failed CreateEvent\n");
2314 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2315 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2316 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2318 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2319 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2320 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2325 ZeroMemory(&ov
, sizeof(ov
));
2326 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2327 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2329 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2333 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2335 fprintf(stderr
, "Failed GetOverlappedResult\n");
2337 CloseHandle(ov
.hEvent
);
2344 CloseHandle(ov
.hEvent
);
2347 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2356 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2358 CharDriverState
*chr
;
2361 chr
= qemu_mallocz(sizeof(CharDriverState
));
2364 s
= qemu_mallocz(sizeof(WinCharState
));
2370 chr
->chr_write
= win_chr_write
;
2371 chr
->chr_close
= win_chr_close
;
2373 if (win_chr_pipe_init(chr
, filename
) < 0) {
2378 qemu_chr_reset(chr
);
2382 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2384 CharDriverState
*chr
;
2387 chr
= qemu_mallocz(sizeof(CharDriverState
));
2390 s
= qemu_mallocz(sizeof(WinCharState
));
2397 chr
->chr_write
= win_chr_write
;
2398 qemu_chr_reset(chr
);
2402 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2406 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2407 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2408 if (fd_out
== INVALID_HANDLE_VALUE
)
2411 return qemu_chr_open_win_file(fd_out
);
2415 /***********************************************************/
2416 /* UDP Net console */
2420 struct sockaddr_in daddr
;
2427 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2429 NetCharDriver
*s
= chr
->opaque
;
2431 return sendto(s
->fd
, buf
, len
, 0,
2432 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2435 static int udp_chr_read_poll(void *opaque
)
2437 CharDriverState
*chr
= opaque
;
2438 NetCharDriver
*s
= chr
->opaque
;
2440 s
->max_size
= qemu_chr_can_read(chr
);
2442 /* If there were any stray characters in the queue process them
2445 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2446 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2448 s
->max_size
= qemu_chr_can_read(chr
);
2453 static void udp_chr_read(void *opaque
)
2455 CharDriverState
*chr
= opaque
;
2456 NetCharDriver
*s
= chr
->opaque
;
2458 if (s
->max_size
== 0)
2460 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2461 s
->bufptr
= s
->bufcnt
;
2466 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2467 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2469 s
->max_size
= qemu_chr_can_read(chr
);
2473 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2475 NetCharDriver
*s
= chr
->opaque
;
2478 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2479 udp_chr_read
, NULL
, chr
);
2483 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2485 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2487 int parse_host_src_port(struct sockaddr_in
*haddr
,
2488 struct sockaddr_in
*saddr
,
2491 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2493 CharDriverState
*chr
= NULL
;
2494 NetCharDriver
*s
= NULL
;
2496 struct sockaddr_in saddr
;
2498 chr
= qemu_mallocz(sizeof(CharDriverState
));
2501 s
= qemu_mallocz(sizeof(NetCharDriver
));
2505 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2507 perror("socket(PF_INET, SOCK_DGRAM)");
2511 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2512 printf("Could not parse: %s\n", def
);
2516 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2526 chr
->chr_write
= udp_chr_write
;
2527 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2540 /***********************************************************/
2541 /* TCP Net console */
2552 static void tcp_chr_accept(void *opaque
);
2554 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2556 TCPCharDriver
*s
= chr
->opaque
;
2558 return send_all(s
->fd
, buf
, len
);
2560 /* XXX: indicate an error ? */
2565 static int tcp_chr_read_poll(void *opaque
)
2567 CharDriverState
*chr
= opaque
;
2568 TCPCharDriver
*s
= chr
->opaque
;
2571 s
->max_size
= qemu_chr_can_read(chr
);
2576 #define IAC_BREAK 243
2577 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2579 char *buf
, int *size
)
2581 /* Handle any telnet client's basic IAC options to satisfy char by
2582 * char mode with no echo. All IAC options will be removed from
2583 * the buf and the do_telnetopt variable will be used to track the
2584 * state of the width of the IAC information.
2586 * IAC commands come in sets of 3 bytes with the exception of the
2587 * "IAC BREAK" command and the double IAC.
2593 for (i
= 0; i
< *size
; i
++) {
2594 if (s
->do_telnetopt
> 1) {
2595 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2596 /* Double IAC means send an IAC */
2600 s
->do_telnetopt
= 1;
2602 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2603 /* Handle IAC break commands by sending a serial break */
2604 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2609 if (s
->do_telnetopt
>= 4) {
2610 s
->do_telnetopt
= 1;
2613 if ((unsigned char)buf
[i
] == IAC
) {
2614 s
->do_telnetopt
= 2;
2625 static void tcp_chr_read(void *opaque
)
2627 CharDriverState
*chr
= opaque
;
2628 TCPCharDriver
*s
= chr
->opaque
;
2632 if (!s
->connected
|| s
->max_size
<= 0)
2635 if (len
> s
->max_size
)
2637 size
= recv(s
->fd
, buf
, len
, 0);
2639 /* connection closed */
2641 if (s
->listen_fd
>= 0) {
2642 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2644 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2647 } else if (size
> 0) {
2648 if (s
->do_telnetopt
)
2649 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2651 qemu_chr_read(chr
, buf
, size
);
2655 static void tcp_chr_connect(void *opaque
)
2657 CharDriverState
*chr
= opaque
;
2658 TCPCharDriver
*s
= chr
->opaque
;
2661 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2662 tcp_chr_read
, NULL
, chr
);
2663 qemu_chr_reset(chr
);
2666 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2667 static void tcp_chr_telnet_init(int fd
)
2670 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2671 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2672 send(fd
, (char *)buf
, 3, 0);
2673 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2674 send(fd
, (char *)buf
, 3, 0);
2675 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2676 send(fd
, (char *)buf
, 3, 0);
2677 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2678 send(fd
, (char *)buf
, 3, 0);
2681 static void socket_set_nodelay(int fd
)
2684 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2687 static void tcp_chr_accept(void *opaque
)
2689 CharDriverState
*chr
= opaque
;
2690 TCPCharDriver
*s
= chr
->opaque
;
2691 struct sockaddr_in saddr
;
2693 struct sockaddr_un uaddr
;
2695 struct sockaddr
*addr
;
2702 len
= sizeof(uaddr
);
2703 addr
= (struct sockaddr
*)&uaddr
;
2707 len
= sizeof(saddr
);
2708 addr
= (struct sockaddr
*)&saddr
;
2710 fd
= accept(s
->listen_fd
, addr
, &len
);
2711 if (fd
< 0 && errno
!= EINTR
) {
2713 } else if (fd
>= 0) {
2714 if (s
->do_telnetopt
)
2715 tcp_chr_telnet_init(fd
);
2719 socket_set_nonblock(fd
);
2721 socket_set_nodelay(fd
);
2723 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2724 tcp_chr_connect(chr
);
2727 static void tcp_chr_close(CharDriverState
*chr
)
2729 TCPCharDriver
*s
= chr
->opaque
;
2732 if (s
->listen_fd
>= 0)
2733 closesocket(s
->listen_fd
);
2737 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2741 CharDriverState
*chr
= NULL
;
2742 TCPCharDriver
*s
= NULL
;
2743 int fd
= -1, ret
, err
, val
;
2745 int is_waitconnect
= 1;
2748 struct sockaddr_in saddr
;
2750 struct sockaddr_un uaddr
;
2752 struct sockaddr
*addr
;
2757 addr
= (struct sockaddr
*)&uaddr
;
2758 addrlen
= sizeof(uaddr
);
2759 if (parse_unix_path(&uaddr
, host_str
) < 0)
2764 addr
= (struct sockaddr
*)&saddr
;
2765 addrlen
= sizeof(saddr
);
2766 if (parse_host_port(&saddr
, host_str
) < 0)
2771 while((ptr
= strchr(ptr
,','))) {
2773 if (!strncmp(ptr
,"server",6)) {
2775 } else if (!strncmp(ptr
,"nowait",6)) {
2777 } else if (!strncmp(ptr
,"nodelay",6)) {
2780 printf("Unknown option: %s\n", ptr
);
2787 chr
= qemu_mallocz(sizeof(CharDriverState
));
2790 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2796 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2799 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2804 if (!is_waitconnect
)
2805 socket_set_nonblock(fd
);
2810 s
->is_unix
= is_unix
;
2811 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2814 chr
->chr_write
= tcp_chr_write
;
2815 chr
->chr_close
= tcp_chr_close
;
2818 /* allow fast reuse */
2822 strncpy(path
, uaddr
.sun_path
, 108);
2829 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2832 ret
= bind(fd
, addr
, addrlen
);
2836 ret
= listen(fd
, 0);
2841 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2843 s
->do_telnetopt
= 1;
2846 ret
= connect(fd
, addr
, addrlen
);
2848 err
= socket_error();
2849 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2850 } else if (err
== EINPROGRESS
) {
2861 socket_set_nodelay(fd
);
2863 tcp_chr_connect(chr
);
2865 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2868 if (is_listen
&& is_waitconnect
) {
2869 printf("QEMU waiting for connection on: %s\n", host_str
);
2870 tcp_chr_accept(chr
);
2871 socket_set_nonblock(s
->listen_fd
);
2883 CharDriverState
*qemu_chr_open(const char *filename
)
2887 if (!strcmp(filename
, "vc")) {
2888 return text_console_init(&display_state
);
2889 } else if (!strcmp(filename
, "null")) {
2890 return qemu_chr_open_null();
2892 if (strstart(filename
, "tcp:", &p
)) {
2893 return qemu_chr_open_tcp(p
, 0, 0);
2895 if (strstart(filename
, "telnet:", &p
)) {
2896 return qemu_chr_open_tcp(p
, 1, 0);
2898 if (strstart(filename
, "udp:", &p
)) {
2899 return qemu_chr_open_udp(p
);
2901 if (strstart(filename
, "mon:", &p
)) {
2902 CharDriverState
*drv
= qemu_chr_open(p
);
2904 drv
= qemu_chr_open_mux(drv
);
2905 monitor_init(drv
, !nographic
);
2908 printf("Unable to open driver: %s\n", p
);
2912 if (strstart(filename
, "unix:", &p
)) {
2913 return qemu_chr_open_tcp(p
, 0, 1);
2914 } else if (strstart(filename
, "file:", &p
)) {
2915 return qemu_chr_open_file_out(p
);
2916 } else if (strstart(filename
, "pipe:", &p
)) {
2917 return qemu_chr_open_pipe(p
);
2918 } else if (!strcmp(filename
, "pty")) {
2919 return qemu_chr_open_pty();
2920 } else if (!strcmp(filename
, "stdio")) {
2921 return qemu_chr_open_stdio();
2924 #if defined(__linux__)
2925 if (strstart(filename
, "/dev/parport", NULL
)) {
2926 return qemu_chr_open_pp(filename
);
2928 if (strstart(filename
, "/dev/", NULL
)) {
2929 return qemu_chr_open_tty(filename
);
2933 if (strstart(filename
, "COM", NULL
)) {
2934 return qemu_chr_open_win(filename
);
2936 if (strstart(filename
, "pipe:", &p
)) {
2937 return qemu_chr_open_win_pipe(p
);
2939 if (strstart(filename
, "file:", &p
)) {
2940 return qemu_chr_open_win_file_out(p
);
2948 void qemu_chr_close(CharDriverState
*chr
)
2951 chr
->chr_close(chr
);
2954 /***********************************************************/
2955 /* network device redirectors */
2957 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2961 for(i
=0;i
<size
;i
+=16) {
2965 fprintf(f
, "%08x ", i
);
2968 fprintf(f
, " %02x", buf
[i
+j
]);
2973 for(j
=0;j
<len
;j
++) {
2975 if (c
< ' ' || c
> '~')
2977 fprintf(f
, "%c", c
);
2983 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2986 for(i
= 0; i
< 6; i
++) {
2987 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3000 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3005 p1
= strchr(p
, sep
);
3011 if (len
> buf_size
- 1)
3013 memcpy(buf
, p
, len
);
3020 int parse_host_src_port(struct sockaddr_in
*haddr
,
3021 struct sockaddr_in
*saddr
,
3022 const char *input_str
)
3024 char *str
= strdup(input_str
);
3025 char *host_str
= str
;
3030 * Chop off any extra arguments at the end of the string which
3031 * would start with a comma, then fill in the src port information
3032 * if it was provided else use the "any address" and "any port".
3034 if ((ptr
= strchr(str
,',')))
3037 if ((src_str
= strchr(input_str
,'@'))) {
3042 if (parse_host_port(haddr
, host_str
) < 0)
3045 if (!src_str
|| *src_str
== '\0')
3048 if (parse_host_port(saddr
, src_str
) < 0)
3059 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3067 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3069 saddr
->sin_family
= AF_INET
;
3070 if (buf
[0] == '\0') {
3071 saddr
->sin_addr
.s_addr
= 0;
3073 if (isdigit(buf
[0])) {
3074 if (!inet_aton(buf
, &saddr
->sin_addr
))
3077 if ((he
= gethostbyname(buf
)) == NULL
)
3079 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3082 port
= strtol(p
, (char **)&r
, 0);
3085 saddr
->sin_port
= htons(port
);
3090 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3095 len
= MIN(108, strlen(str
));
3096 p
= strchr(str
, ',');
3098 len
= MIN(len
, p
- str
);
3100 memset(uaddr
, 0, sizeof(*uaddr
));
3102 uaddr
->sun_family
= AF_UNIX
;
3103 memcpy(uaddr
->sun_path
, str
, len
);
3109 /* find or alloc a new VLAN */
3110 VLANState
*qemu_find_vlan(int id
)
3112 VLANState
**pvlan
, *vlan
;
3113 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3117 vlan
= qemu_mallocz(sizeof(VLANState
));
3122 pvlan
= &first_vlan
;
3123 while (*pvlan
!= NULL
)
3124 pvlan
= &(*pvlan
)->next
;
3129 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3130 IOReadHandler
*fd_read
,
3131 IOCanRWHandler
*fd_can_read
,
3134 VLANClientState
*vc
, **pvc
;
3135 vc
= qemu_mallocz(sizeof(VLANClientState
));
3138 vc
->fd_read
= fd_read
;
3139 vc
->fd_can_read
= fd_can_read
;
3140 vc
->opaque
= opaque
;
3144 pvc
= &vlan
->first_client
;
3145 while (*pvc
!= NULL
)
3146 pvc
= &(*pvc
)->next
;
3151 int qemu_can_send_packet(VLANClientState
*vc1
)
3153 VLANState
*vlan
= vc1
->vlan
;
3154 VLANClientState
*vc
;
3156 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3158 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
3165 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3167 VLANState
*vlan
= vc1
->vlan
;
3168 VLANClientState
*vc
;
3171 printf("vlan %d send:\n", vlan
->id
);
3172 hex_dump(stdout
, buf
, size
);
3174 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3176 vc
->fd_read(vc
->opaque
, buf
, size
);
3181 #if defined(CONFIG_SLIRP)
3183 /* slirp network adapter */
3185 static int slirp_inited
;
3186 static VLANClientState
*slirp_vc
;
3188 int slirp_can_output(void)
3190 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3193 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3196 printf("slirp output:\n");
3197 hex_dump(stdout
, pkt
, pkt_len
);
3201 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3204 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3207 printf("slirp input:\n");
3208 hex_dump(stdout
, buf
, size
);
3210 slirp_input(buf
, size
);
3213 static int net_slirp_init(VLANState
*vlan
)
3215 if (!slirp_inited
) {
3219 slirp_vc
= qemu_new_vlan_client(vlan
,
3220 slirp_receive
, NULL
, NULL
);
3221 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3225 static void net_slirp_redir(const char *redir_str
)
3230 struct in_addr guest_addr
;
3231 int host_port
, guest_port
;
3233 if (!slirp_inited
) {
3239 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3241 if (!strcmp(buf
, "tcp")) {
3243 } else if (!strcmp(buf
, "udp")) {
3249 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3251 host_port
= strtol(buf
, &r
, 0);
3255 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3257 if (buf
[0] == '\0') {
3258 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3260 if (!inet_aton(buf
, &guest_addr
))
3263 guest_port
= strtol(p
, &r
, 0);
3267 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3268 fprintf(stderr
, "qemu: could not set up redirection\n");
3273 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3281 static void smb_exit(void)
3285 char filename
[1024];
3287 /* erase all the files in the directory */
3288 d
= opendir(smb_dir
);
3293 if (strcmp(de
->d_name
, ".") != 0 &&
3294 strcmp(de
->d_name
, "..") != 0) {
3295 snprintf(filename
, sizeof(filename
), "%s/%s",
3296 smb_dir
, de
->d_name
);
3304 /* automatic user mode samba server configuration */
3305 void net_slirp_smb(const char *exported_dir
)
3307 char smb_conf
[1024];
3308 char smb_cmdline
[1024];
3311 if (!slirp_inited
) {
3316 /* XXX: better tmp dir construction */
3317 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3318 if (mkdir(smb_dir
, 0700) < 0) {
3319 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3322 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3324 f
= fopen(smb_conf
, "w");
3326 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3333 "socket address=127.0.0.1\n"
3334 "pid directory=%s\n"
3335 "lock directory=%s\n"
3336 "log file=%s/log.smbd\n"
3337 "smb passwd file=%s/smbpasswd\n"
3338 "security = share\n"
3353 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3354 SMBD_COMMAND
, smb_conf
);
3356 slirp_add_exec(0, smb_cmdline
, 4, 139);
3359 #endif /* !defined(_WIN32) */
3361 #endif /* CONFIG_SLIRP */
3363 #if !defined(_WIN32)
3365 typedef struct TAPState
{
3366 VLANClientState
*vc
;
3370 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3372 TAPState
*s
= opaque
;
3375 ret
= write(s
->fd
, buf
, size
);
3376 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3383 static void tap_send(void *opaque
)
3385 TAPState
*s
= opaque
;
3392 sbuf
.maxlen
= sizeof(buf
);
3394 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3396 size
= read(s
->fd
, buf
, sizeof(buf
));
3399 qemu_send_packet(s
->vc
, buf
, size
);
3405 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3409 s
= qemu_mallocz(sizeof(TAPState
));
3413 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3414 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3415 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3420 static int tap_open(char *ifname
, int ifname_size
)
3426 fd
= open("/dev/tap", O_RDWR
);
3428 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3433 dev
= devname(s
.st_rdev
, S_IFCHR
);
3434 pstrcpy(ifname
, ifname_size
, dev
);
3436 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3439 #elif defined(__sun__)
3440 #define TUNNEWPPA (('T'<<16) | 0x0001)
3442 * Allocate TAP device, returns opened fd.
3443 * Stores dev name in the first arg(must be large enough).
3445 int tap_alloc(char *dev
)
3447 int tap_fd
, if_fd
, ppa
= -1;
3448 static int ip_fd
= 0;
3451 static int arp_fd
= 0;
3452 int ip_muxid
, arp_muxid
;
3453 struct strioctl strioc_if
, strioc_ppa
;
3454 int link_type
= I_PLINK
;;
3456 char actual_name
[32] = "";
3458 memset(&ifr
, 0x0, sizeof(ifr
));
3462 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
3466 /* Check if IP device was opened */
3470 if( (ip_fd
= open("/dev/udp", O_RDWR
, 0)) < 0){
3471 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
3475 if( (tap_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3476 syslog(LOG_ERR
, "Can't open /dev/tap");
3480 /* Assign a new PPA and get its unit number. */
3481 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
3482 strioc_ppa
.ic_timout
= 0;
3483 strioc_ppa
.ic_len
= sizeof(ppa
);
3484 strioc_ppa
.ic_dp
= (char *)&ppa
;
3485 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
3486 syslog (LOG_ERR
, "Can't assign new interface");
3488 if( (if_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3489 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
3492 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
3493 syslog(LOG_ERR
, "Can't push IP module");
3497 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
3498 syslog(LOG_ERR
, "Can't get flags\n");
3500 snprintf (actual_name
, 32, "tap%d", ppa
);
3501 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3504 /* Assign ppa according to the unit number returned by tun device */
3506 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
3507 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
3508 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
3509 syslog (LOG_ERR
, "Can't get flags\n");
3510 /* Push arp module to if_fd */
3511 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
3512 syslog (LOG_ERR
, "Can't push ARP module (2)");
3514 /* Push arp module to ip_fd */
3515 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
3516 syslog (LOG_ERR
, "I_POP failed\n");
3517 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
3518 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
3520 if ((arp_fd
= open ("/dev/tap", O_RDWR
, 0)) < 0)
3521 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
3523 /* Set ifname to arp */
3524 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
3525 strioc_if
.ic_timout
= 0;
3526 strioc_if
.ic_len
= sizeof(ifr
);
3527 strioc_if
.ic_dp
= (char *)&ifr
;
3528 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
3529 syslog (LOG_ERR
, "Can't set ifname to arp\n");
3532 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
3533 syslog(LOG_ERR
, "Can't link TAP device to IP");
3537 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
3538 syslog (LOG_ERR
, "Can't link TAP device to ARP");
3542 memset(&ifr
, 0x0, sizeof(ifr
));
3543 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3544 ifr
.lifr_ip_muxid
= ip_muxid
;
3545 ifr
.lifr_arp_muxid
= arp_muxid
;
3547 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
3549 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
3550 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
3551 syslog (LOG_ERR
, "Can't set multiplexor id");
3554 sprintf(dev
, "tap%d", ppa
);
3558 static int tap_open(char *ifname
, int ifname_size
)
3562 if( (fd
= tap_alloc(dev
)) < 0 ){
3563 fprintf(stderr
, "Cannot allocate TAP device\n");
3566 pstrcpy(ifname
, ifname_size
, dev
);
3567 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3571 static int tap_open(char *ifname
, int ifname_size
)
3576 fd
= open("/dev/net/tun", O_RDWR
);
3578 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3581 memset(&ifr
, 0, sizeof(ifr
));
3582 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3583 if (ifname
[0] != '\0')
3584 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3586 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3587 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3589 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3593 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3594 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3599 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3600 const char *setup_script
)
3603 int pid
, status
, fd
;
3608 if (ifname1
!= NULL
)
3609 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3612 fd
= tap_open(ifname
, sizeof(ifname
));
3616 if (!setup_script
|| !strcmp(setup_script
, "no"))
3618 if (setup_script
[0] != '\0') {
3619 /* try to launch network init script */
3624 *parg
++ = (char *)setup_script
;
3627 execv(setup_script
, args
);
3630 while (waitpid(pid
, &status
, 0) != pid
);
3631 if (!WIFEXITED(status
) ||
3632 WEXITSTATUS(status
) != 0) {
3633 fprintf(stderr
, "%s: could not launch network script\n",
3639 s
= net_tap_fd_init(vlan
, fd
);
3642 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3643 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3647 #endif /* !_WIN32 */
3649 /* network connection */
3650 typedef struct NetSocketState
{
3651 VLANClientState
*vc
;
3653 int state
; /* 0 = getting length, 1 = getting data */
3657 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3660 typedef struct NetSocketListenState
{
3663 } NetSocketListenState
;
3665 /* XXX: we consider we can send the whole packet without blocking */
3666 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3668 NetSocketState
*s
= opaque
;
3672 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3673 send_all(s
->fd
, buf
, size
);
3676 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3678 NetSocketState
*s
= opaque
;
3679 sendto(s
->fd
, buf
, size
, 0,
3680 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3683 static void net_socket_send(void *opaque
)
3685 NetSocketState
*s
= opaque
;
3690 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3692 err
= socket_error();
3693 if (err
!= EWOULDBLOCK
)
3695 } else if (size
== 0) {
3696 /* end of connection */
3698 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3704 /* reassemble a packet from the network */
3710 memcpy(s
->buf
+ s
->index
, buf
, l
);
3714 if (s
->index
== 4) {
3716 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3722 l
= s
->packet_len
- s
->index
;
3725 memcpy(s
->buf
+ s
->index
, buf
, l
);
3729 if (s
->index
>= s
->packet_len
) {
3730 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3739 static void net_socket_send_dgram(void *opaque
)
3741 NetSocketState
*s
= opaque
;
3744 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3748 /* end of connection */
3749 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3752 qemu_send_packet(s
->vc
, s
->buf
, size
);
3755 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3760 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3761 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3762 inet_ntoa(mcastaddr
->sin_addr
),
3763 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3767 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3769 perror("socket(PF_INET, SOCK_DGRAM)");
3774 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3775 (const char *)&val
, sizeof(val
));
3777 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3781 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3787 /* Add host to multicast group */
3788 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3789 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3791 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3792 (const char *)&imr
, sizeof(struct ip_mreq
));
3794 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3798 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3800 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3801 (const char *)&val
, sizeof(val
));
3803 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3807 socket_set_nonblock(fd
);
3815 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3818 struct sockaddr_in saddr
;
3820 socklen_t saddr_len
;
3823 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3824 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3825 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3829 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3831 if (saddr
.sin_addr
.s_addr
==0) {
3832 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3836 /* clone dgram socket */
3837 newfd
= net_socket_mcast_create(&saddr
);
3839 /* error already reported by net_socket_mcast_create() */
3843 /* clone newfd to fd, close newfd */
3848 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3849 fd
, strerror(errno
));
3854 s
= qemu_mallocz(sizeof(NetSocketState
));
3859 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3860 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3862 /* mcast: save bound address as dst */
3863 if (is_connected
) s
->dgram_dst
=saddr
;
3865 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3866 "socket: fd=%d (%s mcast=%s:%d)",
3867 fd
, is_connected
? "cloned" : "",
3868 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3872 static void net_socket_connect(void *opaque
)
3874 NetSocketState
*s
= opaque
;
3875 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3878 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3882 s
= qemu_mallocz(sizeof(NetSocketState
));
3886 s
->vc
= qemu_new_vlan_client(vlan
,
3887 net_socket_receive
, NULL
, s
);
3888 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3889 "socket: fd=%d", fd
);
3891 net_socket_connect(s
);
3893 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3898 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3901 int so_type
=-1, optlen
=sizeof(so_type
);
3903 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3904 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3909 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3911 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3913 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3914 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3915 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3920 static void net_socket_accept(void *opaque
)
3922 NetSocketListenState
*s
= opaque
;
3924 struct sockaddr_in saddr
;
3929 len
= sizeof(saddr
);
3930 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3931 if (fd
< 0 && errno
!= EINTR
) {
3933 } else if (fd
>= 0) {
3937 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3941 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3942 "socket: connection from %s:%d",
3943 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3947 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3949 NetSocketListenState
*s
;
3951 struct sockaddr_in saddr
;
3953 if (parse_host_port(&saddr
, host_str
) < 0)
3956 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3960 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3965 socket_set_nonblock(fd
);
3967 /* allow fast reuse */
3969 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3971 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3976 ret
= listen(fd
, 0);
3983 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3987 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3990 int fd
, connected
, ret
, err
;
3991 struct sockaddr_in saddr
;
3993 if (parse_host_port(&saddr
, host_str
) < 0)
3996 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4001 socket_set_nonblock(fd
);
4005 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4007 err
= socket_error();
4008 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4009 } else if (err
== EINPROGRESS
) {
4021 s
= net_socket_fd_init(vlan
, fd
, connected
);
4024 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4025 "socket: connect to %s:%d",
4026 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4030 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4034 struct sockaddr_in saddr
;
4036 if (parse_host_port(&saddr
, host_str
) < 0)
4040 fd
= net_socket_mcast_create(&saddr
);
4044 s
= net_socket_fd_init(vlan
, fd
, 0);
4048 s
->dgram_dst
= saddr
;
4050 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4051 "socket: mcast=%s:%d",
4052 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4057 static int get_param_value(char *buf
, int buf_size
,
4058 const char *tag
, const char *str
)
4067 while (*p
!= '\0' && *p
!= '=') {
4068 if ((q
- option
) < sizeof(option
) - 1)
4076 if (!strcmp(tag
, option
)) {
4078 while (*p
!= '\0' && *p
!= ',') {
4079 if ((q
- buf
) < buf_size
- 1)
4086 while (*p
!= '\0' && *p
!= ',') {
4097 static int net_client_init(const char *str
)
4108 while (*p
!= '\0' && *p
!= ',') {
4109 if ((q
- device
) < sizeof(device
) - 1)
4117 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4118 vlan_id
= strtol(buf
, NULL
, 0);
4120 vlan
= qemu_find_vlan(vlan_id
);
4122 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4125 if (!strcmp(device
, "nic")) {
4129 if (nb_nics
>= MAX_NICS
) {
4130 fprintf(stderr
, "Too Many NICs\n");
4133 nd
= &nd_table
[nb_nics
];
4134 macaddr
= nd
->macaddr
;
4140 macaddr
[5] = 0x56 + nb_nics
;
4142 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4143 if (parse_macaddr(macaddr
, buf
) < 0) {
4144 fprintf(stderr
, "invalid syntax for ethernet address\n");
4148 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4149 nd
->model
= strdup(buf
);
4155 if (!strcmp(device
, "none")) {
4156 /* does nothing. It is needed to signal that no network cards
4161 if (!strcmp(device
, "user")) {
4162 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4163 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4165 ret
= net_slirp_init(vlan
);
4169 if (!strcmp(device
, "tap")) {
4171 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4172 fprintf(stderr
, "tap: no interface name\n");
4175 ret
= tap_win32_init(vlan
, ifname
);
4178 if (!strcmp(device
, "tap")) {
4180 char setup_script
[1024];
4182 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4183 fd
= strtol(buf
, NULL
, 0);
4185 if (net_tap_fd_init(vlan
, fd
))
4188 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4191 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4192 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4194 ret
= net_tap_init(vlan
, ifname
, setup_script
);
4198 if (!strcmp(device
, "socket")) {
4199 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4201 fd
= strtol(buf
, NULL
, 0);
4203 if (net_socket_fd_init(vlan
, fd
, 1))
4205 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4206 ret
= net_socket_listen_init(vlan
, buf
);
4207 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4208 ret
= net_socket_connect_init(vlan
, buf
);
4209 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4210 ret
= net_socket_mcast_init(vlan
, buf
);
4212 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4217 fprintf(stderr
, "Unknown network device: %s\n", device
);
4221 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4227 void do_info_network(void)
4230 VLANClientState
*vc
;
4232 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4233 term_printf("VLAN %d devices:\n", vlan
->id
);
4234 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4235 term_printf(" %s\n", vc
->info_str
);
4239 /***********************************************************/
4242 static USBPort
*used_usb_ports
;
4243 static USBPort
*free_usb_ports
;
4245 /* ??? Maybe change this to register a hub to keep track of the topology. */
4246 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
4247 usb_attachfn attach
)
4249 port
->opaque
= opaque
;
4250 port
->index
= index
;
4251 port
->attach
= attach
;
4252 port
->next
= free_usb_ports
;
4253 free_usb_ports
= port
;
4256 static int usb_device_add(const char *devname
)
4262 if (!free_usb_ports
)
4265 if (strstart(devname
, "host:", &p
)) {
4266 dev
= usb_host_device_open(p
);
4267 } else if (!strcmp(devname
, "mouse")) {
4268 dev
= usb_mouse_init();
4269 } else if (!strcmp(devname
, "tablet")) {
4270 dev
= usb_tablet_init();
4271 } else if (strstart(devname
, "disk:", &p
)) {
4272 dev
= usb_msd_init(p
);
4279 /* Find a USB port to add the device to. */
4280 port
= free_usb_ports
;
4284 /* Create a new hub and chain it on. */
4285 free_usb_ports
= NULL
;
4286 port
->next
= used_usb_ports
;
4287 used_usb_ports
= port
;
4289 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
4290 usb_attach(port
, hub
);
4291 port
= free_usb_ports
;
4294 free_usb_ports
= port
->next
;
4295 port
->next
= used_usb_ports
;
4296 used_usb_ports
= port
;
4297 usb_attach(port
, dev
);
4301 static int usb_device_del(const char *devname
)
4309 if (!used_usb_ports
)
4312 p
= strchr(devname
, '.');
4315 bus_num
= strtoul(devname
, NULL
, 0);
4316 addr
= strtoul(p
+ 1, NULL
, 0);
4320 lastp
= &used_usb_ports
;
4321 port
= used_usb_ports
;
4322 while (port
&& port
->dev
->addr
!= addr
) {
4323 lastp
= &port
->next
;
4331 *lastp
= port
->next
;
4332 usb_attach(port
, NULL
);
4333 dev
->handle_destroy(dev
);
4334 port
->next
= free_usb_ports
;
4335 free_usb_ports
= port
;
4339 void do_usb_add(const char *devname
)
4342 ret
= usb_device_add(devname
);
4344 term_printf("Could not add USB device '%s'\n", devname
);
4347 void do_usb_del(const char *devname
)
4350 ret
= usb_device_del(devname
);
4352 term_printf("Could not remove USB device '%s'\n", devname
);
4359 const char *speed_str
;
4362 term_printf("USB support not enabled\n");
4366 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4370 switch(dev
->speed
) {
4374 case USB_SPEED_FULL
:
4377 case USB_SPEED_HIGH
:
4384 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4385 0, dev
->addr
, speed_str
, dev
->devname
);
4389 /***********************************************************/
4392 static char *pid_filename
;
4394 /* Remove PID file. Called on normal exit */
4396 static void remove_pidfile(void)
4398 unlink (pid_filename
);
4401 static void create_pidfile(const char *filename
)
4403 struct stat pidstat
;
4406 /* Try to write our PID to the named file */
4407 if (stat(filename
, &pidstat
) < 0) {
4408 if (errno
== ENOENT
) {
4409 if ((f
= fopen (filename
, "w")) == NULL
) {
4410 perror("Opening pidfile");
4413 fprintf(f
, "%d\n", getpid());
4415 pid_filename
= qemu_strdup(filename
);
4416 if (!pid_filename
) {
4417 fprintf(stderr
, "Could not save PID filename");
4420 atexit(remove_pidfile
);
4423 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4429 /***********************************************************/
4432 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4436 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4440 static void dumb_refresh(DisplayState
*ds
)
4445 void dumb_display_init(DisplayState
*ds
)
4450 ds
->dpy_update
= dumb_update
;
4451 ds
->dpy_resize
= dumb_resize
;
4452 ds
->dpy_refresh
= dumb_refresh
;
4455 /***********************************************************/
4458 #define MAX_IO_HANDLERS 64
4460 typedef struct IOHandlerRecord
{
4462 IOCanRWHandler
*fd_read_poll
;
4464 IOHandler
*fd_write
;
4467 /* temporary data */
4469 struct IOHandlerRecord
*next
;
4472 static IOHandlerRecord
*first_io_handler
;
4474 /* XXX: fd_read_poll should be suppressed, but an API change is
4475 necessary in the character devices to suppress fd_can_read(). */
4476 int qemu_set_fd_handler2(int fd
,
4477 IOCanRWHandler
*fd_read_poll
,
4479 IOHandler
*fd_write
,
4482 IOHandlerRecord
**pioh
, *ioh
;
4484 if (!fd_read
&& !fd_write
) {
4485 pioh
= &first_io_handler
;
4490 if (ioh
->fd
== fd
) {
4497 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4501 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4504 ioh
->next
= first_io_handler
;
4505 first_io_handler
= ioh
;
4508 ioh
->fd_read_poll
= fd_read_poll
;
4509 ioh
->fd_read
= fd_read
;
4510 ioh
->fd_write
= fd_write
;
4511 ioh
->opaque
= opaque
;
4517 int qemu_set_fd_handler(int fd
,
4519 IOHandler
*fd_write
,
4522 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4525 /***********************************************************/
4526 /* Polling handling */
4528 typedef struct PollingEntry
{
4531 struct PollingEntry
*next
;
4534 static PollingEntry
*first_polling_entry
;
4536 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4538 PollingEntry
**ppe
, *pe
;
4539 pe
= qemu_mallocz(sizeof(PollingEntry
));
4543 pe
->opaque
= opaque
;
4544 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4549 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4551 PollingEntry
**ppe
, *pe
;
4552 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4554 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4563 /***********************************************************/
4564 /* Wait objects support */
4565 typedef struct WaitObjects
{
4567 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4568 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4569 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4572 static WaitObjects wait_objects
= {0};
4574 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4576 WaitObjects
*w
= &wait_objects
;
4578 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4580 w
->events
[w
->num
] = handle
;
4581 w
->func
[w
->num
] = func
;
4582 w
->opaque
[w
->num
] = opaque
;
4587 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4590 WaitObjects
*w
= &wait_objects
;
4593 for (i
= 0; i
< w
->num
; i
++) {
4594 if (w
->events
[i
] == handle
)
4597 w
->events
[i
] = w
->events
[i
+ 1];
4598 w
->func
[i
] = w
->func
[i
+ 1];
4599 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4607 /***********************************************************/
4608 /* savevm/loadvm support */
4610 #define IO_BUF_SIZE 32768
4614 BlockDriverState
*bs
;
4617 int64_t base_offset
;
4618 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4621 int buf_size
; /* 0 when writing */
4622 uint8_t buf
[IO_BUF_SIZE
];
4625 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4629 f
= qemu_mallocz(sizeof(QEMUFile
));
4632 if (!strcmp(mode
, "wb")) {
4634 } else if (!strcmp(mode
, "rb")) {
4639 f
->outfile
= fopen(filename
, mode
);
4651 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4655 f
= qemu_mallocz(sizeof(QEMUFile
));
4660 f
->is_writable
= is_writable
;
4661 f
->base_offset
= offset
;
4665 void qemu_fflush(QEMUFile
*f
)
4667 if (!f
->is_writable
)
4669 if (f
->buf_index
> 0) {
4671 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4672 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4674 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4675 f
->buf
, f
->buf_index
);
4677 f
->buf_offset
+= f
->buf_index
;
4682 static void qemu_fill_buffer(QEMUFile
*f
)
4689 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4690 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4694 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4695 f
->buf
, IO_BUF_SIZE
);
4701 f
->buf_offset
+= len
;
4704 void qemu_fclose(QEMUFile
*f
)
4714 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4718 l
= IO_BUF_SIZE
- f
->buf_index
;
4721 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4725 if (f
->buf_index
>= IO_BUF_SIZE
)
4730 void qemu_put_byte(QEMUFile
*f
, int v
)
4732 f
->buf
[f
->buf_index
++] = v
;
4733 if (f
->buf_index
>= IO_BUF_SIZE
)
4737 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4743 l
= f
->buf_size
- f
->buf_index
;
4745 qemu_fill_buffer(f
);
4746 l
= f
->buf_size
- f
->buf_index
;
4752 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4757 return size1
- size
;
4760 int qemu_get_byte(QEMUFile
*f
)
4762 if (f
->buf_index
>= f
->buf_size
) {
4763 qemu_fill_buffer(f
);
4764 if (f
->buf_index
>= f
->buf_size
)
4767 return f
->buf
[f
->buf_index
++];
4770 int64_t qemu_ftell(QEMUFile
*f
)
4772 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4775 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4777 if (whence
== SEEK_SET
) {
4779 } else if (whence
== SEEK_CUR
) {
4780 pos
+= qemu_ftell(f
);
4782 /* SEEK_END not supported */
4785 if (f
->is_writable
) {
4787 f
->buf_offset
= pos
;
4789 f
->buf_offset
= pos
;
4796 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4798 qemu_put_byte(f
, v
>> 8);
4799 qemu_put_byte(f
, v
);
4802 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4804 qemu_put_byte(f
, v
>> 24);
4805 qemu_put_byte(f
, v
>> 16);
4806 qemu_put_byte(f
, v
>> 8);
4807 qemu_put_byte(f
, v
);
4810 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4812 qemu_put_be32(f
, v
>> 32);
4813 qemu_put_be32(f
, v
);
4816 unsigned int qemu_get_be16(QEMUFile
*f
)
4819 v
= qemu_get_byte(f
) << 8;
4820 v
|= qemu_get_byte(f
);
4824 unsigned int qemu_get_be32(QEMUFile
*f
)
4827 v
= qemu_get_byte(f
) << 24;
4828 v
|= qemu_get_byte(f
) << 16;
4829 v
|= qemu_get_byte(f
) << 8;
4830 v
|= qemu_get_byte(f
);
4834 uint64_t qemu_get_be64(QEMUFile
*f
)
4837 v
= (uint64_t)qemu_get_be32(f
) << 32;
4838 v
|= qemu_get_be32(f
);
4842 typedef struct SaveStateEntry
{
4846 SaveStateHandler
*save_state
;
4847 LoadStateHandler
*load_state
;
4849 struct SaveStateEntry
*next
;
4852 static SaveStateEntry
*first_se
;
4854 int register_savevm(const char *idstr
,
4857 SaveStateHandler
*save_state
,
4858 LoadStateHandler
*load_state
,
4861 SaveStateEntry
*se
, **pse
;
4863 se
= qemu_malloc(sizeof(SaveStateEntry
));
4866 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4867 se
->instance_id
= instance_id
;
4868 se
->version_id
= version_id
;
4869 se
->save_state
= save_state
;
4870 se
->load_state
= load_state
;
4871 se
->opaque
= opaque
;
4874 /* add at the end of list */
4876 while (*pse
!= NULL
)
4877 pse
= &(*pse
)->next
;
4882 #define QEMU_VM_FILE_MAGIC 0x5145564d
4883 #define QEMU_VM_FILE_VERSION 0x00000002
4885 int qemu_savevm_state(QEMUFile
*f
)
4889 int64_t cur_pos
, len_pos
, total_len_pos
;
4891 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4892 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4893 total_len_pos
= qemu_ftell(f
);
4894 qemu_put_be64(f
, 0); /* total size */
4896 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4898 len
= strlen(se
->idstr
);
4899 qemu_put_byte(f
, len
);
4900 qemu_put_buffer(f
, se
->idstr
, len
);
4902 qemu_put_be32(f
, se
->instance_id
);
4903 qemu_put_be32(f
, se
->version_id
);
4905 /* record size: filled later */
4906 len_pos
= qemu_ftell(f
);
4907 qemu_put_be32(f
, 0);
4909 se
->save_state(f
, se
->opaque
);
4911 /* fill record size */
4912 cur_pos
= qemu_ftell(f
);
4913 len
= cur_pos
- len_pos
- 4;
4914 qemu_fseek(f
, len_pos
, SEEK_SET
);
4915 qemu_put_be32(f
, len
);
4916 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4918 cur_pos
= qemu_ftell(f
);
4919 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4920 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4921 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4927 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4931 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4932 if (!strcmp(se
->idstr
, idstr
) &&
4933 instance_id
== se
->instance_id
)
4939 int qemu_loadvm_state(QEMUFile
*f
)
4942 int len
, ret
, instance_id
, record_len
, version_id
;
4943 int64_t total_len
, end_pos
, cur_pos
;
4947 v
= qemu_get_be32(f
);
4948 if (v
!= QEMU_VM_FILE_MAGIC
)
4950 v
= qemu_get_be32(f
);
4951 if (v
!= QEMU_VM_FILE_VERSION
) {
4956 total_len
= qemu_get_be64(f
);
4957 end_pos
= total_len
+ qemu_ftell(f
);
4959 if (qemu_ftell(f
) >= end_pos
)
4961 len
= qemu_get_byte(f
);
4962 qemu_get_buffer(f
, idstr
, len
);
4964 instance_id
= qemu_get_be32(f
);
4965 version_id
= qemu_get_be32(f
);
4966 record_len
= qemu_get_be32(f
);
4968 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4969 idstr
, instance_id
, version_id
, record_len
);
4971 cur_pos
= qemu_ftell(f
);
4972 se
= find_se(idstr
, instance_id
);
4974 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4975 instance_id
, idstr
);
4977 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4979 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4980 instance_id
, idstr
);
4983 /* always seek to exact end of record */
4984 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4991 /* device can contain snapshots */
4992 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4995 !bdrv_is_removable(bs
) &&
4996 !bdrv_is_read_only(bs
));
4999 /* device must be snapshots in order to have a reliable snapshot */
5000 static int bdrv_has_snapshot(BlockDriverState
*bs
)
5003 !bdrv_is_removable(bs
) &&
5004 !bdrv_is_read_only(bs
));
5007 static BlockDriverState
*get_bs_snapshots(void)
5009 BlockDriverState
*bs
;
5013 return bs_snapshots
;
5014 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5016 if (bdrv_can_snapshot(bs
))
5025 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5028 QEMUSnapshotInfo
*sn_tab
, *sn
;
5032 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5035 for(i
= 0; i
< nb_sns
; i
++) {
5037 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5047 void do_savevm(const char *name
)
5049 BlockDriverState
*bs
, *bs1
;
5050 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5051 int must_delete
, ret
, i
;
5052 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5054 int saved_vm_running
;
5061 bs
= get_bs_snapshots();
5063 term_printf("No block device can accept snapshots\n");
5067 /* ??? Should this occur after vm_stop? */
5070 saved_vm_running
= vm_running
;
5075 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5080 memset(sn
, 0, sizeof(*sn
));
5082 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5083 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5086 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5089 /* fill auxiliary fields */
5092 sn
->date_sec
= tb
.time
;
5093 sn
->date_nsec
= tb
.millitm
* 1000000;
5095 gettimeofday(&tv
, NULL
);
5096 sn
->date_sec
= tv
.tv_sec
;
5097 sn
->date_nsec
= tv
.tv_usec
* 1000;
5099 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
5101 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5102 term_printf("Device %s does not support VM state snapshots\n",
5103 bdrv_get_device_name(bs
));
5107 /* save the VM state */
5108 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
5110 term_printf("Could not open VM state file\n");
5113 ret
= qemu_savevm_state(f
);
5114 sn
->vm_state_size
= qemu_ftell(f
);
5117 term_printf("Error %d while writing VM\n", ret
);
5121 /* create the snapshots */
5123 for(i
= 0; i
< MAX_DISKS
; i
++) {
5125 if (bdrv_has_snapshot(bs1
)) {
5127 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5129 term_printf("Error while deleting snapshot on '%s'\n",
5130 bdrv_get_device_name(bs1
));
5133 ret
= bdrv_snapshot_create(bs1
, sn
);
5135 term_printf("Error while creating snapshot on '%s'\n",
5136 bdrv_get_device_name(bs1
));
5142 if (saved_vm_running
)
5146 void do_loadvm(const char *name
)
5148 BlockDriverState
*bs
, *bs1
;
5149 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5152 int saved_vm_running
;
5154 bs
= get_bs_snapshots();
5156 term_printf("No block device supports snapshots\n");
5160 /* Flush all IO requests so they don't interfere with the new state. */
5163 saved_vm_running
= vm_running
;
5166 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5168 if (bdrv_has_snapshot(bs1
)) {
5169 ret
= bdrv_snapshot_goto(bs1
, name
);
5172 term_printf("Warning: ");
5175 term_printf("Snapshots not supported on device '%s'\n",
5176 bdrv_get_device_name(bs1
));
5179 term_printf("Could not find snapshot '%s' on device '%s'\n",
5180 name
, bdrv_get_device_name(bs1
));
5183 term_printf("Error %d while activating snapshot on '%s'\n",
5184 ret
, bdrv_get_device_name(bs1
));
5187 /* fatal on snapshot block device */
5194 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5195 term_printf("Device %s does not support VM state snapshots\n",
5196 bdrv_get_device_name(bs
));
5200 /* restore the VM state */
5201 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5203 term_printf("Could not open VM state file\n");
5206 ret
= qemu_loadvm_state(f
);
5209 term_printf("Error %d while loading VM state\n", ret
);
5212 if (saved_vm_running
)
5216 void do_delvm(const char *name
)
5218 BlockDriverState
*bs
, *bs1
;
5221 bs
= get_bs_snapshots();
5223 term_printf("No block device supports snapshots\n");
5227 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5229 if (bdrv_has_snapshot(bs1
)) {
5230 ret
= bdrv_snapshot_delete(bs1
, name
);
5232 if (ret
== -ENOTSUP
)
5233 term_printf("Snapshots not supported on device '%s'\n",
5234 bdrv_get_device_name(bs1
));
5236 term_printf("Error %d while deleting snapshot on '%s'\n",
5237 ret
, bdrv_get_device_name(bs1
));
5243 void do_info_snapshots(void)
5245 BlockDriverState
*bs
, *bs1
;
5246 QEMUSnapshotInfo
*sn_tab
, *sn
;
5250 bs
= get_bs_snapshots();
5252 term_printf("No available block device supports snapshots\n");
5255 term_printf("Snapshot devices:");
5256 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5258 if (bdrv_has_snapshot(bs1
)) {
5260 term_printf(" %s", bdrv_get_device_name(bs1
));
5265 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5267 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5270 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5271 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5272 for(i
= 0; i
< nb_sns
; i
++) {
5274 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5279 /***********************************************************/
5280 /* cpu save/restore */
5282 #if defined(TARGET_I386)
5284 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5286 qemu_put_be32(f
, dt
->selector
);
5287 qemu_put_betl(f
, dt
->base
);
5288 qemu_put_be32(f
, dt
->limit
);
5289 qemu_put_be32(f
, dt
->flags
);
5292 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5294 dt
->selector
= qemu_get_be32(f
);
5295 dt
->base
= qemu_get_betl(f
);
5296 dt
->limit
= qemu_get_be32(f
);
5297 dt
->flags
= qemu_get_be32(f
);
5300 void cpu_save(QEMUFile
*f
, void *opaque
)
5302 CPUState
*env
= opaque
;
5303 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5307 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5308 qemu_put_betls(f
, &env
->regs
[i
]);
5309 qemu_put_betls(f
, &env
->eip
);
5310 qemu_put_betls(f
, &env
->eflags
);
5311 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5312 qemu_put_be32s(f
, &hflags
);
5316 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5318 for(i
= 0; i
< 8; i
++) {
5319 fptag
|= ((!env
->fptags
[i
]) << i
);
5322 qemu_put_be16s(f
, &fpuc
);
5323 qemu_put_be16s(f
, &fpus
);
5324 qemu_put_be16s(f
, &fptag
);
5326 #ifdef USE_X86LDOUBLE
5331 qemu_put_be16s(f
, &fpregs_format
);
5333 for(i
= 0; i
< 8; i
++) {
5334 #ifdef USE_X86LDOUBLE
5338 /* we save the real CPU data (in case of MMX usage only 'mant'
5339 contains the MMX register */
5340 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5341 qemu_put_be64(f
, mant
);
5342 qemu_put_be16(f
, exp
);
5345 /* if we use doubles for float emulation, we save the doubles to
5346 avoid losing information in case of MMX usage. It can give
5347 problems if the image is restored on a CPU where long
5348 doubles are used instead. */
5349 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5353 for(i
= 0; i
< 6; i
++)
5354 cpu_put_seg(f
, &env
->segs
[i
]);
5355 cpu_put_seg(f
, &env
->ldt
);
5356 cpu_put_seg(f
, &env
->tr
);
5357 cpu_put_seg(f
, &env
->gdt
);
5358 cpu_put_seg(f
, &env
->idt
);
5360 qemu_put_be32s(f
, &env
->sysenter_cs
);
5361 qemu_put_be32s(f
, &env
->sysenter_esp
);
5362 qemu_put_be32s(f
, &env
->sysenter_eip
);
5364 qemu_put_betls(f
, &env
->cr
[0]);
5365 qemu_put_betls(f
, &env
->cr
[2]);
5366 qemu_put_betls(f
, &env
->cr
[3]);
5367 qemu_put_betls(f
, &env
->cr
[4]);
5369 for(i
= 0; i
< 8; i
++)
5370 qemu_put_betls(f
, &env
->dr
[i
]);
5373 qemu_put_be32s(f
, &env
->a20_mask
);
5376 qemu_put_be32s(f
, &env
->mxcsr
);
5377 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5378 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5379 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5382 #ifdef TARGET_X86_64
5383 qemu_put_be64s(f
, &env
->efer
);
5384 qemu_put_be64s(f
, &env
->star
);
5385 qemu_put_be64s(f
, &env
->lstar
);
5386 qemu_put_be64s(f
, &env
->cstar
);
5387 qemu_put_be64s(f
, &env
->fmask
);
5388 qemu_put_be64s(f
, &env
->kernelgsbase
);
5390 qemu_put_be32s(f
, &env
->smbase
);
5393 #ifdef USE_X86LDOUBLE
5394 /* XXX: add that in a FPU generic layer */
5395 union x86_longdouble
{
5400 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5401 #define EXPBIAS1 1023
5402 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5403 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5405 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5409 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5410 /* exponent + sign */
5411 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5412 e
|= SIGND1(temp
) >> 16;
5417 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5419 CPUState
*env
= opaque
;
5422 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5424 if (version_id
!= 3 && version_id
!= 4)
5426 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5427 qemu_get_betls(f
, &env
->regs
[i
]);
5428 qemu_get_betls(f
, &env
->eip
);
5429 qemu_get_betls(f
, &env
->eflags
);
5430 qemu_get_be32s(f
, &hflags
);
5432 qemu_get_be16s(f
, &fpuc
);
5433 qemu_get_be16s(f
, &fpus
);
5434 qemu_get_be16s(f
, &fptag
);
5435 qemu_get_be16s(f
, &fpregs_format
);
5437 /* NOTE: we cannot always restore the FPU state if the image come
5438 from a host with a different 'USE_X86LDOUBLE' define. We guess
5439 if we are in an MMX state to restore correctly in that case. */
5440 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5441 for(i
= 0; i
< 8; i
++) {
5445 switch(fpregs_format
) {
5447 mant
= qemu_get_be64(f
);
5448 exp
= qemu_get_be16(f
);
5449 #ifdef USE_X86LDOUBLE
5450 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5452 /* difficult case */
5454 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5456 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5460 mant
= qemu_get_be64(f
);
5461 #ifdef USE_X86LDOUBLE
5463 union x86_longdouble
*p
;
5464 /* difficult case */
5465 p
= (void *)&env
->fpregs
[i
];
5470 fp64_to_fp80(p
, mant
);
5474 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5483 /* XXX: restore FPU round state */
5484 env
->fpstt
= (fpus
>> 11) & 7;
5485 env
->fpus
= fpus
& ~0x3800;
5487 for(i
= 0; i
< 8; i
++) {
5488 env
->fptags
[i
] = (fptag
>> i
) & 1;
5491 for(i
= 0; i
< 6; i
++)
5492 cpu_get_seg(f
, &env
->segs
[i
]);
5493 cpu_get_seg(f
, &env
->ldt
);
5494 cpu_get_seg(f
, &env
->tr
);
5495 cpu_get_seg(f
, &env
->gdt
);
5496 cpu_get_seg(f
, &env
->idt
);
5498 qemu_get_be32s(f
, &env
->sysenter_cs
);
5499 qemu_get_be32s(f
, &env
->sysenter_esp
);
5500 qemu_get_be32s(f
, &env
->sysenter_eip
);
5502 qemu_get_betls(f
, &env
->cr
[0]);
5503 qemu_get_betls(f
, &env
->cr
[2]);
5504 qemu_get_betls(f
, &env
->cr
[3]);
5505 qemu_get_betls(f
, &env
->cr
[4]);
5507 for(i
= 0; i
< 8; i
++)
5508 qemu_get_betls(f
, &env
->dr
[i
]);
5511 qemu_get_be32s(f
, &env
->a20_mask
);
5513 qemu_get_be32s(f
, &env
->mxcsr
);
5514 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5515 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5516 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5519 #ifdef TARGET_X86_64
5520 qemu_get_be64s(f
, &env
->efer
);
5521 qemu_get_be64s(f
, &env
->star
);
5522 qemu_get_be64s(f
, &env
->lstar
);
5523 qemu_get_be64s(f
, &env
->cstar
);
5524 qemu_get_be64s(f
, &env
->fmask
);
5525 qemu_get_be64s(f
, &env
->kernelgsbase
);
5527 if (version_id
>= 4)
5528 qemu_get_be32s(f
, &env
->smbase
);
5530 /* XXX: compute hflags from scratch, except for CPL and IIF */
5531 env
->hflags
= hflags
;
5536 #elif defined(TARGET_PPC)
5537 void cpu_save(QEMUFile
*f
, void *opaque
)
5541 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5546 #elif defined(TARGET_MIPS)
5547 void cpu_save(QEMUFile
*f
, void *opaque
)
5551 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5556 #elif defined(TARGET_SPARC)
5557 void cpu_save(QEMUFile
*f
, void *opaque
)
5559 CPUState
*env
= opaque
;
5563 for(i
= 0; i
< 8; i
++)
5564 qemu_put_betls(f
, &env
->gregs
[i
]);
5565 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5566 qemu_put_betls(f
, &env
->regbase
[i
]);
5569 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5575 qemu_put_be32(f
, u
.i
);
5578 qemu_put_betls(f
, &env
->pc
);
5579 qemu_put_betls(f
, &env
->npc
);
5580 qemu_put_betls(f
, &env
->y
);
5582 qemu_put_be32(f
, tmp
);
5583 qemu_put_betls(f
, &env
->fsr
);
5584 qemu_put_betls(f
, &env
->tbr
);
5585 #ifndef TARGET_SPARC64
5586 qemu_put_be32s(f
, &env
->wim
);
5588 for(i
= 0; i
< 16; i
++)
5589 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5593 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5595 CPUState
*env
= opaque
;
5599 for(i
= 0; i
< 8; i
++)
5600 qemu_get_betls(f
, &env
->gregs
[i
]);
5601 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5602 qemu_get_betls(f
, &env
->regbase
[i
]);
5605 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5610 u
.i
= qemu_get_be32(f
);
5614 qemu_get_betls(f
, &env
->pc
);
5615 qemu_get_betls(f
, &env
->npc
);
5616 qemu_get_betls(f
, &env
->y
);
5617 tmp
= qemu_get_be32(f
);
5618 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5619 correctly updated */
5621 qemu_get_betls(f
, &env
->fsr
);
5622 qemu_get_betls(f
, &env
->tbr
);
5623 #ifndef TARGET_SPARC64
5624 qemu_get_be32s(f
, &env
->wim
);
5626 for(i
= 0; i
< 16; i
++)
5627 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5633 #elif defined(TARGET_ARM)
5635 /* ??? Need to implement these. */
5636 void cpu_save(QEMUFile
*f
, void *opaque
)
5640 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5647 #warning No CPU save/restore functions
5651 /***********************************************************/
5652 /* ram save/restore */
5654 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5658 v
= qemu_get_byte(f
);
5661 if (qemu_get_buffer(f
, buf
, len
) != len
)
5665 v
= qemu_get_byte(f
);
5666 memset(buf
, v
, len
);
5674 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5678 if (qemu_get_be32(f
) != phys_ram_size
)
5680 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5681 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5688 #define BDRV_HASH_BLOCK_SIZE 1024
5689 #define IOBUF_SIZE 4096
5690 #define RAM_CBLOCK_MAGIC 0xfabe
5692 typedef struct RamCompressState
{
5695 uint8_t buf
[IOBUF_SIZE
];
5698 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5701 memset(s
, 0, sizeof(*s
));
5703 ret
= deflateInit2(&s
->zstream
, 1,
5705 9, Z_DEFAULT_STRATEGY
);
5708 s
->zstream
.avail_out
= IOBUF_SIZE
;
5709 s
->zstream
.next_out
= s
->buf
;
5713 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5715 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5716 qemu_put_be16(s
->f
, len
);
5717 qemu_put_buffer(s
->f
, buf
, len
);
5720 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5724 s
->zstream
.avail_in
= len
;
5725 s
->zstream
.next_in
= (uint8_t *)buf
;
5726 while (s
->zstream
.avail_in
> 0) {
5727 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5730 if (s
->zstream
.avail_out
== 0) {
5731 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5732 s
->zstream
.avail_out
= IOBUF_SIZE
;
5733 s
->zstream
.next_out
= s
->buf
;
5739 static void ram_compress_close(RamCompressState
*s
)
5743 /* compress last bytes */
5745 ret
= deflate(&s
->zstream
, Z_FINISH
);
5746 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5747 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5749 ram_put_cblock(s
, s
->buf
, len
);
5751 s
->zstream
.avail_out
= IOBUF_SIZE
;
5752 s
->zstream
.next_out
= s
->buf
;
5753 if (ret
== Z_STREAM_END
)
5760 deflateEnd(&s
->zstream
);
5763 typedef struct RamDecompressState
{
5766 uint8_t buf
[IOBUF_SIZE
];
5767 } RamDecompressState
;
5769 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5772 memset(s
, 0, sizeof(*s
));
5774 ret
= inflateInit(&s
->zstream
);
5780 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5784 s
->zstream
.avail_out
= len
;
5785 s
->zstream
.next_out
= buf
;
5786 while (s
->zstream
.avail_out
> 0) {
5787 if (s
->zstream
.avail_in
== 0) {
5788 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5790 clen
= qemu_get_be16(s
->f
);
5791 if (clen
> IOBUF_SIZE
)
5793 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5794 s
->zstream
.avail_in
= clen
;
5795 s
->zstream
.next_in
= s
->buf
;
5797 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5798 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5805 static void ram_decompress_close(RamDecompressState
*s
)
5807 inflateEnd(&s
->zstream
);
5810 static void ram_save(QEMUFile
*f
, void *opaque
)
5813 RamCompressState s1
, *s
= &s1
;
5816 qemu_put_be32(f
, phys_ram_size
);
5817 if (ram_compress_open(s
, f
) < 0)
5819 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5821 if (tight_savevm_enabled
) {
5825 /* find if the memory block is available on a virtual
5828 for(j
= 0; j
< MAX_DISKS
; j
++) {
5830 sector_num
= bdrv_hash_find(bs_table
[j
],
5831 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5832 if (sector_num
>= 0)
5837 goto normal_compress
;
5840 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5841 ram_compress_buf(s
, buf
, 10);
5847 ram_compress_buf(s
, buf
, 1);
5848 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5851 ram_compress_close(s
);
5854 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5856 RamDecompressState s1
, *s
= &s1
;
5860 if (version_id
== 1)
5861 return ram_load_v1(f
, opaque
);
5862 if (version_id
!= 2)
5864 if (qemu_get_be32(f
) != phys_ram_size
)
5866 if (ram_decompress_open(s
, f
) < 0)
5868 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5869 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5870 fprintf(stderr
, "Error while reading ram block header\n");
5874 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5875 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5884 ram_decompress_buf(s
, buf
+ 1, 9);
5886 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5887 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5888 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5891 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5892 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5893 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5894 bs_index
, sector_num
);
5901 printf("Error block header\n");
5905 ram_decompress_close(s
);
5909 /***********************************************************/
5910 /* bottom halves (can be seen as timers which expire ASAP) */
5919 static QEMUBH
*first_bh
= NULL
;
5921 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5924 bh
= qemu_mallocz(sizeof(QEMUBH
));
5928 bh
->opaque
= opaque
;
5932 int qemu_bh_poll(void)
5951 void qemu_bh_schedule(QEMUBH
*bh
)
5953 CPUState
*env
= cpu_single_env
;
5957 bh
->next
= first_bh
;
5960 /* stop the currently executing CPU to execute the BH ASAP */
5962 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5966 void qemu_bh_cancel(QEMUBH
*bh
)
5969 if (bh
->scheduled
) {
5972 pbh
= &(*pbh
)->next
;
5978 void qemu_bh_delete(QEMUBH
*bh
)
5984 /***********************************************************/
5985 /* machine registration */
5987 QEMUMachine
*first_machine
= NULL
;
5989 int qemu_register_machine(QEMUMachine
*m
)
5992 pm
= &first_machine
;
6000 QEMUMachine
*find_machine(const char *name
)
6004 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6005 if (!strcmp(m
->name
, name
))
6011 /***********************************************************/
6012 /* main execution loop */
6014 void gui_update(void *opaque
)
6016 display_state
.dpy_refresh(&display_state
);
6017 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6020 struct vm_change_state_entry
{
6021 VMChangeStateHandler
*cb
;
6023 LIST_ENTRY (vm_change_state_entry
) entries
;
6026 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6028 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6031 VMChangeStateEntry
*e
;
6033 e
= qemu_mallocz(sizeof (*e
));
6039 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6043 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6045 LIST_REMOVE (e
, entries
);
6049 static void vm_state_notify(int running
)
6051 VMChangeStateEntry
*e
;
6053 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6054 e
->cb(e
->opaque
, running
);
6058 /* XXX: support several handlers */
6059 static VMStopHandler
*vm_stop_cb
;
6060 static void *vm_stop_opaque
;
6062 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6065 vm_stop_opaque
= opaque
;
6069 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6083 void vm_stop(int reason
)
6086 cpu_disable_ticks();
6090 vm_stop_cb(vm_stop_opaque
, reason
);
6097 /* reset/shutdown handler */
6099 typedef struct QEMUResetEntry
{
6100 QEMUResetHandler
*func
;
6102 struct QEMUResetEntry
*next
;
6105 static QEMUResetEntry
*first_reset_entry
;
6106 static int reset_requested
;
6107 static int shutdown_requested
;
6108 static int powerdown_requested
;
6110 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6112 QEMUResetEntry
**pre
, *re
;
6114 pre
= &first_reset_entry
;
6115 while (*pre
!= NULL
)
6116 pre
= &(*pre
)->next
;
6117 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6119 re
->opaque
= opaque
;
6124 static void qemu_system_reset(void)
6128 /* reset all devices */
6129 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6130 re
->func(re
->opaque
);
6134 void qemu_system_reset_request(void)
6137 shutdown_requested
= 1;
6139 reset_requested
= 1;
6142 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6145 void qemu_system_shutdown_request(void)
6147 shutdown_requested
= 1;
6149 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6152 void qemu_system_powerdown_request(void)
6154 powerdown_requested
= 1;
6156 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6159 void main_loop_wait(int timeout
)
6161 IOHandlerRecord
*ioh
;
6162 fd_set rfds
, wfds
, xfds
;
6168 /* XXX: need to suppress polling by better using win32 events */
6170 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6171 ret
|= pe
->func(pe
->opaque
);
6174 if (ret
== 0 && timeout
> 0) {
6176 WaitObjects
*w
= &wait_objects
;
6178 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6179 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6180 if (w
->func
[ret
- WAIT_OBJECT_0
])
6181 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6182 } else if (ret
== WAIT_TIMEOUT
) {
6184 err
= GetLastError();
6185 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6189 /* poll any events */
6190 /* XXX: separate device handlers from system ones */
6195 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6199 (!ioh
->fd_read_poll
||
6200 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6201 FD_SET(ioh
->fd
, &rfds
);
6205 if (ioh
->fd_write
) {
6206 FD_SET(ioh
->fd
, &wfds
);
6216 tv
.tv_usec
= timeout
* 1000;
6218 #if defined(CONFIG_SLIRP)
6220 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6223 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6225 IOHandlerRecord
**pioh
;
6227 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6230 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6231 ioh
->fd_read(ioh
->opaque
);
6233 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6234 ioh
->fd_write(ioh
->opaque
);
6238 /* remove deleted IO handlers */
6239 pioh
= &first_io_handler
;
6249 #if defined(CONFIG_SLIRP)
6256 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6263 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6264 qemu_get_clock(vm_clock
));
6265 /* run dma transfers, if any */
6269 /* real time timers */
6270 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6271 qemu_get_clock(rt_clock
));
6274 static CPUState
*cur_cpu
;
6279 #ifdef CONFIG_PROFILER
6284 cur_cpu
= first_cpu
;
6291 env
= env
->next_cpu
;
6294 #ifdef CONFIG_PROFILER
6295 ti
= profile_getclock();
6297 ret
= cpu_exec(env
);
6298 #ifdef CONFIG_PROFILER
6299 qemu_time
+= profile_getclock() - ti
;
6301 if (ret
!= EXCP_HALTED
)
6303 /* all CPUs are halted ? */
6304 if (env
== cur_cpu
) {
6311 if (shutdown_requested
) {
6312 ret
= EXCP_INTERRUPT
;
6315 if (reset_requested
) {
6316 reset_requested
= 0;
6317 qemu_system_reset();
6318 ret
= EXCP_INTERRUPT
;
6320 if (powerdown_requested
) {
6321 powerdown_requested
= 0;
6322 qemu_system_powerdown();
6323 ret
= EXCP_INTERRUPT
;
6325 if (ret
== EXCP_DEBUG
) {
6326 vm_stop(EXCP_DEBUG
);
6328 /* if hlt instruction, we wait until the next IRQ */
6329 /* XXX: use timeout computed from timers */
6330 if (ret
== EXCP_HLT
)
6337 #ifdef CONFIG_PROFILER
6338 ti
= profile_getclock();
6340 main_loop_wait(timeout
);
6341 #ifdef CONFIG_PROFILER
6342 dev_time
+= profile_getclock() - ti
;
6345 cpu_disable_ticks();
6351 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6352 "usage: %s [options] [disk_image]\n"
6354 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6356 "Standard options:\n"
6357 "-M machine select emulated machine (-M ? for list)\n"
6358 "-cpu cpu select CPU (-cpu ? for list)\n"
6359 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6360 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6361 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6362 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6363 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6364 "-snapshot write to temporary files instead of disk image files\n"
6366 "-no-frame open SDL window without a frame and window decorations\n"
6367 "-no-quit disable SDL window close capability\n"
6370 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6372 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6373 "-smp n set the number of CPUs to 'n' [default=1]\n"
6374 "-nographic disable graphical output and redirect serial I/Os to console\n"
6376 "-k language use keyboard layout (for example \"fr\" for French)\n"
6379 "-audio-help print list of audio drivers and their options\n"
6380 "-soundhw c1,... enable audio support\n"
6381 " and only specified sound cards (comma separated list)\n"
6382 " use -soundhw ? to get the list of supported cards\n"
6383 " use -soundhw all to enable all of them\n"
6385 "-localtime set the real time clock to local time [default=utc]\n"
6386 "-full-screen start in full screen\n"
6388 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6390 "-usb enable the USB driver (will be the default soon)\n"
6391 "-usbdevice name add the host or guest USB device 'name'\n"
6392 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6393 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6396 "Network options:\n"
6397 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6398 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6400 "-net user[,vlan=n][,hostname=host]\n"
6401 " connect the user mode network stack to VLAN 'n' and send\n"
6402 " hostname 'host' to DHCP clients\n"
6405 "-net tap[,vlan=n],ifname=name\n"
6406 " connect the host TAP network interface to VLAN 'n'\n"
6408 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6409 " connect the host TAP network interface to VLAN 'n' and use\n"
6410 " the network script 'file' (default=%s);\n"
6411 " use 'script=no' to disable script execution;\n"
6412 " use 'fd=h' to connect to an already opened TAP interface\n"
6414 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6415 " connect the vlan 'n' to another VLAN using a socket connection\n"
6416 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6417 " connect the vlan 'n' to multicast maddr and port\n"
6418 "-net none use it alone to have zero network devices; if no -net option\n"
6419 " is provided, the default is '-net nic -net user'\n"
6422 "-tftp dir allow tftp access to files in dir [-net user]\n"
6423 "-bootp file advertise file in BOOTP replies\n"
6425 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6427 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6428 " redirect TCP or UDP connections from host to guest [-net user]\n"
6431 "Linux boot specific:\n"
6432 "-kernel bzImage use 'bzImage' as kernel image\n"
6433 "-append cmdline use 'cmdline' as kernel command line\n"
6434 "-initrd file use 'file' as initial ram disk\n"
6436 "Debug/Expert options:\n"
6437 "-monitor dev redirect the monitor to char device 'dev'\n"
6438 "-serial dev redirect the serial port to char device 'dev'\n"
6439 "-parallel dev redirect the parallel port to char device 'dev'\n"
6440 "-pidfile file Write PID to 'file'\n"
6441 "-S freeze CPU at startup (use 'c' to start execution)\n"
6442 "-s wait gdb connection to port\n"
6443 "-p port set gdb connection port [default=%s]\n"
6444 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6445 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6446 " translation (t=none or lba) (usually qemu can guess them)\n"
6447 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6449 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6450 "-no-kqemu disable KQEMU kernel module usage\n"
6452 #ifdef USE_CODE_COPY
6453 "-no-code-copy disable code copy acceleration\n"
6456 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6457 " (default is CL-GD5446 PCI VGA)\n"
6458 "-no-acpi disable ACPI\n"
6460 "-no-reboot exit instead of rebooting\n"
6461 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6462 "-vnc display start a VNC server on display\n"
6464 "-daemonize daemonize QEMU after initializing\n"
6466 "-option-rom rom load a file, rom, into the option ROM space\n"
6468 "During emulation, the following keys are useful:\n"
6469 "ctrl-alt-f toggle full screen\n"
6470 "ctrl-alt-n switch to virtual console 'n'\n"
6471 "ctrl-alt toggle mouse and keyboard grab\n"
6473 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6478 DEFAULT_NETWORK_SCRIPT
,
6480 DEFAULT_GDBSTUB_PORT
,
6485 #define HAS_ARG 0x0001
6500 QEMU_OPTION_snapshot
,
6502 QEMU_OPTION_no_fd_bootchk
,
6505 QEMU_OPTION_nographic
,
6507 QEMU_OPTION_audio_help
,
6508 QEMU_OPTION_soundhw
,
6527 QEMU_OPTION_no_code_copy
,
6529 QEMU_OPTION_localtime
,
6530 QEMU_OPTION_cirrusvga
,
6532 QEMU_OPTION_std_vga
,
6534 QEMU_OPTION_monitor
,
6536 QEMU_OPTION_parallel
,
6538 QEMU_OPTION_full_screen
,
6539 QEMU_OPTION_no_frame
,
6540 QEMU_OPTION_no_quit
,
6541 QEMU_OPTION_pidfile
,
6542 QEMU_OPTION_no_kqemu
,
6543 QEMU_OPTION_kernel_kqemu
,
6544 QEMU_OPTION_win2k_hack
,
6546 QEMU_OPTION_usbdevice
,
6549 QEMU_OPTION_no_acpi
,
6550 QEMU_OPTION_no_reboot
,
6551 QEMU_OPTION_daemonize
,
6552 QEMU_OPTION_option_rom
,
6553 QEMU_OPTION_semihosting
6556 typedef struct QEMUOption
{
6562 const QEMUOption qemu_options
[] = {
6563 { "h", 0, QEMU_OPTION_h
},
6564 { "help", 0, QEMU_OPTION_h
},
6566 { "M", HAS_ARG
, QEMU_OPTION_M
},
6567 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
6568 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6569 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6570 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6571 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6572 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6573 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6574 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6575 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6576 { "snapshot", 0, QEMU_OPTION_snapshot
},
6578 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6580 { "m", HAS_ARG
, QEMU_OPTION_m
},
6581 { "nographic", 0, QEMU_OPTION_nographic
},
6582 { "k", HAS_ARG
, QEMU_OPTION_k
},
6584 { "audio-help", 0, QEMU_OPTION_audio_help
},
6585 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6588 { "net", HAS_ARG
, QEMU_OPTION_net
},
6590 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6591 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
6593 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6595 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6598 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6599 { "append", HAS_ARG
, QEMU_OPTION_append
},
6600 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6602 { "S", 0, QEMU_OPTION_S
},
6603 { "s", 0, QEMU_OPTION_s
},
6604 { "p", HAS_ARG
, QEMU_OPTION_p
},
6605 { "d", HAS_ARG
, QEMU_OPTION_d
},
6606 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6607 { "L", HAS_ARG
, QEMU_OPTION_L
},
6608 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6610 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6611 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6613 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6614 { "g", 1, QEMU_OPTION_g
},
6616 { "localtime", 0, QEMU_OPTION_localtime
},
6617 { "std-vga", 0, QEMU_OPTION_std_vga
},
6618 { "echr", 1, QEMU_OPTION_echr
},
6619 { "monitor", 1, QEMU_OPTION_monitor
},
6620 { "serial", 1, QEMU_OPTION_serial
},
6621 { "parallel", 1, QEMU_OPTION_parallel
},
6622 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6623 { "full-screen", 0, QEMU_OPTION_full_screen
},
6625 { "no-frame", 0, QEMU_OPTION_no_frame
},
6626 { "no-quit", 0, QEMU_OPTION_no_quit
},
6628 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6629 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6630 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6631 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6632 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6634 /* temporary options */
6635 { "usb", 0, QEMU_OPTION_usb
},
6636 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6637 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6638 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6639 { "daemonize", 0, QEMU_OPTION_daemonize
},
6640 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6641 #if defined(TARGET_ARM)
6642 { "semihosting", 0, QEMU_OPTION_semihosting
},
6647 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6649 /* this stack is only used during signal handling */
6650 #define SIGNAL_STACK_SIZE 32768
6652 static uint8_t *signal_stack
;
6656 /* password input */
6658 static BlockDriverState
*get_bdrv(int index
)
6660 BlockDriverState
*bs
;
6663 bs
= bs_table
[index
];
6664 } else if (index
< 6) {
6665 bs
= fd_table
[index
- 4];
6672 static void read_passwords(void)
6674 BlockDriverState
*bs
;
6678 for(i
= 0; i
< 6; i
++) {
6680 if (bs
&& bdrv_is_encrypted(bs
)) {
6681 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6682 for(j
= 0; j
< 3; j
++) {
6683 monitor_readline("Password: ",
6684 1, password
, sizeof(password
));
6685 if (bdrv_set_key(bs
, password
) == 0)
6687 term_printf("invalid password\n");
6693 /* XXX: currently we cannot use simultaneously different CPUs */
6694 void register_machines(void)
6696 #if defined(TARGET_I386)
6697 qemu_register_machine(&pc_machine
);
6698 qemu_register_machine(&isapc_machine
);
6699 #elif defined(TARGET_PPC)
6700 qemu_register_machine(&heathrow_machine
);
6701 qemu_register_machine(&core99_machine
);
6702 qemu_register_machine(&prep_machine
);
6703 #elif defined(TARGET_MIPS)
6704 qemu_register_machine(&mips_machine
);
6705 qemu_register_machine(&mips_malta_machine
);
6706 #elif defined(TARGET_SPARC)
6707 #ifdef TARGET_SPARC64
6708 qemu_register_machine(&sun4u_machine
);
6710 qemu_register_machine(&sun4m_machine
);
6712 #elif defined(TARGET_ARM)
6713 qemu_register_machine(&integratorcp_machine
);
6714 qemu_register_machine(&versatilepb_machine
);
6715 qemu_register_machine(&versatileab_machine
);
6716 qemu_register_machine(&realview_machine
);
6717 #elif defined(TARGET_SH4)
6718 qemu_register_machine(&shix_machine
);
6720 #error unsupported CPU
6725 struct soundhw soundhw
[] = {
6732 { .init_isa
= pcspk_audio_init
}
6737 "Creative Sound Blaster 16",
6740 { .init_isa
= SB16_init
}
6747 "Yamaha YMF262 (OPL3)",
6749 "Yamaha YM3812 (OPL2)",
6753 { .init_isa
= Adlib_init
}
6760 "Gravis Ultrasound GF1",
6763 { .init_isa
= GUS_init
}
6769 "ENSONIQ AudioPCI ES1370",
6772 { .init_pci
= es1370_init
}
6775 { NULL
, NULL
, 0, 0, { NULL
} }
6778 static void select_soundhw (const char *optarg
)
6782 if (*optarg
== '?') {
6785 printf ("Valid sound card names (comma separated):\n");
6786 for (c
= soundhw
; c
->name
; ++c
) {
6787 printf ("%-11s %s\n", c
->name
, c
->descr
);
6789 printf ("\n-soundhw all will enable all of the above\n");
6790 exit (*optarg
!= '?');
6798 if (!strcmp (optarg
, "all")) {
6799 for (c
= soundhw
; c
->name
; ++c
) {
6807 e
= strchr (p
, ',');
6808 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6810 for (c
= soundhw
; c
->name
; ++c
) {
6811 if (!strncmp (c
->name
, p
, l
)) {
6820 "Unknown sound card name (too big to show)\n");
6823 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6828 p
+= l
+ (e
!= NULL
);
6832 goto show_valid_cards
;
6838 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6840 exit(STATUS_CONTROL_C_EXIT
);
6845 #define MAX_NET_CLIENTS 32
6847 int main(int argc
, char **argv
)
6849 #ifdef CONFIG_GDBSTUB
6851 const char *gdbstub_port
;
6854 int snapshot
, linux_boot
;
6855 const char *initrd_filename
;
6856 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6857 const char *kernel_filename
, *kernel_cmdline
;
6858 DisplayState
*ds
= &display_state
;
6859 int cyls
, heads
, secs
, translation
;
6860 char net_clients
[MAX_NET_CLIENTS
][256];
6863 const char *r
, *optarg
;
6864 CharDriverState
*monitor_hd
;
6865 char monitor_device
[128];
6866 char serial_devices
[MAX_SERIAL_PORTS
][128];
6867 int serial_device_index
;
6868 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6869 int parallel_device_index
;
6870 const char *loadvm
= NULL
;
6871 QEMUMachine
*machine
;
6872 const char *cpu_model
;
6873 char usb_devices
[MAX_USB_CMDLINE
][128];
6874 int usb_devices_index
;
6877 LIST_INIT (&vm_change_state_head
);
6880 struct sigaction act
;
6881 sigfillset(&act
.sa_mask
);
6883 act
.sa_handler
= SIG_IGN
;
6884 sigaction(SIGPIPE
, &act
, NULL
);
6887 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6888 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6889 QEMU to run on a single CPU */
6894 h
= GetCurrentProcess();
6895 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6896 for(i
= 0; i
< 32; i
++) {
6897 if (mask
& (1 << i
))
6902 SetProcessAffinityMask(h
, mask
);
6908 register_machines();
6909 machine
= first_machine
;
6911 initrd_filename
= NULL
;
6912 for(i
= 0; i
< MAX_FD
; i
++)
6913 fd_filename
[i
] = NULL
;
6914 for(i
= 0; i
< MAX_DISKS
; i
++)
6915 hd_filename
[i
] = NULL
;
6916 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6917 vga_ram_size
= VGA_RAM_SIZE
;
6918 #ifdef CONFIG_GDBSTUB
6920 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6924 kernel_filename
= NULL
;
6925 kernel_cmdline
= "";
6931 cyls
= heads
= secs
= 0;
6932 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6933 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6935 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6936 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6937 serial_devices
[i
][0] = '\0';
6938 serial_device_index
= 0;
6940 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6941 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6942 parallel_devices
[i
][0] = '\0';
6943 parallel_device_index
= 0;
6945 usb_devices_index
= 0;
6950 /* default mac address of the first network interface */
6958 hd_filename
[0] = argv
[optind
++];
6960 const QEMUOption
*popt
;
6963 /* Treat --foo the same as -foo. */
6966 popt
= qemu_options
;
6969 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6973 if (!strcmp(popt
->name
, r
+ 1))
6977 if (popt
->flags
& HAS_ARG
) {
6978 if (optind
>= argc
) {
6979 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6983 optarg
= argv
[optind
++];
6988 switch(popt
->index
) {
6990 machine
= find_machine(optarg
);
6993 printf("Supported machines are:\n");
6994 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6995 printf("%-10s %s%s\n",
6997 m
== first_machine
? " (default)" : "");
7002 case QEMU_OPTION_cpu
:
7003 /* hw initialization will check this */
7004 if (optarg
[0] == '?') {
7005 #if defined(TARGET_PPC)
7006 ppc_cpu_list(stdout
, &fprintf
);
7007 #elif defined(TARGET_ARM)
7015 case QEMU_OPTION_initrd
:
7016 initrd_filename
= optarg
;
7018 case QEMU_OPTION_hda
:
7019 case QEMU_OPTION_hdb
:
7020 case QEMU_OPTION_hdc
:
7021 case QEMU_OPTION_hdd
:
7024 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7025 hd_filename
[hd_index
] = optarg
;
7026 if (hd_index
== cdrom_index
)
7030 case QEMU_OPTION_snapshot
:
7033 case QEMU_OPTION_hdachs
:
7037 cyls
= strtol(p
, (char **)&p
, 0);
7038 if (cyls
< 1 || cyls
> 16383)
7043 heads
= strtol(p
, (char **)&p
, 0);
7044 if (heads
< 1 || heads
> 16)
7049 secs
= strtol(p
, (char **)&p
, 0);
7050 if (secs
< 1 || secs
> 63)
7054 if (!strcmp(p
, "none"))
7055 translation
= BIOS_ATA_TRANSLATION_NONE
;
7056 else if (!strcmp(p
, "lba"))
7057 translation
= BIOS_ATA_TRANSLATION_LBA
;
7058 else if (!strcmp(p
, "auto"))
7059 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7062 } else if (*p
!= '\0') {
7064 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7069 case QEMU_OPTION_nographic
:
7070 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7071 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7074 case QEMU_OPTION_kernel
:
7075 kernel_filename
= optarg
;
7077 case QEMU_OPTION_append
:
7078 kernel_cmdline
= optarg
;
7080 case QEMU_OPTION_cdrom
:
7081 if (cdrom_index
>= 0) {
7082 hd_filename
[cdrom_index
] = optarg
;
7085 case QEMU_OPTION_boot
:
7086 boot_device
= optarg
[0];
7087 if (boot_device
!= 'a' &&
7088 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7090 boot_device
!= 'n' &&
7092 boot_device
!= 'c' && boot_device
!= 'd') {
7093 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7097 case QEMU_OPTION_fda
:
7098 fd_filename
[0] = optarg
;
7100 case QEMU_OPTION_fdb
:
7101 fd_filename
[1] = optarg
;
7104 case QEMU_OPTION_no_fd_bootchk
:
7108 case QEMU_OPTION_no_code_copy
:
7109 code_copy_enabled
= 0;
7111 case QEMU_OPTION_net
:
7112 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7113 fprintf(stderr
, "qemu: too many network clients\n");
7116 pstrcpy(net_clients
[nb_net_clients
],
7117 sizeof(net_clients
[0]),
7122 case QEMU_OPTION_tftp
:
7123 tftp_prefix
= optarg
;
7125 case QEMU_OPTION_bootp
:
7126 bootp_filename
= optarg
;
7129 case QEMU_OPTION_smb
:
7130 net_slirp_smb(optarg
);
7133 case QEMU_OPTION_redir
:
7134 net_slirp_redir(optarg
);
7138 case QEMU_OPTION_audio_help
:
7142 case QEMU_OPTION_soundhw
:
7143 select_soundhw (optarg
);
7150 ram_size
= atoi(optarg
) * 1024 * 1024;
7153 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7154 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7155 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7164 mask
= cpu_str_to_log_mask(optarg
);
7166 printf("Log items (comma separated):\n");
7167 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7168 printf("%-10s %s\n", item
->name
, item
->help
);
7175 #ifdef CONFIG_GDBSTUB
7180 gdbstub_port
= optarg
;
7190 keyboard_layout
= optarg
;
7192 case QEMU_OPTION_localtime
:
7195 case QEMU_OPTION_cirrusvga
:
7196 cirrus_vga_enabled
= 1;
7198 case QEMU_OPTION_std_vga
:
7199 cirrus_vga_enabled
= 0;
7206 w
= strtol(p
, (char **)&p
, 10);
7209 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7215 h
= strtol(p
, (char **)&p
, 10);
7220 depth
= strtol(p
, (char **)&p
, 10);
7221 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7222 depth
!= 24 && depth
!= 32)
7224 } else if (*p
== '\0') {
7225 depth
= graphic_depth
;
7232 graphic_depth
= depth
;
7235 case QEMU_OPTION_echr
:
7238 term_escape_char
= strtol(optarg
, &r
, 0);
7240 printf("Bad argument to echr\n");
7243 case QEMU_OPTION_monitor
:
7244 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7246 case QEMU_OPTION_serial
:
7247 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7248 fprintf(stderr
, "qemu: too many serial ports\n");
7251 pstrcpy(serial_devices
[serial_device_index
],
7252 sizeof(serial_devices
[0]), optarg
);
7253 serial_device_index
++;
7255 case QEMU_OPTION_parallel
:
7256 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7257 fprintf(stderr
, "qemu: too many parallel ports\n");
7260 pstrcpy(parallel_devices
[parallel_device_index
],
7261 sizeof(parallel_devices
[0]), optarg
);
7262 parallel_device_index
++;
7264 case QEMU_OPTION_loadvm
:
7267 case QEMU_OPTION_full_screen
:
7271 case QEMU_OPTION_no_frame
:
7274 case QEMU_OPTION_no_quit
:
7278 case QEMU_OPTION_pidfile
:
7279 create_pidfile(optarg
);
7282 case QEMU_OPTION_win2k_hack
:
7283 win2k_install_hack
= 1;
7287 case QEMU_OPTION_no_kqemu
:
7290 case QEMU_OPTION_kernel_kqemu
:
7294 case QEMU_OPTION_usb
:
7297 case QEMU_OPTION_usbdevice
:
7299 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7300 fprintf(stderr
, "Too many USB devices\n");
7303 pstrcpy(usb_devices
[usb_devices_index
],
7304 sizeof(usb_devices
[usb_devices_index
]),
7306 usb_devices_index
++;
7308 case QEMU_OPTION_smp
:
7309 smp_cpus
= atoi(optarg
);
7310 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7311 fprintf(stderr
, "Invalid number of CPUs\n");
7315 case QEMU_OPTION_vnc
:
7316 vnc_display
= optarg
;
7318 case QEMU_OPTION_no_acpi
:
7321 case QEMU_OPTION_no_reboot
:
7324 case QEMU_OPTION_daemonize
:
7327 case QEMU_OPTION_option_rom
:
7328 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7329 fprintf(stderr
, "Too many option ROMs\n");
7332 option_rom
[nb_option_roms
] = optarg
;
7335 case QEMU_OPTION_semihosting
:
7336 semihosting_enabled
= 1;
7343 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7344 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7351 if (pipe(fds
) == -1)
7362 len
= read(fds
[0], &status
, 1);
7363 if (len
== -1 && (errno
== EINTR
))
7366 if (len
!= 1 || status
!= 0)
7384 signal(SIGTSTP
, SIG_IGN
);
7385 signal(SIGTTOU
, SIG_IGN
);
7386 signal(SIGTTIN
, SIG_IGN
);
7394 linux_boot
= (kernel_filename
!= NULL
);
7397 boot_device
!= 'n' &&
7398 hd_filename
[0] == '\0' &&
7399 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7400 fd_filename
[0] == '\0')
7403 /* boot to floppy or the default cd if no hard disk defined yet */
7404 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7405 if (fd_filename
[0] != '\0')
7411 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7421 /* init network clients */
7422 if (nb_net_clients
== 0) {
7423 /* if no clients, we use a default config */
7424 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7426 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7431 for(i
= 0;i
< nb_net_clients
; i
++) {
7432 if (net_client_init(net_clients
[i
]) < 0)
7437 if (boot_device
== 'n') {
7438 for (i
= 0; i
< nb_nics
; i
++) {
7439 const char *model
= nd_table
[i
].model
;
7443 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7444 if (get_image_size(buf
) > 0) {
7445 option_rom
[nb_option_roms
] = strdup(buf
);
7451 fprintf(stderr
, "No valid PXE rom found for network device\n");
7454 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7458 /* init the memory */
7459 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
7461 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7462 if (!phys_ram_base
) {
7463 fprintf(stderr
, "Could not allocate physical memory\n");
7467 /* we always create the cdrom drive, even if no disk is there */
7469 if (cdrom_index
>= 0) {
7470 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7471 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7474 /* open the virtual block devices */
7475 for(i
= 0; i
< MAX_DISKS
; i
++) {
7476 if (hd_filename
[i
]) {
7479 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7480 bs_table
[i
] = bdrv_new(buf
);
7482 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7483 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7487 if (i
== 0 && cyls
!= 0) {
7488 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7489 bdrv_set_translation_hint(bs_table
[i
], translation
);
7494 /* we always create at least one floppy disk */
7495 fd_table
[0] = bdrv_new("fda");
7496 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7498 for(i
= 0; i
< MAX_FD
; i
++) {
7499 if (fd_filename
[i
]) {
7502 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7503 fd_table
[i
] = bdrv_new(buf
);
7504 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7506 if (fd_filename
[i
] != '\0') {
7507 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7508 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7509 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7517 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7518 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7524 dumb_display_init(ds
);
7525 } else if (vnc_display
!= NULL
) {
7526 vnc_display_init(ds
, vnc_display
);
7528 #if defined(CONFIG_SDL)
7529 sdl_display_init(ds
, full_screen
, no_frame
);
7530 #elif defined(CONFIG_COCOA)
7531 cocoa_display_init(ds
, full_screen
);
7533 dumb_display_init(ds
);
7537 /* Maintain compatibility with multiple stdio monitors */
7538 if (!strcmp(monitor_device
,"stdio")) {
7539 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7540 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
7541 monitor_device
[0] = '\0';
7543 } else if (!strcmp(serial_devices
[i
],"stdio")) {
7544 monitor_device
[0] = '\0';
7545 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
7550 if (monitor_device
[0] != '\0') {
7551 monitor_hd
= qemu_chr_open(monitor_device
);
7553 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7556 monitor_init(monitor_hd
, !nographic
);
7559 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7560 const char *devname
= serial_devices
[i
];
7561 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7562 serial_hds
[i
] = qemu_chr_open(devname
);
7563 if (!serial_hds
[i
]) {
7564 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7568 if (!strcmp(devname
, "vc"))
7569 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7573 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7574 const char *devname
= parallel_devices
[i
];
7575 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7576 parallel_hds
[i
] = qemu_chr_open(devname
);
7577 if (!parallel_hds
[i
]) {
7578 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7582 if (!strcmp(devname
, "vc"))
7583 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7587 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7588 ds
, fd_filename
, snapshot
,
7589 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
7591 /* init USB devices */
7593 for(i
= 0; i
< usb_devices_index
; i
++) {
7594 if (usb_device_add(usb_devices
[i
]) < 0) {
7595 fprintf(stderr
, "Warning: could not add USB device %s\n",
7601 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7602 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7604 #ifdef CONFIG_GDBSTUB
7606 /* XXX: use standard host:port notation and modify options
7608 if (gdbserver_start(gdbstub_port
) < 0) {
7609 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
7619 /* XXX: simplify init */
7632 len
= write(fds
[1], &status
, 1);
7633 if (len
== -1 && (errno
== EINTR
))
7639 fd
= open("/dev/null", O_RDWR
);