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 */
3625 *parg
++ = (char *)setup_script
;
3628 execv(setup_script
, args
);
3631 while (waitpid(pid
, &status
, 0) != pid
);
3632 if (!WIFEXITED(status
) ||
3633 WEXITSTATUS(status
) != 0) {
3634 fprintf(stderr
, "%s: could not launch network script\n",
3640 s
= net_tap_fd_init(vlan
, fd
);
3643 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3644 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3648 #endif /* !_WIN32 */
3650 /* network connection */
3651 typedef struct NetSocketState
{
3652 VLANClientState
*vc
;
3654 int state
; /* 0 = getting length, 1 = getting data */
3658 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3661 typedef struct NetSocketListenState
{
3664 } NetSocketListenState
;
3666 /* XXX: we consider we can send the whole packet without blocking */
3667 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3669 NetSocketState
*s
= opaque
;
3673 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3674 send_all(s
->fd
, buf
, size
);
3677 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3679 NetSocketState
*s
= opaque
;
3680 sendto(s
->fd
, buf
, size
, 0,
3681 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3684 static void net_socket_send(void *opaque
)
3686 NetSocketState
*s
= opaque
;
3691 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3693 err
= socket_error();
3694 if (err
!= EWOULDBLOCK
)
3696 } else if (size
== 0) {
3697 /* end of connection */
3699 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3705 /* reassemble a packet from the network */
3711 memcpy(s
->buf
+ s
->index
, buf
, l
);
3715 if (s
->index
== 4) {
3717 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3723 l
= s
->packet_len
- s
->index
;
3726 memcpy(s
->buf
+ s
->index
, buf
, l
);
3730 if (s
->index
>= s
->packet_len
) {
3731 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3740 static void net_socket_send_dgram(void *opaque
)
3742 NetSocketState
*s
= opaque
;
3745 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3749 /* end of connection */
3750 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3753 qemu_send_packet(s
->vc
, s
->buf
, size
);
3756 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3761 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3762 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3763 inet_ntoa(mcastaddr
->sin_addr
),
3764 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3768 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3770 perror("socket(PF_INET, SOCK_DGRAM)");
3775 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3776 (const char *)&val
, sizeof(val
));
3778 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3782 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3788 /* Add host to multicast group */
3789 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3790 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3792 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3793 (const char *)&imr
, sizeof(struct ip_mreq
));
3795 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3799 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3801 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3802 (const char *)&val
, sizeof(val
));
3804 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3808 socket_set_nonblock(fd
);
3816 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3819 struct sockaddr_in saddr
;
3821 socklen_t saddr_len
;
3824 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3825 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3826 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3830 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3832 if (saddr
.sin_addr
.s_addr
==0) {
3833 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3837 /* clone dgram socket */
3838 newfd
= net_socket_mcast_create(&saddr
);
3840 /* error already reported by net_socket_mcast_create() */
3844 /* clone newfd to fd, close newfd */
3849 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3850 fd
, strerror(errno
));
3855 s
= qemu_mallocz(sizeof(NetSocketState
));
3860 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3861 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3863 /* mcast: save bound address as dst */
3864 if (is_connected
) s
->dgram_dst
=saddr
;
3866 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3867 "socket: fd=%d (%s mcast=%s:%d)",
3868 fd
, is_connected
? "cloned" : "",
3869 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3873 static void net_socket_connect(void *opaque
)
3875 NetSocketState
*s
= opaque
;
3876 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3879 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3883 s
= qemu_mallocz(sizeof(NetSocketState
));
3887 s
->vc
= qemu_new_vlan_client(vlan
,
3888 net_socket_receive
, NULL
, s
);
3889 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3890 "socket: fd=%d", fd
);
3892 net_socket_connect(s
);
3894 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3899 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3902 int so_type
=-1, optlen
=sizeof(so_type
);
3904 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3905 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3910 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3912 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3914 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3915 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3916 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3921 static void net_socket_accept(void *opaque
)
3923 NetSocketListenState
*s
= opaque
;
3925 struct sockaddr_in saddr
;
3930 len
= sizeof(saddr
);
3931 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3932 if (fd
< 0 && errno
!= EINTR
) {
3934 } else if (fd
>= 0) {
3938 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3942 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3943 "socket: connection from %s:%d",
3944 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3948 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3950 NetSocketListenState
*s
;
3952 struct sockaddr_in saddr
;
3954 if (parse_host_port(&saddr
, host_str
) < 0)
3957 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3961 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3966 socket_set_nonblock(fd
);
3968 /* allow fast reuse */
3970 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3972 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3977 ret
= listen(fd
, 0);
3984 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3988 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3991 int fd
, connected
, ret
, err
;
3992 struct sockaddr_in saddr
;
3994 if (parse_host_port(&saddr
, host_str
) < 0)
3997 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4002 socket_set_nonblock(fd
);
4006 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4008 err
= socket_error();
4009 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4010 } else if (err
== EINPROGRESS
) {
4022 s
= net_socket_fd_init(vlan
, fd
, connected
);
4025 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4026 "socket: connect to %s:%d",
4027 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4031 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4035 struct sockaddr_in saddr
;
4037 if (parse_host_port(&saddr
, host_str
) < 0)
4041 fd
= net_socket_mcast_create(&saddr
);
4045 s
= net_socket_fd_init(vlan
, fd
, 0);
4049 s
->dgram_dst
= saddr
;
4051 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4052 "socket: mcast=%s:%d",
4053 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4058 static int get_param_value(char *buf
, int buf_size
,
4059 const char *tag
, const char *str
)
4068 while (*p
!= '\0' && *p
!= '=') {
4069 if ((q
- option
) < sizeof(option
) - 1)
4077 if (!strcmp(tag
, option
)) {
4079 while (*p
!= '\0' && *p
!= ',') {
4080 if ((q
- buf
) < buf_size
- 1)
4087 while (*p
!= '\0' && *p
!= ',') {
4098 static int net_client_init(const char *str
)
4109 while (*p
!= '\0' && *p
!= ',') {
4110 if ((q
- device
) < sizeof(device
) - 1)
4118 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4119 vlan_id
= strtol(buf
, NULL
, 0);
4121 vlan
= qemu_find_vlan(vlan_id
);
4123 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4126 if (!strcmp(device
, "nic")) {
4130 if (nb_nics
>= MAX_NICS
) {
4131 fprintf(stderr
, "Too Many NICs\n");
4134 nd
= &nd_table
[nb_nics
];
4135 macaddr
= nd
->macaddr
;
4141 macaddr
[5] = 0x56 + nb_nics
;
4143 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4144 if (parse_macaddr(macaddr
, buf
) < 0) {
4145 fprintf(stderr
, "invalid syntax for ethernet address\n");
4149 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4150 nd
->model
= strdup(buf
);
4156 if (!strcmp(device
, "none")) {
4157 /* does nothing. It is needed to signal that no network cards
4162 if (!strcmp(device
, "user")) {
4163 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4164 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4166 ret
= net_slirp_init(vlan
);
4170 if (!strcmp(device
, "tap")) {
4172 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4173 fprintf(stderr
, "tap: no interface name\n");
4176 ret
= tap_win32_init(vlan
, ifname
);
4179 if (!strcmp(device
, "tap")) {
4181 char setup_script
[1024];
4183 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4184 fd
= strtol(buf
, NULL
, 0);
4186 if (net_tap_fd_init(vlan
, fd
))
4189 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4192 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4193 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4195 ret
= net_tap_init(vlan
, ifname
, setup_script
);
4199 if (!strcmp(device
, "socket")) {
4200 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4202 fd
= strtol(buf
, NULL
, 0);
4204 if (net_socket_fd_init(vlan
, fd
, 1))
4206 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4207 ret
= net_socket_listen_init(vlan
, buf
);
4208 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4209 ret
= net_socket_connect_init(vlan
, buf
);
4210 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4211 ret
= net_socket_mcast_init(vlan
, buf
);
4213 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4218 fprintf(stderr
, "Unknown network device: %s\n", device
);
4222 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4228 void do_info_network(void)
4231 VLANClientState
*vc
;
4233 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4234 term_printf("VLAN %d devices:\n", vlan
->id
);
4235 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4236 term_printf(" %s\n", vc
->info_str
);
4240 /***********************************************************/
4243 static USBPort
*used_usb_ports
;
4244 static USBPort
*free_usb_ports
;
4246 /* ??? Maybe change this to register a hub to keep track of the topology. */
4247 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
4248 usb_attachfn attach
)
4250 port
->opaque
= opaque
;
4251 port
->index
= index
;
4252 port
->attach
= attach
;
4253 port
->next
= free_usb_ports
;
4254 free_usb_ports
= port
;
4257 static int usb_device_add(const char *devname
)
4263 if (!free_usb_ports
)
4266 if (strstart(devname
, "host:", &p
)) {
4267 dev
= usb_host_device_open(p
);
4268 } else if (!strcmp(devname
, "mouse")) {
4269 dev
= usb_mouse_init();
4270 } else if (!strcmp(devname
, "tablet")) {
4271 dev
= usb_tablet_init();
4272 } else if (strstart(devname
, "disk:", &p
)) {
4273 dev
= usb_msd_init(p
);
4280 /* Find a USB port to add the device to. */
4281 port
= free_usb_ports
;
4285 /* Create a new hub and chain it on. */
4286 free_usb_ports
= NULL
;
4287 port
->next
= used_usb_ports
;
4288 used_usb_ports
= port
;
4290 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
4291 usb_attach(port
, hub
);
4292 port
= free_usb_ports
;
4295 free_usb_ports
= port
->next
;
4296 port
->next
= used_usb_ports
;
4297 used_usb_ports
= port
;
4298 usb_attach(port
, dev
);
4302 static int usb_device_del(const char *devname
)
4310 if (!used_usb_ports
)
4313 p
= strchr(devname
, '.');
4316 bus_num
= strtoul(devname
, NULL
, 0);
4317 addr
= strtoul(p
+ 1, NULL
, 0);
4321 lastp
= &used_usb_ports
;
4322 port
= used_usb_ports
;
4323 while (port
&& port
->dev
->addr
!= addr
) {
4324 lastp
= &port
->next
;
4332 *lastp
= port
->next
;
4333 usb_attach(port
, NULL
);
4334 dev
->handle_destroy(dev
);
4335 port
->next
= free_usb_ports
;
4336 free_usb_ports
= port
;
4340 void do_usb_add(const char *devname
)
4343 ret
= usb_device_add(devname
);
4345 term_printf("Could not add USB device '%s'\n", devname
);
4348 void do_usb_del(const char *devname
)
4351 ret
= usb_device_del(devname
);
4353 term_printf("Could not remove USB device '%s'\n", devname
);
4360 const char *speed_str
;
4363 term_printf("USB support not enabled\n");
4367 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4371 switch(dev
->speed
) {
4375 case USB_SPEED_FULL
:
4378 case USB_SPEED_HIGH
:
4385 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4386 0, dev
->addr
, speed_str
, dev
->devname
);
4390 /***********************************************************/
4393 static char *pid_filename
;
4395 /* Remove PID file. Called on normal exit */
4397 static void remove_pidfile(void)
4399 unlink (pid_filename
);
4402 static void create_pidfile(const char *filename
)
4404 struct stat pidstat
;
4407 /* Try to write our PID to the named file */
4408 if (stat(filename
, &pidstat
) < 0) {
4409 if (errno
== ENOENT
) {
4410 if ((f
= fopen (filename
, "w")) == NULL
) {
4411 perror("Opening pidfile");
4414 fprintf(f
, "%d\n", getpid());
4416 pid_filename
= qemu_strdup(filename
);
4417 if (!pid_filename
) {
4418 fprintf(stderr
, "Could not save PID filename");
4421 atexit(remove_pidfile
);
4424 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4430 /***********************************************************/
4433 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4437 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4441 static void dumb_refresh(DisplayState
*ds
)
4446 void dumb_display_init(DisplayState
*ds
)
4451 ds
->dpy_update
= dumb_update
;
4452 ds
->dpy_resize
= dumb_resize
;
4453 ds
->dpy_refresh
= dumb_refresh
;
4456 /***********************************************************/
4459 #define MAX_IO_HANDLERS 64
4461 typedef struct IOHandlerRecord
{
4463 IOCanRWHandler
*fd_read_poll
;
4465 IOHandler
*fd_write
;
4468 /* temporary data */
4470 struct IOHandlerRecord
*next
;
4473 static IOHandlerRecord
*first_io_handler
;
4475 /* XXX: fd_read_poll should be suppressed, but an API change is
4476 necessary in the character devices to suppress fd_can_read(). */
4477 int qemu_set_fd_handler2(int fd
,
4478 IOCanRWHandler
*fd_read_poll
,
4480 IOHandler
*fd_write
,
4483 IOHandlerRecord
**pioh
, *ioh
;
4485 if (!fd_read
&& !fd_write
) {
4486 pioh
= &first_io_handler
;
4491 if (ioh
->fd
== fd
) {
4498 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4502 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4505 ioh
->next
= first_io_handler
;
4506 first_io_handler
= ioh
;
4509 ioh
->fd_read_poll
= fd_read_poll
;
4510 ioh
->fd_read
= fd_read
;
4511 ioh
->fd_write
= fd_write
;
4512 ioh
->opaque
= opaque
;
4518 int qemu_set_fd_handler(int fd
,
4520 IOHandler
*fd_write
,
4523 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4526 /***********************************************************/
4527 /* Polling handling */
4529 typedef struct PollingEntry
{
4532 struct PollingEntry
*next
;
4535 static PollingEntry
*first_polling_entry
;
4537 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4539 PollingEntry
**ppe
, *pe
;
4540 pe
= qemu_mallocz(sizeof(PollingEntry
));
4544 pe
->opaque
= opaque
;
4545 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4550 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4552 PollingEntry
**ppe
, *pe
;
4553 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4555 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4564 /***********************************************************/
4565 /* Wait objects support */
4566 typedef struct WaitObjects
{
4568 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4569 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4570 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4573 static WaitObjects wait_objects
= {0};
4575 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4577 WaitObjects
*w
= &wait_objects
;
4579 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4581 w
->events
[w
->num
] = handle
;
4582 w
->func
[w
->num
] = func
;
4583 w
->opaque
[w
->num
] = opaque
;
4588 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4591 WaitObjects
*w
= &wait_objects
;
4594 for (i
= 0; i
< w
->num
; i
++) {
4595 if (w
->events
[i
] == handle
)
4598 w
->events
[i
] = w
->events
[i
+ 1];
4599 w
->func
[i
] = w
->func
[i
+ 1];
4600 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4608 /***********************************************************/
4609 /* savevm/loadvm support */
4611 #define IO_BUF_SIZE 32768
4615 BlockDriverState
*bs
;
4618 int64_t base_offset
;
4619 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4622 int buf_size
; /* 0 when writing */
4623 uint8_t buf
[IO_BUF_SIZE
];
4626 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4630 f
= qemu_mallocz(sizeof(QEMUFile
));
4633 if (!strcmp(mode
, "wb")) {
4635 } else if (!strcmp(mode
, "rb")) {
4640 f
->outfile
= fopen(filename
, mode
);
4652 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4656 f
= qemu_mallocz(sizeof(QEMUFile
));
4661 f
->is_writable
= is_writable
;
4662 f
->base_offset
= offset
;
4666 void qemu_fflush(QEMUFile
*f
)
4668 if (!f
->is_writable
)
4670 if (f
->buf_index
> 0) {
4672 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4673 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4675 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4676 f
->buf
, f
->buf_index
);
4678 f
->buf_offset
+= f
->buf_index
;
4683 static void qemu_fill_buffer(QEMUFile
*f
)
4690 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4691 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4695 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4696 f
->buf
, IO_BUF_SIZE
);
4702 f
->buf_offset
+= len
;
4705 void qemu_fclose(QEMUFile
*f
)
4715 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4719 l
= IO_BUF_SIZE
- f
->buf_index
;
4722 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4726 if (f
->buf_index
>= IO_BUF_SIZE
)
4731 void qemu_put_byte(QEMUFile
*f
, int v
)
4733 f
->buf
[f
->buf_index
++] = v
;
4734 if (f
->buf_index
>= IO_BUF_SIZE
)
4738 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4744 l
= f
->buf_size
- f
->buf_index
;
4746 qemu_fill_buffer(f
);
4747 l
= f
->buf_size
- f
->buf_index
;
4753 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4758 return size1
- size
;
4761 int qemu_get_byte(QEMUFile
*f
)
4763 if (f
->buf_index
>= f
->buf_size
) {
4764 qemu_fill_buffer(f
);
4765 if (f
->buf_index
>= f
->buf_size
)
4768 return f
->buf
[f
->buf_index
++];
4771 int64_t qemu_ftell(QEMUFile
*f
)
4773 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4776 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4778 if (whence
== SEEK_SET
) {
4780 } else if (whence
== SEEK_CUR
) {
4781 pos
+= qemu_ftell(f
);
4783 /* SEEK_END not supported */
4786 if (f
->is_writable
) {
4788 f
->buf_offset
= pos
;
4790 f
->buf_offset
= pos
;
4797 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4799 qemu_put_byte(f
, v
>> 8);
4800 qemu_put_byte(f
, v
);
4803 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4805 qemu_put_byte(f
, v
>> 24);
4806 qemu_put_byte(f
, v
>> 16);
4807 qemu_put_byte(f
, v
>> 8);
4808 qemu_put_byte(f
, v
);
4811 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4813 qemu_put_be32(f
, v
>> 32);
4814 qemu_put_be32(f
, v
);
4817 unsigned int qemu_get_be16(QEMUFile
*f
)
4820 v
= qemu_get_byte(f
) << 8;
4821 v
|= qemu_get_byte(f
);
4825 unsigned int qemu_get_be32(QEMUFile
*f
)
4828 v
= qemu_get_byte(f
) << 24;
4829 v
|= qemu_get_byte(f
) << 16;
4830 v
|= qemu_get_byte(f
) << 8;
4831 v
|= qemu_get_byte(f
);
4835 uint64_t qemu_get_be64(QEMUFile
*f
)
4838 v
= (uint64_t)qemu_get_be32(f
) << 32;
4839 v
|= qemu_get_be32(f
);
4843 typedef struct SaveStateEntry
{
4847 SaveStateHandler
*save_state
;
4848 LoadStateHandler
*load_state
;
4850 struct SaveStateEntry
*next
;
4853 static SaveStateEntry
*first_se
;
4855 int register_savevm(const char *idstr
,
4858 SaveStateHandler
*save_state
,
4859 LoadStateHandler
*load_state
,
4862 SaveStateEntry
*se
, **pse
;
4864 se
= qemu_malloc(sizeof(SaveStateEntry
));
4867 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4868 se
->instance_id
= instance_id
;
4869 se
->version_id
= version_id
;
4870 se
->save_state
= save_state
;
4871 se
->load_state
= load_state
;
4872 se
->opaque
= opaque
;
4875 /* add at the end of list */
4877 while (*pse
!= NULL
)
4878 pse
= &(*pse
)->next
;
4883 #define QEMU_VM_FILE_MAGIC 0x5145564d
4884 #define QEMU_VM_FILE_VERSION 0x00000002
4886 int qemu_savevm_state(QEMUFile
*f
)
4890 int64_t cur_pos
, len_pos
, total_len_pos
;
4892 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4893 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4894 total_len_pos
= qemu_ftell(f
);
4895 qemu_put_be64(f
, 0); /* total size */
4897 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4899 len
= strlen(se
->idstr
);
4900 qemu_put_byte(f
, len
);
4901 qemu_put_buffer(f
, se
->idstr
, len
);
4903 qemu_put_be32(f
, se
->instance_id
);
4904 qemu_put_be32(f
, se
->version_id
);
4906 /* record size: filled later */
4907 len_pos
= qemu_ftell(f
);
4908 qemu_put_be32(f
, 0);
4910 se
->save_state(f
, se
->opaque
);
4912 /* fill record size */
4913 cur_pos
= qemu_ftell(f
);
4914 len
= cur_pos
- len_pos
- 4;
4915 qemu_fseek(f
, len_pos
, SEEK_SET
);
4916 qemu_put_be32(f
, len
);
4917 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4919 cur_pos
= qemu_ftell(f
);
4920 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4921 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4922 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4928 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4932 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4933 if (!strcmp(se
->idstr
, idstr
) &&
4934 instance_id
== se
->instance_id
)
4940 int qemu_loadvm_state(QEMUFile
*f
)
4943 int len
, ret
, instance_id
, record_len
, version_id
;
4944 int64_t total_len
, end_pos
, cur_pos
;
4948 v
= qemu_get_be32(f
);
4949 if (v
!= QEMU_VM_FILE_MAGIC
)
4951 v
= qemu_get_be32(f
);
4952 if (v
!= QEMU_VM_FILE_VERSION
) {
4957 total_len
= qemu_get_be64(f
);
4958 end_pos
= total_len
+ qemu_ftell(f
);
4960 if (qemu_ftell(f
) >= end_pos
)
4962 len
= qemu_get_byte(f
);
4963 qemu_get_buffer(f
, idstr
, len
);
4965 instance_id
= qemu_get_be32(f
);
4966 version_id
= qemu_get_be32(f
);
4967 record_len
= qemu_get_be32(f
);
4969 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4970 idstr
, instance_id
, version_id
, record_len
);
4972 cur_pos
= qemu_ftell(f
);
4973 se
= find_se(idstr
, instance_id
);
4975 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4976 instance_id
, idstr
);
4978 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4980 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4981 instance_id
, idstr
);
4984 /* always seek to exact end of record */
4985 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4992 /* device can contain snapshots */
4993 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4996 !bdrv_is_removable(bs
) &&
4997 !bdrv_is_read_only(bs
));
5000 /* device must be snapshots in order to have a reliable snapshot */
5001 static int bdrv_has_snapshot(BlockDriverState
*bs
)
5004 !bdrv_is_removable(bs
) &&
5005 !bdrv_is_read_only(bs
));
5008 static BlockDriverState
*get_bs_snapshots(void)
5010 BlockDriverState
*bs
;
5014 return bs_snapshots
;
5015 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5017 if (bdrv_can_snapshot(bs
))
5026 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5029 QEMUSnapshotInfo
*sn_tab
, *sn
;
5033 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5036 for(i
= 0; i
< nb_sns
; i
++) {
5038 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5048 void do_savevm(const char *name
)
5050 BlockDriverState
*bs
, *bs1
;
5051 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5052 int must_delete
, ret
, i
;
5053 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5055 int saved_vm_running
;
5062 bs
= get_bs_snapshots();
5064 term_printf("No block device can accept snapshots\n");
5068 /* ??? Should this occur after vm_stop? */
5071 saved_vm_running
= vm_running
;
5076 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5081 memset(sn
, 0, sizeof(*sn
));
5083 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5084 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5087 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5090 /* fill auxiliary fields */
5093 sn
->date_sec
= tb
.time
;
5094 sn
->date_nsec
= tb
.millitm
* 1000000;
5096 gettimeofday(&tv
, NULL
);
5097 sn
->date_sec
= tv
.tv_sec
;
5098 sn
->date_nsec
= tv
.tv_usec
* 1000;
5100 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
5102 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5103 term_printf("Device %s does not support VM state snapshots\n",
5104 bdrv_get_device_name(bs
));
5108 /* save the VM state */
5109 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
5111 term_printf("Could not open VM state file\n");
5114 ret
= qemu_savevm_state(f
);
5115 sn
->vm_state_size
= qemu_ftell(f
);
5118 term_printf("Error %d while writing VM\n", ret
);
5122 /* create the snapshots */
5124 for(i
= 0; i
< MAX_DISKS
; i
++) {
5126 if (bdrv_has_snapshot(bs1
)) {
5128 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5130 term_printf("Error while deleting snapshot on '%s'\n",
5131 bdrv_get_device_name(bs1
));
5134 ret
= bdrv_snapshot_create(bs1
, sn
);
5136 term_printf("Error while creating snapshot on '%s'\n",
5137 bdrv_get_device_name(bs1
));
5143 if (saved_vm_running
)
5147 void do_loadvm(const char *name
)
5149 BlockDriverState
*bs
, *bs1
;
5150 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5153 int saved_vm_running
;
5155 bs
= get_bs_snapshots();
5157 term_printf("No block device supports snapshots\n");
5161 /* Flush all IO requests so they don't interfere with the new state. */
5164 saved_vm_running
= vm_running
;
5167 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5169 if (bdrv_has_snapshot(bs1
)) {
5170 ret
= bdrv_snapshot_goto(bs1
, name
);
5173 term_printf("Warning: ");
5176 term_printf("Snapshots not supported on device '%s'\n",
5177 bdrv_get_device_name(bs1
));
5180 term_printf("Could not find snapshot '%s' on device '%s'\n",
5181 name
, bdrv_get_device_name(bs1
));
5184 term_printf("Error %d while activating snapshot on '%s'\n",
5185 ret
, bdrv_get_device_name(bs1
));
5188 /* fatal on snapshot block device */
5195 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5196 term_printf("Device %s does not support VM state snapshots\n",
5197 bdrv_get_device_name(bs
));
5201 /* restore the VM state */
5202 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5204 term_printf("Could not open VM state file\n");
5207 ret
= qemu_loadvm_state(f
);
5210 term_printf("Error %d while loading VM state\n", ret
);
5213 if (saved_vm_running
)
5217 void do_delvm(const char *name
)
5219 BlockDriverState
*bs
, *bs1
;
5222 bs
= get_bs_snapshots();
5224 term_printf("No block device supports snapshots\n");
5228 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5230 if (bdrv_has_snapshot(bs1
)) {
5231 ret
= bdrv_snapshot_delete(bs1
, name
);
5233 if (ret
== -ENOTSUP
)
5234 term_printf("Snapshots not supported on device '%s'\n",
5235 bdrv_get_device_name(bs1
));
5237 term_printf("Error %d while deleting snapshot on '%s'\n",
5238 ret
, bdrv_get_device_name(bs1
));
5244 void do_info_snapshots(void)
5246 BlockDriverState
*bs
, *bs1
;
5247 QEMUSnapshotInfo
*sn_tab
, *sn
;
5251 bs
= get_bs_snapshots();
5253 term_printf("No available block device supports snapshots\n");
5256 term_printf("Snapshot devices:");
5257 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5259 if (bdrv_has_snapshot(bs1
)) {
5261 term_printf(" %s", bdrv_get_device_name(bs1
));
5266 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5268 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5271 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5272 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5273 for(i
= 0; i
< nb_sns
; i
++) {
5275 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5280 /***********************************************************/
5281 /* cpu save/restore */
5283 #if defined(TARGET_I386)
5285 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5287 qemu_put_be32(f
, dt
->selector
);
5288 qemu_put_betl(f
, dt
->base
);
5289 qemu_put_be32(f
, dt
->limit
);
5290 qemu_put_be32(f
, dt
->flags
);
5293 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5295 dt
->selector
= qemu_get_be32(f
);
5296 dt
->base
= qemu_get_betl(f
);
5297 dt
->limit
= qemu_get_be32(f
);
5298 dt
->flags
= qemu_get_be32(f
);
5301 void cpu_save(QEMUFile
*f
, void *opaque
)
5303 CPUState
*env
= opaque
;
5304 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5308 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5309 qemu_put_betls(f
, &env
->regs
[i
]);
5310 qemu_put_betls(f
, &env
->eip
);
5311 qemu_put_betls(f
, &env
->eflags
);
5312 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5313 qemu_put_be32s(f
, &hflags
);
5317 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5319 for(i
= 0; i
< 8; i
++) {
5320 fptag
|= ((!env
->fptags
[i
]) << i
);
5323 qemu_put_be16s(f
, &fpuc
);
5324 qemu_put_be16s(f
, &fpus
);
5325 qemu_put_be16s(f
, &fptag
);
5327 #ifdef USE_X86LDOUBLE
5332 qemu_put_be16s(f
, &fpregs_format
);
5334 for(i
= 0; i
< 8; i
++) {
5335 #ifdef USE_X86LDOUBLE
5339 /* we save the real CPU data (in case of MMX usage only 'mant'
5340 contains the MMX register */
5341 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5342 qemu_put_be64(f
, mant
);
5343 qemu_put_be16(f
, exp
);
5346 /* if we use doubles for float emulation, we save the doubles to
5347 avoid losing information in case of MMX usage. It can give
5348 problems if the image is restored on a CPU where long
5349 doubles are used instead. */
5350 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5354 for(i
= 0; i
< 6; i
++)
5355 cpu_put_seg(f
, &env
->segs
[i
]);
5356 cpu_put_seg(f
, &env
->ldt
);
5357 cpu_put_seg(f
, &env
->tr
);
5358 cpu_put_seg(f
, &env
->gdt
);
5359 cpu_put_seg(f
, &env
->idt
);
5361 qemu_put_be32s(f
, &env
->sysenter_cs
);
5362 qemu_put_be32s(f
, &env
->sysenter_esp
);
5363 qemu_put_be32s(f
, &env
->sysenter_eip
);
5365 qemu_put_betls(f
, &env
->cr
[0]);
5366 qemu_put_betls(f
, &env
->cr
[2]);
5367 qemu_put_betls(f
, &env
->cr
[3]);
5368 qemu_put_betls(f
, &env
->cr
[4]);
5370 for(i
= 0; i
< 8; i
++)
5371 qemu_put_betls(f
, &env
->dr
[i
]);
5374 qemu_put_be32s(f
, &env
->a20_mask
);
5377 qemu_put_be32s(f
, &env
->mxcsr
);
5378 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5379 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5380 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5383 #ifdef TARGET_X86_64
5384 qemu_put_be64s(f
, &env
->efer
);
5385 qemu_put_be64s(f
, &env
->star
);
5386 qemu_put_be64s(f
, &env
->lstar
);
5387 qemu_put_be64s(f
, &env
->cstar
);
5388 qemu_put_be64s(f
, &env
->fmask
);
5389 qemu_put_be64s(f
, &env
->kernelgsbase
);
5391 qemu_put_be32s(f
, &env
->smbase
);
5394 #ifdef USE_X86LDOUBLE
5395 /* XXX: add that in a FPU generic layer */
5396 union x86_longdouble
{
5401 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5402 #define EXPBIAS1 1023
5403 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5404 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5406 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5410 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5411 /* exponent + sign */
5412 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5413 e
|= SIGND1(temp
) >> 16;
5418 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5420 CPUState
*env
= opaque
;
5423 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5425 if (version_id
!= 3 && version_id
!= 4)
5427 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5428 qemu_get_betls(f
, &env
->regs
[i
]);
5429 qemu_get_betls(f
, &env
->eip
);
5430 qemu_get_betls(f
, &env
->eflags
);
5431 qemu_get_be32s(f
, &hflags
);
5433 qemu_get_be16s(f
, &fpuc
);
5434 qemu_get_be16s(f
, &fpus
);
5435 qemu_get_be16s(f
, &fptag
);
5436 qemu_get_be16s(f
, &fpregs_format
);
5438 /* NOTE: we cannot always restore the FPU state if the image come
5439 from a host with a different 'USE_X86LDOUBLE' define. We guess
5440 if we are in an MMX state to restore correctly in that case. */
5441 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5442 for(i
= 0; i
< 8; i
++) {
5446 switch(fpregs_format
) {
5448 mant
= qemu_get_be64(f
);
5449 exp
= qemu_get_be16(f
);
5450 #ifdef USE_X86LDOUBLE
5451 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5453 /* difficult case */
5455 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5457 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5461 mant
= qemu_get_be64(f
);
5462 #ifdef USE_X86LDOUBLE
5464 union x86_longdouble
*p
;
5465 /* difficult case */
5466 p
= (void *)&env
->fpregs
[i
];
5471 fp64_to_fp80(p
, mant
);
5475 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5484 /* XXX: restore FPU round state */
5485 env
->fpstt
= (fpus
>> 11) & 7;
5486 env
->fpus
= fpus
& ~0x3800;
5488 for(i
= 0; i
< 8; i
++) {
5489 env
->fptags
[i
] = (fptag
>> i
) & 1;
5492 for(i
= 0; i
< 6; i
++)
5493 cpu_get_seg(f
, &env
->segs
[i
]);
5494 cpu_get_seg(f
, &env
->ldt
);
5495 cpu_get_seg(f
, &env
->tr
);
5496 cpu_get_seg(f
, &env
->gdt
);
5497 cpu_get_seg(f
, &env
->idt
);
5499 qemu_get_be32s(f
, &env
->sysenter_cs
);
5500 qemu_get_be32s(f
, &env
->sysenter_esp
);
5501 qemu_get_be32s(f
, &env
->sysenter_eip
);
5503 qemu_get_betls(f
, &env
->cr
[0]);
5504 qemu_get_betls(f
, &env
->cr
[2]);
5505 qemu_get_betls(f
, &env
->cr
[3]);
5506 qemu_get_betls(f
, &env
->cr
[4]);
5508 for(i
= 0; i
< 8; i
++)
5509 qemu_get_betls(f
, &env
->dr
[i
]);
5512 qemu_get_be32s(f
, &env
->a20_mask
);
5514 qemu_get_be32s(f
, &env
->mxcsr
);
5515 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5516 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5517 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5520 #ifdef TARGET_X86_64
5521 qemu_get_be64s(f
, &env
->efer
);
5522 qemu_get_be64s(f
, &env
->star
);
5523 qemu_get_be64s(f
, &env
->lstar
);
5524 qemu_get_be64s(f
, &env
->cstar
);
5525 qemu_get_be64s(f
, &env
->fmask
);
5526 qemu_get_be64s(f
, &env
->kernelgsbase
);
5528 if (version_id
>= 4)
5529 qemu_get_be32s(f
, &env
->smbase
);
5531 /* XXX: compute hflags from scratch, except for CPL and IIF */
5532 env
->hflags
= hflags
;
5537 #elif defined(TARGET_PPC)
5538 void cpu_save(QEMUFile
*f
, void *opaque
)
5542 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5547 #elif defined(TARGET_MIPS)
5548 void cpu_save(QEMUFile
*f
, void *opaque
)
5552 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5557 #elif defined(TARGET_SPARC)
5558 void cpu_save(QEMUFile
*f
, void *opaque
)
5560 CPUState
*env
= opaque
;
5564 for(i
= 0; i
< 8; i
++)
5565 qemu_put_betls(f
, &env
->gregs
[i
]);
5566 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5567 qemu_put_betls(f
, &env
->regbase
[i
]);
5570 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5576 qemu_put_be32(f
, u
.i
);
5579 qemu_put_betls(f
, &env
->pc
);
5580 qemu_put_betls(f
, &env
->npc
);
5581 qemu_put_betls(f
, &env
->y
);
5583 qemu_put_be32(f
, tmp
);
5584 qemu_put_betls(f
, &env
->fsr
);
5585 qemu_put_betls(f
, &env
->tbr
);
5586 #ifndef TARGET_SPARC64
5587 qemu_put_be32s(f
, &env
->wim
);
5589 for(i
= 0; i
< 16; i
++)
5590 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5594 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5596 CPUState
*env
= opaque
;
5600 for(i
= 0; i
< 8; i
++)
5601 qemu_get_betls(f
, &env
->gregs
[i
]);
5602 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5603 qemu_get_betls(f
, &env
->regbase
[i
]);
5606 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5611 u
.i
= qemu_get_be32(f
);
5615 qemu_get_betls(f
, &env
->pc
);
5616 qemu_get_betls(f
, &env
->npc
);
5617 qemu_get_betls(f
, &env
->y
);
5618 tmp
= qemu_get_be32(f
);
5619 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5620 correctly updated */
5622 qemu_get_betls(f
, &env
->fsr
);
5623 qemu_get_betls(f
, &env
->tbr
);
5624 #ifndef TARGET_SPARC64
5625 qemu_get_be32s(f
, &env
->wim
);
5627 for(i
= 0; i
< 16; i
++)
5628 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5634 #elif defined(TARGET_ARM)
5636 /* ??? Need to implement these. */
5637 void cpu_save(QEMUFile
*f
, void *opaque
)
5641 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5648 #warning No CPU save/restore functions
5652 /***********************************************************/
5653 /* ram save/restore */
5655 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5659 v
= qemu_get_byte(f
);
5662 if (qemu_get_buffer(f
, buf
, len
) != len
)
5666 v
= qemu_get_byte(f
);
5667 memset(buf
, v
, len
);
5675 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5679 if (qemu_get_be32(f
) != phys_ram_size
)
5681 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5682 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5689 #define BDRV_HASH_BLOCK_SIZE 1024
5690 #define IOBUF_SIZE 4096
5691 #define RAM_CBLOCK_MAGIC 0xfabe
5693 typedef struct RamCompressState
{
5696 uint8_t buf
[IOBUF_SIZE
];
5699 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5702 memset(s
, 0, sizeof(*s
));
5704 ret
= deflateInit2(&s
->zstream
, 1,
5706 9, Z_DEFAULT_STRATEGY
);
5709 s
->zstream
.avail_out
= IOBUF_SIZE
;
5710 s
->zstream
.next_out
= s
->buf
;
5714 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5716 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5717 qemu_put_be16(s
->f
, len
);
5718 qemu_put_buffer(s
->f
, buf
, len
);
5721 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5725 s
->zstream
.avail_in
= len
;
5726 s
->zstream
.next_in
= (uint8_t *)buf
;
5727 while (s
->zstream
.avail_in
> 0) {
5728 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5731 if (s
->zstream
.avail_out
== 0) {
5732 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5733 s
->zstream
.avail_out
= IOBUF_SIZE
;
5734 s
->zstream
.next_out
= s
->buf
;
5740 static void ram_compress_close(RamCompressState
*s
)
5744 /* compress last bytes */
5746 ret
= deflate(&s
->zstream
, Z_FINISH
);
5747 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5748 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5750 ram_put_cblock(s
, s
->buf
, len
);
5752 s
->zstream
.avail_out
= IOBUF_SIZE
;
5753 s
->zstream
.next_out
= s
->buf
;
5754 if (ret
== Z_STREAM_END
)
5761 deflateEnd(&s
->zstream
);
5764 typedef struct RamDecompressState
{
5767 uint8_t buf
[IOBUF_SIZE
];
5768 } RamDecompressState
;
5770 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5773 memset(s
, 0, sizeof(*s
));
5775 ret
= inflateInit(&s
->zstream
);
5781 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5785 s
->zstream
.avail_out
= len
;
5786 s
->zstream
.next_out
= buf
;
5787 while (s
->zstream
.avail_out
> 0) {
5788 if (s
->zstream
.avail_in
== 0) {
5789 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5791 clen
= qemu_get_be16(s
->f
);
5792 if (clen
> IOBUF_SIZE
)
5794 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5795 s
->zstream
.avail_in
= clen
;
5796 s
->zstream
.next_in
= s
->buf
;
5798 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5799 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5806 static void ram_decompress_close(RamDecompressState
*s
)
5808 inflateEnd(&s
->zstream
);
5811 static void ram_save(QEMUFile
*f
, void *opaque
)
5814 RamCompressState s1
, *s
= &s1
;
5817 qemu_put_be32(f
, phys_ram_size
);
5818 if (ram_compress_open(s
, f
) < 0)
5820 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5822 if (tight_savevm_enabled
) {
5826 /* find if the memory block is available on a virtual
5829 for(j
= 0; j
< MAX_DISKS
; j
++) {
5831 sector_num
= bdrv_hash_find(bs_table
[j
],
5832 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5833 if (sector_num
>= 0)
5838 goto normal_compress
;
5841 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5842 ram_compress_buf(s
, buf
, 10);
5848 ram_compress_buf(s
, buf
, 1);
5849 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5852 ram_compress_close(s
);
5855 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5857 RamDecompressState s1
, *s
= &s1
;
5861 if (version_id
== 1)
5862 return ram_load_v1(f
, opaque
);
5863 if (version_id
!= 2)
5865 if (qemu_get_be32(f
) != phys_ram_size
)
5867 if (ram_decompress_open(s
, f
) < 0)
5869 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5870 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5871 fprintf(stderr
, "Error while reading ram block header\n");
5875 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5876 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5885 ram_decompress_buf(s
, buf
+ 1, 9);
5887 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5888 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5889 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5892 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5893 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5894 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5895 bs_index
, sector_num
);
5902 printf("Error block header\n");
5906 ram_decompress_close(s
);
5910 /***********************************************************/
5911 /* bottom halves (can be seen as timers which expire ASAP) */
5920 static QEMUBH
*first_bh
= NULL
;
5922 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5925 bh
= qemu_mallocz(sizeof(QEMUBH
));
5929 bh
->opaque
= opaque
;
5933 int qemu_bh_poll(void)
5952 void qemu_bh_schedule(QEMUBH
*bh
)
5954 CPUState
*env
= cpu_single_env
;
5958 bh
->next
= first_bh
;
5961 /* stop the currently executing CPU to execute the BH ASAP */
5963 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5967 void qemu_bh_cancel(QEMUBH
*bh
)
5970 if (bh
->scheduled
) {
5973 pbh
= &(*pbh
)->next
;
5979 void qemu_bh_delete(QEMUBH
*bh
)
5985 /***********************************************************/
5986 /* machine registration */
5988 QEMUMachine
*first_machine
= NULL
;
5990 int qemu_register_machine(QEMUMachine
*m
)
5993 pm
= &first_machine
;
6001 QEMUMachine
*find_machine(const char *name
)
6005 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6006 if (!strcmp(m
->name
, name
))
6012 /***********************************************************/
6013 /* main execution loop */
6015 void gui_update(void *opaque
)
6017 display_state
.dpy_refresh(&display_state
);
6018 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6021 struct vm_change_state_entry
{
6022 VMChangeStateHandler
*cb
;
6024 LIST_ENTRY (vm_change_state_entry
) entries
;
6027 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6029 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6032 VMChangeStateEntry
*e
;
6034 e
= qemu_mallocz(sizeof (*e
));
6040 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6044 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6046 LIST_REMOVE (e
, entries
);
6050 static void vm_state_notify(int running
)
6052 VMChangeStateEntry
*e
;
6054 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6055 e
->cb(e
->opaque
, running
);
6059 /* XXX: support several handlers */
6060 static VMStopHandler
*vm_stop_cb
;
6061 static void *vm_stop_opaque
;
6063 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6066 vm_stop_opaque
= opaque
;
6070 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6084 void vm_stop(int reason
)
6087 cpu_disable_ticks();
6091 vm_stop_cb(vm_stop_opaque
, reason
);
6098 /* reset/shutdown handler */
6100 typedef struct QEMUResetEntry
{
6101 QEMUResetHandler
*func
;
6103 struct QEMUResetEntry
*next
;
6106 static QEMUResetEntry
*first_reset_entry
;
6107 static int reset_requested
;
6108 static int shutdown_requested
;
6109 static int powerdown_requested
;
6111 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6113 QEMUResetEntry
**pre
, *re
;
6115 pre
= &first_reset_entry
;
6116 while (*pre
!= NULL
)
6117 pre
= &(*pre
)->next
;
6118 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6120 re
->opaque
= opaque
;
6125 static void qemu_system_reset(void)
6129 /* reset all devices */
6130 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6131 re
->func(re
->opaque
);
6135 void qemu_system_reset_request(void)
6138 shutdown_requested
= 1;
6140 reset_requested
= 1;
6143 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6146 void qemu_system_shutdown_request(void)
6148 shutdown_requested
= 1;
6150 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6153 void qemu_system_powerdown_request(void)
6155 powerdown_requested
= 1;
6157 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6160 void main_loop_wait(int timeout
)
6162 IOHandlerRecord
*ioh
;
6163 fd_set rfds
, wfds
, xfds
;
6169 /* XXX: need to suppress polling by better using win32 events */
6171 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6172 ret
|= pe
->func(pe
->opaque
);
6175 if (ret
== 0 && timeout
> 0) {
6177 WaitObjects
*w
= &wait_objects
;
6179 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6180 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6181 if (w
->func
[ret
- WAIT_OBJECT_0
])
6182 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6183 } else if (ret
== WAIT_TIMEOUT
) {
6185 err
= GetLastError();
6186 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6190 /* poll any events */
6191 /* XXX: separate device handlers from system ones */
6196 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6200 (!ioh
->fd_read_poll
||
6201 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6202 FD_SET(ioh
->fd
, &rfds
);
6206 if (ioh
->fd_write
) {
6207 FD_SET(ioh
->fd
, &wfds
);
6217 tv
.tv_usec
= timeout
* 1000;
6219 #if defined(CONFIG_SLIRP)
6221 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6224 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6226 IOHandlerRecord
**pioh
;
6228 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6231 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6232 ioh
->fd_read(ioh
->opaque
);
6234 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6235 ioh
->fd_write(ioh
->opaque
);
6239 /* remove deleted IO handlers */
6240 pioh
= &first_io_handler
;
6250 #if defined(CONFIG_SLIRP)
6257 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6264 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6265 qemu_get_clock(vm_clock
));
6266 /* run dma transfers, if any */
6270 /* real time timers */
6271 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6272 qemu_get_clock(rt_clock
));
6275 static CPUState
*cur_cpu
;
6280 #ifdef CONFIG_PROFILER
6285 cur_cpu
= first_cpu
;
6292 env
= env
->next_cpu
;
6295 #ifdef CONFIG_PROFILER
6296 ti
= profile_getclock();
6298 ret
= cpu_exec(env
);
6299 #ifdef CONFIG_PROFILER
6300 qemu_time
+= profile_getclock() - ti
;
6302 if (ret
== EXCP_HLT
) {
6303 /* Give the next CPU a chance to run. */
6307 if (ret
!= EXCP_HALTED
)
6309 /* all CPUs are halted ? */
6315 if (shutdown_requested
) {
6316 ret
= EXCP_INTERRUPT
;
6319 if (reset_requested
) {
6320 reset_requested
= 0;
6321 qemu_system_reset();
6322 ret
= EXCP_INTERRUPT
;
6324 if (powerdown_requested
) {
6325 powerdown_requested
= 0;
6326 qemu_system_powerdown();
6327 ret
= EXCP_INTERRUPT
;
6329 if (ret
== EXCP_DEBUG
) {
6330 vm_stop(EXCP_DEBUG
);
6332 /* If all cpus are halted then wait until the next IRQ */
6333 /* XXX: use timeout computed from timers */
6334 if (ret
== EXCP_HALTED
)
6341 #ifdef CONFIG_PROFILER
6342 ti
= profile_getclock();
6344 main_loop_wait(timeout
);
6345 #ifdef CONFIG_PROFILER
6346 dev_time
+= profile_getclock() - ti
;
6349 cpu_disable_ticks();
6355 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6356 "usage: %s [options] [disk_image]\n"
6358 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6360 "Standard options:\n"
6361 "-M machine select emulated machine (-M ? for list)\n"
6362 "-cpu cpu select CPU (-cpu ? for list)\n"
6363 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6364 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6365 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6366 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6367 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6368 "-snapshot write to temporary files instead of disk image files\n"
6370 "-no-frame open SDL window without a frame and window decorations\n"
6371 "-no-quit disable SDL window close capability\n"
6374 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6376 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6377 "-smp n set the number of CPUs to 'n' [default=1]\n"
6378 "-nographic disable graphical output and redirect serial I/Os to console\n"
6380 "-k language use keyboard layout (for example \"fr\" for French)\n"
6383 "-audio-help print list of audio drivers and their options\n"
6384 "-soundhw c1,... enable audio support\n"
6385 " and only specified sound cards (comma separated list)\n"
6386 " use -soundhw ? to get the list of supported cards\n"
6387 " use -soundhw all to enable all of them\n"
6389 "-localtime set the real time clock to local time [default=utc]\n"
6390 "-full-screen start in full screen\n"
6392 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6394 "-usb enable the USB driver (will be the default soon)\n"
6395 "-usbdevice name add the host or guest USB device 'name'\n"
6396 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6397 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6399 "-name string set the name of the guest\n"
6401 "Network options:\n"
6402 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6403 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6405 "-net user[,vlan=n][,hostname=host]\n"
6406 " connect the user mode network stack to VLAN 'n' and send\n"
6407 " hostname 'host' to DHCP clients\n"
6410 "-net tap[,vlan=n],ifname=name\n"
6411 " connect the host TAP network interface to VLAN 'n'\n"
6413 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6414 " connect the host TAP network interface to VLAN 'n' and use\n"
6415 " the network script 'file' (default=%s);\n"
6416 " use 'script=no' to disable script execution;\n"
6417 " use 'fd=h' to connect to an already opened TAP interface\n"
6419 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6420 " connect the vlan 'n' to another VLAN using a socket connection\n"
6421 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6422 " connect the vlan 'n' to multicast maddr and port\n"
6423 "-net none use it alone to have zero network devices; if no -net option\n"
6424 " is provided, the default is '-net nic -net user'\n"
6427 "-tftp dir allow tftp access to files in dir [-net user]\n"
6428 "-bootp file advertise file in BOOTP replies\n"
6430 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6432 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6433 " redirect TCP or UDP connections from host to guest [-net user]\n"
6436 "Linux boot specific:\n"
6437 "-kernel bzImage use 'bzImage' as kernel image\n"
6438 "-append cmdline use 'cmdline' as kernel command line\n"
6439 "-initrd file use 'file' as initial ram disk\n"
6441 "Debug/Expert options:\n"
6442 "-monitor dev redirect the monitor to char device 'dev'\n"
6443 "-serial dev redirect the serial port to char device 'dev'\n"
6444 "-parallel dev redirect the parallel port to char device 'dev'\n"
6445 "-pidfile file Write PID to 'file'\n"
6446 "-S freeze CPU at startup (use 'c' to start execution)\n"
6447 "-s wait gdb connection to port\n"
6448 "-p port set gdb connection port [default=%s]\n"
6449 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6450 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6451 " translation (t=none or lba) (usually qemu can guess them)\n"
6452 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6454 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6455 "-no-kqemu disable KQEMU kernel module usage\n"
6457 #ifdef USE_CODE_COPY
6458 "-no-code-copy disable code copy acceleration\n"
6461 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6462 " (default is CL-GD5446 PCI VGA)\n"
6463 "-no-acpi disable ACPI\n"
6465 "-no-reboot exit instead of rebooting\n"
6466 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6467 "-vnc display start a VNC server on display\n"
6469 "-daemonize daemonize QEMU after initializing\n"
6471 "-option-rom rom load a file, rom, into the option ROM space\n"
6473 "During emulation, the following keys are useful:\n"
6474 "ctrl-alt-f toggle full screen\n"
6475 "ctrl-alt-n switch to virtual console 'n'\n"
6476 "ctrl-alt toggle mouse and keyboard grab\n"
6478 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6483 DEFAULT_NETWORK_SCRIPT
,
6485 DEFAULT_GDBSTUB_PORT
,
6490 #define HAS_ARG 0x0001
6505 QEMU_OPTION_snapshot
,
6507 QEMU_OPTION_no_fd_bootchk
,
6510 QEMU_OPTION_nographic
,
6512 QEMU_OPTION_audio_help
,
6513 QEMU_OPTION_soundhw
,
6532 QEMU_OPTION_no_code_copy
,
6534 QEMU_OPTION_localtime
,
6535 QEMU_OPTION_cirrusvga
,
6537 QEMU_OPTION_std_vga
,
6539 QEMU_OPTION_monitor
,
6541 QEMU_OPTION_parallel
,
6543 QEMU_OPTION_full_screen
,
6544 QEMU_OPTION_no_frame
,
6545 QEMU_OPTION_no_quit
,
6546 QEMU_OPTION_pidfile
,
6547 QEMU_OPTION_no_kqemu
,
6548 QEMU_OPTION_kernel_kqemu
,
6549 QEMU_OPTION_win2k_hack
,
6551 QEMU_OPTION_usbdevice
,
6554 QEMU_OPTION_no_acpi
,
6555 QEMU_OPTION_no_reboot
,
6556 QEMU_OPTION_daemonize
,
6557 QEMU_OPTION_option_rom
,
6558 QEMU_OPTION_semihosting
,
6562 typedef struct QEMUOption
{
6568 const QEMUOption qemu_options
[] = {
6569 { "h", 0, QEMU_OPTION_h
},
6570 { "help", 0, QEMU_OPTION_h
},
6572 { "M", HAS_ARG
, QEMU_OPTION_M
},
6573 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
6574 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6575 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6576 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6577 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6578 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6579 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6580 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6581 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6582 { "snapshot", 0, QEMU_OPTION_snapshot
},
6584 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6586 { "m", HAS_ARG
, QEMU_OPTION_m
},
6587 { "nographic", 0, QEMU_OPTION_nographic
},
6588 { "k", HAS_ARG
, QEMU_OPTION_k
},
6590 { "audio-help", 0, QEMU_OPTION_audio_help
},
6591 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6594 { "net", HAS_ARG
, QEMU_OPTION_net
},
6596 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6597 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
6599 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6601 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6604 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6605 { "append", HAS_ARG
, QEMU_OPTION_append
},
6606 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6608 { "S", 0, QEMU_OPTION_S
},
6609 { "s", 0, QEMU_OPTION_s
},
6610 { "p", HAS_ARG
, QEMU_OPTION_p
},
6611 { "d", HAS_ARG
, QEMU_OPTION_d
},
6612 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6613 { "L", HAS_ARG
, QEMU_OPTION_L
},
6614 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6616 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6617 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6619 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6620 { "g", 1, QEMU_OPTION_g
},
6622 { "localtime", 0, QEMU_OPTION_localtime
},
6623 { "std-vga", 0, QEMU_OPTION_std_vga
},
6624 { "echr", 1, QEMU_OPTION_echr
},
6625 { "monitor", 1, QEMU_OPTION_monitor
},
6626 { "serial", 1, QEMU_OPTION_serial
},
6627 { "parallel", 1, QEMU_OPTION_parallel
},
6628 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6629 { "full-screen", 0, QEMU_OPTION_full_screen
},
6631 { "no-frame", 0, QEMU_OPTION_no_frame
},
6632 { "no-quit", 0, QEMU_OPTION_no_quit
},
6634 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6635 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6636 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6637 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6638 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6640 /* temporary options */
6641 { "usb", 0, QEMU_OPTION_usb
},
6642 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6643 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6644 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6645 { "daemonize", 0, QEMU_OPTION_daemonize
},
6646 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6647 #if defined(TARGET_ARM)
6648 { "semihosting", 0, QEMU_OPTION_semihosting
},
6650 { "name", HAS_ARG
, QEMU_OPTION_name
},
6654 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6656 /* this stack is only used during signal handling */
6657 #define SIGNAL_STACK_SIZE 32768
6659 static uint8_t *signal_stack
;
6663 /* password input */
6665 static BlockDriverState
*get_bdrv(int index
)
6667 BlockDriverState
*bs
;
6670 bs
= bs_table
[index
];
6671 } else if (index
< 6) {
6672 bs
= fd_table
[index
- 4];
6679 static void read_passwords(void)
6681 BlockDriverState
*bs
;
6685 for(i
= 0; i
< 6; i
++) {
6687 if (bs
&& bdrv_is_encrypted(bs
)) {
6688 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6689 for(j
= 0; j
< 3; j
++) {
6690 monitor_readline("Password: ",
6691 1, password
, sizeof(password
));
6692 if (bdrv_set_key(bs
, password
) == 0)
6694 term_printf("invalid password\n");
6700 /* XXX: currently we cannot use simultaneously different CPUs */
6701 void register_machines(void)
6703 #if defined(TARGET_I386)
6704 qemu_register_machine(&pc_machine
);
6705 qemu_register_machine(&isapc_machine
);
6706 #elif defined(TARGET_PPC)
6707 qemu_register_machine(&heathrow_machine
);
6708 qemu_register_machine(&core99_machine
);
6709 qemu_register_machine(&prep_machine
);
6710 #elif defined(TARGET_MIPS)
6711 qemu_register_machine(&mips_machine
);
6712 qemu_register_machine(&mips_malta_machine
);
6713 #elif defined(TARGET_SPARC)
6714 #ifdef TARGET_SPARC64
6715 qemu_register_machine(&sun4u_machine
);
6717 qemu_register_machine(&sun4m_machine
);
6719 #elif defined(TARGET_ARM)
6720 qemu_register_machine(&integratorcp_machine
);
6721 qemu_register_machine(&versatilepb_machine
);
6722 qemu_register_machine(&versatileab_machine
);
6723 qemu_register_machine(&realview_machine
);
6724 #elif defined(TARGET_SH4)
6725 qemu_register_machine(&shix_machine
);
6727 #error unsupported CPU
6732 struct soundhw soundhw
[] = {
6739 { .init_isa
= pcspk_audio_init
}
6744 "Creative Sound Blaster 16",
6747 { .init_isa
= SB16_init
}
6754 "Yamaha YMF262 (OPL3)",
6756 "Yamaha YM3812 (OPL2)",
6760 { .init_isa
= Adlib_init
}
6767 "Gravis Ultrasound GF1",
6770 { .init_isa
= GUS_init
}
6776 "ENSONIQ AudioPCI ES1370",
6779 { .init_pci
= es1370_init
}
6782 { NULL
, NULL
, 0, 0, { NULL
} }
6785 static void select_soundhw (const char *optarg
)
6789 if (*optarg
== '?') {
6792 printf ("Valid sound card names (comma separated):\n");
6793 for (c
= soundhw
; c
->name
; ++c
) {
6794 printf ("%-11s %s\n", c
->name
, c
->descr
);
6796 printf ("\n-soundhw all will enable all of the above\n");
6797 exit (*optarg
!= '?');
6805 if (!strcmp (optarg
, "all")) {
6806 for (c
= soundhw
; c
->name
; ++c
) {
6814 e
= strchr (p
, ',');
6815 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6817 for (c
= soundhw
; c
->name
; ++c
) {
6818 if (!strncmp (c
->name
, p
, l
)) {
6827 "Unknown sound card name (too big to show)\n");
6830 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6835 p
+= l
+ (e
!= NULL
);
6839 goto show_valid_cards
;
6845 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6847 exit(STATUS_CONTROL_C_EXIT
);
6852 #define MAX_NET_CLIENTS 32
6854 int main(int argc
, char **argv
)
6856 #ifdef CONFIG_GDBSTUB
6858 const char *gdbstub_port
;
6861 int snapshot
, linux_boot
;
6862 const char *initrd_filename
;
6863 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6864 const char *kernel_filename
, *kernel_cmdline
;
6865 DisplayState
*ds
= &display_state
;
6866 int cyls
, heads
, secs
, translation
;
6867 char net_clients
[MAX_NET_CLIENTS
][256];
6870 const char *r
, *optarg
;
6871 CharDriverState
*monitor_hd
;
6872 char monitor_device
[128];
6873 char serial_devices
[MAX_SERIAL_PORTS
][128];
6874 int serial_device_index
;
6875 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6876 int parallel_device_index
;
6877 const char *loadvm
= NULL
;
6878 QEMUMachine
*machine
;
6879 const char *cpu_model
;
6880 char usb_devices
[MAX_USB_CMDLINE
][128];
6881 int usb_devices_index
;
6884 LIST_INIT (&vm_change_state_head
);
6887 struct sigaction act
;
6888 sigfillset(&act
.sa_mask
);
6890 act
.sa_handler
= SIG_IGN
;
6891 sigaction(SIGPIPE
, &act
, NULL
);
6894 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6895 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6896 QEMU to run on a single CPU */
6901 h
= GetCurrentProcess();
6902 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6903 for(i
= 0; i
< 32; i
++) {
6904 if (mask
& (1 << i
))
6909 SetProcessAffinityMask(h
, mask
);
6915 register_machines();
6916 machine
= first_machine
;
6918 initrd_filename
= NULL
;
6919 for(i
= 0; i
< MAX_FD
; i
++)
6920 fd_filename
[i
] = NULL
;
6921 for(i
= 0; i
< MAX_DISKS
; i
++)
6922 hd_filename
[i
] = NULL
;
6923 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6924 vga_ram_size
= VGA_RAM_SIZE
;
6925 #ifdef CONFIG_GDBSTUB
6927 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6931 kernel_filename
= NULL
;
6932 kernel_cmdline
= "";
6938 cyls
= heads
= secs
= 0;
6939 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6940 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6942 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6943 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6944 serial_devices
[i
][0] = '\0';
6945 serial_device_index
= 0;
6947 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6948 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6949 parallel_devices
[i
][0] = '\0';
6950 parallel_device_index
= 0;
6952 usb_devices_index
= 0;
6957 /* default mac address of the first network interface */
6965 hd_filename
[0] = argv
[optind
++];
6967 const QEMUOption
*popt
;
6970 /* Treat --foo the same as -foo. */
6973 popt
= qemu_options
;
6976 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6980 if (!strcmp(popt
->name
, r
+ 1))
6984 if (popt
->flags
& HAS_ARG
) {
6985 if (optind
>= argc
) {
6986 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6990 optarg
= argv
[optind
++];
6995 switch(popt
->index
) {
6997 machine
= find_machine(optarg
);
7000 printf("Supported machines are:\n");
7001 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7002 printf("%-10s %s%s\n",
7004 m
== first_machine
? " (default)" : "");
7009 case QEMU_OPTION_cpu
:
7010 /* hw initialization will check this */
7011 if (optarg
[0] == '?') {
7012 #if defined(TARGET_PPC)
7013 ppc_cpu_list(stdout
, &fprintf
);
7014 #elif defined(TARGET_ARM)
7016 #elif defined(TARGET_MIPS)
7017 mips_cpu_list(stdout
, &fprintf
);
7024 case QEMU_OPTION_initrd
:
7025 initrd_filename
= optarg
;
7027 case QEMU_OPTION_hda
:
7028 case QEMU_OPTION_hdb
:
7029 case QEMU_OPTION_hdc
:
7030 case QEMU_OPTION_hdd
:
7033 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7034 hd_filename
[hd_index
] = optarg
;
7035 if (hd_index
== cdrom_index
)
7039 case QEMU_OPTION_snapshot
:
7042 case QEMU_OPTION_hdachs
:
7046 cyls
= strtol(p
, (char **)&p
, 0);
7047 if (cyls
< 1 || cyls
> 16383)
7052 heads
= strtol(p
, (char **)&p
, 0);
7053 if (heads
< 1 || heads
> 16)
7058 secs
= strtol(p
, (char **)&p
, 0);
7059 if (secs
< 1 || secs
> 63)
7063 if (!strcmp(p
, "none"))
7064 translation
= BIOS_ATA_TRANSLATION_NONE
;
7065 else if (!strcmp(p
, "lba"))
7066 translation
= BIOS_ATA_TRANSLATION_LBA
;
7067 else if (!strcmp(p
, "auto"))
7068 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7071 } else if (*p
!= '\0') {
7073 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7078 case QEMU_OPTION_nographic
:
7079 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7080 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7083 case QEMU_OPTION_kernel
:
7084 kernel_filename
= optarg
;
7086 case QEMU_OPTION_append
:
7087 kernel_cmdline
= optarg
;
7089 case QEMU_OPTION_cdrom
:
7090 if (cdrom_index
>= 0) {
7091 hd_filename
[cdrom_index
] = optarg
;
7094 case QEMU_OPTION_boot
:
7095 boot_device
= optarg
[0];
7096 if (boot_device
!= 'a' &&
7097 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7099 boot_device
!= 'n' &&
7101 boot_device
!= 'c' && boot_device
!= 'd') {
7102 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7106 case QEMU_OPTION_fda
:
7107 fd_filename
[0] = optarg
;
7109 case QEMU_OPTION_fdb
:
7110 fd_filename
[1] = optarg
;
7113 case QEMU_OPTION_no_fd_bootchk
:
7117 case QEMU_OPTION_no_code_copy
:
7118 code_copy_enabled
= 0;
7120 case QEMU_OPTION_net
:
7121 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7122 fprintf(stderr
, "qemu: too many network clients\n");
7125 pstrcpy(net_clients
[nb_net_clients
],
7126 sizeof(net_clients
[0]),
7131 case QEMU_OPTION_tftp
:
7132 tftp_prefix
= optarg
;
7134 case QEMU_OPTION_bootp
:
7135 bootp_filename
= optarg
;
7138 case QEMU_OPTION_smb
:
7139 net_slirp_smb(optarg
);
7142 case QEMU_OPTION_redir
:
7143 net_slirp_redir(optarg
);
7147 case QEMU_OPTION_audio_help
:
7151 case QEMU_OPTION_soundhw
:
7152 select_soundhw (optarg
);
7159 ram_size
= atoi(optarg
) * 1024 * 1024;
7162 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7163 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7164 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7173 mask
= cpu_str_to_log_mask(optarg
);
7175 printf("Log items (comma separated):\n");
7176 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7177 printf("%-10s %s\n", item
->name
, item
->help
);
7184 #ifdef CONFIG_GDBSTUB
7189 gdbstub_port
= optarg
;
7199 keyboard_layout
= optarg
;
7201 case QEMU_OPTION_localtime
:
7204 case QEMU_OPTION_cirrusvga
:
7205 cirrus_vga_enabled
= 1;
7207 case QEMU_OPTION_std_vga
:
7208 cirrus_vga_enabled
= 0;
7215 w
= strtol(p
, (char **)&p
, 10);
7218 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7224 h
= strtol(p
, (char **)&p
, 10);
7229 depth
= strtol(p
, (char **)&p
, 10);
7230 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7231 depth
!= 24 && depth
!= 32)
7233 } else if (*p
== '\0') {
7234 depth
= graphic_depth
;
7241 graphic_depth
= depth
;
7244 case QEMU_OPTION_echr
:
7247 term_escape_char
= strtol(optarg
, &r
, 0);
7249 printf("Bad argument to echr\n");
7252 case QEMU_OPTION_monitor
:
7253 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7255 case QEMU_OPTION_serial
:
7256 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7257 fprintf(stderr
, "qemu: too many serial ports\n");
7260 pstrcpy(serial_devices
[serial_device_index
],
7261 sizeof(serial_devices
[0]), optarg
);
7262 serial_device_index
++;
7264 case QEMU_OPTION_parallel
:
7265 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7266 fprintf(stderr
, "qemu: too many parallel ports\n");
7269 pstrcpy(parallel_devices
[parallel_device_index
],
7270 sizeof(parallel_devices
[0]), optarg
);
7271 parallel_device_index
++;
7273 case QEMU_OPTION_loadvm
:
7276 case QEMU_OPTION_full_screen
:
7280 case QEMU_OPTION_no_frame
:
7283 case QEMU_OPTION_no_quit
:
7287 case QEMU_OPTION_pidfile
:
7288 create_pidfile(optarg
);
7291 case QEMU_OPTION_win2k_hack
:
7292 win2k_install_hack
= 1;
7296 case QEMU_OPTION_no_kqemu
:
7299 case QEMU_OPTION_kernel_kqemu
:
7303 case QEMU_OPTION_usb
:
7306 case QEMU_OPTION_usbdevice
:
7308 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7309 fprintf(stderr
, "Too many USB devices\n");
7312 pstrcpy(usb_devices
[usb_devices_index
],
7313 sizeof(usb_devices
[usb_devices_index
]),
7315 usb_devices_index
++;
7317 case QEMU_OPTION_smp
:
7318 smp_cpus
= atoi(optarg
);
7319 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7320 fprintf(stderr
, "Invalid number of CPUs\n");
7324 case QEMU_OPTION_vnc
:
7325 vnc_display
= optarg
;
7327 case QEMU_OPTION_no_acpi
:
7330 case QEMU_OPTION_no_reboot
:
7333 case QEMU_OPTION_daemonize
:
7336 case QEMU_OPTION_option_rom
:
7337 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7338 fprintf(stderr
, "Too many option ROMs\n");
7341 option_rom
[nb_option_roms
] = optarg
;
7344 case QEMU_OPTION_semihosting
:
7345 semihosting_enabled
= 1;
7347 case QEMU_OPTION_name
:
7355 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7356 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7363 if (pipe(fds
) == -1)
7374 len
= read(fds
[0], &status
, 1);
7375 if (len
== -1 && (errno
== EINTR
))
7378 if (len
!= 1 || status
!= 0)
7396 signal(SIGTSTP
, SIG_IGN
);
7397 signal(SIGTTOU
, SIG_IGN
);
7398 signal(SIGTTIN
, SIG_IGN
);
7406 linux_boot
= (kernel_filename
!= NULL
);
7409 boot_device
!= 'n' &&
7410 hd_filename
[0] == '\0' &&
7411 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7412 fd_filename
[0] == '\0')
7415 /* boot to floppy or the default cd if no hard disk defined yet */
7416 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7417 if (fd_filename
[0] != '\0')
7423 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7433 /* init network clients */
7434 if (nb_net_clients
== 0) {
7435 /* if no clients, we use a default config */
7436 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7438 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7443 for(i
= 0;i
< nb_net_clients
; i
++) {
7444 if (net_client_init(net_clients
[i
]) < 0)
7449 if (boot_device
== 'n') {
7450 for (i
= 0; i
< nb_nics
; i
++) {
7451 const char *model
= nd_table
[i
].model
;
7455 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7456 if (get_image_size(buf
) > 0) {
7457 option_rom
[nb_option_roms
] = strdup(buf
);
7463 fprintf(stderr
, "No valid PXE rom found for network device\n");
7466 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7470 /* init the memory */
7471 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
7473 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7474 if (!phys_ram_base
) {
7475 fprintf(stderr
, "Could not allocate physical memory\n");
7479 /* we always create the cdrom drive, even if no disk is there */
7481 if (cdrom_index
>= 0) {
7482 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7483 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7486 /* open the virtual block devices */
7487 for(i
= 0; i
< MAX_DISKS
; i
++) {
7488 if (hd_filename
[i
]) {
7491 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7492 bs_table
[i
] = bdrv_new(buf
);
7494 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7495 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7499 if (i
== 0 && cyls
!= 0) {
7500 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7501 bdrv_set_translation_hint(bs_table
[i
], translation
);
7506 /* we always create at least one floppy disk */
7507 fd_table
[0] = bdrv_new("fda");
7508 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7510 for(i
= 0; i
< MAX_FD
; i
++) {
7511 if (fd_filename
[i
]) {
7514 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7515 fd_table
[i
] = bdrv_new(buf
);
7516 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7518 if (fd_filename
[i
] != '\0') {
7519 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7520 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7521 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7529 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7530 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7536 dumb_display_init(ds
);
7537 } else if (vnc_display
!= NULL
) {
7538 vnc_display_init(ds
, vnc_display
);
7540 #if defined(CONFIG_SDL)
7541 sdl_display_init(ds
, full_screen
, no_frame
);
7542 #elif defined(CONFIG_COCOA)
7543 cocoa_display_init(ds
, full_screen
);
7545 dumb_display_init(ds
);
7549 /* Maintain compatibility with multiple stdio monitors */
7550 if (!strcmp(monitor_device
,"stdio")) {
7551 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7552 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
7553 monitor_device
[0] = '\0';
7555 } else if (!strcmp(serial_devices
[i
],"stdio")) {
7556 monitor_device
[0] = '\0';
7557 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
7562 if (monitor_device
[0] != '\0') {
7563 monitor_hd
= qemu_chr_open(monitor_device
);
7565 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7568 monitor_init(monitor_hd
, !nographic
);
7571 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7572 const char *devname
= serial_devices
[i
];
7573 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7574 serial_hds
[i
] = qemu_chr_open(devname
);
7575 if (!serial_hds
[i
]) {
7576 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7580 if (!strcmp(devname
, "vc"))
7581 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7585 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7586 const char *devname
= parallel_devices
[i
];
7587 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7588 parallel_hds
[i
] = qemu_chr_open(devname
);
7589 if (!parallel_hds
[i
]) {
7590 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7594 if (!strcmp(devname
, "vc"))
7595 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7599 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7600 ds
, fd_filename
, snapshot
,
7601 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
7603 /* init USB devices */
7605 for(i
= 0; i
< usb_devices_index
; i
++) {
7606 if (usb_device_add(usb_devices
[i
]) < 0) {
7607 fprintf(stderr
, "Warning: could not add USB device %s\n",
7613 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7614 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7616 #ifdef CONFIG_GDBSTUB
7618 /* XXX: use standard host:port notation and modify options
7620 if (gdbserver_start(gdbstub_port
) < 0) {
7621 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
7631 /* XXX: simplify init */
7644 len
= write(fds
[1], &status
, 1);
7645 if (len
== -1 && (errno
== EINTR
))
7651 fd
= open("/dev/null", O_RDWR
);