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;
192 const char *qemu_name
;
194 /***********************************************************/
195 /* x86 ISA bus support */
197 target_phys_addr_t isa_mem_base
= 0;
200 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
208 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
210 #ifdef DEBUG_UNUSED_IOPORT
211 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
215 /* default is to make two byte accesses */
216 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
219 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
220 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
221 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
225 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
227 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
228 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
229 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
232 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
234 #ifdef DEBUG_UNUSED_IOPORT
235 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
240 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
242 #ifdef DEBUG_UNUSED_IOPORT
243 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
247 void init_ioports(void)
251 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
252 ioport_read_table
[0][i
] = default_ioport_readb
;
253 ioport_write_table
[0][i
] = default_ioport_writeb
;
254 ioport_read_table
[1][i
] = default_ioport_readw
;
255 ioport_write_table
[1][i
] = default_ioport_writew
;
256 ioport_read_table
[2][i
] = default_ioport_readl
;
257 ioport_write_table
[2][i
] = default_ioport_writel
;
261 /* size is the word size in byte */
262 int register_ioport_read(int start
, int length
, int size
,
263 IOPortReadFunc
*func
, void *opaque
)
269 } else if (size
== 2) {
271 } else if (size
== 4) {
274 hw_error("register_ioport_read: invalid size");
277 for(i
= start
; i
< start
+ length
; i
+= size
) {
278 ioport_read_table
[bsize
][i
] = func
;
279 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
280 hw_error("register_ioport_read: invalid opaque");
281 ioport_opaque
[i
] = opaque
;
286 /* size is the word size in byte */
287 int register_ioport_write(int start
, int length
, int size
,
288 IOPortWriteFunc
*func
, void *opaque
)
294 } else if (size
== 2) {
296 } else if (size
== 4) {
299 hw_error("register_ioport_write: invalid size");
302 for(i
= start
; i
< start
+ length
; i
+= size
) {
303 ioport_write_table
[bsize
][i
] = func
;
304 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
305 hw_error("register_ioport_write: invalid opaque");
306 ioport_opaque
[i
] = opaque
;
311 void isa_unassign_ioport(int start
, int length
)
315 for(i
= start
; i
< start
+ length
; i
++) {
316 ioport_read_table
[0][i
] = default_ioport_readb
;
317 ioport_read_table
[1][i
] = default_ioport_readw
;
318 ioport_read_table
[2][i
] = default_ioport_readl
;
320 ioport_write_table
[0][i
] = default_ioport_writeb
;
321 ioport_write_table
[1][i
] = default_ioport_writew
;
322 ioport_write_table
[2][i
] = default_ioport_writel
;
326 /***********************************************************/
328 void cpu_outb(CPUState
*env
, int addr
, int val
)
331 if (loglevel
& CPU_LOG_IOPORT
)
332 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
334 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
337 env
->last_io_time
= cpu_get_time_fast();
341 void cpu_outw(CPUState
*env
, int addr
, int val
)
344 if (loglevel
& CPU_LOG_IOPORT
)
345 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
347 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
350 env
->last_io_time
= cpu_get_time_fast();
354 void cpu_outl(CPUState
*env
, int addr
, int val
)
357 if (loglevel
& CPU_LOG_IOPORT
)
358 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
360 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
363 env
->last_io_time
= cpu_get_time_fast();
367 int cpu_inb(CPUState
*env
, int addr
)
370 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
372 if (loglevel
& CPU_LOG_IOPORT
)
373 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
377 env
->last_io_time
= cpu_get_time_fast();
382 int cpu_inw(CPUState
*env
, int addr
)
385 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
387 if (loglevel
& CPU_LOG_IOPORT
)
388 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
392 env
->last_io_time
= cpu_get_time_fast();
397 int cpu_inl(CPUState
*env
, int addr
)
400 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
402 if (loglevel
& CPU_LOG_IOPORT
)
403 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
407 env
->last_io_time
= cpu_get_time_fast();
412 /***********************************************************/
413 void hw_error(const char *fmt
, ...)
419 fprintf(stderr
, "qemu: hardware error: ");
420 vfprintf(stderr
, fmt
, ap
);
421 fprintf(stderr
, "\n");
422 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
423 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
425 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
427 cpu_dump_state(env
, stderr
, fprintf
, 0);
434 /***********************************************************/
437 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
438 static void *qemu_put_kbd_event_opaque
;
439 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
440 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
442 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
444 qemu_put_kbd_event_opaque
= opaque
;
445 qemu_put_kbd_event
= func
;
448 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
449 void *opaque
, int absolute
,
452 QEMUPutMouseEntry
*s
, *cursor
;
454 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
458 s
->qemu_put_mouse_event
= func
;
459 s
->qemu_put_mouse_event_opaque
= opaque
;
460 s
->qemu_put_mouse_event_absolute
= absolute
;
461 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
464 if (!qemu_put_mouse_event_head
) {
465 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
469 cursor
= qemu_put_mouse_event_head
;
470 while (cursor
->next
!= NULL
)
471 cursor
= cursor
->next
;
474 qemu_put_mouse_event_current
= s
;
479 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
481 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
483 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
486 cursor
= qemu_put_mouse_event_head
;
487 while (cursor
!= NULL
&& cursor
!= entry
) {
489 cursor
= cursor
->next
;
492 if (cursor
== NULL
) // does not exist or list empty
494 else if (prev
== NULL
) { // entry is head
495 qemu_put_mouse_event_head
= cursor
->next
;
496 if (qemu_put_mouse_event_current
== entry
)
497 qemu_put_mouse_event_current
= cursor
->next
;
498 qemu_free(entry
->qemu_put_mouse_event_name
);
503 prev
->next
= entry
->next
;
505 if (qemu_put_mouse_event_current
== entry
)
506 qemu_put_mouse_event_current
= prev
;
508 qemu_free(entry
->qemu_put_mouse_event_name
);
512 void kbd_put_keycode(int keycode
)
514 if (qemu_put_kbd_event
) {
515 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
519 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
521 QEMUPutMouseEvent
*mouse_event
;
522 void *mouse_event_opaque
;
524 if (!qemu_put_mouse_event_current
) {
529 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
531 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
534 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
538 int kbd_mouse_is_absolute(void)
540 if (!qemu_put_mouse_event_current
)
543 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
546 void do_info_mice(void)
548 QEMUPutMouseEntry
*cursor
;
551 if (!qemu_put_mouse_event_head
) {
552 term_printf("No mouse devices connected\n");
556 term_printf("Mouse devices available:\n");
557 cursor
= qemu_put_mouse_event_head
;
558 while (cursor
!= NULL
) {
559 term_printf("%c Mouse #%d: %s\n",
560 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
561 index
, cursor
->qemu_put_mouse_event_name
);
563 cursor
= cursor
->next
;
567 void do_mouse_set(int index
)
569 QEMUPutMouseEntry
*cursor
;
572 if (!qemu_put_mouse_event_head
) {
573 term_printf("No mouse devices connected\n");
577 cursor
= qemu_put_mouse_event_head
;
578 while (cursor
!= NULL
&& index
!= i
) {
580 cursor
= cursor
->next
;
584 qemu_put_mouse_event_current
= cursor
;
586 term_printf("Mouse at given index not found\n");
589 /* compute with 96 bit intermediate result: (a*b)/c */
590 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
595 #ifdef WORDS_BIGENDIAN
605 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
606 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
609 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
613 /***********************************************************/
614 /* real time host monotonic timer */
616 #define QEMU_TIMER_BASE 1000000000LL
620 static int64_t clock_freq
;
622 static void init_get_clock(void)
626 ret
= QueryPerformanceFrequency(&freq
);
628 fprintf(stderr
, "Could not calibrate ticks\n");
631 clock_freq
= freq
.QuadPart
;
634 static int64_t get_clock(void)
637 QueryPerformanceCounter(&ti
);
638 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
643 static int use_rt_clock
;
645 static void init_get_clock(void)
648 #if defined(__linux__)
651 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
658 static int64_t get_clock(void)
660 #if defined(__linux__)
663 clock_gettime(CLOCK_MONOTONIC
, &ts
);
664 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
668 /* XXX: using gettimeofday leads to problems if the date
669 changes, so it should be avoided. */
671 gettimeofday(&tv
, NULL
);
672 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
678 /***********************************************************/
679 /* guest cycle counter */
681 static int64_t cpu_ticks_prev
;
682 static int64_t cpu_ticks_offset
;
683 static int64_t cpu_clock_offset
;
684 static int cpu_ticks_enabled
;
686 /* return the host CPU cycle counter and handle stop/restart */
687 int64_t cpu_get_ticks(void)
689 if (!cpu_ticks_enabled
) {
690 return cpu_ticks_offset
;
693 ticks
= cpu_get_real_ticks();
694 if (cpu_ticks_prev
> ticks
) {
695 /* Note: non increasing ticks may happen if the host uses
697 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
699 cpu_ticks_prev
= ticks
;
700 return ticks
+ cpu_ticks_offset
;
704 /* return the host CPU monotonic timer and handle stop/restart */
705 static int64_t cpu_get_clock(void)
708 if (!cpu_ticks_enabled
) {
709 return cpu_clock_offset
;
712 return ti
+ cpu_clock_offset
;
716 /* enable cpu_get_ticks() */
717 void cpu_enable_ticks(void)
719 if (!cpu_ticks_enabled
) {
720 cpu_ticks_offset
-= cpu_get_real_ticks();
721 cpu_clock_offset
-= get_clock();
722 cpu_ticks_enabled
= 1;
726 /* disable cpu_get_ticks() : the clock is stopped. You must not call
727 cpu_get_ticks() after that. */
728 void cpu_disable_ticks(void)
730 if (cpu_ticks_enabled
) {
731 cpu_ticks_offset
= cpu_get_ticks();
732 cpu_clock_offset
= cpu_get_clock();
733 cpu_ticks_enabled
= 0;
737 /***********************************************************/
740 #define QEMU_TIMER_REALTIME 0
741 #define QEMU_TIMER_VIRTUAL 1
745 /* XXX: add frequency */
753 struct QEMUTimer
*next
;
759 static QEMUTimer
*active_timers
[2];
761 static MMRESULT timerID
;
762 static HANDLE host_alarm
= NULL
;
763 static unsigned int period
= 1;
765 /* frequency of the times() clock tick */
766 static int timer_freq
;
769 QEMUClock
*qemu_new_clock(int type
)
772 clock
= qemu_mallocz(sizeof(QEMUClock
));
779 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
783 ts
= qemu_mallocz(sizeof(QEMUTimer
));
790 void qemu_free_timer(QEMUTimer
*ts
)
795 /* stop a timer, but do not dealloc it */
796 void qemu_del_timer(QEMUTimer
*ts
)
800 /* NOTE: this code must be signal safe because
801 qemu_timer_expired() can be called from a signal. */
802 pt
= &active_timers
[ts
->clock
->type
];
815 /* modify the current timer so that it will be fired when current_time
816 >= expire_time. The corresponding callback will be called. */
817 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
823 /* add the timer in the sorted list */
824 /* NOTE: this code must be signal safe because
825 qemu_timer_expired() can be called from a signal. */
826 pt
= &active_timers
[ts
->clock
->type
];
831 if (t
->expire_time
> expire_time
)
835 ts
->expire_time
= expire_time
;
840 int qemu_timer_pending(QEMUTimer
*ts
)
843 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
850 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
854 return (timer_head
->expire_time
<= current_time
);
857 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
863 if (!ts
|| ts
->expire_time
> current_time
)
865 /* remove timer from the list before calling the callback */
866 *ptimer_head
= ts
->next
;
869 /* run the callback (the timer list can be modified) */
874 int64_t qemu_get_clock(QEMUClock
*clock
)
876 switch(clock
->type
) {
877 case QEMU_TIMER_REALTIME
:
878 return get_clock() / 1000000;
880 case QEMU_TIMER_VIRTUAL
:
881 return cpu_get_clock();
885 static void init_timers(void)
888 ticks_per_sec
= QEMU_TIMER_BASE
;
889 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
890 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
894 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
896 uint64_t expire_time
;
898 if (qemu_timer_pending(ts
)) {
899 expire_time
= ts
->expire_time
;
903 qemu_put_be64(f
, expire_time
);
906 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
908 uint64_t expire_time
;
910 expire_time
= qemu_get_be64(f
);
911 if (expire_time
!= -1) {
912 qemu_mod_timer(ts
, expire_time
);
918 static void timer_save(QEMUFile
*f
, void *opaque
)
920 if (cpu_ticks_enabled
) {
921 hw_error("cannot save state if virtual timers are running");
923 qemu_put_be64s(f
, &cpu_ticks_offset
);
924 qemu_put_be64s(f
, &ticks_per_sec
);
925 qemu_put_be64s(f
, &cpu_clock_offset
);
928 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
930 if (version_id
!= 1 && version_id
!= 2)
932 if (cpu_ticks_enabled
) {
935 qemu_get_be64s(f
, &cpu_ticks_offset
);
936 qemu_get_be64s(f
, &ticks_per_sec
);
937 if (version_id
== 2) {
938 qemu_get_be64s(f
, &cpu_clock_offset
);
944 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
945 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
947 static void host_alarm_handler(int host_signum
)
951 #define DISP_FREQ 1000
953 static int64_t delta_min
= INT64_MAX
;
954 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
956 ti
= qemu_get_clock(vm_clock
);
957 if (last_clock
!= 0) {
958 delta
= ti
- last_clock
;
959 if (delta
< delta_min
)
961 if (delta
> delta_max
)
964 if (++count
== DISP_FREQ
) {
965 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
966 muldiv64(delta_min
, 1000000, ticks_per_sec
),
967 muldiv64(delta_max
, 1000000, ticks_per_sec
),
968 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
969 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
971 delta_min
= INT64_MAX
;
979 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
980 qemu_get_clock(vm_clock
)) ||
981 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
982 qemu_get_clock(rt_clock
))) {
984 SetEvent(host_alarm
);
986 CPUState
*env
= cpu_single_env
;
988 /* stop the currently executing cpu because a timer occured */
989 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
991 if (env
->kqemu_enabled
) {
992 kqemu_cpu_interrupt(env
);
1001 #if defined(__linux__)
1003 #define RTC_FREQ 1024
1007 static int start_rtc_timer(void)
1009 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1012 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1013 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1014 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1015 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1018 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1023 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1029 static int start_rtc_timer(void)
1034 #endif /* !defined(__linux__) */
1036 #endif /* !defined(_WIN32) */
1038 static void init_timer_alarm(void)
1045 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1046 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1047 if (period
< tc
.wPeriodMin
)
1048 period
= tc
.wPeriodMin
;
1049 timeBeginPeriod(period
);
1050 timerID
= timeSetEvent(1, // interval (ms)
1051 period
, // resolution
1052 host_alarm_handler
, // function
1053 (DWORD
)&count
, // user parameter
1054 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1056 perror("failed timer alarm");
1059 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1061 perror("failed CreateEvent");
1064 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1066 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1069 struct sigaction act
;
1070 struct itimerval itv
;
1072 /* get times() syscall frequency */
1073 timer_freq
= sysconf(_SC_CLK_TCK
);
1076 sigfillset(&act
.sa_mask
);
1078 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1079 act
.sa_flags
|= SA_ONSTACK
;
1081 act
.sa_handler
= host_alarm_handler
;
1082 sigaction(SIGALRM
, &act
, NULL
);
1084 itv
.it_interval
.tv_sec
= 0;
1085 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1086 itv
.it_value
.tv_sec
= 0;
1087 itv
.it_value
.tv_usec
= 10 * 1000;
1088 setitimer(ITIMER_REAL
, &itv
, NULL
);
1089 /* we probe the tick duration of the kernel to inform the user if
1090 the emulated kernel requested a too high timer frequency */
1091 getitimer(ITIMER_REAL
, &itv
);
1093 #if defined(__linux__)
1094 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1095 have timers with 1 ms resolution. The correct solution will
1096 be to use the POSIX real time timers available in recent
1098 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1099 /* try to use /dev/rtc to have a faster timer */
1100 if (start_rtc_timer() < 0)
1102 /* disable itimer */
1103 itv
.it_interval
.tv_sec
= 0;
1104 itv
.it_interval
.tv_usec
= 0;
1105 itv
.it_value
.tv_sec
= 0;
1106 itv
.it_value
.tv_usec
= 0;
1107 setitimer(ITIMER_REAL
, &itv
, NULL
);
1110 sigaction(SIGIO
, &act
, NULL
);
1111 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1112 fcntl(rtc_fd
, F_SETOWN
, getpid());
1114 #endif /* defined(__linux__) */
1117 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1118 PIT_FREQ
) / 1000000;
1124 void quit_timers(void)
1127 timeKillEvent(timerID
);
1128 timeEndPeriod(period
);
1130 CloseHandle(host_alarm
);
1136 /***********************************************************/
1137 /* character device */
1139 static void qemu_chr_event(CharDriverState
*s
, int event
)
1143 s
->chr_event(s
->handler_opaque
, event
);
1146 static void qemu_chr_reset_bh(void *opaque
)
1148 CharDriverState
*s
= opaque
;
1149 qemu_chr_event(s
, CHR_EVENT_RESET
);
1150 qemu_bh_delete(s
->bh
);
1154 void qemu_chr_reset(CharDriverState
*s
)
1156 if (s
->bh
== NULL
) {
1157 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1158 qemu_bh_schedule(s
->bh
);
1162 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1164 return s
->chr_write(s
, buf
, len
);
1167 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1171 return s
->chr_ioctl(s
, cmd
, arg
);
1174 int qemu_chr_can_read(CharDriverState
*s
)
1176 if (!s
->chr_can_read
)
1178 return s
->chr_can_read(s
->handler_opaque
);
1181 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1183 s
->chr_read(s
->handler_opaque
, buf
, len
);
1187 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1192 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1193 qemu_chr_write(s
, buf
, strlen(buf
));
1197 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1199 if (s
->chr_send_event
)
1200 s
->chr_send_event(s
, event
);
1203 void qemu_chr_add_handlers(CharDriverState
*s
,
1204 IOCanRWHandler
*fd_can_read
,
1205 IOReadHandler
*fd_read
,
1206 IOEventHandler
*fd_event
,
1209 s
->chr_can_read
= fd_can_read
;
1210 s
->chr_read
= fd_read
;
1211 s
->chr_event
= fd_event
;
1212 s
->handler_opaque
= opaque
;
1213 if (s
->chr_update_read_handler
)
1214 s
->chr_update_read_handler(s
);
1217 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1222 static CharDriverState
*qemu_chr_open_null(void)
1224 CharDriverState
*chr
;
1226 chr
= qemu_mallocz(sizeof(CharDriverState
));
1229 chr
->chr_write
= null_chr_write
;
1233 /* MUX driver for serial I/O splitting */
1234 static int term_timestamps
;
1235 static int64_t term_timestamps_start
;
1238 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1239 IOReadHandler
*chr_read
[MAX_MUX
];
1240 IOEventHandler
*chr_event
[MAX_MUX
];
1241 void *ext_opaque
[MAX_MUX
];
1242 CharDriverState
*drv
;
1244 int term_got_escape
;
1249 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1251 MuxDriver
*d
= chr
->opaque
;
1253 if (!term_timestamps
) {
1254 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1259 for(i
= 0; i
< len
; i
++) {
1260 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1261 if (buf
[i
] == '\n') {
1267 if (term_timestamps_start
== -1)
1268 term_timestamps_start
= ti
;
1269 ti
-= term_timestamps_start
;
1270 secs
= ti
/ 1000000000;
1271 snprintf(buf1
, sizeof(buf1
),
1272 "[%02d:%02d:%02d.%03d] ",
1276 (int)((ti
/ 1000000) % 1000));
1277 d
->drv
->chr_write(d
->drv
, buf1
, strlen(buf1
));
1284 static char *mux_help
[] = {
1285 "% h print this help\n\r",
1286 "% x exit emulator\n\r",
1287 "% s save disk data back to file (if -snapshot)\n\r",
1288 "% t toggle console timestamps\n\r"
1289 "% b send break (magic sysrq)\n\r",
1290 "% c switch between console and monitor\n\r",
1295 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1296 static void mux_print_help(CharDriverState
*chr
)
1299 char ebuf
[15] = "Escape-Char";
1300 char cbuf
[50] = "\n\r";
1302 if (term_escape_char
> 0 && term_escape_char
< 26) {
1303 sprintf(cbuf
,"\n\r");
1304 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1306 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char
);
1308 chr
->chr_write(chr
, cbuf
, strlen(cbuf
));
1309 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1310 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1311 if (mux_help
[i
][j
] == '%')
1312 chr
->chr_write(chr
, ebuf
, strlen(ebuf
));
1314 chr
->chr_write(chr
, &mux_help
[i
][j
], 1);
1319 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1321 if (d
->term_got_escape
) {
1322 d
->term_got_escape
= 0;
1323 if (ch
== term_escape_char
)
1328 mux_print_help(chr
);
1332 char *term
= "QEMU: Terminated\n\r";
1333 chr
->chr_write(chr
,term
,strlen(term
));
1340 for (i
= 0; i
< MAX_DISKS
; i
++) {
1342 bdrv_commit(bs_table
[i
]);
1348 chr
->chr_event(chr
->opaque
, CHR_EVENT_BREAK
);
1351 /* Switch to the next registered device */
1353 if (chr
->focus
>= d
->mux_cnt
)
1357 term_timestamps
= !term_timestamps
;
1358 term_timestamps_start
= -1;
1361 } else if (ch
== term_escape_char
) {
1362 d
->term_got_escape
= 1;
1370 static int mux_chr_can_read(void *opaque
)
1372 CharDriverState
*chr
= opaque
;
1373 MuxDriver
*d
= chr
->opaque
;
1374 if (d
->chr_can_read
[chr
->focus
])
1375 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1379 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1381 CharDriverState
*chr
= opaque
;
1382 MuxDriver
*d
= chr
->opaque
;
1384 for(i
= 0; i
< size
; i
++)
1385 if (mux_proc_byte(chr
, d
, buf
[i
]))
1386 d
->chr_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
], &buf
[i
], 1);
1389 static void mux_chr_event(void *opaque
, int event
)
1391 CharDriverState
*chr
= opaque
;
1392 MuxDriver
*d
= chr
->opaque
;
1395 /* Send the event to all registered listeners */
1396 for (i
= 0; i
< d
->mux_cnt
; i
++)
1397 if (d
->chr_event
[i
])
1398 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1401 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1403 MuxDriver
*d
= chr
->opaque
;
1405 if (d
->mux_cnt
>= MAX_MUX
) {
1406 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1409 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1410 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1411 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1412 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1413 /* Fix up the real driver with mux routines */
1414 if (d
->mux_cnt
== 0) {
1415 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1416 mux_chr_event
, chr
);
1418 chr
->focus
= d
->mux_cnt
;
1422 CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1424 CharDriverState
*chr
;
1427 chr
= qemu_mallocz(sizeof(CharDriverState
));
1430 d
= qemu_mallocz(sizeof(MuxDriver
));
1439 chr
->chr_write
= mux_chr_write
;
1440 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1447 static void socket_cleanup(void)
1452 static int socket_init(void)
1457 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1459 err
= WSAGetLastError();
1460 fprintf(stderr
, "WSAStartup: %d\n", err
);
1463 atexit(socket_cleanup
);
1467 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1473 ret
= send(fd
, buf
, len
, 0);
1476 errno
= WSAGetLastError();
1477 if (errno
!= WSAEWOULDBLOCK
) {
1480 } else if (ret
== 0) {
1490 void socket_set_nonblock(int fd
)
1492 unsigned long opt
= 1;
1493 ioctlsocket(fd
, FIONBIO
, &opt
);
1498 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1504 ret
= write(fd
, buf
, len
);
1506 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1508 } else if (ret
== 0) {
1518 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1520 return unix_write(fd
, buf
, len1
);
1523 void socket_set_nonblock(int fd
)
1525 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1527 #endif /* !_WIN32 */
1536 #define STDIO_MAX_CLIENTS 1
1537 static int stdio_nb_clients
= 0;
1539 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1541 FDCharDriver
*s
= chr
->opaque
;
1542 return unix_write(s
->fd_out
, buf
, len
);
1545 static int fd_chr_read_poll(void *opaque
)
1547 CharDriverState
*chr
= opaque
;
1548 FDCharDriver
*s
= chr
->opaque
;
1550 s
->max_size
= qemu_chr_can_read(chr
);
1554 static void fd_chr_read(void *opaque
)
1556 CharDriverState
*chr
= opaque
;
1557 FDCharDriver
*s
= chr
->opaque
;
1562 if (len
> s
->max_size
)
1566 size
= read(s
->fd_in
, buf
, len
);
1568 /* FD has been closed. Remove it from the active list. */
1569 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1573 qemu_chr_read(chr
, buf
, size
);
1577 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1579 FDCharDriver
*s
= chr
->opaque
;
1581 if (s
->fd_in
>= 0) {
1582 if (nographic
&& s
->fd_in
== 0) {
1584 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1585 fd_chr_read
, NULL
, chr
);
1590 /* open a character device to a unix fd */
1591 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1593 CharDriverState
*chr
;
1596 chr
= qemu_mallocz(sizeof(CharDriverState
));
1599 s
= qemu_mallocz(sizeof(FDCharDriver
));
1607 chr
->chr_write
= fd_chr_write
;
1608 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1610 qemu_chr_reset(chr
);
1615 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1619 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1622 return qemu_chr_open_fd(-1, fd_out
);
1625 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1628 char filename_in
[256], filename_out
[256];
1630 snprintf(filename_in
, 256, "%s.in", filename
);
1631 snprintf(filename_out
, 256, "%s.out", filename
);
1632 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1633 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1634 if (fd_in
< 0 || fd_out
< 0) {
1639 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1643 return qemu_chr_open_fd(fd_in
, fd_out
);
1647 /* for STDIO, we handle the case where several clients use it
1650 #define TERM_FIFO_MAX_SIZE 1
1652 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1653 static int term_fifo_size
;
1655 static int stdio_read_poll(void *opaque
)
1657 CharDriverState
*chr
= opaque
;
1659 /* try to flush the queue if needed */
1660 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1661 qemu_chr_read(chr
, term_fifo
, 1);
1664 /* see if we can absorb more chars */
1665 if (term_fifo_size
== 0)
1671 static void stdio_read(void *opaque
)
1675 CharDriverState
*chr
= opaque
;
1677 size
= read(0, buf
, 1);
1679 /* stdin has been closed. Remove it from the active list. */
1680 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1684 if (qemu_chr_can_read(chr
) > 0) {
1685 qemu_chr_read(chr
, buf
, 1);
1686 } else if (term_fifo_size
== 0) {
1687 term_fifo
[term_fifo_size
++] = buf
[0];
1692 /* init terminal so that we can grab keys */
1693 static struct termios oldtty
;
1694 static int old_fd0_flags
;
1696 static void term_exit(void)
1698 tcsetattr (0, TCSANOW
, &oldtty
);
1699 fcntl(0, F_SETFL
, old_fd0_flags
);
1702 static void term_init(void)
1706 tcgetattr (0, &tty
);
1708 old_fd0_flags
= fcntl(0, F_GETFL
);
1710 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1711 |INLCR
|IGNCR
|ICRNL
|IXON
);
1712 tty
.c_oflag
|= OPOST
;
1713 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1714 /* if graphical mode, we allow Ctrl-C handling */
1716 tty
.c_lflag
&= ~ISIG
;
1717 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1720 tty
.c_cc
[VTIME
] = 0;
1722 tcsetattr (0, TCSANOW
, &tty
);
1726 fcntl(0, F_SETFL
, O_NONBLOCK
);
1729 static CharDriverState
*qemu_chr_open_stdio(void)
1731 CharDriverState
*chr
;
1733 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1735 chr
= qemu_chr_open_fd(0, 1);
1736 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
1743 #if defined(__linux__)
1744 static CharDriverState
*qemu_chr_open_pty(void)
1747 char slave_name
[1024];
1748 int master_fd
, slave_fd
;
1750 /* Not satisfying */
1751 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1755 /* Disabling local echo and line-buffered output */
1756 tcgetattr (master_fd
, &tty
);
1757 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1759 tty
.c_cc
[VTIME
] = 0;
1760 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1762 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1763 return qemu_chr_open_fd(master_fd
, master_fd
);
1766 static void tty_serial_init(int fd
, int speed
,
1767 int parity
, int data_bits
, int stop_bits
)
1773 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1774 speed
, parity
, data_bits
, stop_bits
);
1776 tcgetattr (fd
, &tty
);
1818 cfsetispeed(&tty
, spd
);
1819 cfsetospeed(&tty
, spd
);
1821 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1822 |INLCR
|IGNCR
|ICRNL
|IXON
);
1823 tty
.c_oflag
|= OPOST
;
1824 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1825 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1846 tty
.c_cflag
|= PARENB
;
1849 tty
.c_cflag
|= PARENB
| PARODD
;
1853 tty
.c_cflag
|= CSTOPB
;
1855 tcsetattr (fd
, TCSANOW
, &tty
);
1858 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1860 FDCharDriver
*s
= chr
->opaque
;
1863 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1865 QEMUSerialSetParams
*ssp
= arg
;
1866 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1867 ssp
->data_bits
, ssp
->stop_bits
);
1870 case CHR_IOCTL_SERIAL_SET_BREAK
:
1872 int enable
= *(int *)arg
;
1874 tcsendbreak(s
->fd_in
, 1);
1883 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1885 CharDriverState
*chr
;
1888 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1891 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1892 tty_serial_init(fd
, 115200, 'N', 8, 1);
1893 chr
= qemu_chr_open_fd(fd
, fd
);
1896 chr
->chr_ioctl
= tty_serial_ioctl
;
1897 qemu_chr_reset(chr
);
1904 } ParallelCharDriver
;
1906 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
1908 if (s
->mode
!= mode
) {
1910 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
1917 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1919 ParallelCharDriver
*drv
= chr
->opaque
;
1924 case CHR_IOCTL_PP_READ_DATA
:
1925 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1927 *(uint8_t *)arg
= b
;
1929 case CHR_IOCTL_PP_WRITE_DATA
:
1930 b
= *(uint8_t *)arg
;
1931 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1934 case CHR_IOCTL_PP_READ_CONTROL
:
1935 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1937 /* Linux gives only the lowest bits, and no way to know data
1938 direction! For better compatibility set the fixed upper
1940 *(uint8_t *)arg
= b
| 0xc0;
1942 case CHR_IOCTL_PP_WRITE_CONTROL
:
1943 b
= *(uint8_t *)arg
;
1944 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1947 case CHR_IOCTL_PP_READ_STATUS
:
1948 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1950 *(uint8_t *)arg
= b
;
1952 case CHR_IOCTL_PP_EPP_READ_ADDR
:
1953 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1954 struct ParallelIOArg
*parg
= arg
;
1955 int n
= read(fd
, parg
->buffer
, parg
->count
);
1956 if (n
!= parg
->count
) {
1961 case CHR_IOCTL_PP_EPP_READ
:
1962 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1963 struct ParallelIOArg
*parg
= arg
;
1964 int n
= read(fd
, parg
->buffer
, parg
->count
);
1965 if (n
!= parg
->count
) {
1970 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
1971 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1972 struct ParallelIOArg
*parg
= arg
;
1973 int n
= write(fd
, parg
->buffer
, parg
->count
);
1974 if (n
!= parg
->count
) {
1979 case CHR_IOCTL_PP_EPP_WRITE
:
1980 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1981 struct ParallelIOArg
*parg
= arg
;
1982 int n
= write(fd
, parg
->buffer
, parg
->count
);
1983 if (n
!= parg
->count
) {
1994 static void pp_close(CharDriverState
*chr
)
1996 ParallelCharDriver
*drv
= chr
->opaque
;
1999 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2000 ioctl(fd
, PPRELEASE
);
2005 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2007 CharDriverState
*chr
;
2008 ParallelCharDriver
*drv
;
2011 fd
= open(filename
, O_RDWR
);
2015 if (ioctl(fd
, PPCLAIM
) < 0) {
2020 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2026 drv
->mode
= IEEE1284_MODE_COMPAT
;
2028 chr
= qemu_mallocz(sizeof(CharDriverState
));
2034 chr
->chr_write
= null_chr_write
;
2035 chr
->chr_ioctl
= pp_ioctl
;
2036 chr
->chr_close
= pp_close
;
2039 qemu_chr_reset(chr
);
2045 static CharDriverState
*qemu_chr_open_pty(void)
2051 #endif /* !defined(_WIN32) */
2056 HANDLE hcom
, hrecv
, hsend
;
2057 OVERLAPPED orecv
, osend
;
2062 #define NSENDBUF 2048
2063 #define NRECVBUF 2048
2064 #define MAXCONNECT 1
2065 #define NTIMEOUT 5000
2067 static int win_chr_poll(void *opaque
);
2068 static int win_chr_pipe_poll(void *opaque
);
2070 static void win_chr_close(CharDriverState
*chr
)
2072 WinCharState
*s
= chr
->opaque
;
2075 CloseHandle(s
->hsend
);
2079 CloseHandle(s
->hrecv
);
2083 CloseHandle(s
->hcom
);
2087 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2089 qemu_del_polling_cb(win_chr_poll
, chr
);
2092 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2094 WinCharState
*s
= chr
->opaque
;
2096 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2101 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2103 fprintf(stderr
, "Failed CreateEvent\n");
2106 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2108 fprintf(stderr
, "Failed CreateEvent\n");
2112 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2113 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2114 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2115 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2120 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2121 fprintf(stderr
, "Failed SetupComm\n");
2125 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2126 size
= sizeof(COMMCONFIG
);
2127 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2128 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2129 CommConfigDialog(filename
, NULL
, &comcfg
);
2131 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2132 fprintf(stderr
, "Failed SetCommState\n");
2136 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2137 fprintf(stderr
, "Failed SetCommMask\n");
2141 cto
.ReadIntervalTimeout
= MAXDWORD
;
2142 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2143 fprintf(stderr
, "Failed SetCommTimeouts\n");
2147 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2148 fprintf(stderr
, "Failed ClearCommError\n");
2151 qemu_add_polling_cb(win_chr_poll
, chr
);
2159 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2161 WinCharState
*s
= chr
->opaque
;
2162 DWORD len
, ret
, size
, err
;
2165 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2166 s
->osend
.hEvent
= s
->hsend
;
2169 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2171 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2173 err
= GetLastError();
2174 if (err
== ERROR_IO_PENDING
) {
2175 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2193 static int win_chr_read_poll(CharDriverState
*chr
)
2195 WinCharState
*s
= chr
->opaque
;
2197 s
->max_size
= qemu_chr_can_read(chr
);
2201 static void win_chr_readfile(CharDriverState
*chr
)
2203 WinCharState
*s
= chr
->opaque
;
2208 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2209 s
->orecv
.hEvent
= s
->hrecv
;
2210 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2212 err
= GetLastError();
2213 if (err
== ERROR_IO_PENDING
) {
2214 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2219 qemu_chr_read(chr
, buf
, size
);
2223 static void win_chr_read(CharDriverState
*chr
)
2225 WinCharState
*s
= chr
->opaque
;
2227 if (s
->len
> s
->max_size
)
2228 s
->len
= s
->max_size
;
2232 win_chr_readfile(chr
);
2235 static int win_chr_poll(void *opaque
)
2237 CharDriverState
*chr
= opaque
;
2238 WinCharState
*s
= chr
->opaque
;
2242 ClearCommError(s
->hcom
, &comerr
, &status
);
2243 if (status
.cbInQue
> 0) {
2244 s
->len
= status
.cbInQue
;
2245 win_chr_read_poll(chr
);
2252 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2254 CharDriverState
*chr
;
2257 chr
= qemu_mallocz(sizeof(CharDriverState
));
2260 s
= qemu_mallocz(sizeof(WinCharState
));
2266 chr
->chr_write
= win_chr_write
;
2267 chr
->chr_close
= win_chr_close
;
2269 if (win_chr_init(chr
, filename
) < 0) {
2274 qemu_chr_reset(chr
);
2278 static int win_chr_pipe_poll(void *opaque
)
2280 CharDriverState
*chr
= opaque
;
2281 WinCharState
*s
= chr
->opaque
;
2284 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2287 win_chr_read_poll(chr
);
2294 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2296 WinCharState
*s
= chr
->opaque
;
2304 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2306 fprintf(stderr
, "Failed CreateEvent\n");
2309 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2311 fprintf(stderr
, "Failed CreateEvent\n");
2315 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2316 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2317 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2319 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2320 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2321 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2326 ZeroMemory(&ov
, sizeof(ov
));
2327 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2328 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2330 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2334 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2336 fprintf(stderr
, "Failed GetOverlappedResult\n");
2338 CloseHandle(ov
.hEvent
);
2345 CloseHandle(ov
.hEvent
);
2348 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2357 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2359 CharDriverState
*chr
;
2362 chr
= qemu_mallocz(sizeof(CharDriverState
));
2365 s
= qemu_mallocz(sizeof(WinCharState
));
2371 chr
->chr_write
= win_chr_write
;
2372 chr
->chr_close
= win_chr_close
;
2374 if (win_chr_pipe_init(chr
, filename
) < 0) {
2379 qemu_chr_reset(chr
);
2383 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2385 CharDriverState
*chr
;
2388 chr
= qemu_mallocz(sizeof(CharDriverState
));
2391 s
= qemu_mallocz(sizeof(WinCharState
));
2398 chr
->chr_write
= win_chr_write
;
2399 qemu_chr_reset(chr
);
2403 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2407 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2408 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2409 if (fd_out
== INVALID_HANDLE_VALUE
)
2412 return qemu_chr_open_win_file(fd_out
);
2416 /***********************************************************/
2417 /* UDP Net console */
2421 struct sockaddr_in daddr
;
2428 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2430 NetCharDriver
*s
= chr
->opaque
;
2432 return sendto(s
->fd
, buf
, len
, 0,
2433 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2436 static int udp_chr_read_poll(void *opaque
)
2438 CharDriverState
*chr
= opaque
;
2439 NetCharDriver
*s
= chr
->opaque
;
2441 s
->max_size
= qemu_chr_can_read(chr
);
2443 /* If there were any stray characters in the queue process them
2446 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2447 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2449 s
->max_size
= qemu_chr_can_read(chr
);
2454 static void udp_chr_read(void *opaque
)
2456 CharDriverState
*chr
= opaque
;
2457 NetCharDriver
*s
= chr
->opaque
;
2459 if (s
->max_size
== 0)
2461 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2462 s
->bufptr
= s
->bufcnt
;
2467 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2468 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2470 s
->max_size
= qemu_chr_can_read(chr
);
2474 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2476 NetCharDriver
*s
= chr
->opaque
;
2479 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2480 udp_chr_read
, NULL
, chr
);
2484 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2486 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2488 int parse_host_src_port(struct sockaddr_in
*haddr
,
2489 struct sockaddr_in
*saddr
,
2492 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2494 CharDriverState
*chr
= NULL
;
2495 NetCharDriver
*s
= NULL
;
2497 struct sockaddr_in saddr
;
2499 chr
= qemu_mallocz(sizeof(CharDriverState
));
2502 s
= qemu_mallocz(sizeof(NetCharDriver
));
2506 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2508 perror("socket(PF_INET, SOCK_DGRAM)");
2512 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2513 printf("Could not parse: %s\n", def
);
2517 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2527 chr
->chr_write
= udp_chr_write
;
2528 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2541 /***********************************************************/
2542 /* TCP Net console */
2553 static void tcp_chr_accept(void *opaque
);
2555 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2557 TCPCharDriver
*s
= chr
->opaque
;
2559 return send_all(s
->fd
, buf
, len
);
2561 /* XXX: indicate an error ? */
2566 static int tcp_chr_read_poll(void *opaque
)
2568 CharDriverState
*chr
= opaque
;
2569 TCPCharDriver
*s
= chr
->opaque
;
2572 s
->max_size
= qemu_chr_can_read(chr
);
2577 #define IAC_BREAK 243
2578 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2580 char *buf
, int *size
)
2582 /* Handle any telnet client's basic IAC options to satisfy char by
2583 * char mode with no echo. All IAC options will be removed from
2584 * the buf and the do_telnetopt variable will be used to track the
2585 * state of the width of the IAC information.
2587 * IAC commands come in sets of 3 bytes with the exception of the
2588 * "IAC BREAK" command and the double IAC.
2594 for (i
= 0; i
< *size
; i
++) {
2595 if (s
->do_telnetopt
> 1) {
2596 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2597 /* Double IAC means send an IAC */
2601 s
->do_telnetopt
= 1;
2603 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2604 /* Handle IAC break commands by sending a serial break */
2605 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2610 if (s
->do_telnetopt
>= 4) {
2611 s
->do_telnetopt
= 1;
2614 if ((unsigned char)buf
[i
] == IAC
) {
2615 s
->do_telnetopt
= 2;
2626 static void tcp_chr_read(void *opaque
)
2628 CharDriverState
*chr
= opaque
;
2629 TCPCharDriver
*s
= chr
->opaque
;
2633 if (!s
->connected
|| s
->max_size
<= 0)
2636 if (len
> s
->max_size
)
2638 size
= recv(s
->fd
, buf
, len
, 0);
2640 /* connection closed */
2642 if (s
->listen_fd
>= 0) {
2643 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2645 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2648 } else if (size
> 0) {
2649 if (s
->do_telnetopt
)
2650 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2652 qemu_chr_read(chr
, buf
, size
);
2656 static void tcp_chr_connect(void *opaque
)
2658 CharDriverState
*chr
= opaque
;
2659 TCPCharDriver
*s
= chr
->opaque
;
2662 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2663 tcp_chr_read
, NULL
, chr
);
2664 qemu_chr_reset(chr
);
2667 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2668 static void tcp_chr_telnet_init(int fd
)
2671 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2672 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2673 send(fd
, (char *)buf
, 3, 0);
2674 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2675 send(fd
, (char *)buf
, 3, 0);
2676 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2677 send(fd
, (char *)buf
, 3, 0);
2678 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2679 send(fd
, (char *)buf
, 3, 0);
2682 static void socket_set_nodelay(int fd
)
2685 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2688 static void tcp_chr_accept(void *opaque
)
2690 CharDriverState
*chr
= opaque
;
2691 TCPCharDriver
*s
= chr
->opaque
;
2692 struct sockaddr_in saddr
;
2694 struct sockaddr_un uaddr
;
2696 struct sockaddr
*addr
;
2703 len
= sizeof(uaddr
);
2704 addr
= (struct sockaddr
*)&uaddr
;
2708 len
= sizeof(saddr
);
2709 addr
= (struct sockaddr
*)&saddr
;
2711 fd
= accept(s
->listen_fd
, addr
, &len
);
2712 if (fd
< 0 && errno
!= EINTR
) {
2714 } else if (fd
>= 0) {
2715 if (s
->do_telnetopt
)
2716 tcp_chr_telnet_init(fd
);
2720 socket_set_nonblock(fd
);
2722 socket_set_nodelay(fd
);
2724 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2725 tcp_chr_connect(chr
);
2728 static void tcp_chr_close(CharDriverState
*chr
)
2730 TCPCharDriver
*s
= chr
->opaque
;
2733 if (s
->listen_fd
>= 0)
2734 closesocket(s
->listen_fd
);
2738 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2742 CharDriverState
*chr
= NULL
;
2743 TCPCharDriver
*s
= NULL
;
2744 int fd
= -1, ret
, err
, val
;
2746 int is_waitconnect
= 1;
2749 struct sockaddr_in saddr
;
2751 struct sockaddr_un uaddr
;
2753 struct sockaddr
*addr
;
2758 addr
= (struct sockaddr
*)&uaddr
;
2759 addrlen
= sizeof(uaddr
);
2760 if (parse_unix_path(&uaddr
, host_str
) < 0)
2765 addr
= (struct sockaddr
*)&saddr
;
2766 addrlen
= sizeof(saddr
);
2767 if (parse_host_port(&saddr
, host_str
) < 0)
2772 while((ptr
= strchr(ptr
,','))) {
2774 if (!strncmp(ptr
,"server",6)) {
2776 } else if (!strncmp(ptr
,"nowait",6)) {
2778 } else if (!strncmp(ptr
,"nodelay",6)) {
2781 printf("Unknown option: %s\n", ptr
);
2788 chr
= qemu_mallocz(sizeof(CharDriverState
));
2791 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2797 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2800 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2805 if (!is_waitconnect
)
2806 socket_set_nonblock(fd
);
2811 s
->is_unix
= is_unix
;
2812 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2815 chr
->chr_write
= tcp_chr_write
;
2816 chr
->chr_close
= tcp_chr_close
;
2819 /* allow fast reuse */
2823 strncpy(path
, uaddr
.sun_path
, 108);
2830 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2833 ret
= bind(fd
, addr
, addrlen
);
2837 ret
= listen(fd
, 0);
2842 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2844 s
->do_telnetopt
= 1;
2847 ret
= connect(fd
, addr
, addrlen
);
2849 err
= socket_error();
2850 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2851 } else if (err
== EINPROGRESS
) {
2862 socket_set_nodelay(fd
);
2864 tcp_chr_connect(chr
);
2866 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2869 if (is_listen
&& is_waitconnect
) {
2870 printf("QEMU waiting for connection on: %s\n", host_str
);
2871 tcp_chr_accept(chr
);
2872 socket_set_nonblock(s
->listen_fd
);
2884 CharDriverState
*qemu_chr_open(const char *filename
)
2888 if (!strcmp(filename
, "vc")) {
2889 return text_console_init(&display_state
);
2890 } else if (!strcmp(filename
, "null")) {
2891 return qemu_chr_open_null();
2893 if (strstart(filename
, "tcp:", &p
)) {
2894 return qemu_chr_open_tcp(p
, 0, 0);
2896 if (strstart(filename
, "telnet:", &p
)) {
2897 return qemu_chr_open_tcp(p
, 1, 0);
2899 if (strstart(filename
, "udp:", &p
)) {
2900 return qemu_chr_open_udp(p
);
2902 if (strstart(filename
, "mon:", &p
)) {
2903 CharDriverState
*drv
= qemu_chr_open(p
);
2905 drv
= qemu_chr_open_mux(drv
);
2906 monitor_init(drv
, !nographic
);
2909 printf("Unable to open driver: %s\n", p
);
2913 if (strstart(filename
, "unix:", &p
)) {
2914 return qemu_chr_open_tcp(p
, 0, 1);
2915 } else if (strstart(filename
, "file:", &p
)) {
2916 return qemu_chr_open_file_out(p
);
2917 } else if (strstart(filename
, "pipe:", &p
)) {
2918 return qemu_chr_open_pipe(p
);
2919 } else if (!strcmp(filename
, "pty")) {
2920 return qemu_chr_open_pty();
2921 } else if (!strcmp(filename
, "stdio")) {
2922 return qemu_chr_open_stdio();
2925 #if defined(__linux__)
2926 if (strstart(filename
, "/dev/parport", NULL
)) {
2927 return qemu_chr_open_pp(filename
);
2929 if (strstart(filename
, "/dev/", NULL
)) {
2930 return qemu_chr_open_tty(filename
);
2934 if (strstart(filename
, "COM", NULL
)) {
2935 return qemu_chr_open_win(filename
);
2937 if (strstart(filename
, "pipe:", &p
)) {
2938 return qemu_chr_open_win_pipe(p
);
2940 if (strstart(filename
, "file:", &p
)) {
2941 return qemu_chr_open_win_file_out(p
);
2949 void qemu_chr_close(CharDriverState
*chr
)
2952 chr
->chr_close(chr
);
2955 /***********************************************************/
2956 /* network device redirectors */
2958 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2962 for(i
=0;i
<size
;i
+=16) {
2966 fprintf(f
, "%08x ", i
);
2969 fprintf(f
, " %02x", buf
[i
+j
]);
2974 for(j
=0;j
<len
;j
++) {
2976 if (c
< ' ' || c
> '~')
2978 fprintf(f
, "%c", c
);
2984 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2987 for(i
= 0; i
< 6; i
++) {
2988 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3001 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3006 p1
= strchr(p
, sep
);
3012 if (len
> buf_size
- 1)
3014 memcpy(buf
, p
, len
);
3021 int parse_host_src_port(struct sockaddr_in
*haddr
,
3022 struct sockaddr_in
*saddr
,
3023 const char *input_str
)
3025 char *str
= strdup(input_str
);
3026 char *host_str
= str
;
3031 * Chop off any extra arguments at the end of the string which
3032 * would start with a comma, then fill in the src port information
3033 * if it was provided else use the "any address" and "any port".
3035 if ((ptr
= strchr(str
,',')))
3038 if ((src_str
= strchr(input_str
,'@'))) {
3043 if (parse_host_port(haddr
, host_str
) < 0)
3046 if (!src_str
|| *src_str
== '\0')
3049 if (parse_host_port(saddr
, src_str
) < 0)
3060 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3068 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3070 saddr
->sin_family
= AF_INET
;
3071 if (buf
[0] == '\0') {
3072 saddr
->sin_addr
.s_addr
= 0;
3074 if (isdigit(buf
[0])) {
3075 if (!inet_aton(buf
, &saddr
->sin_addr
))
3078 if ((he
= gethostbyname(buf
)) == NULL
)
3080 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3083 port
= strtol(p
, (char **)&r
, 0);
3086 saddr
->sin_port
= htons(port
);
3091 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3096 len
= MIN(108, strlen(str
));
3097 p
= strchr(str
, ',');
3099 len
= MIN(len
, p
- str
);
3101 memset(uaddr
, 0, sizeof(*uaddr
));
3103 uaddr
->sun_family
= AF_UNIX
;
3104 memcpy(uaddr
->sun_path
, str
, len
);
3110 /* find or alloc a new VLAN */
3111 VLANState
*qemu_find_vlan(int id
)
3113 VLANState
**pvlan
, *vlan
;
3114 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3118 vlan
= qemu_mallocz(sizeof(VLANState
));
3123 pvlan
= &first_vlan
;
3124 while (*pvlan
!= NULL
)
3125 pvlan
= &(*pvlan
)->next
;
3130 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3131 IOReadHandler
*fd_read
,
3132 IOCanRWHandler
*fd_can_read
,
3135 VLANClientState
*vc
, **pvc
;
3136 vc
= qemu_mallocz(sizeof(VLANClientState
));
3139 vc
->fd_read
= fd_read
;
3140 vc
->fd_can_read
= fd_can_read
;
3141 vc
->opaque
= opaque
;
3145 pvc
= &vlan
->first_client
;
3146 while (*pvc
!= NULL
)
3147 pvc
= &(*pvc
)->next
;
3152 int qemu_can_send_packet(VLANClientState
*vc1
)
3154 VLANState
*vlan
= vc1
->vlan
;
3155 VLANClientState
*vc
;
3157 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3159 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
3166 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3168 VLANState
*vlan
= vc1
->vlan
;
3169 VLANClientState
*vc
;
3172 printf("vlan %d send:\n", vlan
->id
);
3173 hex_dump(stdout
, buf
, size
);
3175 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3177 vc
->fd_read(vc
->opaque
, buf
, size
);
3182 #if defined(CONFIG_SLIRP)
3184 /* slirp network adapter */
3186 static int slirp_inited
;
3187 static VLANClientState
*slirp_vc
;
3189 int slirp_can_output(void)
3191 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3194 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3197 printf("slirp output:\n");
3198 hex_dump(stdout
, pkt
, pkt_len
);
3202 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3205 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3208 printf("slirp input:\n");
3209 hex_dump(stdout
, buf
, size
);
3211 slirp_input(buf
, size
);
3214 static int net_slirp_init(VLANState
*vlan
)
3216 if (!slirp_inited
) {
3220 slirp_vc
= qemu_new_vlan_client(vlan
,
3221 slirp_receive
, NULL
, NULL
);
3222 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3226 static void net_slirp_redir(const char *redir_str
)
3231 struct in_addr guest_addr
;
3232 int host_port
, guest_port
;
3234 if (!slirp_inited
) {
3240 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3242 if (!strcmp(buf
, "tcp")) {
3244 } else if (!strcmp(buf
, "udp")) {
3250 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3252 host_port
= strtol(buf
, &r
, 0);
3256 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3258 if (buf
[0] == '\0') {
3259 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3261 if (!inet_aton(buf
, &guest_addr
))
3264 guest_port
= strtol(p
, &r
, 0);
3268 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3269 fprintf(stderr
, "qemu: could not set up redirection\n");
3274 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3282 static void smb_exit(void)
3286 char filename
[1024];
3288 /* erase all the files in the directory */
3289 d
= opendir(smb_dir
);
3294 if (strcmp(de
->d_name
, ".") != 0 &&
3295 strcmp(de
->d_name
, "..") != 0) {
3296 snprintf(filename
, sizeof(filename
), "%s/%s",
3297 smb_dir
, de
->d_name
);
3305 /* automatic user mode samba server configuration */
3306 void net_slirp_smb(const char *exported_dir
)
3308 char smb_conf
[1024];
3309 char smb_cmdline
[1024];
3312 if (!slirp_inited
) {
3317 /* XXX: better tmp dir construction */
3318 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3319 if (mkdir(smb_dir
, 0700) < 0) {
3320 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3323 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3325 f
= fopen(smb_conf
, "w");
3327 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3334 "socket address=127.0.0.1\n"
3335 "pid directory=%s\n"
3336 "lock directory=%s\n"
3337 "log file=%s/log.smbd\n"
3338 "smb passwd file=%s/smbpasswd\n"
3339 "security = share\n"
3354 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3355 SMBD_COMMAND
, smb_conf
);
3357 slirp_add_exec(0, smb_cmdline
, 4, 139);
3360 #endif /* !defined(_WIN32) */
3362 #endif /* CONFIG_SLIRP */
3364 #if !defined(_WIN32)
3366 typedef struct TAPState
{
3367 VLANClientState
*vc
;
3371 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3373 TAPState
*s
= opaque
;
3376 ret
= write(s
->fd
, buf
, size
);
3377 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3384 static void tap_send(void *opaque
)
3386 TAPState
*s
= opaque
;
3393 sbuf
.maxlen
= sizeof(buf
);
3395 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3397 size
= read(s
->fd
, buf
, sizeof(buf
));
3400 qemu_send_packet(s
->vc
, buf
, size
);
3406 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3410 s
= qemu_mallocz(sizeof(TAPState
));
3414 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3415 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3416 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3421 static int tap_open(char *ifname
, int ifname_size
)
3427 fd
= open("/dev/tap", O_RDWR
);
3429 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3434 dev
= devname(s
.st_rdev
, S_IFCHR
);
3435 pstrcpy(ifname
, ifname_size
, dev
);
3437 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3440 #elif defined(__sun__)
3441 #define TUNNEWPPA (('T'<<16) | 0x0001)
3443 * Allocate TAP device, returns opened fd.
3444 * Stores dev name in the first arg(must be large enough).
3446 int tap_alloc(char *dev
)
3448 int tap_fd
, if_fd
, ppa
= -1;
3449 static int ip_fd
= 0;
3452 static int arp_fd
= 0;
3453 int ip_muxid
, arp_muxid
;
3454 struct strioctl strioc_if
, strioc_ppa
;
3455 int link_type
= I_PLINK
;;
3457 char actual_name
[32] = "";
3459 memset(&ifr
, 0x0, sizeof(ifr
));
3463 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
3467 /* Check if IP device was opened */
3471 if( (ip_fd
= open("/dev/udp", O_RDWR
, 0)) < 0){
3472 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
3476 if( (tap_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3477 syslog(LOG_ERR
, "Can't open /dev/tap");
3481 /* Assign a new PPA and get its unit number. */
3482 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
3483 strioc_ppa
.ic_timout
= 0;
3484 strioc_ppa
.ic_len
= sizeof(ppa
);
3485 strioc_ppa
.ic_dp
= (char *)&ppa
;
3486 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
3487 syslog (LOG_ERR
, "Can't assign new interface");
3489 if( (if_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3490 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
3493 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
3494 syslog(LOG_ERR
, "Can't push IP module");
3498 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
3499 syslog(LOG_ERR
, "Can't get flags\n");
3501 snprintf (actual_name
, 32, "tap%d", ppa
);
3502 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3505 /* Assign ppa according to the unit number returned by tun device */
3507 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
3508 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
3509 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
3510 syslog (LOG_ERR
, "Can't get flags\n");
3511 /* Push arp module to if_fd */
3512 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
3513 syslog (LOG_ERR
, "Can't push ARP module (2)");
3515 /* Push arp module to ip_fd */
3516 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
3517 syslog (LOG_ERR
, "I_POP failed\n");
3518 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
3519 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
3521 if ((arp_fd
= open ("/dev/tap", O_RDWR
, 0)) < 0)
3522 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
3524 /* Set ifname to arp */
3525 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
3526 strioc_if
.ic_timout
= 0;
3527 strioc_if
.ic_len
= sizeof(ifr
);
3528 strioc_if
.ic_dp
= (char *)&ifr
;
3529 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
3530 syslog (LOG_ERR
, "Can't set ifname to arp\n");
3533 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
3534 syslog(LOG_ERR
, "Can't link TAP device to IP");
3538 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
3539 syslog (LOG_ERR
, "Can't link TAP device to ARP");
3543 memset(&ifr
, 0x0, sizeof(ifr
));
3544 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3545 ifr
.lifr_ip_muxid
= ip_muxid
;
3546 ifr
.lifr_arp_muxid
= arp_muxid
;
3548 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
3550 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
3551 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
3552 syslog (LOG_ERR
, "Can't set multiplexor id");
3555 sprintf(dev
, "tap%d", ppa
);
3559 static int tap_open(char *ifname
, int ifname_size
)
3563 if( (fd
= tap_alloc(dev
)) < 0 ){
3564 fprintf(stderr
, "Cannot allocate TAP device\n");
3567 pstrcpy(ifname
, ifname_size
, dev
);
3568 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3572 static int tap_open(char *ifname
, int ifname_size
)
3577 fd
= open("/dev/net/tun", O_RDWR
);
3579 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3582 memset(&ifr
, 0, sizeof(ifr
));
3583 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3584 if (ifname
[0] != '\0')
3585 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3587 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3588 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3590 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3594 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3595 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3600 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3601 const char *setup_script
)
3604 int pid
, status
, fd
;
3609 if (ifname1
!= NULL
)
3610 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3613 fd
= tap_open(ifname
, sizeof(ifname
));
3617 if (!setup_script
|| !strcmp(setup_script
, "no"))
3619 if (setup_script
[0] != '\0') {
3620 /* try to launch network init script */
3624 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
3625 for (i
= 0; i
< open_max
; i
++)
3626 if (i
!= STDIN_FILENO
&&
3627 i
!= STDOUT_FILENO
&&
3628 i
!= STDERR_FILENO
&&
3633 *parg
++ = (char *)setup_script
;
3636 execv(setup_script
, args
);
3639 while (waitpid(pid
, &status
, 0) != pid
);
3640 if (!WIFEXITED(status
) ||
3641 WEXITSTATUS(status
) != 0) {
3642 fprintf(stderr
, "%s: could not launch network script\n",
3648 s
= net_tap_fd_init(vlan
, fd
);
3651 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3652 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3656 #endif /* !_WIN32 */
3658 /* network connection */
3659 typedef struct NetSocketState
{
3660 VLANClientState
*vc
;
3662 int state
; /* 0 = getting length, 1 = getting data */
3666 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3669 typedef struct NetSocketListenState
{
3672 } NetSocketListenState
;
3674 /* XXX: we consider we can send the whole packet without blocking */
3675 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3677 NetSocketState
*s
= opaque
;
3681 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3682 send_all(s
->fd
, buf
, size
);
3685 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3687 NetSocketState
*s
= opaque
;
3688 sendto(s
->fd
, buf
, size
, 0,
3689 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3692 static void net_socket_send(void *opaque
)
3694 NetSocketState
*s
= opaque
;
3699 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3701 err
= socket_error();
3702 if (err
!= EWOULDBLOCK
)
3704 } else if (size
== 0) {
3705 /* end of connection */
3707 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3713 /* reassemble a packet from the network */
3719 memcpy(s
->buf
+ s
->index
, buf
, l
);
3723 if (s
->index
== 4) {
3725 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3731 l
= s
->packet_len
- s
->index
;
3734 memcpy(s
->buf
+ s
->index
, buf
, l
);
3738 if (s
->index
>= s
->packet_len
) {
3739 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3748 static void net_socket_send_dgram(void *opaque
)
3750 NetSocketState
*s
= opaque
;
3753 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3757 /* end of connection */
3758 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3761 qemu_send_packet(s
->vc
, s
->buf
, size
);
3764 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3769 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3770 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3771 inet_ntoa(mcastaddr
->sin_addr
),
3772 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3776 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3778 perror("socket(PF_INET, SOCK_DGRAM)");
3783 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3784 (const char *)&val
, sizeof(val
));
3786 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3790 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3796 /* Add host to multicast group */
3797 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3798 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3800 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3801 (const char *)&imr
, sizeof(struct ip_mreq
));
3803 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3807 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3809 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3810 (const char *)&val
, sizeof(val
));
3812 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3816 socket_set_nonblock(fd
);
3824 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3827 struct sockaddr_in saddr
;
3829 socklen_t saddr_len
;
3832 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3833 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3834 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3838 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3840 if (saddr
.sin_addr
.s_addr
==0) {
3841 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3845 /* clone dgram socket */
3846 newfd
= net_socket_mcast_create(&saddr
);
3848 /* error already reported by net_socket_mcast_create() */
3852 /* clone newfd to fd, close newfd */
3857 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3858 fd
, strerror(errno
));
3863 s
= qemu_mallocz(sizeof(NetSocketState
));
3868 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3869 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3871 /* mcast: save bound address as dst */
3872 if (is_connected
) s
->dgram_dst
=saddr
;
3874 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3875 "socket: fd=%d (%s mcast=%s:%d)",
3876 fd
, is_connected
? "cloned" : "",
3877 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3881 static void net_socket_connect(void *opaque
)
3883 NetSocketState
*s
= opaque
;
3884 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3887 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3891 s
= qemu_mallocz(sizeof(NetSocketState
));
3895 s
->vc
= qemu_new_vlan_client(vlan
,
3896 net_socket_receive
, NULL
, s
);
3897 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3898 "socket: fd=%d", fd
);
3900 net_socket_connect(s
);
3902 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3907 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3910 int so_type
=-1, optlen
=sizeof(so_type
);
3912 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3913 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3918 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3920 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3922 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3923 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3924 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3929 static void net_socket_accept(void *opaque
)
3931 NetSocketListenState
*s
= opaque
;
3933 struct sockaddr_in saddr
;
3938 len
= sizeof(saddr
);
3939 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3940 if (fd
< 0 && errno
!= EINTR
) {
3942 } else if (fd
>= 0) {
3946 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3950 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3951 "socket: connection from %s:%d",
3952 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3956 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3958 NetSocketListenState
*s
;
3960 struct sockaddr_in saddr
;
3962 if (parse_host_port(&saddr
, host_str
) < 0)
3965 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3969 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3974 socket_set_nonblock(fd
);
3976 /* allow fast reuse */
3978 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3980 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3985 ret
= listen(fd
, 0);
3992 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3996 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3999 int fd
, connected
, ret
, err
;
4000 struct sockaddr_in saddr
;
4002 if (parse_host_port(&saddr
, host_str
) < 0)
4005 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4010 socket_set_nonblock(fd
);
4014 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4016 err
= socket_error();
4017 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4018 } else if (err
== EINPROGRESS
) {
4030 s
= net_socket_fd_init(vlan
, fd
, connected
);
4033 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4034 "socket: connect to %s:%d",
4035 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4039 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4043 struct sockaddr_in saddr
;
4045 if (parse_host_port(&saddr
, host_str
) < 0)
4049 fd
= net_socket_mcast_create(&saddr
);
4053 s
= net_socket_fd_init(vlan
, fd
, 0);
4057 s
->dgram_dst
= saddr
;
4059 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4060 "socket: mcast=%s:%d",
4061 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4066 static int get_param_value(char *buf
, int buf_size
,
4067 const char *tag
, const char *str
)
4076 while (*p
!= '\0' && *p
!= '=') {
4077 if ((q
- option
) < sizeof(option
) - 1)
4085 if (!strcmp(tag
, option
)) {
4087 while (*p
!= '\0' && *p
!= ',') {
4088 if ((q
- buf
) < buf_size
- 1)
4095 while (*p
!= '\0' && *p
!= ',') {
4106 static int net_client_init(const char *str
)
4117 while (*p
!= '\0' && *p
!= ',') {
4118 if ((q
- device
) < sizeof(device
) - 1)
4126 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4127 vlan_id
= strtol(buf
, NULL
, 0);
4129 vlan
= qemu_find_vlan(vlan_id
);
4131 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4134 if (!strcmp(device
, "nic")) {
4138 if (nb_nics
>= MAX_NICS
) {
4139 fprintf(stderr
, "Too Many NICs\n");
4142 nd
= &nd_table
[nb_nics
];
4143 macaddr
= nd
->macaddr
;
4149 macaddr
[5] = 0x56 + nb_nics
;
4151 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4152 if (parse_macaddr(macaddr
, buf
) < 0) {
4153 fprintf(stderr
, "invalid syntax for ethernet address\n");
4157 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4158 nd
->model
= strdup(buf
);
4164 if (!strcmp(device
, "none")) {
4165 /* does nothing. It is needed to signal that no network cards
4170 if (!strcmp(device
, "user")) {
4171 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4172 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4174 ret
= net_slirp_init(vlan
);
4178 if (!strcmp(device
, "tap")) {
4180 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4181 fprintf(stderr
, "tap: no interface name\n");
4184 ret
= tap_win32_init(vlan
, ifname
);
4187 if (!strcmp(device
, "tap")) {
4189 char setup_script
[1024];
4191 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4192 fd
= strtol(buf
, NULL
, 0);
4194 if (net_tap_fd_init(vlan
, fd
))
4197 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4200 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4201 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4203 ret
= net_tap_init(vlan
, ifname
, setup_script
);
4207 if (!strcmp(device
, "socket")) {
4208 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4210 fd
= strtol(buf
, NULL
, 0);
4212 if (net_socket_fd_init(vlan
, fd
, 1))
4214 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4215 ret
= net_socket_listen_init(vlan
, buf
);
4216 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4217 ret
= net_socket_connect_init(vlan
, buf
);
4218 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4219 ret
= net_socket_mcast_init(vlan
, buf
);
4221 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4226 fprintf(stderr
, "Unknown network device: %s\n", device
);
4230 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4236 void do_info_network(void)
4239 VLANClientState
*vc
;
4241 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4242 term_printf("VLAN %d devices:\n", vlan
->id
);
4243 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4244 term_printf(" %s\n", vc
->info_str
);
4248 /***********************************************************/
4251 static USBPort
*used_usb_ports
;
4252 static USBPort
*free_usb_ports
;
4254 /* ??? Maybe change this to register a hub to keep track of the topology. */
4255 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
4256 usb_attachfn attach
)
4258 port
->opaque
= opaque
;
4259 port
->index
= index
;
4260 port
->attach
= attach
;
4261 port
->next
= free_usb_ports
;
4262 free_usb_ports
= port
;
4265 static int usb_device_add(const char *devname
)
4271 if (!free_usb_ports
)
4274 if (strstart(devname
, "host:", &p
)) {
4275 dev
= usb_host_device_open(p
);
4276 } else if (!strcmp(devname
, "mouse")) {
4277 dev
= usb_mouse_init();
4278 } else if (!strcmp(devname
, "tablet")) {
4279 dev
= usb_tablet_init();
4280 } else if (strstart(devname
, "disk:", &p
)) {
4281 dev
= usb_msd_init(p
);
4288 /* Find a USB port to add the device to. */
4289 port
= free_usb_ports
;
4293 /* Create a new hub and chain it on. */
4294 free_usb_ports
= NULL
;
4295 port
->next
= used_usb_ports
;
4296 used_usb_ports
= port
;
4298 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
4299 usb_attach(port
, hub
);
4300 port
= free_usb_ports
;
4303 free_usb_ports
= port
->next
;
4304 port
->next
= used_usb_ports
;
4305 used_usb_ports
= port
;
4306 usb_attach(port
, dev
);
4310 static int usb_device_del(const char *devname
)
4318 if (!used_usb_ports
)
4321 p
= strchr(devname
, '.');
4324 bus_num
= strtoul(devname
, NULL
, 0);
4325 addr
= strtoul(p
+ 1, NULL
, 0);
4329 lastp
= &used_usb_ports
;
4330 port
= used_usb_ports
;
4331 while (port
&& port
->dev
->addr
!= addr
) {
4332 lastp
= &port
->next
;
4340 *lastp
= port
->next
;
4341 usb_attach(port
, NULL
);
4342 dev
->handle_destroy(dev
);
4343 port
->next
= free_usb_ports
;
4344 free_usb_ports
= port
;
4348 void do_usb_add(const char *devname
)
4351 ret
= usb_device_add(devname
);
4353 term_printf("Could not add USB device '%s'\n", devname
);
4356 void do_usb_del(const char *devname
)
4359 ret
= usb_device_del(devname
);
4361 term_printf("Could not remove USB device '%s'\n", devname
);
4368 const char *speed_str
;
4371 term_printf("USB support not enabled\n");
4375 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4379 switch(dev
->speed
) {
4383 case USB_SPEED_FULL
:
4386 case USB_SPEED_HIGH
:
4393 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4394 0, dev
->addr
, speed_str
, dev
->devname
);
4398 static int create_pidfile(const char *filename
)
4404 fd
= open(filename
, O_RDWR
| O_CREAT
, 0600);
4408 /* XXX: No locking for Win32 implemented */
4410 if (lockf(fd
, F_TLOCK
, 0) == -1)
4414 len
= snprintf(buffer
, sizeof(buffer
), "%ld\n", (long)getpid());
4415 if (write(fd
, buffer
, len
) != len
)
4421 /***********************************************************/
4424 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4428 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4432 static void dumb_refresh(DisplayState
*ds
)
4437 void dumb_display_init(DisplayState
*ds
)
4442 ds
->dpy_update
= dumb_update
;
4443 ds
->dpy_resize
= dumb_resize
;
4444 ds
->dpy_refresh
= dumb_refresh
;
4447 /***********************************************************/
4450 #define MAX_IO_HANDLERS 64
4452 typedef struct IOHandlerRecord
{
4454 IOCanRWHandler
*fd_read_poll
;
4456 IOHandler
*fd_write
;
4459 /* temporary data */
4461 struct IOHandlerRecord
*next
;
4464 static IOHandlerRecord
*first_io_handler
;
4466 /* XXX: fd_read_poll should be suppressed, but an API change is
4467 necessary in the character devices to suppress fd_can_read(). */
4468 int qemu_set_fd_handler2(int fd
,
4469 IOCanRWHandler
*fd_read_poll
,
4471 IOHandler
*fd_write
,
4474 IOHandlerRecord
**pioh
, *ioh
;
4476 if (!fd_read
&& !fd_write
) {
4477 pioh
= &first_io_handler
;
4482 if (ioh
->fd
== fd
) {
4489 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4493 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4496 ioh
->next
= first_io_handler
;
4497 first_io_handler
= ioh
;
4500 ioh
->fd_read_poll
= fd_read_poll
;
4501 ioh
->fd_read
= fd_read
;
4502 ioh
->fd_write
= fd_write
;
4503 ioh
->opaque
= opaque
;
4509 int qemu_set_fd_handler(int fd
,
4511 IOHandler
*fd_write
,
4514 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4517 /***********************************************************/
4518 /* Polling handling */
4520 typedef struct PollingEntry
{
4523 struct PollingEntry
*next
;
4526 static PollingEntry
*first_polling_entry
;
4528 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4530 PollingEntry
**ppe
, *pe
;
4531 pe
= qemu_mallocz(sizeof(PollingEntry
));
4535 pe
->opaque
= opaque
;
4536 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4541 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4543 PollingEntry
**ppe
, *pe
;
4544 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4546 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4555 /***********************************************************/
4556 /* Wait objects support */
4557 typedef struct WaitObjects
{
4559 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4560 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4561 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4564 static WaitObjects wait_objects
= {0};
4566 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4568 WaitObjects
*w
= &wait_objects
;
4570 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4572 w
->events
[w
->num
] = handle
;
4573 w
->func
[w
->num
] = func
;
4574 w
->opaque
[w
->num
] = opaque
;
4579 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4582 WaitObjects
*w
= &wait_objects
;
4585 for (i
= 0; i
< w
->num
; i
++) {
4586 if (w
->events
[i
] == handle
)
4589 w
->events
[i
] = w
->events
[i
+ 1];
4590 w
->func
[i
] = w
->func
[i
+ 1];
4591 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4599 /***********************************************************/
4600 /* savevm/loadvm support */
4602 #define IO_BUF_SIZE 32768
4606 BlockDriverState
*bs
;
4609 int64_t base_offset
;
4610 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4613 int buf_size
; /* 0 when writing */
4614 uint8_t buf
[IO_BUF_SIZE
];
4617 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4621 f
= qemu_mallocz(sizeof(QEMUFile
));
4624 if (!strcmp(mode
, "wb")) {
4626 } else if (!strcmp(mode
, "rb")) {
4631 f
->outfile
= fopen(filename
, mode
);
4643 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4647 f
= qemu_mallocz(sizeof(QEMUFile
));
4652 f
->is_writable
= is_writable
;
4653 f
->base_offset
= offset
;
4657 void qemu_fflush(QEMUFile
*f
)
4659 if (!f
->is_writable
)
4661 if (f
->buf_index
> 0) {
4663 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4664 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4666 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4667 f
->buf
, f
->buf_index
);
4669 f
->buf_offset
+= f
->buf_index
;
4674 static void qemu_fill_buffer(QEMUFile
*f
)
4681 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4682 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4686 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4687 f
->buf
, IO_BUF_SIZE
);
4693 f
->buf_offset
+= len
;
4696 void qemu_fclose(QEMUFile
*f
)
4706 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4710 l
= IO_BUF_SIZE
- f
->buf_index
;
4713 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4717 if (f
->buf_index
>= IO_BUF_SIZE
)
4722 void qemu_put_byte(QEMUFile
*f
, int v
)
4724 f
->buf
[f
->buf_index
++] = v
;
4725 if (f
->buf_index
>= IO_BUF_SIZE
)
4729 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4735 l
= f
->buf_size
- f
->buf_index
;
4737 qemu_fill_buffer(f
);
4738 l
= f
->buf_size
- f
->buf_index
;
4744 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4749 return size1
- size
;
4752 int qemu_get_byte(QEMUFile
*f
)
4754 if (f
->buf_index
>= f
->buf_size
) {
4755 qemu_fill_buffer(f
);
4756 if (f
->buf_index
>= f
->buf_size
)
4759 return f
->buf
[f
->buf_index
++];
4762 int64_t qemu_ftell(QEMUFile
*f
)
4764 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4767 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4769 if (whence
== SEEK_SET
) {
4771 } else if (whence
== SEEK_CUR
) {
4772 pos
+= qemu_ftell(f
);
4774 /* SEEK_END not supported */
4777 if (f
->is_writable
) {
4779 f
->buf_offset
= pos
;
4781 f
->buf_offset
= pos
;
4788 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4790 qemu_put_byte(f
, v
>> 8);
4791 qemu_put_byte(f
, v
);
4794 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4796 qemu_put_byte(f
, v
>> 24);
4797 qemu_put_byte(f
, v
>> 16);
4798 qemu_put_byte(f
, v
>> 8);
4799 qemu_put_byte(f
, v
);
4802 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4804 qemu_put_be32(f
, v
>> 32);
4805 qemu_put_be32(f
, v
);
4808 unsigned int qemu_get_be16(QEMUFile
*f
)
4811 v
= qemu_get_byte(f
) << 8;
4812 v
|= qemu_get_byte(f
);
4816 unsigned int qemu_get_be32(QEMUFile
*f
)
4819 v
= qemu_get_byte(f
) << 24;
4820 v
|= qemu_get_byte(f
) << 16;
4821 v
|= qemu_get_byte(f
) << 8;
4822 v
|= qemu_get_byte(f
);
4826 uint64_t qemu_get_be64(QEMUFile
*f
)
4829 v
= (uint64_t)qemu_get_be32(f
) << 32;
4830 v
|= qemu_get_be32(f
);
4834 typedef struct SaveStateEntry
{
4838 SaveStateHandler
*save_state
;
4839 LoadStateHandler
*load_state
;
4841 struct SaveStateEntry
*next
;
4844 static SaveStateEntry
*first_se
;
4846 int register_savevm(const char *idstr
,
4849 SaveStateHandler
*save_state
,
4850 LoadStateHandler
*load_state
,
4853 SaveStateEntry
*se
, **pse
;
4855 se
= qemu_malloc(sizeof(SaveStateEntry
));
4858 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4859 se
->instance_id
= instance_id
;
4860 se
->version_id
= version_id
;
4861 se
->save_state
= save_state
;
4862 se
->load_state
= load_state
;
4863 se
->opaque
= opaque
;
4866 /* add at the end of list */
4868 while (*pse
!= NULL
)
4869 pse
= &(*pse
)->next
;
4874 #define QEMU_VM_FILE_MAGIC 0x5145564d
4875 #define QEMU_VM_FILE_VERSION 0x00000002
4877 int qemu_savevm_state(QEMUFile
*f
)
4881 int64_t cur_pos
, len_pos
, total_len_pos
;
4883 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4884 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4885 total_len_pos
= qemu_ftell(f
);
4886 qemu_put_be64(f
, 0); /* total size */
4888 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4890 len
= strlen(se
->idstr
);
4891 qemu_put_byte(f
, len
);
4892 qemu_put_buffer(f
, se
->idstr
, len
);
4894 qemu_put_be32(f
, se
->instance_id
);
4895 qemu_put_be32(f
, se
->version_id
);
4897 /* record size: filled later */
4898 len_pos
= qemu_ftell(f
);
4899 qemu_put_be32(f
, 0);
4901 se
->save_state(f
, se
->opaque
);
4903 /* fill record size */
4904 cur_pos
= qemu_ftell(f
);
4905 len
= cur_pos
- len_pos
- 4;
4906 qemu_fseek(f
, len_pos
, SEEK_SET
);
4907 qemu_put_be32(f
, len
);
4908 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4910 cur_pos
= qemu_ftell(f
);
4911 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4912 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4913 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4919 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4923 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4924 if (!strcmp(se
->idstr
, idstr
) &&
4925 instance_id
== se
->instance_id
)
4931 int qemu_loadvm_state(QEMUFile
*f
)
4934 int len
, ret
, instance_id
, record_len
, version_id
;
4935 int64_t total_len
, end_pos
, cur_pos
;
4939 v
= qemu_get_be32(f
);
4940 if (v
!= QEMU_VM_FILE_MAGIC
)
4942 v
= qemu_get_be32(f
);
4943 if (v
!= QEMU_VM_FILE_VERSION
) {
4948 total_len
= qemu_get_be64(f
);
4949 end_pos
= total_len
+ qemu_ftell(f
);
4951 if (qemu_ftell(f
) >= end_pos
)
4953 len
= qemu_get_byte(f
);
4954 qemu_get_buffer(f
, idstr
, len
);
4956 instance_id
= qemu_get_be32(f
);
4957 version_id
= qemu_get_be32(f
);
4958 record_len
= qemu_get_be32(f
);
4960 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4961 idstr
, instance_id
, version_id
, record_len
);
4963 cur_pos
= qemu_ftell(f
);
4964 se
= find_se(idstr
, instance_id
);
4966 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4967 instance_id
, idstr
);
4969 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4971 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4972 instance_id
, idstr
);
4975 /* always seek to exact end of record */
4976 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4983 /* device can contain snapshots */
4984 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4987 !bdrv_is_removable(bs
) &&
4988 !bdrv_is_read_only(bs
));
4991 /* device must be snapshots in order to have a reliable snapshot */
4992 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4995 !bdrv_is_removable(bs
) &&
4996 !bdrv_is_read_only(bs
));
4999 static BlockDriverState
*get_bs_snapshots(void)
5001 BlockDriverState
*bs
;
5005 return bs_snapshots
;
5006 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5008 if (bdrv_can_snapshot(bs
))
5017 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5020 QEMUSnapshotInfo
*sn_tab
, *sn
;
5024 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5027 for(i
= 0; i
< nb_sns
; i
++) {
5029 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5039 void do_savevm(const char *name
)
5041 BlockDriverState
*bs
, *bs1
;
5042 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5043 int must_delete
, ret
, i
;
5044 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5046 int saved_vm_running
;
5053 bs
= get_bs_snapshots();
5055 term_printf("No block device can accept snapshots\n");
5059 /* ??? Should this occur after vm_stop? */
5062 saved_vm_running
= vm_running
;
5067 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5072 memset(sn
, 0, sizeof(*sn
));
5074 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5075 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5078 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5081 /* fill auxiliary fields */
5084 sn
->date_sec
= tb
.time
;
5085 sn
->date_nsec
= tb
.millitm
* 1000000;
5087 gettimeofday(&tv
, NULL
);
5088 sn
->date_sec
= tv
.tv_sec
;
5089 sn
->date_nsec
= tv
.tv_usec
* 1000;
5091 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
5093 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5094 term_printf("Device %s does not support VM state snapshots\n",
5095 bdrv_get_device_name(bs
));
5099 /* save the VM state */
5100 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
5102 term_printf("Could not open VM state file\n");
5105 ret
= qemu_savevm_state(f
);
5106 sn
->vm_state_size
= qemu_ftell(f
);
5109 term_printf("Error %d while writing VM\n", ret
);
5113 /* create the snapshots */
5115 for(i
= 0; i
< MAX_DISKS
; i
++) {
5117 if (bdrv_has_snapshot(bs1
)) {
5119 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5121 term_printf("Error while deleting snapshot on '%s'\n",
5122 bdrv_get_device_name(bs1
));
5125 ret
= bdrv_snapshot_create(bs1
, sn
);
5127 term_printf("Error while creating snapshot on '%s'\n",
5128 bdrv_get_device_name(bs1
));
5134 if (saved_vm_running
)
5138 void do_loadvm(const char *name
)
5140 BlockDriverState
*bs
, *bs1
;
5141 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5144 int saved_vm_running
;
5146 bs
= get_bs_snapshots();
5148 term_printf("No block device supports snapshots\n");
5152 /* Flush all IO requests so they don't interfere with the new state. */
5155 saved_vm_running
= vm_running
;
5158 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5160 if (bdrv_has_snapshot(bs1
)) {
5161 ret
= bdrv_snapshot_goto(bs1
, name
);
5164 term_printf("Warning: ");
5167 term_printf("Snapshots not supported on device '%s'\n",
5168 bdrv_get_device_name(bs1
));
5171 term_printf("Could not find snapshot '%s' on device '%s'\n",
5172 name
, bdrv_get_device_name(bs1
));
5175 term_printf("Error %d while activating snapshot on '%s'\n",
5176 ret
, bdrv_get_device_name(bs1
));
5179 /* fatal on snapshot block device */
5186 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5187 term_printf("Device %s does not support VM state snapshots\n",
5188 bdrv_get_device_name(bs
));
5192 /* restore the VM state */
5193 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5195 term_printf("Could not open VM state file\n");
5198 ret
= qemu_loadvm_state(f
);
5201 term_printf("Error %d while loading VM state\n", ret
);
5204 if (saved_vm_running
)
5208 void do_delvm(const char *name
)
5210 BlockDriverState
*bs
, *bs1
;
5213 bs
= get_bs_snapshots();
5215 term_printf("No block device supports snapshots\n");
5219 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5221 if (bdrv_has_snapshot(bs1
)) {
5222 ret
= bdrv_snapshot_delete(bs1
, name
);
5224 if (ret
== -ENOTSUP
)
5225 term_printf("Snapshots not supported on device '%s'\n",
5226 bdrv_get_device_name(bs1
));
5228 term_printf("Error %d while deleting snapshot on '%s'\n",
5229 ret
, bdrv_get_device_name(bs1
));
5235 void do_info_snapshots(void)
5237 BlockDriverState
*bs
, *bs1
;
5238 QEMUSnapshotInfo
*sn_tab
, *sn
;
5242 bs
= get_bs_snapshots();
5244 term_printf("No available block device supports snapshots\n");
5247 term_printf("Snapshot devices:");
5248 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5250 if (bdrv_has_snapshot(bs1
)) {
5252 term_printf(" %s", bdrv_get_device_name(bs1
));
5257 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5259 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5262 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5263 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5264 for(i
= 0; i
< nb_sns
; i
++) {
5266 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5271 /***********************************************************/
5272 /* cpu save/restore */
5274 #if defined(TARGET_I386)
5276 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5278 qemu_put_be32(f
, dt
->selector
);
5279 qemu_put_betl(f
, dt
->base
);
5280 qemu_put_be32(f
, dt
->limit
);
5281 qemu_put_be32(f
, dt
->flags
);
5284 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5286 dt
->selector
= qemu_get_be32(f
);
5287 dt
->base
= qemu_get_betl(f
);
5288 dt
->limit
= qemu_get_be32(f
);
5289 dt
->flags
= qemu_get_be32(f
);
5292 void cpu_save(QEMUFile
*f
, void *opaque
)
5294 CPUState
*env
= opaque
;
5295 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5299 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5300 qemu_put_betls(f
, &env
->regs
[i
]);
5301 qemu_put_betls(f
, &env
->eip
);
5302 qemu_put_betls(f
, &env
->eflags
);
5303 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5304 qemu_put_be32s(f
, &hflags
);
5308 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5310 for(i
= 0; i
< 8; i
++) {
5311 fptag
|= ((!env
->fptags
[i
]) << i
);
5314 qemu_put_be16s(f
, &fpuc
);
5315 qemu_put_be16s(f
, &fpus
);
5316 qemu_put_be16s(f
, &fptag
);
5318 #ifdef USE_X86LDOUBLE
5323 qemu_put_be16s(f
, &fpregs_format
);
5325 for(i
= 0; i
< 8; i
++) {
5326 #ifdef USE_X86LDOUBLE
5330 /* we save the real CPU data (in case of MMX usage only 'mant'
5331 contains the MMX register */
5332 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5333 qemu_put_be64(f
, mant
);
5334 qemu_put_be16(f
, exp
);
5337 /* if we use doubles for float emulation, we save the doubles to
5338 avoid losing information in case of MMX usage. It can give
5339 problems if the image is restored on a CPU where long
5340 doubles are used instead. */
5341 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5345 for(i
= 0; i
< 6; i
++)
5346 cpu_put_seg(f
, &env
->segs
[i
]);
5347 cpu_put_seg(f
, &env
->ldt
);
5348 cpu_put_seg(f
, &env
->tr
);
5349 cpu_put_seg(f
, &env
->gdt
);
5350 cpu_put_seg(f
, &env
->idt
);
5352 qemu_put_be32s(f
, &env
->sysenter_cs
);
5353 qemu_put_be32s(f
, &env
->sysenter_esp
);
5354 qemu_put_be32s(f
, &env
->sysenter_eip
);
5356 qemu_put_betls(f
, &env
->cr
[0]);
5357 qemu_put_betls(f
, &env
->cr
[2]);
5358 qemu_put_betls(f
, &env
->cr
[3]);
5359 qemu_put_betls(f
, &env
->cr
[4]);
5361 for(i
= 0; i
< 8; i
++)
5362 qemu_put_betls(f
, &env
->dr
[i
]);
5365 qemu_put_be32s(f
, &env
->a20_mask
);
5368 qemu_put_be32s(f
, &env
->mxcsr
);
5369 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5370 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5371 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5374 #ifdef TARGET_X86_64
5375 qemu_put_be64s(f
, &env
->efer
);
5376 qemu_put_be64s(f
, &env
->star
);
5377 qemu_put_be64s(f
, &env
->lstar
);
5378 qemu_put_be64s(f
, &env
->cstar
);
5379 qemu_put_be64s(f
, &env
->fmask
);
5380 qemu_put_be64s(f
, &env
->kernelgsbase
);
5382 qemu_put_be32s(f
, &env
->smbase
);
5385 #ifdef USE_X86LDOUBLE
5386 /* XXX: add that in a FPU generic layer */
5387 union x86_longdouble
{
5392 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5393 #define EXPBIAS1 1023
5394 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5395 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5397 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5401 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5402 /* exponent + sign */
5403 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5404 e
|= SIGND1(temp
) >> 16;
5409 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5411 CPUState
*env
= opaque
;
5414 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5416 if (version_id
!= 3 && version_id
!= 4)
5418 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5419 qemu_get_betls(f
, &env
->regs
[i
]);
5420 qemu_get_betls(f
, &env
->eip
);
5421 qemu_get_betls(f
, &env
->eflags
);
5422 qemu_get_be32s(f
, &hflags
);
5424 qemu_get_be16s(f
, &fpuc
);
5425 qemu_get_be16s(f
, &fpus
);
5426 qemu_get_be16s(f
, &fptag
);
5427 qemu_get_be16s(f
, &fpregs_format
);
5429 /* NOTE: we cannot always restore the FPU state if the image come
5430 from a host with a different 'USE_X86LDOUBLE' define. We guess
5431 if we are in an MMX state to restore correctly in that case. */
5432 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5433 for(i
= 0; i
< 8; i
++) {
5437 switch(fpregs_format
) {
5439 mant
= qemu_get_be64(f
);
5440 exp
= qemu_get_be16(f
);
5441 #ifdef USE_X86LDOUBLE
5442 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5444 /* difficult case */
5446 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5448 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5452 mant
= qemu_get_be64(f
);
5453 #ifdef USE_X86LDOUBLE
5455 union x86_longdouble
*p
;
5456 /* difficult case */
5457 p
= (void *)&env
->fpregs
[i
];
5462 fp64_to_fp80(p
, mant
);
5466 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5475 /* XXX: restore FPU round state */
5476 env
->fpstt
= (fpus
>> 11) & 7;
5477 env
->fpus
= fpus
& ~0x3800;
5479 for(i
= 0; i
< 8; i
++) {
5480 env
->fptags
[i
] = (fptag
>> i
) & 1;
5483 for(i
= 0; i
< 6; i
++)
5484 cpu_get_seg(f
, &env
->segs
[i
]);
5485 cpu_get_seg(f
, &env
->ldt
);
5486 cpu_get_seg(f
, &env
->tr
);
5487 cpu_get_seg(f
, &env
->gdt
);
5488 cpu_get_seg(f
, &env
->idt
);
5490 qemu_get_be32s(f
, &env
->sysenter_cs
);
5491 qemu_get_be32s(f
, &env
->sysenter_esp
);
5492 qemu_get_be32s(f
, &env
->sysenter_eip
);
5494 qemu_get_betls(f
, &env
->cr
[0]);
5495 qemu_get_betls(f
, &env
->cr
[2]);
5496 qemu_get_betls(f
, &env
->cr
[3]);
5497 qemu_get_betls(f
, &env
->cr
[4]);
5499 for(i
= 0; i
< 8; i
++)
5500 qemu_get_betls(f
, &env
->dr
[i
]);
5503 qemu_get_be32s(f
, &env
->a20_mask
);
5505 qemu_get_be32s(f
, &env
->mxcsr
);
5506 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5507 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5508 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5511 #ifdef TARGET_X86_64
5512 qemu_get_be64s(f
, &env
->efer
);
5513 qemu_get_be64s(f
, &env
->star
);
5514 qemu_get_be64s(f
, &env
->lstar
);
5515 qemu_get_be64s(f
, &env
->cstar
);
5516 qemu_get_be64s(f
, &env
->fmask
);
5517 qemu_get_be64s(f
, &env
->kernelgsbase
);
5519 if (version_id
>= 4)
5520 qemu_get_be32s(f
, &env
->smbase
);
5522 /* XXX: compute hflags from scratch, except for CPL and IIF */
5523 env
->hflags
= hflags
;
5528 #elif defined(TARGET_PPC)
5529 void cpu_save(QEMUFile
*f
, void *opaque
)
5533 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5538 #elif defined(TARGET_MIPS)
5539 void cpu_save(QEMUFile
*f
, void *opaque
)
5543 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5548 #elif defined(TARGET_SPARC)
5549 void cpu_save(QEMUFile
*f
, void *opaque
)
5551 CPUState
*env
= opaque
;
5555 for(i
= 0; i
< 8; i
++)
5556 qemu_put_betls(f
, &env
->gregs
[i
]);
5557 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5558 qemu_put_betls(f
, &env
->regbase
[i
]);
5561 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5567 qemu_put_be32(f
, u
.i
);
5570 qemu_put_betls(f
, &env
->pc
);
5571 qemu_put_betls(f
, &env
->npc
);
5572 qemu_put_betls(f
, &env
->y
);
5574 qemu_put_be32(f
, tmp
);
5575 qemu_put_betls(f
, &env
->fsr
);
5576 qemu_put_betls(f
, &env
->tbr
);
5577 #ifndef TARGET_SPARC64
5578 qemu_put_be32s(f
, &env
->wim
);
5580 for(i
= 0; i
< 16; i
++)
5581 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5585 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5587 CPUState
*env
= opaque
;
5591 for(i
= 0; i
< 8; i
++)
5592 qemu_get_betls(f
, &env
->gregs
[i
]);
5593 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5594 qemu_get_betls(f
, &env
->regbase
[i
]);
5597 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5602 u
.i
= qemu_get_be32(f
);
5606 qemu_get_betls(f
, &env
->pc
);
5607 qemu_get_betls(f
, &env
->npc
);
5608 qemu_get_betls(f
, &env
->y
);
5609 tmp
= qemu_get_be32(f
);
5610 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5611 correctly updated */
5613 qemu_get_betls(f
, &env
->fsr
);
5614 qemu_get_betls(f
, &env
->tbr
);
5615 #ifndef TARGET_SPARC64
5616 qemu_get_be32s(f
, &env
->wim
);
5618 for(i
= 0; i
< 16; i
++)
5619 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5625 #elif defined(TARGET_ARM)
5627 /* ??? Need to implement these. */
5628 void cpu_save(QEMUFile
*f
, void *opaque
)
5632 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5639 #warning No CPU save/restore functions
5643 /***********************************************************/
5644 /* ram save/restore */
5646 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5650 v
= qemu_get_byte(f
);
5653 if (qemu_get_buffer(f
, buf
, len
) != len
)
5657 v
= qemu_get_byte(f
);
5658 memset(buf
, v
, len
);
5666 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5670 if (qemu_get_be32(f
) != phys_ram_size
)
5672 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5673 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5680 #define BDRV_HASH_BLOCK_SIZE 1024
5681 #define IOBUF_SIZE 4096
5682 #define RAM_CBLOCK_MAGIC 0xfabe
5684 typedef struct RamCompressState
{
5687 uint8_t buf
[IOBUF_SIZE
];
5690 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5693 memset(s
, 0, sizeof(*s
));
5695 ret
= deflateInit2(&s
->zstream
, 1,
5697 9, Z_DEFAULT_STRATEGY
);
5700 s
->zstream
.avail_out
= IOBUF_SIZE
;
5701 s
->zstream
.next_out
= s
->buf
;
5705 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5707 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5708 qemu_put_be16(s
->f
, len
);
5709 qemu_put_buffer(s
->f
, buf
, len
);
5712 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5716 s
->zstream
.avail_in
= len
;
5717 s
->zstream
.next_in
= (uint8_t *)buf
;
5718 while (s
->zstream
.avail_in
> 0) {
5719 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5722 if (s
->zstream
.avail_out
== 0) {
5723 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5724 s
->zstream
.avail_out
= IOBUF_SIZE
;
5725 s
->zstream
.next_out
= s
->buf
;
5731 static void ram_compress_close(RamCompressState
*s
)
5735 /* compress last bytes */
5737 ret
= deflate(&s
->zstream
, Z_FINISH
);
5738 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5739 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5741 ram_put_cblock(s
, s
->buf
, len
);
5743 s
->zstream
.avail_out
= IOBUF_SIZE
;
5744 s
->zstream
.next_out
= s
->buf
;
5745 if (ret
== Z_STREAM_END
)
5752 deflateEnd(&s
->zstream
);
5755 typedef struct RamDecompressState
{
5758 uint8_t buf
[IOBUF_SIZE
];
5759 } RamDecompressState
;
5761 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5764 memset(s
, 0, sizeof(*s
));
5766 ret
= inflateInit(&s
->zstream
);
5772 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5776 s
->zstream
.avail_out
= len
;
5777 s
->zstream
.next_out
= buf
;
5778 while (s
->zstream
.avail_out
> 0) {
5779 if (s
->zstream
.avail_in
== 0) {
5780 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5782 clen
= qemu_get_be16(s
->f
);
5783 if (clen
> IOBUF_SIZE
)
5785 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5786 s
->zstream
.avail_in
= clen
;
5787 s
->zstream
.next_in
= s
->buf
;
5789 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5790 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5797 static void ram_decompress_close(RamDecompressState
*s
)
5799 inflateEnd(&s
->zstream
);
5802 static void ram_save(QEMUFile
*f
, void *opaque
)
5805 RamCompressState s1
, *s
= &s1
;
5808 qemu_put_be32(f
, phys_ram_size
);
5809 if (ram_compress_open(s
, f
) < 0)
5811 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5813 if (tight_savevm_enabled
) {
5817 /* find if the memory block is available on a virtual
5820 for(j
= 0; j
< MAX_DISKS
; j
++) {
5822 sector_num
= bdrv_hash_find(bs_table
[j
],
5823 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5824 if (sector_num
>= 0)
5829 goto normal_compress
;
5832 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5833 ram_compress_buf(s
, buf
, 10);
5839 ram_compress_buf(s
, buf
, 1);
5840 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5843 ram_compress_close(s
);
5846 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5848 RamDecompressState s1
, *s
= &s1
;
5852 if (version_id
== 1)
5853 return ram_load_v1(f
, opaque
);
5854 if (version_id
!= 2)
5856 if (qemu_get_be32(f
) != phys_ram_size
)
5858 if (ram_decompress_open(s
, f
) < 0)
5860 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5861 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5862 fprintf(stderr
, "Error while reading ram block header\n");
5866 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5867 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5876 ram_decompress_buf(s
, buf
+ 1, 9);
5878 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5879 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5880 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5883 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5884 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5885 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5886 bs_index
, sector_num
);
5893 printf("Error block header\n");
5897 ram_decompress_close(s
);
5901 /***********************************************************/
5902 /* bottom halves (can be seen as timers which expire ASAP) */
5911 static QEMUBH
*first_bh
= NULL
;
5913 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5916 bh
= qemu_mallocz(sizeof(QEMUBH
));
5920 bh
->opaque
= opaque
;
5924 int qemu_bh_poll(void)
5943 void qemu_bh_schedule(QEMUBH
*bh
)
5945 CPUState
*env
= cpu_single_env
;
5949 bh
->next
= first_bh
;
5952 /* stop the currently executing CPU to execute the BH ASAP */
5954 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5958 void qemu_bh_cancel(QEMUBH
*bh
)
5961 if (bh
->scheduled
) {
5964 pbh
= &(*pbh
)->next
;
5970 void qemu_bh_delete(QEMUBH
*bh
)
5976 /***********************************************************/
5977 /* machine registration */
5979 QEMUMachine
*first_machine
= NULL
;
5981 int qemu_register_machine(QEMUMachine
*m
)
5984 pm
= &first_machine
;
5992 QEMUMachine
*find_machine(const char *name
)
5996 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5997 if (!strcmp(m
->name
, name
))
6003 /***********************************************************/
6004 /* main execution loop */
6006 void gui_update(void *opaque
)
6008 display_state
.dpy_refresh(&display_state
);
6009 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6012 struct vm_change_state_entry
{
6013 VMChangeStateHandler
*cb
;
6015 LIST_ENTRY (vm_change_state_entry
) entries
;
6018 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6020 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6023 VMChangeStateEntry
*e
;
6025 e
= qemu_mallocz(sizeof (*e
));
6031 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6035 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6037 LIST_REMOVE (e
, entries
);
6041 static void vm_state_notify(int running
)
6043 VMChangeStateEntry
*e
;
6045 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6046 e
->cb(e
->opaque
, running
);
6050 /* XXX: support several handlers */
6051 static VMStopHandler
*vm_stop_cb
;
6052 static void *vm_stop_opaque
;
6054 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6057 vm_stop_opaque
= opaque
;
6061 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6075 void vm_stop(int reason
)
6078 cpu_disable_ticks();
6082 vm_stop_cb(vm_stop_opaque
, reason
);
6089 /* reset/shutdown handler */
6091 typedef struct QEMUResetEntry
{
6092 QEMUResetHandler
*func
;
6094 struct QEMUResetEntry
*next
;
6097 static QEMUResetEntry
*first_reset_entry
;
6098 static int reset_requested
;
6099 static int shutdown_requested
;
6100 static int powerdown_requested
;
6102 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6104 QEMUResetEntry
**pre
, *re
;
6106 pre
= &first_reset_entry
;
6107 while (*pre
!= NULL
)
6108 pre
= &(*pre
)->next
;
6109 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6111 re
->opaque
= opaque
;
6116 static void qemu_system_reset(void)
6120 /* reset all devices */
6121 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6122 re
->func(re
->opaque
);
6126 void qemu_system_reset_request(void)
6129 shutdown_requested
= 1;
6131 reset_requested
= 1;
6134 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6137 void qemu_system_shutdown_request(void)
6139 shutdown_requested
= 1;
6141 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6144 void qemu_system_powerdown_request(void)
6146 powerdown_requested
= 1;
6148 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6151 void main_loop_wait(int timeout
)
6153 IOHandlerRecord
*ioh
;
6154 fd_set rfds
, wfds
, xfds
;
6160 /* XXX: need to suppress polling by better using win32 events */
6162 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6163 ret
|= pe
->func(pe
->opaque
);
6166 if (ret
== 0 && timeout
> 0) {
6168 WaitObjects
*w
= &wait_objects
;
6170 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6171 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6172 if (w
->func
[ret
- WAIT_OBJECT_0
])
6173 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6174 } else if (ret
== WAIT_TIMEOUT
) {
6176 err
= GetLastError();
6177 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6181 /* poll any events */
6182 /* XXX: separate device handlers from system ones */
6187 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6191 (!ioh
->fd_read_poll
||
6192 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6193 FD_SET(ioh
->fd
, &rfds
);
6197 if (ioh
->fd_write
) {
6198 FD_SET(ioh
->fd
, &wfds
);
6208 tv
.tv_usec
= timeout
* 1000;
6210 #if defined(CONFIG_SLIRP)
6212 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6215 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6217 IOHandlerRecord
**pioh
;
6219 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6222 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6223 ioh
->fd_read(ioh
->opaque
);
6225 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6226 ioh
->fd_write(ioh
->opaque
);
6230 /* remove deleted IO handlers */
6231 pioh
= &first_io_handler
;
6241 #if defined(CONFIG_SLIRP)
6248 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6255 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6256 qemu_get_clock(vm_clock
));
6257 /* run dma transfers, if any */
6261 /* real time timers */
6262 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6263 qemu_get_clock(rt_clock
));
6266 static CPUState
*cur_cpu
;
6271 #ifdef CONFIG_PROFILER
6276 cur_cpu
= first_cpu
;
6283 env
= env
->next_cpu
;
6286 #ifdef CONFIG_PROFILER
6287 ti
= profile_getclock();
6289 ret
= cpu_exec(env
);
6290 #ifdef CONFIG_PROFILER
6291 qemu_time
+= profile_getclock() - ti
;
6293 if (ret
== EXCP_HLT
) {
6294 /* Give the next CPU a chance to run. */
6298 if (ret
!= EXCP_HALTED
)
6300 /* all CPUs are halted ? */
6306 if (shutdown_requested
) {
6307 ret
= EXCP_INTERRUPT
;
6310 if (reset_requested
) {
6311 reset_requested
= 0;
6312 qemu_system_reset();
6313 ret
= EXCP_INTERRUPT
;
6315 if (powerdown_requested
) {
6316 powerdown_requested
= 0;
6317 qemu_system_powerdown();
6318 ret
= EXCP_INTERRUPT
;
6320 if (ret
== EXCP_DEBUG
) {
6321 vm_stop(EXCP_DEBUG
);
6323 /* If all cpus are halted then wait until the next IRQ */
6324 /* XXX: use timeout computed from timers */
6325 if (ret
== EXCP_HALTED
)
6332 #ifdef CONFIG_PROFILER
6333 ti
= profile_getclock();
6335 main_loop_wait(timeout
);
6336 #ifdef CONFIG_PROFILER
6337 dev_time
+= profile_getclock() - ti
;
6340 cpu_disable_ticks();
6346 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6347 "usage: %s [options] [disk_image]\n"
6349 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6351 "Standard options:\n"
6352 "-M machine select emulated machine (-M ? for list)\n"
6353 "-cpu cpu select CPU (-cpu ? for list)\n"
6354 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6355 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6356 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6357 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6358 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6359 "-snapshot write to temporary files instead of disk image files\n"
6361 "-no-frame open SDL window without a frame and window decorations\n"
6362 "-no-quit disable SDL window close capability\n"
6365 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6367 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6368 "-smp n set the number of CPUs to 'n' [default=1]\n"
6369 "-nographic disable graphical output and redirect serial I/Os to console\n"
6371 "-k language use keyboard layout (for example \"fr\" for French)\n"
6374 "-audio-help print list of audio drivers and their options\n"
6375 "-soundhw c1,... enable audio support\n"
6376 " and only specified sound cards (comma separated list)\n"
6377 " use -soundhw ? to get the list of supported cards\n"
6378 " use -soundhw all to enable all of them\n"
6380 "-localtime set the real time clock to local time [default=utc]\n"
6381 "-full-screen start in full screen\n"
6383 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6385 "-usb enable the USB driver (will be the default soon)\n"
6386 "-usbdevice name add the host or guest USB device 'name'\n"
6387 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6388 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6390 "-name string set the name of the guest\n"
6392 "Network options:\n"
6393 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6394 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6396 "-net user[,vlan=n][,hostname=host]\n"
6397 " connect the user mode network stack to VLAN 'n' and send\n"
6398 " hostname 'host' to DHCP clients\n"
6401 "-net tap[,vlan=n],ifname=name\n"
6402 " connect the host TAP network interface to VLAN 'n'\n"
6404 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6405 " connect the host TAP network interface to VLAN 'n' and use\n"
6406 " the network script 'file' (default=%s);\n"
6407 " use 'script=no' to disable script execution;\n"
6408 " use 'fd=h' to connect to an already opened TAP interface\n"
6410 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6411 " connect the vlan 'n' to another VLAN using a socket connection\n"
6412 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6413 " connect the vlan 'n' to multicast maddr and port\n"
6414 "-net none use it alone to have zero network devices; if no -net option\n"
6415 " is provided, the default is '-net nic -net user'\n"
6418 "-tftp dir allow tftp access to files in dir [-net user]\n"
6419 "-bootp file advertise file in BOOTP replies\n"
6421 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6423 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6424 " redirect TCP or UDP connections from host to guest [-net user]\n"
6427 "Linux boot specific:\n"
6428 "-kernel bzImage use 'bzImage' as kernel image\n"
6429 "-append cmdline use 'cmdline' as kernel command line\n"
6430 "-initrd file use 'file' as initial ram disk\n"
6432 "Debug/Expert options:\n"
6433 "-monitor dev redirect the monitor to char device 'dev'\n"
6434 "-serial dev redirect the serial port to char device 'dev'\n"
6435 "-parallel dev redirect the parallel port to char device 'dev'\n"
6436 "-pidfile file Write PID to 'file'\n"
6437 "-S freeze CPU at startup (use 'c' to start execution)\n"
6438 "-s wait gdb connection to port\n"
6439 "-p port set gdb connection port [default=%s]\n"
6440 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6441 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6442 " translation (t=none or lba) (usually qemu can guess them)\n"
6443 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6445 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6446 "-no-kqemu disable KQEMU kernel module usage\n"
6448 #ifdef USE_CODE_COPY
6449 "-no-code-copy disable code copy acceleration\n"
6452 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6453 " (default is CL-GD5446 PCI VGA)\n"
6454 "-no-acpi disable ACPI\n"
6456 "-no-reboot exit instead of rebooting\n"
6457 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6458 "-vnc display start a VNC server on display\n"
6460 "-daemonize daemonize QEMU after initializing\n"
6462 "-option-rom rom load a file, rom, into the option ROM space\n"
6464 "During emulation, the following keys are useful:\n"
6465 "ctrl-alt-f toggle full screen\n"
6466 "ctrl-alt-n switch to virtual console 'n'\n"
6467 "ctrl-alt toggle mouse and keyboard grab\n"
6469 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6474 DEFAULT_NETWORK_SCRIPT
,
6476 DEFAULT_GDBSTUB_PORT
,
6481 #define HAS_ARG 0x0001
6496 QEMU_OPTION_snapshot
,
6498 QEMU_OPTION_no_fd_bootchk
,
6501 QEMU_OPTION_nographic
,
6503 QEMU_OPTION_audio_help
,
6504 QEMU_OPTION_soundhw
,
6523 QEMU_OPTION_no_code_copy
,
6525 QEMU_OPTION_localtime
,
6526 QEMU_OPTION_cirrusvga
,
6528 QEMU_OPTION_std_vga
,
6530 QEMU_OPTION_monitor
,
6532 QEMU_OPTION_parallel
,
6534 QEMU_OPTION_full_screen
,
6535 QEMU_OPTION_no_frame
,
6536 QEMU_OPTION_no_quit
,
6537 QEMU_OPTION_pidfile
,
6538 QEMU_OPTION_no_kqemu
,
6539 QEMU_OPTION_kernel_kqemu
,
6540 QEMU_OPTION_win2k_hack
,
6542 QEMU_OPTION_usbdevice
,
6545 QEMU_OPTION_no_acpi
,
6546 QEMU_OPTION_no_reboot
,
6547 QEMU_OPTION_daemonize
,
6548 QEMU_OPTION_option_rom
,
6549 QEMU_OPTION_semihosting
,
6553 typedef struct QEMUOption
{
6559 const QEMUOption qemu_options
[] = {
6560 { "h", 0, QEMU_OPTION_h
},
6561 { "help", 0, QEMU_OPTION_h
},
6563 { "M", HAS_ARG
, QEMU_OPTION_M
},
6564 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
6565 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6566 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6567 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6568 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6569 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6570 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6571 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6572 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6573 { "snapshot", 0, QEMU_OPTION_snapshot
},
6575 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6577 { "m", HAS_ARG
, QEMU_OPTION_m
},
6578 { "nographic", 0, QEMU_OPTION_nographic
},
6579 { "k", HAS_ARG
, QEMU_OPTION_k
},
6581 { "audio-help", 0, QEMU_OPTION_audio_help
},
6582 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6585 { "net", HAS_ARG
, QEMU_OPTION_net
},
6587 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6588 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
6590 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6592 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6595 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6596 { "append", HAS_ARG
, QEMU_OPTION_append
},
6597 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6599 { "S", 0, QEMU_OPTION_S
},
6600 { "s", 0, QEMU_OPTION_s
},
6601 { "p", HAS_ARG
, QEMU_OPTION_p
},
6602 { "d", HAS_ARG
, QEMU_OPTION_d
},
6603 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6604 { "L", HAS_ARG
, QEMU_OPTION_L
},
6605 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6607 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6608 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6610 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6611 { "g", 1, QEMU_OPTION_g
},
6613 { "localtime", 0, QEMU_OPTION_localtime
},
6614 { "std-vga", 0, QEMU_OPTION_std_vga
},
6615 { "echr", 1, QEMU_OPTION_echr
},
6616 { "monitor", 1, QEMU_OPTION_monitor
},
6617 { "serial", 1, QEMU_OPTION_serial
},
6618 { "parallel", 1, QEMU_OPTION_parallel
},
6619 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6620 { "full-screen", 0, QEMU_OPTION_full_screen
},
6622 { "no-frame", 0, QEMU_OPTION_no_frame
},
6623 { "no-quit", 0, QEMU_OPTION_no_quit
},
6625 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6626 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6627 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6628 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6629 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6631 /* temporary options */
6632 { "usb", 0, QEMU_OPTION_usb
},
6633 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6634 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6635 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6636 { "daemonize", 0, QEMU_OPTION_daemonize
},
6637 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6638 #if defined(TARGET_ARM)
6639 { "semihosting", 0, QEMU_OPTION_semihosting
},
6641 { "name", HAS_ARG
, QEMU_OPTION_name
},
6645 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6647 /* this stack is only used during signal handling */
6648 #define SIGNAL_STACK_SIZE 32768
6650 static uint8_t *signal_stack
;
6654 /* password input */
6656 static BlockDriverState
*get_bdrv(int index
)
6658 BlockDriverState
*bs
;
6661 bs
= bs_table
[index
];
6662 } else if (index
< 6) {
6663 bs
= fd_table
[index
- 4];
6670 static void read_passwords(void)
6672 BlockDriverState
*bs
;
6676 for(i
= 0; i
< 6; i
++) {
6678 if (bs
&& bdrv_is_encrypted(bs
)) {
6679 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6680 for(j
= 0; j
< 3; j
++) {
6681 monitor_readline("Password: ",
6682 1, password
, sizeof(password
));
6683 if (bdrv_set_key(bs
, password
) == 0)
6685 term_printf("invalid password\n");
6691 /* XXX: currently we cannot use simultaneously different CPUs */
6692 void register_machines(void)
6694 #if defined(TARGET_I386)
6695 qemu_register_machine(&pc_machine
);
6696 qemu_register_machine(&isapc_machine
);
6697 #elif defined(TARGET_PPC)
6698 qemu_register_machine(&heathrow_machine
);
6699 qemu_register_machine(&core99_machine
);
6700 qemu_register_machine(&prep_machine
);
6701 #elif defined(TARGET_MIPS)
6702 qemu_register_machine(&mips_machine
);
6703 qemu_register_machine(&mips_malta_machine
);
6704 #elif defined(TARGET_SPARC)
6705 #ifdef TARGET_SPARC64
6706 qemu_register_machine(&sun4u_machine
);
6708 qemu_register_machine(&sun4m_machine
);
6710 #elif defined(TARGET_ARM)
6711 qemu_register_machine(&integratorcp_machine
);
6712 qemu_register_machine(&versatilepb_machine
);
6713 qemu_register_machine(&versatileab_machine
);
6714 qemu_register_machine(&realview_machine
);
6715 #elif defined(TARGET_SH4)
6716 qemu_register_machine(&shix_machine
);
6718 #error unsupported CPU
6723 struct soundhw soundhw
[] = {
6730 { .init_isa
= pcspk_audio_init
}
6735 "Creative Sound Blaster 16",
6738 { .init_isa
= SB16_init
}
6745 "Yamaha YMF262 (OPL3)",
6747 "Yamaha YM3812 (OPL2)",
6751 { .init_isa
= Adlib_init
}
6758 "Gravis Ultrasound GF1",
6761 { .init_isa
= GUS_init
}
6767 "ENSONIQ AudioPCI ES1370",
6770 { .init_pci
= es1370_init
}
6773 { NULL
, NULL
, 0, 0, { NULL
} }
6776 static void select_soundhw (const char *optarg
)
6780 if (*optarg
== '?') {
6783 printf ("Valid sound card names (comma separated):\n");
6784 for (c
= soundhw
; c
->name
; ++c
) {
6785 printf ("%-11s %s\n", c
->name
, c
->descr
);
6787 printf ("\n-soundhw all will enable all of the above\n");
6788 exit (*optarg
!= '?');
6796 if (!strcmp (optarg
, "all")) {
6797 for (c
= soundhw
; c
->name
; ++c
) {
6805 e
= strchr (p
, ',');
6806 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6808 for (c
= soundhw
; c
->name
; ++c
) {
6809 if (!strncmp (c
->name
, p
, l
)) {
6818 "Unknown sound card name (too big to show)\n");
6821 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6826 p
+= l
+ (e
!= NULL
);
6830 goto show_valid_cards
;
6836 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6838 exit(STATUS_CONTROL_C_EXIT
);
6843 #define MAX_NET_CLIENTS 32
6845 int main(int argc
, char **argv
)
6847 #ifdef CONFIG_GDBSTUB
6849 const char *gdbstub_port
;
6852 int snapshot
, linux_boot
;
6853 const char *initrd_filename
;
6854 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6855 const char *kernel_filename
, *kernel_cmdline
;
6856 DisplayState
*ds
= &display_state
;
6857 int cyls
, heads
, secs
, translation
;
6858 char net_clients
[MAX_NET_CLIENTS
][256];
6861 const char *r
, *optarg
;
6862 CharDriverState
*monitor_hd
;
6863 char monitor_device
[128];
6864 char serial_devices
[MAX_SERIAL_PORTS
][128];
6865 int serial_device_index
;
6866 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6867 int parallel_device_index
;
6868 const char *loadvm
= NULL
;
6869 QEMUMachine
*machine
;
6870 const char *cpu_model
;
6871 char usb_devices
[MAX_USB_CMDLINE
][128];
6872 int usb_devices_index
;
6874 const char *pid_file
= NULL
;
6876 LIST_INIT (&vm_change_state_head
);
6879 struct sigaction act
;
6880 sigfillset(&act
.sa_mask
);
6882 act
.sa_handler
= SIG_IGN
;
6883 sigaction(SIGPIPE
, &act
, NULL
);
6886 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6887 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6888 QEMU to run on a single CPU */
6893 h
= GetCurrentProcess();
6894 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6895 for(i
= 0; i
< 32; i
++) {
6896 if (mask
& (1 << i
))
6901 SetProcessAffinityMask(h
, mask
);
6907 register_machines();
6908 machine
= first_machine
;
6910 initrd_filename
= NULL
;
6911 for(i
= 0; i
< MAX_FD
; i
++)
6912 fd_filename
[i
] = NULL
;
6913 for(i
= 0; i
< MAX_DISKS
; i
++)
6914 hd_filename
[i
] = NULL
;
6915 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6916 vga_ram_size
= VGA_RAM_SIZE
;
6917 #ifdef CONFIG_GDBSTUB
6919 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6923 kernel_filename
= NULL
;
6924 kernel_cmdline
= "";
6930 cyls
= heads
= secs
= 0;
6931 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6932 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6934 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6935 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6936 serial_devices
[i
][0] = '\0';
6937 serial_device_index
= 0;
6939 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6940 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6941 parallel_devices
[i
][0] = '\0';
6942 parallel_device_index
= 0;
6944 usb_devices_index
= 0;
6949 /* default mac address of the first network interface */
6957 hd_filename
[0] = argv
[optind
++];
6959 const QEMUOption
*popt
;
6962 /* Treat --foo the same as -foo. */
6965 popt
= qemu_options
;
6968 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6972 if (!strcmp(popt
->name
, r
+ 1))
6976 if (popt
->flags
& HAS_ARG
) {
6977 if (optind
>= argc
) {
6978 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6982 optarg
= argv
[optind
++];
6987 switch(popt
->index
) {
6989 machine
= find_machine(optarg
);
6992 printf("Supported machines are:\n");
6993 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6994 printf("%-10s %s%s\n",
6996 m
== first_machine
? " (default)" : "");
7001 case QEMU_OPTION_cpu
:
7002 /* hw initialization will check this */
7003 if (optarg
[0] == '?') {
7004 #if defined(TARGET_PPC)
7005 ppc_cpu_list(stdout
, &fprintf
);
7006 #elif defined(TARGET_ARM)
7008 #elif defined(TARGET_MIPS)
7009 mips_cpu_list(stdout
, &fprintf
);
7016 case QEMU_OPTION_initrd
:
7017 initrd_filename
= optarg
;
7019 case QEMU_OPTION_hda
:
7020 case QEMU_OPTION_hdb
:
7021 case QEMU_OPTION_hdc
:
7022 case QEMU_OPTION_hdd
:
7025 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7026 hd_filename
[hd_index
] = optarg
;
7027 if (hd_index
== cdrom_index
)
7031 case QEMU_OPTION_snapshot
:
7034 case QEMU_OPTION_hdachs
:
7038 cyls
= strtol(p
, (char **)&p
, 0);
7039 if (cyls
< 1 || cyls
> 16383)
7044 heads
= strtol(p
, (char **)&p
, 0);
7045 if (heads
< 1 || heads
> 16)
7050 secs
= strtol(p
, (char **)&p
, 0);
7051 if (secs
< 1 || secs
> 63)
7055 if (!strcmp(p
, "none"))
7056 translation
= BIOS_ATA_TRANSLATION_NONE
;
7057 else if (!strcmp(p
, "lba"))
7058 translation
= BIOS_ATA_TRANSLATION_LBA
;
7059 else if (!strcmp(p
, "auto"))
7060 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7063 } else if (*p
!= '\0') {
7065 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7070 case QEMU_OPTION_nographic
:
7071 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7072 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7075 case QEMU_OPTION_kernel
:
7076 kernel_filename
= optarg
;
7078 case QEMU_OPTION_append
:
7079 kernel_cmdline
= optarg
;
7081 case QEMU_OPTION_cdrom
:
7082 if (cdrom_index
>= 0) {
7083 hd_filename
[cdrom_index
] = optarg
;
7086 case QEMU_OPTION_boot
:
7087 boot_device
= optarg
[0];
7088 if (boot_device
!= 'a' &&
7089 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7091 boot_device
!= 'n' &&
7093 boot_device
!= 'c' && boot_device
!= 'd') {
7094 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7098 case QEMU_OPTION_fda
:
7099 fd_filename
[0] = optarg
;
7101 case QEMU_OPTION_fdb
:
7102 fd_filename
[1] = optarg
;
7105 case QEMU_OPTION_no_fd_bootchk
:
7109 case QEMU_OPTION_no_code_copy
:
7110 code_copy_enabled
= 0;
7112 case QEMU_OPTION_net
:
7113 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7114 fprintf(stderr
, "qemu: too many network clients\n");
7117 pstrcpy(net_clients
[nb_net_clients
],
7118 sizeof(net_clients
[0]),
7123 case QEMU_OPTION_tftp
:
7124 tftp_prefix
= optarg
;
7126 case QEMU_OPTION_bootp
:
7127 bootp_filename
= optarg
;
7130 case QEMU_OPTION_smb
:
7131 net_slirp_smb(optarg
);
7134 case QEMU_OPTION_redir
:
7135 net_slirp_redir(optarg
);
7139 case QEMU_OPTION_audio_help
:
7143 case QEMU_OPTION_soundhw
:
7144 select_soundhw (optarg
);
7151 ram_size
= atoi(optarg
) * 1024 * 1024;
7154 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7155 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7156 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7165 mask
= cpu_str_to_log_mask(optarg
);
7167 printf("Log items (comma separated):\n");
7168 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7169 printf("%-10s %s\n", item
->name
, item
->help
);
7176 #ifdef CONFIG_GDBSTUB
7181 gdbstub_port
= optarg
;
7191 keyboard_layout
= optarg
;
7193 case QEMU_OPTION_localtime
:
7196 case QEMU_OPTION_cirrusvga
:
7197 cirrus_vga_enabled
= 1;
7199 case QEMU_OPTION_std_vga
:
7200 cirrus_vga_enabled
= 0;
7207 w
= strtol(p
, (char **)&p
, 10);
7210 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7216 h
= strtol(p
, (char **)&p
, 10);
7221 depth
= strtol(p
, (char **)&p
, 10);
7222 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7223 depth
!= 24 && depth
!= 32)
7225 } else if (*p
== '\0') {
7226 depth
= graphic_depth
;
7233 graphic_depth
= depth
;
7236 case QEMU_OPTION_echr
:
7239 term_escape_char
= strtol(optarg
, &r
, 0);
7241 printf("Bad argument to echr\n");
7244 case QEMU_OPTION_monitor
:
7245 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7247 case QEMU_OPTION_serial
:
7248 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7249 fprintf(stderr
, "qemu: too many serial ports\n");
7252 pstrcpy(serial_devices
[serial_device_index
],
7253 sizeof(serial_devices
[0]), optarg
);
7254 serial_device_index
++;
7256 case QEMU_OPTION_parallel
:
7257 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7258 fprintf(stderr
, "qemu: too many parallel ports\n");
7261 pstrcpy(parallel_devices
[parallel_device_index
],
7262 sizeof(parallel_devices
[0]), optarg
);
7263 parallel_device_index
++;
7265 case QEMU_OPTION_loadvm
:
7268 case QEMU_OPTION_full_screen
:
7272 case QEMU_OPTION_no_frame
:
7275 case QEMU_OPTION_no_quit
:
7279 case QEMU_OPTION_pidfile
:
7283 case QEMU_OPTION_win2k_hack
:
7284 win2k_install_hack
= 1;
7288 case QEMU_OPTION_no_kqemu
:
7291 case QEMU_OPTION_kernel_kqemu
:
7295 case QEMU_OPTION_usb
:
7298 case QEMU_OPTION_usbdevice
:
7300 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7301 fprintf(stderr
, "Too many USB devices\n");
7304 pstrcpy(usb_devices
[usb_devices_index
],
7305 sizeof(usb_devices
[usb_devices_index
]),
7307 usb_devices_index
++;
7309 case QEMU_OPTION_smp
:
7310 smp_cpus
= atoi(optarg
);
7311 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7312 fprintf(stderr
, "Invalid number of CPUs\n");
7316 case QEMU_OPTION_vnc
:
7317 vnc_display
= optarg
;
7319 case QEMU_OPTION_no_acpi
:
7322 case QEMU_OPTION_no_reboot
:
7325 case QEMU_OPTION_daemonize
:
7328 case QEMU_OPTION_option_rom
:
7329 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7330 fprintf(stderr
, "Too many option ROMs\n");
7333 option_rom
[nb_option_roms
] = optarg
;
7336 case QEMU_OPTION_semihosting
:
7337 semihosting_enabled
= 1;
7339 case QEMU_OPTION_name
:
7347 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7348 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7355 if (pipe(fds
) == -1)
7366 len
= read(fds
[0], &status
, 1);
7367 if (len
== -1 && (errno
== EINTR
))
7372 else if (status
== 1) {
7373 fprintf(stderr
, "Could not acquire pidfile\n");
7391 signal(SIGTSTP
, SIG_IGN
);
7392 signal(SIGTTOU
, SIG_IGN
);
7393 signal(SIGTTIN
, SIG_IGN
);
7397 if (pid_file
&& create_pidfile(pid_file
) != 0) {
7400 write(fds
[1], &status
, 1);
7402 fprintf(stderr
, "Could not acquire pid file\n");
7410 linux_boot
= (kernel_filename
!= NULL
);
7413 boot_device
!= 'n' &&
7414 hd_filename
[0] == '\0' &&
7415 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7416 fd_filename
[0] == '\0')
7419 /* boot to floppy or the default cd if no hard disk defined yet */
7420 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7421 if (fd_filename
[0] != '\0')
7427 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7437 /* init network clients */
7438 if (nb_net_clients
== 0) {
7439 /* if no clients, we use a default config */
7440 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7442 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7447 for(i
= 0;i
< nb_net_clients
; i
++) {
7448 if (net_client_init(net_clients
[i
]) < 0)
7453 if (boot_device
== 'n') {
7454 for (i
= 0; i
< nb_nics
; i
++) {
7455 const char *model
= nd_table
[i
].model
;
7459 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7460 if (get_image_size(buf
) > 0) {
7461 option_rom
[nb_option_roms
] = strdup(buf
);
7467 fprintf(stderr
, "No valid PXE rom found for network device\n");
7470 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7474 /* init the memory */
7475 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
7477 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7478 if (!phys_ram_base
) {
7479 fprintf(stderr
, "Could not allocate physical memory\n");
7483 /* we always create the cdrom drive, even if no disk is there */
7485 if (cdrom_index
>= 0) {
7486 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7487 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7490 /* open the virtual block devices */
7491 for(i
= 0; i
< MAX_DISKS
; i
++) {
7492 if (hd_filename
[i
]) {
7495 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7496 bs_table
[i
] = bdrv_new(buf
);
7498 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7499 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7503 if (i
== 0 && cyls
!= 0) {
7504 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7505 bdrv_set_translation_hint(bs_table
[i
], translation
);
7510 /* we always create at least one floppy disk */
7511 fd_table
[0] = bdrv_new("fda");
7512 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7514 for(i
= 0; i
< MAX_FD
; i
++) {
7515 if (fd_filename
[i
]) {
7518 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7519 fd_table
[i
] = bdrv_new(buf
);
7520 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7522 if (fd_filename
[i
] != '\0') {
7523 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7524 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7525 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7533 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7534 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7540 dumb_display_init(ds
);
7541 } else if (vnc_display
!= NULL
) {
7542 vnc_display_init(ds
, vnc_display
);
7544 #if defined(CONFIG_SDL)
7545 sdl_display_init(ds
, full_screen
, no_frame
);
7546 #elif defined(CONFIG_COCOA)
7547 cocoa_display_init(ds
, full_screen
);
7549 dumb_display_init(ds
);
7553 /* Maintain compatibility with multiple stdio monitors */
7554 if (!strcmp(monitor_device
,"stdio")) {
7555 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7556 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
7557 monitor_device
[0] = '\0';
7559 } else if (!strcmp(serial_devices
[i
],"stdio")) {
7560 monitor_device
[0] = '\0';
7561 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
7566 if (monitor_device
[0] != '\0') {
7567 monitor_hd
= qemu_chr_open(monitor_device
);
7569 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7572 monitor_init(monitor_hd
, !nographic
);
7575 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7576 const char *devname
= serial_devices
[i
];
7577 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7578 serial_hds
[i
] = qemu_chr_open(devname
);
7579 if (!serial_hds
[i
]) {
7580 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7584 if (!strcmp(devname
, "vc"))
7585 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7589 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7590 const char *devname
= parallel_devices
[i
];
7591 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7592 parallel_hds
[i
] = qemu_chr_open(devname
);
7593 if (!parallel_hds
[i
]) {
7594 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7598 if (!strcmp(devname
, "vc"))
7599 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7603 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7604 ds
, fd_filename
, snapshot
,
7605 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
7607 /* init USB devices */
7609 for(i
= 0; i
< usb_devices_index
; i
++) {
7610 if (usb_device_add(usb_devices
[i
]) < 0) {
7611 fprintf(stderr
, "Warning: could not add USB device %s\n",
7617 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7618 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7620 #ifdef CONFIG_GDBSTUB
7622 /* XXX: use standard host:port notation and modify options
7624 if (gdbserver_start(gdbstub_port
) < 0) {
7625 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
7635 /* XXX: simplify init */
7648 len
= write(fds
[1], &status
, 1);
7649 if (len
== -1 && (errno
== EINTR
))
7655 fd
= open("/dev/null", O_RDWR
);