4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
78 #if defined(CONFIG_SLIRP)
84 #include <sys/timeb.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
90 #include "qemu_socket.h"
96 #endif /* CONFIG_SDL */
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
111 #define SMBD_COMMAND "/usr/sbin/smbd"
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
120 #define DEFAULT_RAM_SIZE 144
122 #define DEFAULT_RAM_SIZE 128
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
134 char phys_ram_file
[1024];
135 void *ioport_opaque
[MAX_IOPORTS
];
136 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
137 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState
*bs_table
[MAX_DISKS
+ 1], *fd_table
[MAX_FD
];
141 /* point to the block driver where the snapshots are managed */
142 BlockDriverState
*bs_snapshots
;
144 static DisplayState display_state
;
146 const char* keyboard_layout
= NULL
;
147 int64_t ticks_per_sec
;
148 int boot_device
= 'c';
150 int pit_min_timer_count
= 0;
152 NICInfo nd_table
[MAX_NICS
];
153 QEMUTimer
*gui_timer
;
156 int cirrus_vga_enabled
= 1;
158 int graphic_width
= 1024;
159 int graphic_height
= 768;
161 int graphic_width
= 800;
162 int graphic_height
= 600;
164 int graphic_depth
= 15;
168 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
169 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
171 int win2k_install_hack
= 0;
174 static VLANState
*first_vlan
;
176 const char *vnc_display
;
177 #if defined(TARGET_SPARC)
179 #elif defined(TARGET_I386)
184 int acpi_enabled
= 1;
188 const char *option_rom
[MAX_OPTION_ROMS
];
190 int semihosting_enabled
= 0;
192 const char *qemu_name
;
194 /***********************************************************/
195 /* x86 ISA bus support */
197 target_phys_addr_t isa_mem_base
= 0;
200 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
208 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
210 #ifdef DEBUG_UNUSED_IOPORT
211 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
215 /* default is to make two byte accesses */
216 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
219 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
220 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
221 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
225 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
227 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
228 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
229 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
232 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
234 #ifdef DEBUG_UNUSED_IOPORT
235 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
240 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
242 #ifdef DEBUG_UNUSED_IOPORT
243 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
247 void init_ioports(void)
251 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
252 ioport_read_table
[0][i
] = default_ioport_readb
;
253 ioport_write_table
[0][i
] = default_ioport_writeb
;
254 ioport_read_table
[1][i
] = default_ioport_readw
;
255 ioport_write_table
[1][i
] = default_ioport_writew
;
256 ioport_read_table
[2][i
] = default_ioport_readl
;
257 ioport_write_table
[2][i
] = default_ioport_writel
;
261 /* size is the word size in byte */
262 int register_ioport_read(int start
, int length
, int size
,
263 IOPortReadFunc
*func
, void *opaque
)
269 } else if (size
== 2) {
271 } else if (size
== 4) {
274 hw_error("register_ioport_read: invalid size");
277 for(i
= start
; i
< start
+ length
; i
+= size
) {
278 ioport_read_table
[bsize
][i
] = func
;
279 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
280 hw_error("register_ioport_read: invalid opaque");
281 ioport_opaque
[i
] = opaque
;
286 /* size is the word size in byte */
287 int register_ioport_write(int start
, int length
, int size
,
288 IOPortWriteFunc
*func
, void *opaque
)
294 } else if (size
== 2) {
296 } else if (size
== 4) {
299 hw_error("register_ioport_write: invalid size");
302 for(i
= start
; i
< start
+ length
; i
+= size
) {
303 ioport_write_table
[bsize
][i
] = func
;
304 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
305 hw_error("register_ioport_write: invalid opaque");
306 ioport_opaque
[i
] = opaque
;
311 void isa_unassign_ioport(int start
, int length
)
315 for(i
= start
; i
< start
+ length
; i
++) {
316 ioport_read_table
[0][i
] = default_ioport_readb
;
317 ioport_read_table
[1][i
] = default_ioport_readw
;
318 ioport_read_table
[2][i
] = default_ioport_readl
;
320 ioport_write_table
[0][i
] = default_ioport_writeb
;
321 ioport_write_table
[1][i
] = default_ioport_writew
;
322 ioport_write_table
[2][i
] = default_ioport_writel
;
326 /***********************************************************/
328 void cpu_outb(CPUState
*env
, int addr
, int val
)
331 if (loglevel
& CPU_LOG_IOPORT
)
332 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
334 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
337 env
->last_io_time
= cpu_get_time_fast();
341 void cpu_outw(CPUState
*env
, int addr
, int val
)
344 if (loglevel
& CPU_LOG_IOPORT
)
345 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
347 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
350 env
->last_io_time
= cpu_get_time_fast();
354 void cpu_outl(CPUState
*env
, int addr
, int val
)
357 if (loglevel
& CPU_LOG_IOPORT
)
358 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
360 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
363 env
->last_io_time
= cpu_get_time_fast();
367 int cpu_inb(CPUState
*env
, int addr
)
370 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
372 if (loglevel
& CPU_LOG_IOPORT
)
373 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
377 env
->last_io_time
= cpu_get_time_fast();
382 int cpu_inw(CPUState
*env
, int addr
)
385 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
387 if (loglevel
& CPU_LOG_IOPORT
)
388 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
392 env
->last_io_time
= cpu_get_time_fast();
397 int cpu_inl(CPUState
*env
, int addr
)
400 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
402 if (loglevel
& CPU_LOG_IOPORT
)
403 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
407 env
->last_io_time
= cpu_get_time_fast();
412 /***********************************************************/
413 void hw_error(const char *fmt
, ...)
419 fprintf(stderr
, "qemu: hardware error: ");
420 vfprintf(stderr
, fmt
, ap
);
421 fprintf(stderr
, "\n");
422 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
423 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
425 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
427 cpu_dump_state(env
, stderr
, fprintf
, 0);
434 /***********************************************************/
437 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
438 static void *qemu_put_kbd_event_opaque
;
439 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
440 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
442 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
444 qemu_put_kbd_event_opaque
= opaque
;
445 qemu_put_kbd_event
= func
;
448 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
449 void *opaque
, int absolute
,
452 QEMUPutMouseEntry
*s
, *cursor
;
454 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
458 s
->qemu_put_mouse_event
= func
;
459 s
->qemu_put_mouse_event_opaque
= opaque
;
460 s
->qemu_put_mouse_event_absolute
= absolute
;
461 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
464 if (!qemu_put_mouse_event_head
) {
465 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
469 cursor
= qemu_put_mouse_event_head
;
470 while (cursor
->next
!= NULL
)
471 cursor
= cursor
->next
;
474 qemu_put_mouse_event_current
= s
;
479 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
481 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
483 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
486 cursor
= qemu_put_mouse_event_head
;
487 while (cursor
!= NULL
&& cursor
!= entry
) {
489 cursor
= cursor
->next
;
492 if (cursor
== NULL
) // does not exist or list empty
494 else if (prev
== NULL
) { // entry is head
495 qemu_put_mouse_event_head
= cursor
->next
;
496 if (qemu_put_mouse_event_current
== entry
)
497 qemu_put_mouse_event_current
= cursor
->next
;
498 qemu_free(entry
->qemu_put_mouse_event_name
);
503 prev
->next
= entry
->next
;
505 if (qemu_put_mouse_event_current
== entry
)
506 qemu_put_mouse_event_current
= prev
;
508 qemu_free(entry
->qemu_put_mouse_event_name
);
512 void kbd_put_keycode(int keycode
)
514 if (qemu_put_kbd_event
) {
515 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
519 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
521 QEMUPutMouseEvent
*mouse_event
;
522 void *mouse_event_opaque
;
524 if (!qemu_put_mouse_event_current
) {
529 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
531 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
534 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
538 int kbd_mouse_is_absolute(void)
540 if (!qemu_put_mouse_event_current
)
543 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
546 void do_info_mice(void)
548 QEMUPutMouseEntry
*cursor
;
551 if (!qemu_put_mouse_event_head
) {
552 term_printf("No mouse devices connected\n");
556 term_printf("Mouse devices available:\n");
557 cursor
= qemu_put_mouse_event_head
;
558 while (cursor
!= NULL
) {
559 term_printf("%c Mouse #%d: %s\n",
560 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
561 index
, cursor
->qemu_put_mouse_event_name
);
563 cursor
= cursor
->next
;
567 void do_mouse_set(int index
)
569 QEMUPutMouseEntry
*cursor
;
572 if (!qemu_put_mouse_event_head
) {
573 term_printf("No mouse devices connected\n");
577 cursor
= qemu_put_mouse_event_head
;
578 while (cursor
!= NULL
&& index
!= i
) {
580 cursor
= cursor
->next
;
584 qemu_put_mouse_event_current
= cursor
;
586 term_printf("Mouse at given index not found\n");
589 /* compute with 96 bit intermediate result: (a*b)/c */
590 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
595 #ifdef WORDS_BIGENDIAN
605 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
606 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
609 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
613 /***********************************************************/
614 /* real time host monotonic timer */
616 #define QEMU_TIMER_BASE 1000000000LL
620 static int64_t clock_freq
;
622 static void init_get_clock(void)
626 ret
= QueryPerformanceFrequency(&freq
);
628 fprintf(stderr
, "Could not calibrate ticks\n");
631 clock_freq
= freq
.QuadPart
;
634 static int64_t get_clock(void)
637 QueryPerformanceCounter(&ti
);
638 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
643 static int use_rt_clock
;
645 static void init_get_clock(void)
648 #if defined(__linux__)
651 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
658 static int64_t get_clock(void)
660 #if defined(__linux__)
663 clock_gettime(CLOCK_MONOTONIC
, &ts
);
664 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
668 /* XXX: using gettimeofday leads to problems if the date
669 changes, so it should be avoided. */
671 gettimeofday(&tv
, NULL
);
672 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
678 /***********************************************************/
679 /* guest cycle counter */
681 static int64_t cpu_ticks_prev
;
682 static int64_t cpu_ticks_offset
;
683 static int64_t cpu_clock_offset
;
684 static int cpu_ticks_enabled
;
686 /* return the host CPU cycle counter and handle stop/restart */
687 int64_t cpu_get_ticks(void)
689 if (!cpu_ticks_enabled
) {
690 return cpu_ticks_offset
;
693 ticks
= cpu_get_real_ticks();
694 if (cpu_ticks_prev
> ticks
) {
695 /* Note: non increasing ticks may happen if the host uses
697 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
699 cpu_ticks_prev
= ticks
;
700 return ticks
+ cpu_ticks_offset
;
704 /* return the host CPU monotonic timer and handle stop/restart */
705 static int64_t cpu_get_clock(void)
708 if (!cpu_ticks_enabled
) {
709 return cpu_clock_offset
;
712 return ti
+ cpu_clock_offset
;
716 /* enable cpu_get_ticks() */
717 void cpu_enable_ticks(void)
719 if (!cpu_ticks_enabled
) {
720 cpu_ticks_offset
-= cpu_get_real_ticks();
721 cpu_clock_offset
-= get_clock();
722 cpu_ticks_enabled
= 1;
726 /* disable cpu_get_ticks() : the clock is stopped. You must not call
727 cpu_get_ticks() after that. */
728 void cpu_disable_ticks(void)
730 if (cpu_ticks_enabled
) {
731 cpu_ticks_offset
= cpu_get_ticks();
732 cpu_clock_offset
= cpu_get_clock();
733 cpu_ticks_enabled
= 0;
737 /***********************************************************/
740 #define QEMU_TIMER_REALTIME 0
741 #define QEMU_TIMER_VIRTUAL 1
745 /* XXX: add frequency */
753 struct QEMUTimer
*next
;
759 static QEMUTimer
*active_timers
[2];
761 static MMRESULT timerID
;
762 static HANDLE host_alarm
= NULL
;
763 static unsigned int period
= 1;
765 /* frequency of the times() clock tick */
766 static int timer_freq
;
769 QEMUClock
*qemu_new_clock(int type
)
772 clock
= qemu_mallocz(sizeof(QEMUClock
));
779 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
783 ts
= qemu_mallocz(sizeof(QEMUTimer
));
790 void qemu_free_timer(QEMUTimer
*ts
)
795 /* stop a timer, but do not dealloc it */
796 void qemu_del_timer(QEMUTimer
*ts
)
800 /* NOTE: this code must be signal safe because
801 qemu_timer_expired() can be called from a signal. */
802 pt
= &active_timers
[ts
->clock
->type
];
815 /* modify the current timer so that it will be fired when current_time
816 >= expire_time. The corresponding callback will be called. */
817 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
823 /* add the timer in the sorted list */
824 /* NOTE: this code must be signal safe because
825 qemu_timer_expired() can be called from a signal. */
826 pt
= &active_timers
[ts
->clock
->type
];
831 if (t
->expire_time
> expire_time
)
835 ts
->expire_time
= expire_time
;
840 int qemu_timer_pending(QEMUTimer
*ts
)
843 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
850 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
854 return (timer_head
->expire_time
<= current_time
);
857 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
863 if (!ts
|| ts
->expire_time
> current_time
)
865 /* remove timer from the list before calling the callback */
866 *ptimer_head
= ts
->next
;
869 /* run the callback (the timer list can be modified) */
874 int64_t qemu_get_clock(QEMUClock
*clock
)
876 switch(clock
->type
) {
877 case QEMU_TIMER_REALTIME
:
878 return get_clock() / 1000000;
880 case QEMU_TIMER_VIRTUAL
:
881 return cpu_get_clock();
885 static void init_timers(void)
888 ticks_per_sec
= QEMU_TIMER_BASE
;
889 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
890 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
894 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
896 uint64_t expire_time
;
898 if (qemu_timer_pending(ts
)) {
899 expire_time
= ts
->expire_time
;
903 qemu_put_be64(f
, expire_time
);
906 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
908 uint64_t expire_time
;
910 expire_time
= qemu_get_be64(f
);
911 if (expire_time
!= -1) {
912 qemu_mod_timer(ts
, expire_time
);
918 static void timer_save(QEMUFile
*f
, void *opaque
)
920 if (cpu_ticks_enabled
) {
921 hw_error("cannot save state if virtual timers are running");
923 qemu_put_be64s(f
, &cpu_ticks_offset
);
924 qemu_put_be64s(f
, &ticks_per_sec
);
925 qemu_put_be64s(f
, &cpu_clock_offset
);
928 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
930 if (version_id
!= 1 && version_id
!= 2)
932 if (cpu_ticks_enabled
) {
935 qemu_get_be64s(f
, &cpu_ticks_offset
);
936 qemu_get_be64s(f
, &ticks_per_sec
);
937 if (version_id
== 2) {
938 qemu_get_be64s(f
, &cpu_clock_offset
);
944 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
945 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
947 static void host_alarm_handler(int host_signum
)
951 #define DISP_FREQ 1000
953 static int64_t delta_min
= INT64_MAX
;
954 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
956 ti
= qemu_get_clock(vm_clock
);
957 if (last_clock
!= 0) {
958 delta
= ti
- last_clock
;
959 if (delta
< delta_min
)
961 if (delta
> delta_max
)
964 if (++count
== DISP_FREQ
) {
965 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
966 muldiv64(delta_min
, 1000000, ticks_per_sec
),
967 muldiv64(delta_max
, 1000000, ticks_per_sec
),
968 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
969 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
971 delta_min
= INT64_MAX
;
979 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
980 qemu_get_clock(vm_clock
)) ||
981 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
982 qemu_get_clock(rt_clock
))) {
984 SetEvent(host_alarm
);
986 CPUState
*env
= cpu_single_env
;
988 /* stop the currently executing cpu because a timer occured */
989 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
991 if (env
->kqemu_enabled
) {
992 kqemu_cpu_interrupt(env
);
1001 #if defined(__linux__)
1003 #define RTC_FREQ 1024
1007 static int start_rtc_timer(void)
1009 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1012 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1013 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1014 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1015 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1018 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1023 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1029 static int start_rtc_timer(void)
1034 #endif /* !defined(__linux__) */
1036 #endif /* !defined(_WIN32) */
1038 static void init_timer_alarm(void)
1045 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1046 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1047 if (period
< tc
.wPeriodMin
)
1048 period
= tc
.wPeriodMin
;
1049 timeBeginPeriod(period
);
1050 timerID
= timeSetEvent(1, // interval (ms)
1051 period
, // resolution
1052 host_alarm_handler
, // function
1053 (DWORD
)&count
, // user parameter
1054 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1056 perror("failed timer alarm");
1059 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1061 perror("failed CreateEvent");
1064 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1066 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1069 struct sigaction act
;
1070 struct itimerval itv
;
1072 /* get times() syscall frequency */
1073 timer_freq
= sysconf(_SC_CLK_TCK
);
1076 sigfillset(&act
.sa_mask
);
1078 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1079 act
.sa_flags
|= SA_ONSTACK
;
1081 act
.sa_handler
= host_alarm_handler
;
1082 sigaction(SIGALRM
, &act
, NULL
);
1084 itv
.it_interval
.tv_sec
= 0;
1085 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1086 itv
.it_value
.tv_sec
= 0;
1087 itv
.it_value
.tv_usec
= 10 * 1000;
1088 setitimer(ITIMER_REAL
, &itv
, NULL
);
1089 /* we probe the tick duration of the kernel to inform the user if
1090 the emulated kernel requested a too high timer frequency */
1091 getitimer(ITIMER_REAL
, &itv
);
1093 #if defined(__linux__)
1094 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1095 have timers with 1 ms resolution. The correct solution will
1096 be to use the POSIX real time timers available in recent
1098 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1099 /* try to use /dev/rtc to have a faster timer */
1100 if (start_rtc_timer() < 0)
1102 /* disable itimer */
1103 itv
.it_interval
.tv_sec
= 0;
1104 itv
.it_interval
.tv_usec
= 0;
1105 itv
.it_value
.tv_sec
= 0;
1106 itv
.it_value
.tv_usec
= 0;
1107 setitimer(ITIMER_REAL
, &itv
, NULL
);
1110 sigaction(SIGIO
, &act
, NULL
);
1111 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1112 fcntl(rtc_fd
, F_SETOWN
, getpid());
1114 #endif /* defined(__linux__) */
1117 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1118 PIT_FREQ
) / 1000000;
1124 void quit_timers(void)
1127 timeKillEvent(timerID
);
1128 timeEndPeriod(period
);
1130 CloseHandle(host_alarm
);
1136 /***********************************************************/
1137 /* character device */
1139 static void qemu_chr_event(CharDriverState
*s
, int event
)
1143 s
->chr_event(s
->handler_opaque
, event
);
1146 static void qemu_chr_reset_bh(void *opaque
)
1148 CharDriverState
*s
= opaque
;
1149 qemu_chr_event(s
, CHR_EVENT_RESET
);
1150 qemu_bh_delete(s
->bh
);
1154 void qemu_chr_reset(CharDriverState
*s
)
1156 if (s
->bh
== NULL
) {
1157 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1158 qemu_bh_schedule(s
->bh
);
1162 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1164 return s
->chr_write(s
, buf
, len
);
1167 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1171 return s
->chr_ioctl(s
, cmd
, arg
);
1174 int qemu_chr_can_read(CharDriverState
*s
)
1176 if (!s
->chr_can_read
)
1178 return s
->chr_can_read(s
->handler_opaque
);
1181 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1183 s
->chr_read(s
->handler_opaque
, buf
, len
);
1187 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1192 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1193 qemu_chr_write(s
, buf
, strlen(buf
));
1197 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1199 if (s
->chr_send_event
)
1200 s
->chr_send_event(s
, event
);
1203 void qemu_chr_add_handlers(CharDriverState
*s
,
1204 IOCanRWHandler
*fd_can_read
,
1205 IOReadHandler
*fd_read
,
1206 IOEventHandler
*fd_event
,
1209 s
->chr_can_read
= fd_can_read
;
1210 s
->chr_read
= fd_read
;
1211 s
->chr_event
= fd_event
;
1212 s
->handler_opaque
= opaque
;
1213 if (s
->chr_update_read_handler
)
1214 s
->chr_update_read_handler(s
);
1217 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1222 static CharDriverState
*qemu_chr_open_null(void)
1224 CharDriverState
*chr
;
1226 chr
= qemu_mallocz(sizeof(CharDriverState
));
1229 chr
->chr_write
= null_chr_write
;
1233 /* MUX driver for serial I/O splitting */
1234 static int term_timestamps
;
1235 static int64_t term_timestamps_start
;
1238 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1239 IOReadHandler
*chr_read
[MAX_MUX
];
1240 IOEventHandler
*chr_event
[MAX_MUX
];
1241 void *ext_opaque
[MAX_MUX
];
1242 CharDriverState
*drv
;
1244 int term_got_escape
;
1249 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1251 MuxDriver
*d
= chr
->opaque
;
1253 if (!term_timestamps
) {
1254 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1259 for(i
= 0; i
< len
; i
++) {
1260 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1261 if (buf
[i
] == '\n') {
1267 if (term_timestamps_start
== -1)
1268 term_timestamps_start
= ti
;
1269 ti
-= term_timestamps_start
;
1270 secs
= ti
/ 1000000000;
1271 snprintf(buf1
, sizeof(buf1
),
1272 "[%02d:%02d:%02d.%03d] ",
1276 (int)((ti
/ 1000000) % 1000));
1277 d
->drv
->chr_write(d
->drv
, buf1
, strlen(buf1
));
1284 static char *mux_help
[] = {
1285 "% h print this help\n\r",
1286 "% x exit emulator\n\r",
1287 "% s save disk data back to file (if -snapshot)\n\r",
1288 "% t toggle console timestamps\n\r"
1289 "% b send break (magic sysrq)\n\r",
1290 "% c switch between console and monitor\n\r",
1295 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1296 static void mux_print_help(CharDriverState
*chr
)
1299 char ebuf
[15] = "Escape-Char";
1300 char cbuf
[50] = "\n\r";
1302 if (term_escape_char
> 0 && term_escape_char
< 26) {
1303 sprintf(cbuf
,"\n\r");
1304 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1306 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char
);
1308 chr
->chr_write(chr
, cbuf
, strlen(cbuf
));
1309 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1310 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1311 if (mux_help
[i
][j
] == '%')
1312 chr
->chr_write(chr
, ebuf
, strlen(ebuf
));
1314 chr
->chr_write(chr
, &mux_help
[i
][j
], 1);
1319 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1321 if (d
->term_got_escape
) {
1322 d
->term_got_escape
= 0;
1323 if (ch
== term_escape_char
)
1328 mux_print_help(chr
);
1332 char *term
= "QEMU: Terminated\n\r";
1333 chr
->chr_write(chr
,term
,strlen(term
));
1340 for (i
= 0; i
< MAX_DISKS
; i
++) {
1342 bdrv_commit(bs_table
[i
]);
1348 chr
->chr_event(chr
->opaque
, CHR_EVENT_BREAK
);
1351 /* Switch to the next registered device */
1353 if (chr
->focus
>= d
->mux_cnt
)
1357 term_timestamps
= !term_timestamps
;
1358 term_timestamps_start
= -1;
1361 } else if (ch
== term_escape_char
) {
1362 d
->term_got_escape
= 1;
1370 static int mux_chr_can_read(void *opaque
)
1372 CharDriverState
*chr
= opaque
;
1373 MuxDriver
*d
= chr
->opaque
;
1374 if (d
->chr_can_read
[chr
->focus
])
1375 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1379 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1381 CharDriverState
*chr
= opaque
;
1382 MuxDriver
*d
= chr
->opaque
;
1384 for(i
= 0; i
< size
; i
++)
1385 if (mux_proc_byte(chr
, d
, buf
[i
]))
1386 d
->chr_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
], &buf
[i
], 1);
1389 static void mux_chr_event(void *opaque
, int event
)
1391 CharDriverState
*chr
= opaque
;
1392 MuxDriver
*d
= chr
->opaque
;
1395 /* Send the event to all registered listeners */
1396 for (i
= 0; i
< d
->mux_cnt
; i
++)
1397 if (d
->chr_event
[i
])
1398 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1401 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1403 MuxDriver
*d
= chr
->opaque
;
1405 if (d
->mux_cnt
>= MAX_MUX
) {
1406 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1409 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1410 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1411 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1412 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1413 /* Fix up the real driver with mux routines */
1414 if (d
->mux_cnt
== 0) {
1415 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1416 mux_chr_event
, chr
);
1418 chr
->focus
= d
->mux_cnt
;
1422 CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1424 CharDriverState
*chr
;
1427 chr
= qemu_mallocz(sizeof(CharDriverState
));
1430 d
= qemu_mallocz(sizeof(MuxDriver
));
1439 chr
->chr_write
= mux_chr_write
;
1440 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1447 static void socket_cleanup(void)
1452 static int socket_init(void)
1457 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1459 err
= WSAGetLastError();
1460 fprintf(stderr
, "WSAStartup: %d\n", err
);
1463 atexit(socket_cleanup
);
1467 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1473 ret
= send(fd
, buf
, len
, 0);
1476 errno
= WSAGetLastError();
1477 if (errno
!= WSAEWOULDBLOCK
) {
1480 } else if (ret
== 0) {
1490 void socket_set_nonblock(int fd
)
1492 unsigned long opt
= 1;
1493 ioctlsocket(fd
, FIONBIO
, &opt
);
1498 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1504 ret
= write(fd
, buf
, len
);
1506 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1508 } else if (ret
== 0) {
1518 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1520 return unix_write(fd
, buf
, len1
);
1523 void socket_set_nonblock(int fd
)
1525 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1527 #endif /* !_WIN32 */
1536 #define STDIO_MAX_CLIENTS 1
1537 static int stdio_nb_clients
= 0;
1539 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1541 FDCharDriver
*s
= chr
->opaque
;
1542 return unix_write(s
->fd_out
, buf
, len
);
1545 static int fd_chr_read_poll(void *opaque
)
1547 CharDriverState
*chr
= opaque
;
1548 FDCharDriver
*s
= chr
->opaque
;
1550 s
->max_size
= qemu_chr_can_read(chr
);
1554 static void fd_chr_read(void *opaque
)
1556 CharDriverState
*chr
= opaque
;
1557 FDCharDriver
*s
= chr
->opaque
;
1562 if (len
> s
->max_size
)
1566 size
= read(s
->fd_in
, buf
, len
);
1568 /* FD has been closed. Remove it from the active list. */
1569 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1573 qemu_chr_read(chr
, buf
, size
);
1577 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1579 FDCharDriver
*s
= chr
->opaque
;
1581 if (s
->fd_in
>= 0) {
1582 if (nographic
&& s
->fd_in
== 0) {
1584 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1585 fd_chr_read
, NULL
, chr
);
1590 /* open a character device to a unix fd */
1591 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1593 CharDriverState
*chr
;
1596 chr
= qemu_mallocz(sizeof(CharDriverState
));
1599 s
= qemu_mallocz(sizeof(FDCharDriver
));
1607 chr
->chr_write
= fd_chr_write
;
1608 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1610 qemu_chr_reset(chr
);
1615 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1619 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1622 return qemu_chr_open_fd(-1, fd_out
);
1625 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1628 char filename_in
[256], filename_out
[256];
1630 snprintf(filename_in
, 256, "%s.in", filename
);
1631 snprintf(filename_out
, 256, "%s.out", filename
);
1632 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1633 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1634 if (fd_in
< 0 || fd_out
< 0) {
1639 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1643 return qemu_chr_open_fd(fd_in
, fd_out
);
1647 /* for STDIO, we handle the case where several clients use it
1650 #define TERM_FIFO_MAX_SIZE 1
1652 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1653 static int term_fifo_size
;
1655 static int stdio_read_poll(void *opaque
)
1657 CharDriverState
*chr
= opaque
;
1659 /* try to flush the queue if needed */
1660 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1661 qemu_chr_read(chr
, term_fifo
, 1);
1664 /* see if we can absorb more chars */
1665 if (term_fifo_size
== 0)
1671 static void stdio_read(void *opaque
)
1675 CharDriverState
*chr
= opaque
;
1677 size
= read(0, buf
, 1);
1679 /* stdin has been closed. Remove it from the active list. */
1680 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1684 if (qemu_chr_can_read(chr
) > 0) {
1685 qemu_chr_read(chr
, buf
, 1);
1686 } else if (term_fifo_size
== 0) {
1687 term_fifo
[term_fifo_size
++] = buf
[0];
1692 /* init terminal so that we can grab keys */
1693 static struct termios oldtty
;
1694 static int old_fd0_flags
;
1696 static void term_exit(void)
1698 tcsetattr (0, TCSANOW
, &oldtty
);
1699 fcntl(0, F_SETFL
, old_fd0_flags
);
1702 static void term_init(void)
1706 tcgetattr (0, &tty
);
1708 old_fd0_flags
= fcntl(0, F_GETFL
);
1710 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1711 |INLCR
|IGNCR
|ICRNL
|IXON
);
1712 tty
.c_oflag
|= OPOST
;
1713 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1714 /* if graphical mode, we allow Ctrl-C handling */
1716 tty
.c_lflag
&= ~ISIG
;
1717 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1720 tty
.c_cc
[VTIME
] = 0;
1722 tcsetattr (0, TCSANOW
, &tty
);
1726 fcntl(0, F_SETFL
, O_NONBLOCK
);
1729 static CharDriverState
*qemu_chr_open_stdio(void)
1731 CharDriverState
*chr
;
1733 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1735 chr
= qemu_chr_open_fd(0, 1);
1736 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
1743 #if defined(__linux__)
1744 static CharDriverState
*qemu_chr_open_pty(void)
1747 char slave_name
[1024];
1748 int master_fd
, slave_fd
;
1750 /* Not satisfying */
1751 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1755 /* Disabling local echo and line-buffered output */
1756 tcgetattr (master_fd
, &tty
);
1757 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1759 tty
.c_cc
[VTIME
] = 0;
1760 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1762 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1763 return qemu_chr_open_fd(master_fd
, master_fd
);
1766 static void tty_serial_init(int fd
, int speed
,
1767 int parity
, int data_bits
, int stop_bits
)
1773 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1774 speed
, parity
, data_bits
, stop_bits
);
1776 tcgetattr (fd
, &tty
);
1818 cfsetispeed(&tty
, spd
);
1819 cfsetospeed(&tty
, spd
);
1821 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1822 |INLCR
|IGNCR
|ICRNL
|IXON
);
1823 tty
.c_oflag
|= OPOST
;
1824 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1825 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1846 tty
.c_cflag
|= PARENB
;
1849 tty
.c_cflag
|= PARENB
| PARODD
;
1853 tty
.c_cflag
|= CSTOPB
;
1855 tcsetattr (fd
, TCSANOW
, &tty
);
1858 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1860 FDCharDriver
*s
= chr
->opaque
;
1863 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1865 QEMUSerialSetParams
*ssp
= arg
;
1866 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1867 ssp
->data_bits
, ssp
->stop_bits
);
1870 case CHR_IOCTL_SERIAL_SET_BREAK
:
1872 int enable
= *(int *)arg
;
1874 tcsendbreak(s
->fd_in
, 1);
1883 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1885 CharDriverState
*chr
;
1888 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1891 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1892 tty_serial_init(fd
, 115200, 'N', 8, 1);
1893 chr
= qemu_chr_open_fd(fd
, fd
);
1896 chr
->chr_ioctl
= tty_serial_ioctl
;
1897 qemu_chr_reset(chr
);
1904 } ParallelCharDriver
;
1906 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
1908 if (s
->mode
!= mode
) {
1910 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
1917 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1919 ParallelCharDriver
*drv
= chr
->opaque
;
1924 case CHR_IOCTL_PP_READ_DATA
:
1925 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1927 *(uint8_t *)arg
= b
;
1929 case CHR_IOCTL_PP_WRITE_DATA
:
1930 b
= *(uint8_t *)arg
;
1931 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1934 case CHR_IOCTL_PP_READ_CONTROL
:
1935 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1937 /* Linux gives only the lowest bits, and no way to know data
1938 direction! For better compatibility set the fixed upper
1940 *(uint8_t *)arg
= b
| 0xc0;
1942 case CHR_IOCTL_PP_WRITE_CONTROL
:
1943 b
= *(uint8_t *)arg
;
1944 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1947 case CHR_IOCTL_PP_READ_STATUS
:
1948 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1950 *(uint8_t *)arg
= b
;
1952 case CHR_IOCTL_PP_EPP_READ_ADDR
:
1953 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1954 struct ParallelIOArg
*parg
= arg
;
1955 int n
= read(fd
, parg
->buffer
, parg
->count
);
1956 if (n
!= parg
->count
) {
1961 case CHR_IOCTL_PP_EPP_READ
:
1962 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1963 struct ParallelIOArg
*parg
= arg
;
1964 int n
= read(fd
, parg
->buffer
, parg
->count
);
1965 if (n
!= parg
->count
) {
1970 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
1971 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
1972 struct ParallelIOArg
*parg
= arg
;
1973 int n
= write(fd
, parg
->buffer
, parg
->count
);
1974 if (n
!= parg
->count
) {
1979 case CHR_IOCTL_PP_EPP_WRITE
:
1980 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
1981 struct ParallelIOArg
*parg
= arg
;
1982 int n
= write(fd
, parg
->buffer
, parg
->count
);
1983 if (n
!= parg
->count
) {
1994 static void pp_close(CharDriverState
*chr
)
1996 ParallelCharDriver
*drv
= chr
->opaque
;
1999 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2000 ioctl(fd
, PPRELEASE
);
2005 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2007 CharDriverState
*chr
;
2008 ParallelCharDriver
*drv
;
2011 fd
= open(filename
, O_RDWR
);
2015 if (ioctl(fd
, PPCLAIM
) < 0) {
2020 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2026 drv
->mode
= IEEE1284_MODE_COMPAT
;
2028 chr
= qemu_mallocz(sizeof(CharDriverState
));
2034 chr
->chr_write
= null_chr_write
;
2035 chr
->chr_ioctl
= pp_ioctl
;
2036 chr
->chr_close
= pp_close
;
2039 qemu_chr_reset(chr
);
2045 static CharDriverState
*qemu_chr_open_pty(void)
2051 #endif /* !defined(_WIN32) */
2056 HANDLE hcom
, hrecv
, hsend
;
2057 OVERLAPPED orecv
, osend
;
2062 #define NSENDBUF 2048
2063 #define NRECVBUF 2048
2064 #define MAXCONNECT 1
2065 #define NTIMEOUT 5000
2067 static int win_chr_poll(void *opaque
);
2068 static int win_chr_pipe_poll(void *opaque
);
2070 static void win_chr_close(CharDriverState
*chr
)
2072 WinCharState
*s
= chr
->opaque
;
2075 CloseHandle(s
->hsend
);
2079 CloseHandle(s
->hrecv
);
2083 CloseHandle(s
->hcom
);
2087 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2089 qemu_del_polling_cb(win_chr_poll
, chr
);
2092 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2094 WinCharState
*s
= chr
->opaque
;
2096 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2101 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2103 fprintf(stderr
, "Failed CreateEvent\n");
2106 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2108 fprintf(stderr
, "Failed CreateEvent\n");
2112 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2113 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2114 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2115 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2120 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2121 fprintf(stderr
, "Failed SetupComm\n");
2125 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2126 size
= sizeof(COMMCONFIG
);
2127 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2128 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2129 CommConfigDialog(filename
, NULL
, &comcfg
);
2131 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2132 fprintf(stderr
, "Failed SetCommState\n");
2136 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2137 fprintf(stderr
, "Failed SetCommMask\n");
2141 cto
.ReadIntervalTimeout
= MAXDWORD
;
2142 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2143 fprintf(stderr
, "Failed SetCommTimeouts\n");
2147 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2148 fprintf(stderr
, "Failed ClearCommError\n");
2151 qemu_add_polling_cb(win_chr_poll
, chr
);
2159 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2161 WinCharState
*s
= chr
->opaque
;
2162 DWORD len
, ret
, size
, err
;
2165 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2166 s
->osend
.hEvent
= s
->hsend
;
2169 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2171 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2173 err
= GetLastError();
2174 if (err
== ERROR_IO_PENDING
) {
2175 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2193 static int win_chr_read_poll(CharDriverState
*chr
)
2195 WinCharState
*s
= chr
->opaque
;
2197 s
->max_size
= qemu_chr_can_read(chr
);
2201 static void win_chr_readfile(CharDriverState
*chr
)
2203 WinCharState
*s
= chr
->opaque
;
2208 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2209 s
->orecv
.hEvent
= s
->hrecv
;
2210 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2212 err
= GetLastError();
2213 if (err
== ERROR_IO_PENDING
) {
2214 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2219 qemu_chr_read(chr
, buf
, size
);
2223 static void win_chr_read(CharDriverState
*chr
)
2225 WinCharState
*s
= chr
->opaque
;
2227 if (s
->len
> s
->max_size
)
2228 s
->len
= s
->max_size
;
2232 win_chr_readfile(chr
);
2235 static int win_chr_poll(void *opaque
)
2237 CharDriverState
*chr
= opaque
;
2238 WinCharState
*s
= chr
->opaque
;
2242 ClearCommError(s
->hcom
, &comerr
, &status
);
2243 if (status
.cbInQue
> 0) {
2244 s
->len
= status
.cbInQue
;
2245 win_chr_read_poll(chr
);
2252 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2254 CharDriverState
*chr
;
2257 chr
= qemu_mallocz(sizeof(CharDriverState
));
2260 s
= qemu_mallocz(sizeof(WinCharState
));
2266 chr
->chr_write
= win_chr_write
;
2267 chr
->chr_close
= win_chr_close
;
2269 if (win_chr_init(chr
, filename
) < 0) {
2274 qemu_chr_reset(chr
);
2278 static int win_chr_pipe_poll(void *opaque
)
2280 CharDriverState
*chr
= opaque
;
2281 WinCharState
*s
= chr
->opaque
;
2284 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2287 win_chr_read_poll(chr
);
2294 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2296 WinCharState
*s
= chr
->opaque
;
2304 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2306 fprintf(stderr
, "Failed CreateEvent\n");
2309 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2311 fprintf(stderr
, "Failed CreateEvent\n");
2315 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2316 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2317 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2319 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2320 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2321 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2326 ZeroMemory(&ov
, sizeof(ov
));
2327 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2328 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2330 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2334 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2336 fprintf(stderr
, "Failed GetOverlappedResult\n");
2338 CloseHandle(ov
.hEvent
);
2345 CloseHandle(ov
.hEvent
);
2348 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2357 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2359 CharDriverState
*chr
;
2362 chr
= qemu_mallocz(sizeof(CharDriverState
));
2365 s
= qemu_mallocz(sizeof(WinCharState
));
2371 chr
->chr_write
= win_chr_write
;
2372 chr
->chr_close
= win_chr_close
;
2374 if (win_chr_pipe_init(chr
, filename
) < 0) {
2379 qemu_chr_reset(chr
);
2383 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2385 CharDriverState
*chr
;
2388 chr
= qemu_mallocz(sizeof(CharDriverState
));
2391 s
= qemu_mallocz(sizeof(WinCharState
));
2398 chr
->chr_write
= win_chr_write
;
2399 qemu_chr_reset(chr
);
2403 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2407 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2408 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2409 if (fd_out
== INVALID_HANDLE_VALUE
)
2412 return qemu_chr_open_win_file(fd_out
);
2416 /***********************************************************/
2417 /* UDP Net console */
2421 struct sockaddr_in daddr
;
2428 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2430 NetCharDriver
*s
= chr
->opaque
;
2432 return sendto(s
->fd
, buf
, len
, 0,
2433 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2436 static int udp_chr_read_poll(void *opaque
)
2438 CharDriverState
*chr
= opaque
;
2439 NetCharDriver
*s
= chr
->opaque
;
2441 s
->max_size
= qemu_chr_can_read(chr
);
2443 /* If there were any stray characters in the queue process them
2446 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2447 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2449 s
->max_size
= qemu_chr_can_read(chr
);
2454 static void udp_chr_read(void *opaque
)
2456 CharDriverState
*chr
= opaque
;
2457 NetCharDriver
*s
= chr
->opaque
;
2459 if (s
->max_size
== 0)
2461 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2462 s
->bufptr
= s
->bufcnt
;
2467 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2468 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2470 s
->max_size
= qemu_chr_can_read(chr
);
2474 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2476 NetCharDriver
*s
= chr
->opaque
;
2479 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2480 udp_chr_read
, NULL
, chr
);
2484 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2486 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2488 int parse_host_src_port(struct sockaddr_in
*haddr
,
2489 struct sockaddr_in
*saddr
,
2492 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2494 CharDriverState
*chr
= NULL
;
2495 NetCharDriver
*s
= NULL
;
2497 struct sockaddr_in saddr
;
2499 chr
= qemu_mallocz(sizeof(CharDriverState
));
2502 s
= qemu_mallocz(sizeof(NetCharDriver
));
2506 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2508 perror("socket(PF_INET, SOCK_DGRAM)");
2512 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2513 printf("Could not parse: %s\n", def
);
2517 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2527 chr
->chr_write
= udp_chr_write
;
2528 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2541 /***********************************************************/
2542 /* TCP Net console */
2553 static void tcp_chr_accept(void *opaque
);
2555 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2557 TCPCharDriver
*s
= chr
->opaque
;
2559 return send_all(s
->fd
, buf
, len
);
2561 /* XXX: indicate an error ? */
2566 static int tcp_chr_read_poll(void *opaque
)
2568 CharDriverState
*chr
= opaque
;
2569 TCPCharDriver
*s
= chr
->opaque
;
2572 s
->max_size
= qemu_chr_can_read(chr
);
2577 #define IAC_BREAK 243
2578 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2580 char *buf
, int *size
)
2582 /* Handle any telnet client's basic IAC options to satisfy char by
2583 * char mode with no echo. All IAC options will be removed from
2584 * the buf and the do_telnetopt variable will be used to track the
2585 * state of the width of the IAC information.
2587 * IAC commands come in sets of 3 bytes with the exception of the
2588 * "IAC BREAK" command and the double IAC.
2594 for (i
= 0; i
< *size
; i
++) {
2595 if (s
->do_telnetopt
> 1) {
2596 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2597 /* Double IAC means send an IAC */
2601 s
->do_telnetopt
= 1;
2603 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2604 /* Handle IAC break commands by sending a serial break */
2605 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2610 if (s
->do_telnetopt
>= 4) {
2611 s
->do_telnetopt
= 1;
2614 if ((unsigned char)buf
[i
] == IAC
) {
2615 s
->do_telnetopt
= 2;
2626 static void tcp_chr_read(void *opaque
)
2628 CharDriverState
*chr
= opaque
;
2629 TCPCharDriver
*s
= chr
->opaque
;
2633 if (!s
->connected
|| s
->max_size
<= 0)
2636 if (len
> s
->max_size
)
2638 size
= recv(s
->fd
, buf
, len
, 0);
2640 /* connection closed */
2642 if (s
->listen_fd
>= 0) {
2643 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2645 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2648 } else if (size
> 0) {
2649 if (s
->do_telnetopt
)
2650 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2652 qemu_chr_read(chr
, buf
, size
);
2656 static void tcp_chr_connect(void *opaque
)
2658 CharDriverState
*chr
= opaque
;
2659 TCPCharDriver
*s
= chr
->opaque
;
2662 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2663 tcp_chr_read
, NULL
, chr
);
2664 qemu_chr_reset(chr
);
2667 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2668 static void tcp_chr_telnet_init(int fd
)
2671 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2672 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2673 send(fd
, (char *)buf
, 3, 0);
2674 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2675 send(fd
, (char *)buf
, 3, 0);
2676 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2677 send(fd
, (char *)buf
, 3, 0);
2678 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2679 send(fd
, (char *)buf
, 3, 0);
2682 static void socket_set_nodelay(int fd
)
2685 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2688 static void tcp_chr_accept(void *opaque
)
2690 CharDriverState
*chr
= opaque
;
2691 TCPCharDriver
*s
= chr
->opaque
;
2692 struct sockaddr_in saddr
;
2694 struct sockaddr_un uaddr
;
2696 struct sockaddr
*addr
;
2703 len
= sizeof(uaddr
);
2704 addr
= (struct sockaddr
*)&uaddr
;
2708 len
= sizeof(saddr
);
2709 addr
= (struct sockaddr
*)&saddr
;
2711 fd
= accept(s
->listen_fd
, addr
, &len
);
2712 if (fd
< 0 && errno
!= EINTR
) {
2714 } else if (fd
>= 0) {
2715 if (s
->do_telnetopt
)
2716 tcp_chr_telnet_init(fd
);
2720 socket_set_nonblock(fd
);
2722 socket_set_nodelay(fd
);
2724 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2725 tcp_chr_connect(chr
);
2728 static void tcp_chr_close(CharDriverState
*chr
)
2730 TCPCharDriver
*s
= chr
->opaque
;
2733 if (s
->listen_fd
>= 0)
2734 closesocket(s
->listen_fd
);
2738 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2742 CharDriverState
*chr
= NULL
;
2743 TCPCharDriver
*s
= NULL
;
2744 int fd
= -1, ret
, err
, val
;
2746 int is_waitconnect
= 1;
2749 struct sockaddr_in saddr
;
2751 struct sockaddr_un uaddr
;
2753 struct sockaddr
*addr
;
2758 addr
= (struct sockaddr
*)&uaddr
;
2759 addrlen
= sizeof(uaddr
);
2760 if (parse_unix_path(&uaddr
, host_str
) < 0)
2765 addr
= (struct sockaddr
*)&saddr
;
2766 addrlen
= sizeof(saddr
);
2767 if (parse_host_port(&saddr
, host_str
) < 0)
2772 while((ptr
= strchr(ptr
,','))) {
2774 if (!strncmp(ptr
,"server",6)) {
2776 } else if (!strncmp(ptr
,"nowait",6)) {
2778 } else if (!strncmp(ptr
,"nodelay",6)) {
2781 printf("Unknown option: %s\n", ptr
);
2788 chr
= qemu_mallocz(sizeof(CharDriverState
));
2791 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2797 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2800 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2805 if (!is_waitconnect
)
2806 socket_set_nonblock(fd
);
2811 s
->is_unix
= is_unix
;
2812 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2815 chr
->chr_write
= tcp_chr_write
;
2816 chr
->chr_close
= tcp_chr_close
;
2819 /* allow fast reuse */
2823 strncpy(path
, uaddr
.sun_path
, 108);
2830 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2833 ret
= bind(fd
, addr
, addrlen
);
2837 ret
= listen(fd
, 0);
2842 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2844 s
->do_telnetopt
= 1;
2847 ret
= connect(fd
, addr
, addrlen
);
2849 err
= socket_error();
2850 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2851 } else if (err
== EINPROGRESS
) {
2862 socket_set_nodelay(fd
);
2864 tcp_chr_connect(chr
);
2866 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2869 if (is_listen
&& is_waitconnect
) {
2870 printf("QEMU waiting for connection on: %s\n", host_str
);
2871 tcp_chr_accept(chr
);
2872 socket_set_nonblock(s
->listen_fd
);
2884 CharDriverState
*qemu_chr_open(const char *filename
)
2888 if (!strcmp(filename
, "vc")) {
2889 return text_console_init(&display_state
);
2890 } else if (!strcmp(filename
, "null")) {
2891 return qemu_chr_open_null();
2893 if (strstart(filename
, "tcp:", &p
)) {
2894 return qemu_chr_open_tcp(p
, 0, 0);
2896 if (strstart(filename
, "telnet:", &p
)) {
2897 return qemu_chr_open_tcp(p
, 1, 0);
2899 if (strstart(filename
, "udp:", &p
)) {
2900 return qemu_chr_open_udp(p
);
2902 if (strstart(filename
, "mon:", &p
)) {
2903 CharDriverState
*drv
= qemu_chr_open(p
);
2905 drv
= qemu_chr_open_mux(drv
);
2906 monitor_init(drv
, !nographic
);
2909 printf("Unable to open driver: %s\n", p
);
2913 if (strstart(filename
, "unix:", &p
)) {
2914 return qemu_chr_open_tcp(p
, 0, 1);
2915 } else if (strstart(filename
, "file:", &p
)) {
2916 return qemu_chr_open_file_out(p
);
2917 } else if (strstart(filename
, "pipe:", &p
)) {
2918 return qemu_chr_open_pipe(p
);
2919 } else if (!strcmp(filename
, "pty")) {
2920 return qemu_chr_open_pty();
2921 } else if (!strcmp(filename
, "stdio")) {
2922 return qemu_chr_open_stdio();
2925 #if defined(__linux__)
2926 if (strstart(filename
, "/dev/parport", NULL
)) {
2927 return qemu_chr_open_pp(filename
);
2929 if (strstart(filename
, "/dev/", NULL
)) {
2930 return qemu_chr_open_tty(filename
);
2934 if (strstart(filename
, "COM", NULL
)) {
2935 return qemu_chr_open_win(filename
);
2937 if (strstart(filename
, "pipe:", &p
)) {
2938 return qemu_chr_open_win_pipe(p
);
2940 if (strstart(filename
, "file:", &p
)) {
2941 return qemu_chr_open_win_file_out(p
);
2949 void qemu_chr_close(CharDriverState
*chr
)
2952 chr
->chr_close(chr
);
2955 /***********************************************************/
2956 /* network device redirectors */
2958 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2962 for(i
=0;i
<size
;i
+=16) {
2966 fprintf(f
, "%08x ", i
);
2969 fprintf(f
, " %02x", buf
[i
+j
]);
2974 for(j
=0;j
<len
;j
++) {
2976 if (c
< ' ' || c
> '~')
2978 fprintf(f
, "%c", c
);
2984 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2987 for(i
= 0; i
< 6; i
++) {
2988 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3001 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3006 p1
= strchr(p
, sep
);
3012 if (len
> buf_size
- 1)
3014 memcpy(buf
, p
, len
);
3021 int parse_host_src_port(struct sockaddr_in
*haddr
,
3022 struct sockaddr_in
*saddr
,
3023 const char *input_str
)
3025 char *str
= strdup(input_str
);
3026 char *host_str
= str
;
3031 * Chop off any extra arguments at the end of the string which
3032 * would start with a comma, then fill in the src port information
3033 * if it was provided else use the "any address" and "any port".
3035 if ((ptr
= strchr(str
,',')))
3038 if ((src_str
= strchr(input_str
,'@'))) {
3043 if (parse_host_port(haddr
, host_str
) < 0)
3046 if (!src_str
|| *src_str
== '\0')
3049 if (parse_host_port(saddr
, src_str
) < 0)
3060 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3068 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3070 saddr
->sin_family
= AF_INET
;
3071 if (buf
[0] == '\0') {
3072 saddr
->sin_addr
.s_addr
= 0;
3074 if (isdigit(buf
[0])) {
3075 if (!inet_aton(buf
, &saddr
->sin_addr
))
3078 if ((he
= gethostbyname(buf
)) == NULL
)
3080 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3083 port
= strtol(p
, (char **)&r
, 0);
3086 saddr
->sin_port
= htons(port
);
3091 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3096 len
= MIN(108, strlen(str
));
3097 p
= strchr(str
, ',');
3099 len
= MIN(len
, p
- str
);
3101 memset(uaddr
, 0, sizeof(*uaddr
));
3103 uaddr
->sun_family
= AF_UNIX
;
3104 memcpy(uaddr
->sun_path
, str
, len
);
3110 /* find or alloc a new VLAN */
3111 VLANState
*qemu_find_vlan(int id
)
3113 VLANState
**pvlan
, *vlan
;
3114 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3118 vlan
= qemu_mallocz(sizeof(VLANState
));
3123 pvlan
= &first_vlan
;
3124 while (*pvlan
!= NULL
)
3125 pvlan
= &(*pvlan
)->next
;
3130 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3131 IOReadHandler
*fd_read
,
3132 IOCanRWHandler
*fd_can_read
,
3135 VLANClientState
*vc
, **pvc
;
3136 vc
= qemu_mallocz(sizeof(VLANClientState
));
3139 vc
->fd_read
= fd_read
;
3140 vc
->fd_can_read
= fd_can_read
;
3141 vc
->opaque
= opaque
;
3145 pvc
= &vlan
->first_client
;
3146 while (*pvc
!= NULL
)
3147 pvc
= &(*pvc
)->next
;
3152 int qemu_can_send_packet(VLANClientState
*vc1
)
3154 VLANState
*vlan
= vc1
->vlan
;
3155 VLANClientState
*vc
;
3157 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3159 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
3166 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3168 VLANState
*vlan
= vc1
->vlan
;
3169 VLANClientState
*vc
;
3172 printf("vlan %d send:\n", vlan
->id
);
3173 hex_dump(stdout
, buf
, size
);
3175 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3177 vc
->fd_read(vc
->opaque
, buf
, size
);
3182 #if defined(CONFIG_SLIRP)
3184 /* slirp network adapter */
3186 static int slirp_inited
;
3187 static VLANClientState
*slirp_vc
;
3189 int slirp_can_output(void)
3191 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3194 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3197 printf("slirp output:\n");
3198 hex_dump(stdout
, pkt
, pkt_len
);
3202 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3205 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3208 printf("slirp input:\n");
3209 hex_dump(stdout
, buf
, size
);
3211 slirp_input(buf
, size
);
3214 static int net_slirp_init(VLANState
*vlan
)
3216 if (!slirp_inited
) {
3220 slirp_vc
= qemu_new_vlan_client(vlan
,
3221 slirp_receive
, NULL
, NULL
);
3222 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3226 static void net_slirp_redir(const char *redir_str
)
3231 struct in_addr guest_addr
;
3232 int host_port
, guest_port
;
3234 if (!slirp_inited
) {
3240 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3242 if (!strcmp(buf
, "tcp")) {
3244 } else if (!strcmp(buf
, "udp")) {
3250 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3252 host_port
= strtol(buf
, &r
, 0);
3256 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3258 if (buf
[0] == '\0') {
3259 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3261 if (!inet_aton(buf
, &guest_addr
))
3264 guest_port
= strtol(p
, &r
, 0);
3268 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3269 fprintf(stderr
, "qemu: could not set up redirection\n");
3274 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3282 static void smb_exit(void)
3286 char filename
[1024];
3288 /* erase all the files in the directory */
3289 d
= opendir(smb_dir
);
3294 if (strcmp(de
->d_name
, ".") != 0 &&
3295 strcmp(de
->d_name
, "..") != 0) {
3296 snprintf(filename
, sizeof(filename
), "%s/%s",
3297 smb_dir
, de
->d_name
);
3305 /* automatic user mode samba server configuration */
3306 void net_slirp_smb(const char *exported_dir
)
3308 char smb_conf
[1024];
3309 char smb_cmdline
[1024];
3312 if (!slirp_inited
) {
3317 /* XXX: better tmp dir construction */
3318 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3319 if (mkdir(smb_dir
, 0700) < 0) {
3320 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3323 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3325 f
= fopen(smb_conf
, "w");
3327 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3334 "socket address=127.0.0.1\n"
3335 "pid directory=%s\n"
3336 "lock directory=%s\n"
3337 "log file=%s/log.smbd\n"
3338 "smb passwd file=%s/smbpasswd\n"
3339 "security = share\n"
3354 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3355 SMBD_COMMAND
, smb_conf
);
3357 slirp_add_exec(0, smb_cmdline
, 4, 139);
3360 #endif /* !defined(_WIN32) */
3362 #endif /* CONFIG_SLIRP */
3364 #if !defined(_WIN32)
3366 typedef struct TAPState
{
3367 VLANClientState
*vc
;
3371 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3373 TAPState
*s
= opaque
;
3376 ret
= write(s
->fd
, buf
, size
);
3377 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3384 static void tap_send(void *opaque
)
3386 TAPState
*s
= opaque
;
3393 sbuf
.maxlen
= sizeof(buf
);
3395 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3397 size
= read(s
->fd
, buf
, sizeof(buf
));
3400 qemu_send_packet(s
->vc
, buf
, size
);
3406 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3410 s
= qemu_mallocz(sizeof(TAPState
));
3414 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3415 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3416 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3421 static int tap_open(char *ifname
, int ifname_size
)
3427 fd
= open("/dev/tap", O_RDWR
);
3429 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3434 dev
= devname(s
.st_rdev
, S_IFCHR
);
3435 pstrcpy(ifname
, ifname_size
, dev
);
3437 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3440 #elif defined(__sun__)
3441 #define TUNNEWPPA (('T'<<16) | 0x0001)
3443 * Allocate TAP device, returns opened fd.
3444 * Stores dev name in the first arg(must be large enough).
3446 int tap_alloc(char *dev
)
3448 int tap_fd
, if_fd
, ppa
= -1;
3449 static int ip_fd
= 0;
3452 static int arp_fd
= 0;
3453 int ip_muxid
, arp_muxid
;
3454 struct strioctl strioc_if
, strioc_ppa
;
3455 int link_type
= I_PLINK
;;
3457 char actual_name
[32] = "";
3459 memset(&ifr
, 0x0, sizeof(ifr
));
3463 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
3467 /* Check if IP device was opened */
3471 if( (ip_fd
= open("/dev/udp", O_RDWR
, 0)) < 0){
3472 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
3476 if( (tap_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3477 syslog(LOG_ERR
, "Can't open /dev/tap");
3481 /* Assign a new PPA and get its unit number. */
3482 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
3483 strioc_ppa
.ic_timout
= 0;
3484 strioc_ppa
.ic_len
= sizeof(ppa
);
3485 strioc_ppa
.ic_dp
= (char *)&ppa
;
3486 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
3487 syslog (LOG_ERR
, "Can't assign new interface");
3489 if( (if_fd
= open("/dev/tap", O_RDWR
, 0)) < 0){
3490 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
3493 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
3494 syslog(LOG_ERR
, "Can't push IP module");
3498 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
3499 syslog(LOG_ERR
, "Can't get flags\n");
3501 snprintf (actual_name
, 32, "tap%d", ppa
);
3502 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3505 /* Assign ppa according to the unit number returned by tun device */
3507 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
3508 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
3509 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
3510 syslog (LOG_ERR
, "Can't get flags\n");
3511 /* Push arp module to if_fd */
3512 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
3513 syslog (LOG_ERR
, "Can't push ARP module (2)");
3515 /* Push arp module to ip_fd */
3516 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
3517 syslog (LOG_ERR
, "I_POP failed\n");
3518 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
3519 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
3521 if ((arp_fd
= open ("/dev/tap", O_RDWR
, 0)) < 0)
3522 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
3524 /* Set ifname to arp */
3525 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
3526 strioc_if
.ic_timout
= 0;
3527 strioc_if
.ic_len
= sizeof(ifr
);
3528 strioc_if
.ic_dp
= (char *)&ifr
;
3529 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
3530 syslog (LOG_ERR
, "Can't set ifname to arp\n");
3533 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
3534 syslog(LOG_ERR
, "Can't link TAP device to IP");
3538 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
3539 syslog (LOG_ERR
, "Can't link TAP device to ARP");
3543 memset(&ifr
, 0x0, sizeof(ifr
));
3544 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
3545 ifr
.lifr_ip_muxid
= ip_muxid
;
3546 ifr
.lifr_arp_muxid
= arp_muxid
;
3548 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
3550 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
3551 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
3552 syslog (LOG_ERR
, "Can't set multiplexor id");
3555 sprintf(dev
, "tap%d", ppa
);
3559 static int tap_open(char *ifname
, int ifname_size
)
3563 if( (fd
= tap_alloc(dev
)) < 0 ){
3564 fprintf(stderr
, "Cannot allocate TAP device\n");
3567 pstrcpy(ifname
, ifname_size
, dev
);
3568 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3572 static int tap_open(char *ifname
, int ifname_size
)
3577 fd
= open("/dev/net/tun", O_RDWR
);
3579 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3582 memset(&ifr
, 0, sizeof(ifr
));
3583 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3584 if (ifname
[0] != '\0')
3585 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3587 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3588 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3590 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3594 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3595 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3600 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3601 const char *setup_script
)
3604 int pid
, status
, fd
;
3609 if (ifname1
!= NULL
)
3610 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3613 fd
= tap_open(ifname
, sizeof(ifname
));
3617 if (!setup_script
|| !strcmp(setup_script
, "no"))
3619 if (setup_script
[0] != '\0') {
3620 /* try to launch network init script */
3624 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
3625 for (i
= 0; i
< open_max
; i
++)
3626 if (i
!= STDIN_FILENO
&&
3627 i
!= STDOUT_FILENO
&&
3628 i
!= STDERR_FILENO
&&
3633 *parg
++ = (char *)setup_script
;
3636 execv(setup_script
, args
);
3639 while (waitpid(pid
, &status
, 0) != pid
);
3640 if (!WIFEXITED(status
) ||
3641 WEXITSTATUS(status
) != 0) {
3642 fprintf(stderr
, "%s: could not launch network script\n",
3648 s
= net_tap_fd_init(vlan
, fd
);
3651 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3652 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3656 #endif /* !_WIN32 */
3658 /* network connection */
3659 typedef struct NetSocketState
{
3660 VLANClientState
*vc
;
3662 int state
; /* 0 = getting length, 1 = getting data */
3666 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3669 typedef struct NetSocketListenState
{
3672 } NetSocketListenState
;
3674 /* XXX: we consider we can send the whole packet without blocking */
3675 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3677 NetSocketState
*s
= opaque
;
3681 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3682 send_all(s
->fd
, buf
, size
);
3685 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3687 NetSocketState
*s
= opaque
;
3688 sendto(s
->fd
, buf
, size
, 0,
3689 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3692 static void net_socket_send(void *opaque
)
3694 NetSocketState
*s
= opaque
;
3699 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3701 err
= socket_error();
3702 if (err
!= EWOULDBLOCK
)
3704 } else if (size
== 0) {
3705 /* end of connection */
3707 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3713 /* reassemble a packet from the network */
3719 memcpy(s
->buf
+ s
->index
, buf
, l
);
3723 if (s
->index
== 4) {
3725 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3731 l
= s
->packet_len
- s
->index
;
3734 memcpy(s
->buf
+ s
->index
, buf
, l
);
3738 if (s
->index
>= s
->packet_len
) {
3739 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3748 static void net_socket_send_dgram(void *opaque
)
3750 NetSocketState
*s
= opaque
;
3753 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3757 /* end of connection */
3758 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3761 qemu_send_packet(s
->vc
, s
->buf
, size
);
3764 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3769 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3770 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3771 inet_ntoa(mcastaddr
->sin_addr
),
3772 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3776 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3778 perror("socket(PF_INET, SOCK_DGRAM)");
3783 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3784 (const char *)&val
, sizeof(val
));
3786 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3790 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3796 /* Add host to multicast group */
3797 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3798 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3800 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3801 (const char *)&imr
, sizeof(struct ip_mreq
));
3803 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3807 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3809 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3810 (const char *)&val
, sizeof(val
));
3812 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3816 socket_set_nonblock(fd
);
3824 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3827 struct sockaddr_in saddr
;
3829 socklen_t saddr_len
;
3832 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3833 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3834 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3838 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3840 if (saddr
.sin_addr
.s_addr
==0) {
3841 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3845 /* clone dgram socket */
3846 newfd
= net_socket_mcast_create(&saddr
);
3848 /* error already reported by net_socket_mcast_create() */
3852 /* clone newfd to fd, close newfd */
3857 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3858 fd
, strerror(errno
));
3863 s
= qemu_mallocz(sizeof(NetSocketState
));
3868 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3869 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3871 /* mcast: save bound address as dst */
3872 if (is_connected
) s
->dgram_dst
=saddr
;
3874 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3875 "socket: fd=%d (%s mcast=%s:%d)",
3876 fd
, is_connected
? "cloned" : "",
3877 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3881 static void net_socket_connect(void *opaque
)
3883 NetSocketState
*s
= opaque
;
3884 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3887 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3891 s
= qemu_mallocz(sizeof(NetSocketState
));
3895 s
->vc
= qemu_new_vlan_client(vlan
,
3896 net_socket_receive
, NULL
, s
);
3897 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3898 "socket: fd=%d", fd
);
3900 net_socket_connect(s
);
3902 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3907 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3910 int so_type
=-1, optlen
=sizeof(so_type
);
3912 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3913 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3918 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3920 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3922 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3923 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3924 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3929 static void net_socket_accept(void *opaque
)
3931 NetSocketListenState
*s
= opaque
;
3933 struct sockaddr_in saddr
;
3938 len
= sizeof(saddr
);
3939 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3940 if (fd
< 0 && errno
!= EINTR
) {
3942 } else if (fd
>= 0) {
3946 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3950 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3951 "socket: connection from %s:%d",
3952 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3956 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3958 NetSocketListenState
*s
;
3960 struct sockaddr_in saddr
;
3962 if (parse_host_port(&saddr
, host_str
) < 0)
3965 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3969 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3974 socket_set_nonblock(fd
);
3976 /* allow fast reuse */
3978 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3980 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3985 ret
= listen(fd
, 0);
3992 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3996 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3999 int fd
, connected
, ret
, err
;
4000 struct sockaddr_in saddr
;
4002 if (parse_host_port(&saddr
, host_str
) < 0)
4005 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4010 socket_set_nonblock(fd
);
4014 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4016 err
= socket_error();
4017 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4018 } else if (err
== EINPROGRESS
) {
4030 s
= net_socket_fd_init(vlan
, fd
, connected
);
4033 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4034 "socket: connect to %s:%d",
4035 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4039 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4043 struct sockaddr_in saddr
;
4045 if (parse_host_port(&saddr
, host_str
) < 0)
4049 fd
= net_socket_mcast_create(&saddr
);
4053 s
= net_socket_fd_init(vlan
, fd
, 0);
4057 s
->dgram_dst
= saddr
;
4059 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4060 "socket: mcast=%s:%d",
4061 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4066 static int get_param_value(char *buf
, int buf_size
,
4067 const char *tag
, const char *str
)
4076 while (*p
!= '\0' && *p
!= '=') {
4077 if ((q
- option
) < sizeof(option
) - 1)
4085 if (!strcmp(tag
, option
)) {
4087 while (*p
!= '\0' && *p
!= ',') {
4088 if ((q
- buf
) < buf_size
- 1)
4095 while (*p
!= '\0' && *p
!= ',') {
4106 static int net_client_init(const char *str
)
4117 while (*p
!= '\0' && *p
!= ',') {
4118 if ((q
- device
) < sizeof(device
) - 1)
4126 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4127 vlan_id
= strtol(buf
, NULL
, 0);
4129 vlan
= qemu_find_vlan(vlan_id
);
4131 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4134 if (!strcmp(device
, "nic")) {
4138 if (nb_nics
>= MAX_NICS
) {
4139 fprintf(stderr
, "Too Many NICs\n");
4142 nd
= &nd_table
[nb_nics
];
4143 macaddr
= nd
->macaddr
;
4149 macaddr
[5] = 0x56 + nb_nics
;
4151 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4152 if (parse_macaddr(macaddr
, buf
) < 0) {
4153 fprintf(stderr
, "invalid syntax for ethernet address\n");
4157 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4158 nd
->model
= strdup(buf
);
4164 if (!strcmp(device
, "none")) {
4165 /* does nothing. It is needed to signal that no network cards
4170 if (!strcmp(device
, "user")) {
4171 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4172 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4174 ret
= net_slirp_init(vlan
);
4178 if (!strcmp(device
, "tap")) {
4180 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4181 fprintf(stderr
, "tap: no interface name\n");
4184 ret
= tap_win32_init(vlan
, ifname
);
4187 if (!strcmp(device
, "tap")) {
4189 char setup_script
[1024];
4191 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4192 fd
= strtol(buf
, NULL
, 0);
4194 if (net_tap_fd_init(vlan
, fd
))
4197 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4200 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4201 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4203 ret
= net_tap_init(vlan
, ifname
, setup_script
);
4207 if (!strcmp(device
, "socket")) {
4208 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4210 fd
= strtol(buf
, NULL
, 0);
4212 if (net_socket_fd_init(vlan
, fd
, 1))
4214 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4215 ret
= net_socket_listen_init(vlan
, buf
);
4216 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4217 ret
= net_socket_connect_init(vlan
, buf
);
4218 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4219 ret
= net_socket_mcast_init(vlan
, buf
);
4221 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4226 fprintf(stderr
, "Unknown network device: %s\n", device
);
4230 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4236 void do_info_network(void)
4239 VLANClientState
*vc
;
4241 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4242 term_printf("VLAN %d devices:\n", vlan
->id
);
4243 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4244 term_printf(" %s\n", vc
->info_str
);
4248 /***********************************************************/
4251 static USBPort
*used_usb_ports
;
4252 static USBPort
*free_usb_ports
;
4254 /* ??? Maybe change this to register a hub to keep track of the topology. */
4255 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
4256 usb_attachfn attach
)
4258 port
->opaque
= opaque
;
4259 port
->index
= index
;
4260 port
->attach
= attach
;
4261 port
->next
= free_usb_ports
;
4262 free_usb_ports
= port
;
4265 static int usb_device_add(const char *devname
)
4271 if (!free_usb_ports
)
4274 if (strstart(devname
, "host:", &p
)) {
4275 dev
= usb_host_device_open(p
);
4276 } else if (!strcmp(devname
, "mouse")) {
4277 dev
= usb_mouse_init();
4278 } else if (!strcmp(devname
, "tablet")) {
4279 dev
= usb_tablet_init();
4280 } else if (strstart(devname
, "disk:", &p
)) {
4281 dev
= usb_msd_init(p
);
4288 /* Find a USB port to add the device to. */
4289 port
= free_usb_ports
;
4293 /* Create a new hub and chain it on. */
4294 free_usb_ports
= NULL
;
4295 port
->next
= used_usb_ports
;
4296 used_usb_ports
= port
;
4298 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
4299 usb_attach(port
, hub
);
4300 port
= free_usb_ports
;
4303 free_usb_ports
= port
->next
;
4304 port
->next
= used_usb_ports
;
4305 used_usb_ports
= port
;
4306 usb_attach(port
, dev
);
4310 static int usb_device_del(const char *devname
)
4318 if (!used_usb_ports
)
4321 p
= strchr(devname
, '.');
4324 bus_num
= strtoul(devname
, NULL
, 0);
4325 addr
= strtoul(p
+ 1, NULL
, 0);
4329 lastp
= &used_usb_ports
;
4330 port
= used_usb_ports
;
4331 while (port
&& port
->dev
->addr
!= addr
) {
4332 lastp
= &port
->next
;
4340 *lastp
= port
->next
;
4341 usb_attach(port
, NULL
);
4342 dev
->handle_destroy(dev
);
4343 port
->next
= free_usb_ports
;
4344 free_usb_ports
= port
;
4348 void do_usb_add(const char *devname
)
4351 ret
= usb_device_add(devname
);
4353 term_printf("Could not add USB device '%s'\n", devname
);
4356 void do_usb_del(const char *devname
)
4359 ret
= usb_device_del(devname
);
4361 term_printf("Could not remove USB device '%s'\n", devname
);
4368 const char *speed_str
;
4371 term_printf("USB support not enabled\n");
4375 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4379 switch(dev
->speed
) {
4383 case USB_SPEED_FULL
:
4386 case USB_SPEED_HIGH
:
4393 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4394 0, dev
->addr
, speed_str
, dev
->devname
);
4398 static int create_pidfile(const char *filename
)
4404 fd
= open(filename
, O_RDWR
| O_CREAT
, 0600);
4408 if (lockf(fd
, F_TLOCK
, 0) == -1)
4411 len
= snprintf(buffer
, sizeof(buffer
), "%ld\n", (long)getpid());
4412 if (write(fd
, buffer
, len
) != len
)
4418 /***********************************************************/
4421 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4425 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4429 static void dumb_refresh(DisplayState
*ds
)
4434 void dumb_display_init(DisplayState
*ds
)
4439 ds
->dpy_update
= dumb_update
;
4440 ds
->dpy_resize
= dumb_resize
;
4441 ds
->dpy_refresh
= dumb_refresh
;
4444 /***********************************************************/
4447 #define MAX_IO_HANDLERS 64
4449 typedef struct IOHandlerRecord
{
4451 IOCanRWHandler
*fd_read_poll
;
4453 IOHandler
*fd_write
;
4456 /* temporary data */
4458 struct IOHandlerRecord
*next
;
4461 static IOHandlerRecord
*first_io_handler
;
4463 /* XXX: fd_read_poll should be suppressed, but an API change is
4464 necessary in the character devices to suppress fd_can_read(). */
4465 int qemu_set_fd_handler2(int fd
,
4466 IOCanRWHandler
*fd_read_poll
,
4468 IOHandler
*fd_write
,
4471 IOHandlerRecord
**pioh
, *ioh
;
4473 if (!fd_read
&& !fd_write
) {
4474 pioh
= &first_io_handler
;
4479 if (ioh
->fd
== fd
) {
4486 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4490 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4493 ioh
->next
= first_io_handler
;
4494 first_io_handler
= ioh
;
4497 ioh
->fd_read_poll
= fd_read_poll
;
4498 ioh
->fd_read
= fd_read
;
4499 ioh
->fd_write
= fd_write
;
4500 ioh
->opaque
= opaque
;
4506 int qemu_set_fd_handler(int fd
,
4508 IOHandler
*fd_write
,
4511 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4514 /***********************************************************/
4515 /* Polling handling */
4517 typedef struct PollingEntry
{
4520 struct PollingEntry
*next
;
4523 static PollingEntry
*first_polling_entry
;
4525 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4527 PollingEntry
**ppe
, *pe
;
4528 pe
= qemu_mallocz(sizeof(PollingEntry
));
4532 pe
->opaque
= opaque
;
4533 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4538 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4540 PollingEntry
**ppe
, *pe
;
4541 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4543 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4552 /***********************************************************/
4553 /* Wait objects support */
4554 typedef struct WaitObjects
{
4556 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4557 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4558 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4561 static WaitObjects wait_objects
= {0};
4563 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4565 WaitObjects
*w
= &wait_objects
;
4567 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4569 w
->events
[w
->num
] = handle
;
4570 w
->func
[w
->num
] = func
;
4571 w
->opaque
[w
->num
] = opaque
;
4576 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4579 WaitObjects
*w
= &wait_objects
;
4582 for (i
= 0; i
< w
->num
; i
++) {
4583 if (w
->events
[i
] == handle
)
4586 w
->events
[i
] = w
->events
[i
+ 1];
4587 w
->func
[i
] = w
->func
[i
+ 1];
4588 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4596 /***********************************************************/
4597 /* savevm/loadvm support */
4599 #define IO_BUF_SIZE 32768
4603 BlockDriverState
*bs
;
4606 int64_t base_offset
;
4607 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4610 int buf_size
; /* 0 when writing */
4611 uint8_t buf
[IO_BUF_SIZE
];
4614 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4618 f
= qemu_mallocz(sizeof(QEMUFile
));
4621 if (!strcmp(mode
, "wb")) {
4623 } else if (!strcmp(mode
, "rb")) {
4628 f
->outfile
= fopen(filename
, mode
);
4640 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4644 f
= qemu_mallocz(sizeof(QEMUFile
));
4649 f
->is_writable
= is_writable
;
4650 f
->base_offset
= offset
;
4654 void qemu_fflush(QEMUFile
*f
)
4656 if (!f
->is_writable
)
4658 if (f
->buf_index
> 0) {
4660 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4661 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4663 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4664 f
->buf
, f
->buf_index
);
4666 f
->buf_offset
+= f
->buf_index
;
4671 static void qemu_fill_buffer(QEMUFile
*f
)
4678 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4679 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4683 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4684 f
->buf
, IO_BUF_SIZE
);
4690 f
->buf_offset
+= len
;
4693 void qemu_fclose(QEMUFile
*f
)
4703 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4707 l
= IO_BUF_SIZE
- f
->buf_index
;
4710 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4714 if (f
->buf_index
>= IO_BUF_SIZE
)
4719 void qemu_put_byte(QEMUFile
*f
, int v
)
4721 f
->buf
[f
->buf_index
++] = v
;
4722 if (f
->buf_index
>= IO_BUF_SIZE
)
4726 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4732 l
= f
->buf_size
- f
->buf_index
;
4734 qemu_fill_buffer(f
);
4735 l
= f
->buf_size
- f
->buf_index
;
4741 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4746 return size1
- size
;
4749 int qemu_get_byte(QEMUFile
*f
)
4751 if (f
->buf_index
>= f
->buf_size
) {
4752 qemu_fill_buffer(f
);
4753 if (f
->buf_index
>= f
->buf_size
)
4756 return f
->buf
[f
->buf_index
++];
4759 int64_t qemu_ftell(QEMUFile
*f
)
4761 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4764 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4766 if (whence
== SEEK_SET
) {
4768 } else if (whence
== SEEK_CUR
) {
4769 pos
+= qemu_ftell(f
);
4771 /* SEEK_END not supported */
4774 if (f
->is_writable
) {
4776 f
->buf_offset
= pos
;
4778 f
->buf_offset
= pos
;
4785 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4787 qemu_put_byte(f
, v
>> 8);
4788 qemu_put_byte(f
, v
);
4791 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4793 qemu_put_byte(f
, v
>> 24);
4794 qemu_put_byte(f
, v
>> 16);
4795 qemu_put_byte(f
, v
>> 8);
4796 qemu_put_byte(f
, v
);
4799 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4801 qemu_put_be32(f
, v
>> 32);
4802 qemu_put_be32(f
, v
);
4805 unsigned int qemu_get_be16(QEMUFile
*f
)
4808 v
= qemu_get_byte(f
) << 8;
4809 v
|= qemu_get_byte(f
);
4813 unsigned int qemu_get_be32(QEMUFile
*f
)
4816 v
= qemu_get_byte(f
) << 24;
4817 v
|= qemu_get_byte(f
) << 16;
4818 v
|= qemu_get_byte(f
) << 8;
4819 v
|= qemu_get_byte(f
);
4823 uint64_t qemu_get_be64(QEMUFile
*f
)
4826 v
= (uint64_t)qemu_get_be32(f
) << 32;
4827 v
|= qemu_get_be32(f
);
4831 typedef struct SaveStateEntry
{
4835 SaveStateHandler
*save_state
;
4836 LoadStateHandler
*load_state
;
4838 struct SaveStateEntry
*next
;
4841 static SaveStateEntry
*first_se
;
4843 int register_savevm(const char *idstr
,
4846 SaveStateHandler
*save_state
,
4847 LoadStateHandler
*load_state
,
4850 SaveStateEntry
*se
, **pse
;
4852 se
= qemu_malloc(sizeof(SaveStateEntry
));
4855 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4856 se
->instance_id
= instance_id
;
4857 se
->version_id
= version_id
;
4858 se
->save_state
= save_state
;
4859 se
->load_state
= load_state
;
4860 se
->opaque
= opaque
;
4863 /* add at the end of list */
4865 while (*pse
!= NULL
)
4866 pse
= &(*pse
)->next
;
4871 #define QEMU_VM_FILE_MAGIC 0x5145564d
4872 #define QEMU_VM_FILE_VERSION 0x00000002
4874 int qemu_savevm_state(QEMUFile
*f
)
4878 int64_t cur_pos
, len_pos
, total_len_pos
;
4880 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4881 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4882 total_len_pos
= qemu_ftell(f
);
4883 qemu_put_be64(f
, 0); /* total size */
4885 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4887 len
= strlen(se
->idstr
);
4888 qemu_put_byte(f
, len
);
4889 qemu_put_buffer(f
, se
->idstr
, len
);
4891 qemu_put_be32(f
, se
->instance_id
);
4892 qemu_put_be32(f
, se
->version_id
);
4894 /* record size: filled later */
4895 len_pos
= qemu_ftell(f
);
4896 qemu_put_be32(f
, 0);
4898 se
->save_state(f
, se
->opaque
);
4900 /* fill record size */
4901 cur_pos
= qemu_ftell(f
);
4902 len
= cur_pos
- len_pos
- 4;
4903 qemu_fseek(f
, len_pos
, SEEK_SET
);
4904 qemu_put_be32(f
, len
);
4905 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4907 cur_pos
= qemu_ftell(f
);
4908 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4909 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4910 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4916 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4920 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4921 if (!strcmp(se
->idstr
, idstr
) &&
4922 instance_id
== se
->instance_id
)
4928 int qemu_loadvm_state(QEMUFile
*f
)
4931 int len
, ret
, instance_id
, record_len
, version_id
;
4932 int64_t total_len
, end_pos
, cur_pos
;
4936 v
= qemu_get_be32(f
);
4937 if (v
!= QEMU_VM_FILE_MAGIC
)
4939 v
= qemu_get_be32(f
);
4940 if (v
!= QEMU_VM_FILE_VERSION
) {
4945 total_len
= qemu_get_be64(f
);
4946 end_pos
= total_len
+ qemu_ftell(f
);
4948 if (qemu_ftell(f
) >= end_pos
)
4950 len
= qemu_get_byte(f
);
4951 qemu_get_buffer(f
, idstr
, len
);
4953 instance_id
= qemu_get_be32(f
);
4954 version_id
= qemu_get_be32(f
);
4955 record_len
= qemu_get_be32(f
);
4957 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4958 idstr
, instance_id
, version_id
, record_len
);
4960 cur_pos
= qemu_ftell(f
);
4961 se
= find_se(idstr
, instance_id
);
4963 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4964 instance_id
, idstr
);
4966 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4968 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4969 instance_id
, idstr
);
4972 /* always seek to exact end of record */
4973 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4980 /* device can contain snapshots */
4981 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4984 !bdrv_is_removable(bs
) &&
4985 !bdrv_is_read_only(bs
));
4988 /* device must be snapshots in order to have a reliable snapshot */
4989 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4992 !bdrv_is_removable(bs
) &&
4993 !bdrv_is_read_only(bs
));
4996 static BlockDriverState
*get_bs_snapshots(void)
4998 BlockDriverState
*bs
;
5002 return bs_snapshots
;
5003 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5005 if (bdrv_can_snapshot(bs
))
5014 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5017 QEMUSnapshotInfo
*sn_tab
, *sn
;
5021 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5024 for(i
= 0; i
< nb_sns
; i
++) {
5026 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5036 void do_savevm(const char *name
)
5038 BlockDriverState
*bs
, *bs1
;
5039 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5040 int must_delete
, ret
, i
;
5041 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5043 int saved_vm_running
;
5050 bs
= get_bs_snapshots();
5052 term_printf("No block device can accept snapshots\n");
5056 /* ??? Should this occur after vm_stop? */
5059 saved_vm_running
= vm_running
;
5064 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5069 memset(sn
, 0, sizeof(*sn
));
5071 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5072 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5075 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5078 /* fill auxiliary fields */
5081 sn
->date_sec
= tb
.time
;
5082 sn
->date_nsec
= tb
.millitm
* 1000000;
5084 gettimeofday(&tv
, NULL
);
5085 sn
->date_sec
= tv
.tv_sec
;
5086 sn
->date_nsec
= tv
.tv_usec
* 1000;
5088 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
5090 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5091 term_printf("Device %s does not support VM state snapshots\n",
5092 bdrv_get_device_name(bs
));
5096 /* save the VM state */
5097 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
5099 term_printf("Could not open VM state file\n");
5102 ret
= qemu_savevm_state(f
);
5103 sn
->vm_state_size
= qemu_ftell(f
);
5106 term_printf("Error %d while writing VM\n", ret
);
5110 /* create the snapshots */
5112 for(i
= 0; i
< MAX_DISKS
; i
++) {
5114 if (bdrv_has_snapshot(bs1
)) {
5116 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5118 term_printf("Error while deleting snapshot on '%s'\n",
5119 bdrv_get_device_name(bs1
));
5122 ret
= bdrv_snapshot_create(bs1
, sn
);
5124 term_printf("Error while creating snapshot on '%s'\n",
5125 bdrv_get_device_name(bs1
));
5131 if (saved_vm_running
)
5135 void do_loadvm(const char *name
)
5137 BlockDriverState
*bs
, *bs1
;
5138 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5141 int saved_vm_running
;
5143 bs
= get_bs_snapshots();
5145 term_printf("No block device supports snapshots\n");
5149 /* Flush all IO requests so they don't interfere with the new state. */
5152 saved_vm_running
= vm_running
;
5155 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5157 if (bdrv_has_snapshot(bs1
)) {
5158 ret
= bdrv_snapshot_goto(bs1
, name
);
5161 term_printf("Warning: ");
5164 term_printf("Snapshots not supported on device '%s'\n",
5165 bdrv_get_device_name(bs1
));
5168 term_printf("Could not find snapshot '%s' on device '%s'\n",
5169 name
, bdrv_get_device_name(bs1
));
5172 term_printf("Error %d while activating snapshot on '%s'\n",
5173 ret
, bdrv_get_device_name(bs1
));
5176 /* fatal on snapshot block device */
5183 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5184 term_printf("Device %s does not support VM state snapshots\n",
5185 bdrv_get_device_name(bs
));
5189 /* restore the VM state */
5190 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5192 term_printf("Could not open VM state file\n");
5195 ret
= qemu_loadvm_state(f
);
5198 term_printf("Error %d while loading VM state\n", ret
);
5201 if (saved_vm_running
)
5205 void do_delvm(const char *name
)
5207 BlockDriverState
*bs
, *bs1
;
5210 bs
= get_bs_snapshots();
5212 term_printf("No block device supports snapshots\n");
5216 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5218 if (bdrv_has_snapshot(bs1
)) {
5219 ret
= bdrv_snapshot_delete(bs1
, name
);
5221 if (ret
== -ENOTSUP
)
5222 term_printf("Snapshots not supported on device '%s'\n",
5223 bdrv_get_device_name(bs1
));
5225 term_printf("Error %d while deleting snapshot on '%s'\n",
5226 ret
, bdrv_get_device_name(bs1
));
5232 void do_info_snapshots(void)
5234 BlockDriverState
*bs
, *bs1
;
5235 QEMUSnapshotInfo
*sn_tab
, *sn
;
5239 bs
= get_bs_snapshots();
5241 term_printf("No available block device supports snapshots\n");
5244 term_printf("Snapshot devices:");
5245 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5247 if (bdrv_has_snapshot(bs1
)) {
5249 term_printf(" %s", bdrv_get_device_name(bs1
));
5254 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5256 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5259 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5260 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5261 for(i
= 0; i
< nb_sns
; i
++) {
5263 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5268 /***********************************************************/
5269 /* cpu save/restore */
5271 #if defined(TARGET_I386)
5273 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5275 qemu_put_be32(f
, dt
->selector
);
5276 qemu_put_betl(f
, dt
->base
);
5277 qemu_put_be32(f
, dt
->limit
);
5278 qemu_put_be32(f
, dt
->flags
);
5281 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5283 dt
->selector
= qemu_get_be32(f
);
5284 dt
->base
= qemu_get_betl(f
);
5285 dt
->limit
= qemu_get_be32(f
);
5286 dt
->flags
= qemu_get_be32(f
);
5289 void cpu_save(QEMUFile
*f
, void *opaque
)
5291 CPUState
*env
= opaque
;
5292 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5296 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5297 qemu_put_betls(f
, &env
->regs
[i
]);
5298 qemu_put_betls(f
, &env
->eip
);
5299 qemu_put_betls(f
, &env
->eflags
);
5300 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5301 qemu_put_be32s(f
, &hflags
);
5305 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5307 for(i
= 0; i
< 8; i
++) {
5308 fptag
|= ((!env
->fptags
[i
]) << i
);
5311 qemu_put_be16s(f
, &fpuc
);
5312 qemu_put_be16s(f
, &fpus
);
5313 qemu_put_be16s(f
, &fptag
);
5315 #ifdef USE_X86LDOUBLE
5320 qemu_put_be16s(f
, &fpregs_format
);
5322 for(i
= 0; i
< 8; i
++) {
5323 #ifdef USE_X86LDOUBLE
5327 /* we save the real CPU data (in case of MMX usage only 'mant'
5328 contains the MMX register */
5329 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5330 qemu_put_be64(f
, mant
);
5331 qemu_put_be16(f
, exp
);
5334 /* if we use doubles for float emulation, we save the doubles to
5335 avoid losing information in case of MMX usage. It can give
5336 problems if the image is restored on a CPU where long
5337 doubles are used instead. */
5338 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5342 for(i
= 0; i
< 6; i
++)
5343 cpu_put_seg(f
, &env
->segs
[i
]);
5344 cpu_put_seg(f
, &env
->ldt
);
5345 cpu_put_seg(f
, &env
->tr
);
5346 cpu_put_seg(f
, &env
->gdt
);
5347 cpu_put_seg(f
, &env
->idt
);
5349 qemu_put_be32s(f
, &env
->sysenter_cs
);
5350 qemu_put_be32s(f
, &env
->sysenter_esp
);
5351 qemu_put_be32s(f
, &env
->sysenter_eip
);
5353 qemu_put_betls(f
, &env
->cr
[0]);
5354 qemu_put_betls(f
, &env
->cr
[2]);
5355 qemu_put_betls(f
, &env
->cr
[3]);
5356 qemu_put_betls(f
, &env
->cr
[4]);
5358 for(i
= 0; i
< 8; i
++)
5359 qemu_put_betls(f
, &env
->dr
[i
]);
5362 qemu_put_be32s(f
, &env
->a20_mask
);
5365 qemu_put_be32s(f
, &env
->mxcsr
);
5366 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5367 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5368 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5371 #ifdef TARGET_X86_64
5372 qemu_put_be64s(f
, &env
->efer
);
5373 qemu_put_be64s(f
, &env
->star
);
5374 qemu_put_be64s(f
, &env
->lstar
);
5375 qemu_put_be64s(f
, &env
->cstar
);
5376 qemu_put_be64s(f
, &env
->fmask
);
5377 qemu_put_be64s(f
, &env
->kernelgsbase
);
5379 qemu_put_be32s(f
, &env
->smbase
);
5382 #ifdef USE_X86LDOUBLE
5383 /* XXX: add that in a FPU generic layer */
5384 union x86_longdouble
{
5389 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5390 #define EXPBIAS1 1023
5391 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5392 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5394 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5398 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5399 /* exponent + sign */
5400 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5401 e
|= SIGND1(temp
) >> 16;
5406 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5408 CPUState
*env
= opaque
;
5411 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5413 if (version_id
!= 3 && version_id
!= 4)
5415 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5416 qemu_get_betls(f
, &env
->regs
[i
]);
5417 qemu_get_betls(f
, &env
->eip
);
5418 qemu_get_betls(f
, &env
->eflags
);
5419 qemu_get_be32s(f
, &hflags
);
5421 qemu_get_be16s(f
, &fpuc
);
5422 qemu_get_be16s(f
, &fpus
);
5423 qemu_get_be16s(f
, &fptag
);
5424 qemu_get_be16s(f
, &fpregs_format
);
5426 /* NOTE: we cannot always restore the FPU state if the image come
5427 from a host with a different 'USE_X86LDOUBLE' define. We guess
5428 if we are in an MMX state to restore correctly in that case. */
5429 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5430 for(i
= 0; i
< 8; i
++) {
5434 switch(fpregs_format
) {
5436 mant
= qemu_get_be64(f
);
5437 exp
= qemu_get_be16(f
);
5438 #ifdef USE_X86LDOUBLE
5439 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5441 /* difficult case */
5443 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5445 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5449 mant
= qemu_get_be64(f
);
5450 #ifdef USE_X86LDOUBLE
5452 union x86_longdouble
*p
;
5453 /* difficult case */
5454 p
= (void *)&env
->fpregs
[i
];
5459 fp64_to_fp80(p
, mant
);
5463 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5472 /* XXX: restore FPU round state */
5473 env
->fpstt
= (fpus
>> 11) & 7;
5474 env
->fpus
= fpus
& ~0x3800;
5476 for(i
= 0; i
< 8; i
++) {
5477 env
->fptags
[i
] = (fptag
>> i
) & 1;
5480 for(i
= 0; i
< 6; i
++)
5481 cpu_get_seg(f
, &env
->segs
[i
]);
5482 cpu_get_seg(f
, &env
->ldt
);
5483 cpu_get_seg(f
, &env
->tr
);
5484 cpu_get_seg(f
, &env
->gdt
);
5485 cpu_get_seg(f
, &env
->idt
);
5487 qemu_get_be32s(f
, &env
->sysenter_cs
);
5488 qemu_get_be32s(f
, &env
->sysenter_esp
);
5489 qemu_get_be32s(f
, &env
->sysenter_eip
);
5491 qemu_get_betls(f
, &env
->cr
[0]);
5492 qemu_get_betls(f
, &env
->cr
[2]);
5493 qemu_get_betls(f
, &env
->cr
[3]);
5494 qemu_get_betls(f
, &env
->cr
[4]);
5496 for(i
= 0; i
< 8; i
++)
5497 qemu_get_betls(f
, &env
->dr
[i
]);
5500 qemu_get_be32s(f
, &env
->a20_mask
);
5502 qemu_get_be32s(f
, &env
->mxcsr
);
5503 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5504 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5505 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5508 #ifdef TARGET_X86_64
5509 qemu_get_be64s(f
, &env
->efer
);
5510 qemu_get_be64s(f
, &env
->star
);
5511 qemu_get_be64s(f
, &env
->lstar
);
5512 qemu_get_be64s(f
, &env
->cstar
);
5513 qemu_get_be64s(f
, &env
->fmask
);
5514 qemu_get_be64s(f
, &env
->kernelgsbase
);
5516 if (version_id
>= 4)
5517 qemu_get_be32s(f
, &env
->smbase
);
5519 /* XXX: compute hflags from scratch, except for CPL and IIF */
5520 env
->hflags
= hflags
;
5525 #elif defined(TARGET_PPC)
5526 void cpu_save(QEMUFile
*f
, void *opaque
)
5530 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5535 #elif defined(TARGET_MIPS)
5536 void cpu_save(QEMUFile
*f
, void *opaque
)
5540 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5545 #elif defined(TARGET_SPARC)
5546 void cpu_save(QEMUFile
*f
, void *opaque
)
5548 CPUState
*env
= opaque
;
5552 for(i
= 0; i
< 8; i
++)
5553 qemu_put_betls(f
, &env
->gregs
[i
]);
5554 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5555 qemu_put_betls(f
, &env
->regbase
[i
]);
5558 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5564 qemu_put_be32(f
, u
.i
);
5567 qemu_put_betls(f
, &env
->pc
);
5568 qemu_put_betls(f
, &env
->npc
);
5569 qemu_put_betls(f
, &env
->y
);
5571 qemu_put_be32(f
, tmp
);
5572 qemu_put_betls(f
, &env
->fsr
);
5573 qemu_put_betls(f
, &env
->tbr
);
5574 #ifndef TARGET_SPARC64
5575 qemu_put_be32s(f
, &env
->wim
);
5577 for(i
= 0; i
< 16; i
++)
5578 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5582 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5584 CPUState
*env
= opaque
;
5588 for(i
= 0; i
< 8; i
++)
5589 qemu_get_betls(f
, &env
->gregs
[i
]);
5590 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5591 qemu_get_betls(f
, &env
->regbase
[i
]);
5594 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5599 u
.i
= qemu_get_be32(f
);
5603 qemu_get_betls(f
, &env
->pc
);
5604 qemu_get_betls(f
, &env
->npc
);
5605 qemu_get_betls(f
, &env
->y
);
5606 tmp
= qemu_get_be32(f
);
5607 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5608 correctly updated */
5610 qemu_get_betls(f
, &env
->fsr
);
5611 qemu_get_betls(f
, &env
->tbr
);
5612 #ifndef TARGET_SPARC64
5613 qemu_get_be32s(f
, &env
->wim
);
5615 for(i
= 0; i
< 16; i
++)
5616 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5622 #elif defined(TARGET_ARM)
5624 /* ??? Need to implement these. */
5625 void cpu_save(QEMUFile
*f
, void *opaque
)
5629 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5636 #warning No CPU save/restore functions
5640 /***********************************************************/
5641 /* ram save/restore */
5643 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5647 v
= qemu_get_byte(f
);
5650 if (qemu_get_buffer(f
, buf
, len
) != len
)
5654 v
= qemu_get_byte(f
);
5655 memset(buf
, v
, len
);
5663 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5667 if (qemu_get_be32(f
) != phys_ram_size
)
5669 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5670 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5677 #define BDRV_HASH_BLOCK_SIZE 1024
5678 #define IOBUF_SIZE 4096
5679 #define RAM_CBLOCK_MAGIC 0xfabe
5681 typedef struct RamCompressState
{
5684 uint8_t buf
[IOBUF_SIZE
];
5687 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5690 memset(s
, 0, sizeof(*s
));
5692 ret
= deflateInit2(&s
->zstream
, 1,
5694 9, Z_DEFAULT_STRATEGY
);
5697 s
->zstream
.avail_out
= IOBUF_SIZE
;
5698 s
->zstream
.next_out
= s
->buf
;
5702 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5704 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5705 qemu_put_be16(s
->f
, len
);
5706 qemu_put_buffer(s
->f
, buf
, len
);
5709 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5713 s
->zstream
.avail_in
= len
;
5714 s
->zstream
.next_in
= (uint8_t *)buf
;
5715 while (s
->zstream
.avail_in
> 0) {
5716 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5719 if (s
->zstream
.avail_out
== 0) {
5720 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5721 s
->zstream
.avail_out
= IOBUF_SIZE
;
5722 s
->zstream
.next_out
= s
->buf
;
5728 static void ram_compress_close(RamCompressState
*s
)
5732 /* compress last bytes */
5734 ret
= deflate(&s
->zstream
, Z_FINISH
);
5735 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5736 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5738 ram_put_cblock(s
, s
->buf
, len
);
5740 s
->zstream
.avail_out
= IOBUF_SIZE
;
5741 s
->zstream
.next_out
= s
->buf
;
5742 if (ret
== Z_STREAM_END
)
5749 deflateEnd(&s
->zstream
);
5752 typedef struct RamDecompressState
{
5755 uint8_t buf
[IOBUF_SIZE
];
5756 } RamDecompressState
;
5758 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5761 memset(s
, 0, sizeof(*s
));
5763 ret
= inflateInit(&s
->zstream
);
5769 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5773 s
->zstream
.avail_out
= len
;
5774 s
->zstream
.next_out
= buf
;
5775 while (s
->zstream
.avail_out
> 0) {
5776 if (s
->zstream
.avail_in
== 0) {
5777 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5779 clen
= qemu_get_be16(s
->f
);
5780 if (clen
> IOBUF_SIZE
)
5782 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5783 s
->zstream
.avail_in
= clen
;
5784 s
->zstream
.next_in
= s
->buf
;
5786 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5787 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5794 static void ram_decompress_close(RamDecompressState
*s
)
5796 inflateEnd(&s
->zstream
);
5799 static void ram_save(QEMUFile
*f
, void *opaque
)
5802 RamCompressState s1
, *s
= &s1
;
5805 qemu_put_be32(f
, phys_ram_size
);
5806 if (ram_compress_open(s
, f
) < 0)
5808 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5810 if (tight_savevm_enabled
) {
5814 /* find if the memory block is available on a virtual
5817 for(j
= 0; j
< MAX_DISKS
; j
++) {
5819 sector_num
= bdrv_hash_find(bs_table
[j
],
5820 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5821 if (sector_num
>= 0)
5826 goto normal_compress
;
5829 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5830 ram_compress_buf(s
, buf
, 10);
5836 ram_compress_buf(s
, buf
, 1);
5837 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5840 ram_compress_close(s
);
5843 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5845 RamDecompressState s1
, *s
= &s1
;
5849 if (version_id
== 1)
5850 return ram_load_v1(f
, opaque
);
5851 if (version_id
!= 2)
5853 if (qemu_get_be32(f
) != phys_ram_size
)
5855 if (ram_decompress_open(s
, f
) < 0)
5857 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5858 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5859 fprintf(stderr
, "Error while reading ram block header\n");
5863 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5864 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5873 ram_decompress_buf(s
, buf
+ 1, 9);
5875 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5876 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5877 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5880 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5881 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5882 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5883 bs_index
, sector_num
);
5890 printf("Error block header\n");
5894 ram_decompress_close(s
);
5898 /***********************************************************/
5899 /* bottom halves (can be seen as timers which expire ASAP) */
5908 static QEMUBH
*first_bh
= NULL
;
5910 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5913 bh
= qemu_mallocz(sizeof(QEMUBH
));
5917 bh
->opaque
= opaque
;
5921 int qemu_bh_poll(void)
5940 void qemu_bh_schedule(QEMUBH
*bh
)
5942 CPUState
*env
= cpu_single_env
;
5946 bh
->next
= first_bh
;
5949 /* stop the currently executing CPU to execute the BH ASAP */
5951 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5955 void qemu_bh_cancel(QEMUBH
*bh
)
5958 if (bh
->scheduled
) {
5961 pbh
= &(*pbh
)->next
;
5967 void qemu_bh_delete(QEMUBH
*bh
)
5973 /***********************************************************/
5974 /* machine registration */
5976 QEMUMachine
*first_machine
= NULL
;
5978 int qemu_register_machine(QEMUMachine
*m
)
5981 pm
= &first_machine
;
5989 QEMUMachine
*find_machine(const char *name
)
5993 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5994 if (!strcmp(m
->name
, name
))
6000 /***********************************************************/
6001 /* main execution loop */
6003 void gui_update(void *opaque
)
6005 display_state
.dpy_refresh(&display_state
);
6006 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6009 struct vm_change_state_entry
{
6010 VMChangeStateHandler
*cb
;
6012 LIST_ENTRY (vm_change_state_entry
) entries
;
6015 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6017 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6020 VMChangeStateEntry
*e
;
6022 e
= qemu_mallocz(sizeof (*e
));
6028 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6032 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6034 LIST_REMOVE (e
, entries
);
6038 static void vm_state_notify(int running
)
6040 VMChangeStateEntry
*e
;
6042 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6043 e
->cb(e
->opaque
, running
);
6047 /* XXX: support several handlers */
6048 static VMStopHandler
*vm_stop_cb
;
6049 static void *vm_stop_opaque
;
6051 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6054 vm_stop_opaque
= opaque
;
6058 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6072 void vm_stop(int reason
)
6075 cpu_disable_ticks();
6079 vm_stop_cb(vm_stop_opaque
, reason
);
6086 /* reset/shutdown handler */
6088 typedef struct QEMUResetEntry
{
6089 QEMUResetHandler
*func
;
6091 struct QEMUResetEntry
*next
;
6094 static QEMUResetEntry
*first_reset_entry
;
6095 static int reset_requested
;
6096 static int shutdown_requested
;
6097 static int powerdown_requested
;
6099 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6101 QEMUResetEntry
**pre
, *re
;
6103 pre
= &first_reset_entry
;
6104 while (*pre
!= NULL
)
6105 pre
= &(*pre
)->next
;
6106 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6108 re
->opaque
= opaque
;
6113 static void qemu_system_reset(void)
6117 /* reset all devices */
6118 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6119 re
->func(re
->opaque
);
6123 void qemu_system_reset_request(void)
6126 shutdown_requested
= 1;
6128 reset_requested
= 1;
6131 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6134 void qemu_system_shutdown_request(void)
6136 shutdown_requested
= 1;
6138 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6141 void qemu_system_powerdown_request(void)
6143 powerdown_requested
= 1;
6145 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6148 void main_loop_wait(int timeout
)
6150 IOHandlerRecord
*ioh
;
6151 fd_set rfds
, wfds
, xfds
;
6157 /* XXX: need to suppress polling by better using win32 events */
6159 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6160 ret
|= pe
->func(pe
->opaque
);
6163 if (ret
== 0 && timeout
> 0) {
6165 WaitObjects
*w
= &wait_objects
;
6167 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6168 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6169 if (w
->func
[ret
- WAIT_OBJECT_0
])
6170 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6171 } else if (ret
== WAIT_TIMEOUT
) {
6173 err
= GetLastError();
6174 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6178 /* poll any events */
6179 /* XXX: separate device handlers from system ones */
6184 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6188 (!ioh
->fd_read_poll
||
6189 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6190 FD_SET(ioh
->fd
, &rfds
);
6194 if (ioh
->fd_write
) {
6195 FD_SET(ioh
->fd
, &wfds
);
6205 tv
.tv_usec
= timeout
* 1000;
6207 #if defined(CONFIG_SLIRP)
6209 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6212 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6214 IOHandlerRecord
**pioh
;
6216 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6219 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6220 ioh
->fd_read(ioh
->opaque
);
6222 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6223 ioh
->fd_write(ioh
->opaque
);
6227 /* remove deleted IO handlers */
6228 pioh
= &first_io_handler
;
6238 #if defined(CONFIG_SLIRP)
6245 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6252 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6253 qemu_get_clock(vm_clock
));
6254 /* run dma transfers, if any */
6258 /* real time timers */
6259 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6260 qemu_get_clock(rt_clock
));
6263 static CPUState
*cur_cpu
;
6268 #ifdef CONFIG_PROFILER
6273 cur_cpu
= first_cpu
;
6280 env
= env
->next_cpu
;
6283 #ifdef CONFIG_PROFILER
6284 ti
= profile_getclock();
6286 ret
= cpu_exec(env
);
6287 #ifdef CONFIG_PROFILER
6288 qemu_time
+= profile_getclock() - ti
;
6290 if (ret
== EXCP_HLT
) {
6291 /* Give the next CPU a chance to run. */
6295 if (ret
!= EXCP_HALTED
)
6297 /* all CPUs are halted ? */
6303 if (shutdown_requested
) {
6304 ret
= EXCP_INTERRUPT
;
6307 if (reset_requested
) {
6308 reset_requested
= 0;
6309 qemu_system_reset();
6310 ret
= EXCP_INTERRUPT
;
6312 if (powerdown_requested
) {
6313 powerdown_requested
= 0;
6314 qemu_system_powerdown();
6315 ret
= EXCP_INTERRUPT
;
6317 if (ret
== EXCP_DEBUG
) {
6318 vm_stop(EXCP_DEBUG
);
6320 /* If all cpus are halted then wait until the next IRQ */
6321 /* XXX: use timeout computed from timers */
6322 if (ret
== EXCP_HALTED
)
6329 #ifdef CONFIG_PROFILER
6330 ti
= profile_getclock();
6332 main_loop_wait(timeout
);
6333 #ifdef CONFIG_PROFILER
6334 dev_time
+= profile_getclock() - ti
;
6337 cpu_disable_ticks();
6343 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6344 "usage: %s [options] [disk_image]\n"
6346 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6348 "Standard options:\n"
6349 "-M machine select emulated machine (-M ? for list)\n"
6350 "-cpu cpu select CPU (-cpu ? for list)\n"
6351 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6352 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6353 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6354 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6355 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6356 "-snapshot write to temporary files instead of disk image files\n"
6358 "-no-frame open SDL window without a frame and window decorations\n"
6359 "-no-quit disable SDL window close capability\n"
6362 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6364 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6365 "-smp n set the number of CPUs to 'n' [default=1]\n"
6366 "-nographic disable graphical output and redirect serial I/Os to console\n"
6368 "-k language use keyboard layout (for example \"fr\" for French)\n"
6371 "-audio-help print list of audio drivers and their options\n"
6372 "-soundhw c1,... enable audio support\n"
6373 " and only specified sound cards (comma separated list)\n"
6374 " use -soundhw ? to get the list of supported cards\n"
6375 " use -soundhw all to enable all of them\n"
6377 "-localtime set the real time clock to local time [default=utc]\n"
6378 "-full-screen start in full screen\n"
6380 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6382 "-usb enable the USB driver (will be the default soon)\n"
6383 "-usbdevice name add the host or guest USB device 'name'\n"
6384 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6385 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6387 "-name string set the name of the guest\n"
6389 "Network options:\n"
6390 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6391 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6393 "-net user[,vlan=n][,hostname=host]\n"
6394 " connect the user mode network stack to VLAN 'n' and send\n"
6395 " hostname 'host' to DHCP clients\n"
6398 "-net tap[,vlan=n],ifname=name\n"
6399 " connect the host TAP network interface to VLAN 'n'\n"
6401 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6402 " connect the host TAP network interface to VLAN 'n' and use\n"
6403 " the network script 'file' (default=%s);\n"
6404 " use 'script=no' to disable script execution;\n"
6405 " use 'fd=h' to connect to an already opened TAP interface\n"
6407 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6408 " connect the vlan 'n' to another VLAN using a socket connection\n"
6409 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6410 " connect the vlan 'n' to multicast maddr and port\n"
6411 "-net none use it alone to have zero network devices; if no -net option\n"
6412 " is provided, the default is '-net nic -net user'\n"
6415 "-tftp dir allow tftp access to files in dir [-net user]\n"
6416 "-bootp file advertise file in BOOTP replies\n"
6418 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6420 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6421 " redirect TCP or UDP connections from host to guest [-net user]\n"
6424 "Linux boot specific:\n"
6425 "-kernel bzImage use 'bzImage' as kernel image\n"
6426 "-append cmdline use 'cmdline' as kernel command line\n"
6427 "-initrd file use 'file' as initial ram disk\n"
6429 "Debug/Expert options:\n"
6430 "-monitor dev redirect the monitor to char device 'dev'\n"
6431 "-serial dev redirect the serial port to char device 'dev'\n"
6432 "-parallel dev redirect the parallel port to char device 'dev'\n"
6433 "-pidfile file Write PID to 'file'\n"
6434 "-S freeze CPU at startup (use 'c' to start execution)\n"
6435 "-s wait gdb connection to port\n"
6436 "-p port set gdb connection port [default=%s]\n"
6437 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6438 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6439 " translation (t=none or lba) (usually qemu can guess them)\n"
6440 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6442 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6443 "-no-kqemu disable KQEMU kernel module usage\n"
6445 #ifdef USE_CODE_COPY
6446 "-no-code-copy disable code copy acceleration\n"
6449 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6450 " (default is CL-GD5446 PCI VGA)\n"
6451 "-no-acpi disable ACPI\n"
6453 "-no-reboot exit instead of rebooting\n"
6454 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6455 "-vnc display start a VNC server on display\n"
6457 "-daemonize daemonize QEMU after initializing\n"
6459 "-option-rom rom load a file, rom, into the option ROM space\n"
6461 "During emulation, the following keys are useful:\n"
6462 "ctrl-alt-f toggle full screen\n"
6463 "ctrl-alt-n switch to virtual console 'n'\n"
6464 "ctrl-alt toggle mouse and keyboard grab\n"
6466 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6471 DEFAULT_NETWORK_SCRIPT
,
6473 DEFAULT_GDBSTUB_PORT
,
6478 #define HAS_ARG 0x0001
6493 QEMU_OPTION_snapshot
,
6495 QEMU_OPTION_no_fd_bootchk
,
6498 QEMU_OPTION_nographic
,
6500 QEMU_OPTION_audio_help
,
6501 QEMU_OPTION_soundhw
,
6520 QEMU_OPTION_no_code_copy
,
6522 QEMU_OPTION_localtime
,
6523 QEMU_OPTION_cirrusvga
,
6525 QEMU_OPTION_std_vga
,
6527 QEMU_OPTION_monitor
,
6529 QEMU_OPTION_parallel
,
6531 QEMU_OPTION_full_screen
,
6532 QEMU_OPTION_no_frame
,
6533 QEMU_OPTION_no_quit
,
6534 QEMU_OPTION_pidfile
,
6535 QEMU_OPTION_no_kqemu
,
6536 QEMU_OPTION_kernel_kqemu
,
6537 QEMU_OPTION_win2k_hack
,
6539 QEMU_OPTION_usbdevice
,
6542 QEMU_OPTION_no_acpi
,
6543 QEMU_OPTION_no_reboot
,
6544 QEMU_OPTION_daemonize
,
6545 QEMU_OPTION_option_rom
,
6546 QEMU_OPTION_semihosting
,
6550 typedef struct QEMUOption
{
6556 const QEMUOption qemu_options
[] = {
6557 { "h", 0, QEMU_OPTION_h
},
6558 { "help", 0, QEMU_OPTION_h
},
6560 { "M", HAS_ARG
, QEMU_OPTION_M
},
6561 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
6562 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6563 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6564 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6565 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6566 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6567 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6568 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6569 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6570 { "snapshot", 0, QEMU_OPTION_snapshot
},
6572 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6574 { "m", HAS_ARG
, QEMU_OPTION_m
},
6575 { "nographic", 0, QEMU_OPTION_nographic
},
6576 { "k", HAS_ARG
, QEMU_OPTION_k
},
6578 { "audio-help", 0, QEMU_OPTION_audio_help
},
6579 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6582 { "net", HAS_ARG
, QEMU_OPTION_net
},
6584 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6585 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
6587 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6589 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6592 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6593 { "append", HAS_ARG
, QEMU_OPTION_append
},
6594 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6596 { "S", 0, QEMU_OPTION_S
},
6597 { "s", 0, QEMU_OPTION_s
},
6598 { "p", HAS_ARG
, QEMU_OPTION_p
},
6599 { "d", HAS_ARG
, QEMU_OPTION_d
},
6600 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6601 { "L", HAS_ARG
, QEMU_OPTION_L
},
6602 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6604 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6605 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6607 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6608 { "g", 1, QEMU_OPTION_g
},
6610 { "localtime", 0, QEMU_OPTION_localtime
},
6611 { "std-vga", 0, QEMU_OPTION_std_vga
},
6612 { "echr", 1, QEMU_OPTION_echr
},
6613 { "monitor", 1, QEMU_OPTION_monitor
},
6614 { "serial", 1, QEMU_OPTION_serial
},
6615 { "parallel", 1, QEMU_OPTION_parallel
},
6616 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6617 { "full-screen", 0, QEMU_OPTION_full_screen
},
6619 { "no-frame", 0, QEMU_OPTION_no_frame
},
6620 { "no-quit", 0, QEMU_OPTION_no_quit
},
6622 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6623 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6624 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6625 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6626 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6628 /* temporary options */
6629 { "usb", 0, QEMU_OPTION_usb
},
6630 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6631 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6632 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6633 { "daemonize", 0, QEMU_OPTION_daemonize
},
6634 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6635 #if defined(TARGET_ARM)
6636 { "semihosting", 0, QEMU_OPTION_semihosting
},
6638 { "name", HAS_ARG
, QEMU_OPTION_name
},
6642 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6644 /* this stack is only used during signal handling */
6645 #define SIGNAL_STACK_SIZE 32768
6647 static uint8_t *signal_stack
;
6651 /* password input */
6653 static BlockDriverState
*get_bdrv(int index
)
6655 BlockDriverState
*bs
;
6658 bs
= bs_table
[index
];
6659 } else if (index
< 6) {
6660 bs
= fd_table
[index
- 4];
6667 static void read_passwords(void)
6669 BlockDriverState
*bs
;
6673 for(i
= 0; i
< 6; i
++) {
6675 if (bs
&& bdrv_is_encrypted(bs
)) {
6676 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6677 for(j
= 0; j
< 3; j
++) {
6678 monitor_readline("Password: ",
6679 1, password
, sizeof(password
));
6680 if (bdrv_set_key(bs
, password
) == 0)
6682 term_printf("invalid password\n");
6688 /* XXX: currently we cannot use simultaneously different CPUs */
6689 void register_machines(void)
6691 #if defined(TARGET_I386)
6692 qemu_register_machine(&pc_machine
);
6693 qemu_register_machine(&isapc_machine
);
6694 #elif defined(TARGET_PPC)
6695 qemu_register_machine(&heathrow_machine
);
6696 qemu_register_machine(&core99_machine
);
6697 qemu_register_machine(&prep_machine
);
6698 #elif defined(TARGET_MIPS)
6699 qemu_register_machine(&mips_machine
);
6700 qemu_register_machine(&mips_malta_machine
);
6701 #elif defined(TARGET_SPARC)
6702 #ifdef TARGET_SPARC64
6703 qemu_register_machine(&sun4u_machine
);
6705 qemu_register_machine(&sun4m_machine
);
6707 #elif defined(TARGET_ARM)
6708 qemu_register_machine(&integratorcp_machine
);
6709 qemu_register_machine(&versatilepb_machine
);
6710 qemu_register_machine(&versatileab_machine
);
6711 qemu_register_machine(&realview_machine
);
6712 #elif defined(TARGET_SH4)
6713 qemu_register_machine(&shix_machine
);
6715 #error unsupported CPU
6720 struct soundhw soundhw
[] = {
6727 { .init_isa
= pcspk_audio_init
}
6732 "Creative Sound Blaster 16",
6735 { .init_isa
= SB16_init
}
6742 "Yamaha YMF262 (OPL3)",
6744 "Yamaha YM3812 (OPL2)",
6748 { .init_isa
= Adlib_init
}
6755 "Gravis Ultrasound GF1",
6758 { .init_isa
= GUS_init
}
6764 "ENSONIQ AudioPCI ES1370",
6767 { .init_pci
= es1370_init
}
6770 { NULL
, NULL
, 0, 0, { NULL
} }
6773 static void select_soundhw (const char *optarg
)
6777 if (*optarg
== '?') {
6780 printf ("Valid sound card names (comma separated):\n");
6781 for (c
= soundhw
; c
->name
; ++c
) {
6782 printf ("%-11s %s\n", c
->name
, c
->descr
);
6784 printf ("\n-soundhw all will enable all of the above\n");
6785 exit (*optarg
!= '?');
6793 if (!strcmp (optarg
, "all")) {
6794 for (c
= soundhw
; c
->name
; ++c
) {
6802 e
= strchr (p
, ',');
6803 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6805 for (c
= soundhw
; c
->name
; ++c
) {
6806 if (!strncmp (c
->name
, p
, l
)) {
6815 "Unknown sound card name (too big to show)\n");
6818 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6823 p
+= l
+ (e
!= NULL
);
6827 goto show_valid_cards
;
6833 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6835 exit(STATUS_CONTROL_C_EXIT
);
6840 #define MAX_NET_CLIENTS 32
6842 int main(int argc
, char **argv
)
6844 #ifdef CONFIG_GDBSTUB
6846 const char *gdbstub_port
;
6849 int snapshot
, linux_boot
;
6850 const char *initrd_filename
;
6851 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6852 const char *kernel_filename
, *kernel_cmdline
;
6853 DisplayState
*ds
= &display_state
;
6854 int cyls
, heads
, secs
, translation
;
6855 char net_clients
[MAX_NET_CLIENTS
][256];
6858 const char *r
, *optarg
;
6859 CharDriverState
*monitor_hd
;
6860 char monitor_device
[128];
6861 char serial_devices
[MAX_SERIAL_PORTS
][128];
6862 int serial_device_index
;
6863 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6864 int parallel_device_index
;
6865 const char *loadvm
= NULL
;
6866 QEMUMachine
*machine
;
6867 const char *cpu_model
;
6868 char usb_devices
[MAX_USB_CMDLINE
][128];
6869 int usb_devices_index
;
6871 const char *pid_file
= NULL
;
6873 LIST_INIT (&vm_change_state_head
);
6876 struct sigaction act
;
6877 sigfillset(&act
.sa_mask
);
6879 act
.sa_handler
= SIG_IGN
;
6880 sigaction(SIGPIPE
, &act
, NULL
);
6883 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6884 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6885 QEMU to run on a single CPU */
6890 h
= GetCurrentProcess();
6891 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6892 for(i
= 0; i
< 32; i
++) {
6893 if (mask
& (1 << i
))
6898 SetProcessAffinityMask(h
, mask
);
6904 register_machines();
6905 machine
= first_machine
;
6907 initrd_filename
= NULL
;
6908 for(i
= 0; i
< MAX_FD
; i
++)
6909 fd_filename
[i
] = NULL
;
6910 for(i
= 0; i
< MAX_DISKS
; i
++)
6911 hd_filename
[i
] = NULL
;
6912 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6913 vga_ram_size
= VGA_RAM_SIZE
;
6914 #ifdef CONFIG_GDBSTUB
6916 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6920 kernel_filename
= NULL
;
6921 kernel_cmdline
= "";
6927 cyls
= heads
= secs
= 0;
6928 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6929 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6931 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6932 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6933 serial_devices
[i
][0] = '\0';
6934 serial_device_index
= 0;
6936 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6937 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6938 parallel_devices
[i
][0] = '\0';
6939 parallel_device_index
= 0;
6941 usb_devices_index
= 0;
6946 /* default mac address of the first network interface */
6954 hd_filename
[0] = argv
[optind
++];
6956 const QEMUOption
*popt
;
6959 /* Treat --foo the same as -foo. */
6962 popt
= qemu_options
;
6965 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6969 if (!strcmp(popt
->name
, r
+ 1))
6973 if (popt
->flags
& HAS_ARG
) {
6974 if (optind
>= argc
) {
6975 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6979 optarg
= argv
[optind
++];
6984 switch(popt
->index
) {
6986 machine
= find_machine(optarg
);
6989 printf("Supported machines are:\n");
6990 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6991 printf("%-10s %s%s\n",
6993 m
== first_machine
? " (default)" : "");
6998 case QEMU_OPTION_cpu
:
6999 /* hw initialization will check this */
7000 if (optarg
[0] == '?') {
7001 #if defined(TARGET_PPC)
7002 ppc_cpu_list(stdout
, &fprintf
);
7003 #elif defined(TARGET_ARM)
7005 #elif defined(TARGET_MIPS)
7006 mips_cpu_list(stdout
, &fprintf
);
7013 case QEMU_OPTION_initrd
:
7014 initrd_filename
= optarg
;
7016 case QEMU_OPTION_hda
:
7017 case QEMU_OPTION_hdb
:
7018 case QEMU_OPTION_hdc
:
7019 case QEMU_OPTION_hdd
:
7022 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7023 hd_filename
[hd_index
] = optarg
;
7024 if (hd_index
== cdrom_index
)
7028 case QEMU_OPTION_snapshot
:
7031 case QEMU_OPTION_hdachs
:
7035 cyls
= strtol(p
, (char **)&p
, 0);
7036 if (cyls
< 1 || cyls
> 16383)
7041 heads
= strtol(p
, (char **)&p
, 0);
7042 if (heads
< 1 || heads
> 16)
7047 secs
= strtol(p
, (char **)&p
, 0);
7048 if (secs
< 1 || secs
> 63)
7052 if (!strcmp(p
, "none"))
7053 translation
= BIOS_ATA_TRANSLATION_NONE
;
7054 else if (!strcmp(p
, "lba"))
7055 translation
= BIOS_ATA_TRANSLATION_LBA
;
7056 else if (!strcmp(p
, "auto"))
7057 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7060 } else if (*p
!= '\0') {
7062 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7067 case QEMU_OPTION_nographic
:
7068 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7069 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7072 case QEMU_OPTION_kernel
:
7073 kernel_filename
= optarg
;
7075 case QEMU_OPTION_append
:
7076 kernel_cmdline
= optarg
;
7078 case QEMU_OPTION_cdrom
:
7079 if (cdrom_index
>= 0) {
7080 hd_filename
[cdrom_index
] = optarg
;
7083 case QEMU_OPTION_boot
:
7084 boot_device
= optarg
[0];
7085 if (boot_device
!= 'a' &&
7086 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7088 boot_device
!= 'n' &&
7090 boot_device
!= 'c' && boot_device
!= 'd') {
7091 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7095 case QEMU_OPTION_fda
:
7096 fd_filename
[0] = optarg
;
7098 case QEMU_OPTION_fdb
:
7099 fd_filename
[1] = optarg
;
7102 case QEMU_OPTION_no_fd_bootchk
:
7106 case QEMU_OPTION_no_code_copy
:
7107 code_copy_enabled
= 0;
7109 case QEMU_OPTION_net
:
7110 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7111 fprintf(stderr
, "qemu: too many network clients\n");
7114 pstrcpy(net_clients
[nb_net_clients
],
7115 sizeof(net_clients
[0]),
7120 case QEMU_OPTION_tftp
:
7121 tftp_prefix
= optarg
;
7123 case QEMU_OPTION_bootp
:
7124 bootp_filename
= optarg
;
7127 case QEMU_OPTION_smb
:
7128 net_slirp_smb(optarg
);
7131 case QEMU_OPTION_redir
:
7132 net_slirp_redir(optarg
);
7136 case QEMU_OPTION_audio_help
:
7140 case QEMU_OPTION_soundhw
:
7141 select_soundhw (optarg
);
7148 ram_size
= atoi(optarg
) * 1024 * 1024;
7151 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7152 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7153 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7162 mask
= cpu_str_to_log_mask(optarg
);
7164 printf("Log items (comma separated):\n");
7165 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7166 printf("%-10s %s\n", item
->name
, item
->help
);
7173 #ifdef CONFIG_GDBSTUB
7178 gdbstub_port
= optarg
;
7188 keyboard_layout
= optarg
;
7190 case QEMU_OPTION_localtime
:
7193 case QEMU_OPTION_cirrusvga
:
7194 cirrus_vga_enabled
= 1;
7196 case QEMU_OPTION_std_vga
:
7197 cirrus_vga_enabled
= 0;
7204 w
= strtol(p
, (char **)&p
, 10);
7207 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7213 h
= strtol(p
, (char **)&p
, 10);
7218 depth
= strtol(p
, (char **)&p
, 10);
7219 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7220 depth
!= 24 && depth
!= 32)
7222 } else if (*p
== '\0') {
7223 depth
= graphic_depth
;
7230 graphic_depth
= depth
;
7233 case QEMU_OPTION_echr
:
7236 term_escape_char
= strtol(optarg
, &r
, 0);
7238 printf("Bad argument to echr\n");
7241 case QEMU_OPTION_monitor
:
7242 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7244 case QEMU_OPTION_serial
:
7245 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7246 fprintf(stderr
, "qemu: too many serial ports\n");
7249 pstrcpy(serial_devices
[serial_device_index
],
7250 sizeof(serial_devices
[0]), optarg
);
7251 serial_device_index
++;
7253 case QEMU_OPTION_parallel
:
7254 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7255 fprintf(stderr
, "qemu: too many parallel ports\n");
7258 pstrcpy(parallel_devices
[parallel_device_index
],
7259 sizeof(parallel_devices
[0]), optarg
);
7260 parallel_device_index
++;
7262 case QEMU_OPTION_loadvm
:
7265 case QEMU_OPTION_full_screen
:
7269 case QEMU_OPTION_no_frame
:
7272 case QEMU_OPTION_no_quit
:
7276 case QEMU_OPTION_pidfile
:
7280 case QEMU_OPTION_win2k_hack
:
7281 win2k_install_hack
= 1;
7285 case QEMU_OPTION_no_kqemu
:
7288 case QEMU_OPTION_kernel_kqemu
:
7292 case QEMU_OPTION_usb
:
7295 case QEMU_OPTION_usbdevice
:
7297 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7298 fprintf(stderr
, "Too many USB devices\n");
7301 pstrcpy(usb_devices
[usb_devices_index
],
7302 sizeof(usb_devices
[usb_devices_index
]),
7304 usb_devices_index
++;
7306 case QEMU_OPTION_smp
:
7307 smp_cpus
= atoi(optarg
);
7308 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7309 fprintf(stderr
, "Invalid number of CPUs\n");
7313 case QEMU_OPTION_vnc
:
7314 vnc_display
= optarg
;
7316 case QEMU_OPTION_no_acpi
:
7319 case QEMU_OPTION_no_reboot
:
7322 case QEMU_OPTION_daemonize
:
7325 case QEMU_OPTION_option_rom
:
7326 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7327 fprintf(stderr
, "Too many option ROMs\n");
7330 option_rom
[nb_option_roms
] = optarg
;
7333 case QEMU_OPTION_semihosting
:
7334 semihosting_enabled
= 1;
7336 case QEMU_OPTION_name
:
7344 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7345 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7352 if (pipe(fds
) == -1)
7363 len
= read(fds
[0], &status
, 1);
7364 if (len
== -1 && (errno
== EINTR
))
7369 else if (status
== 1) {
7370 fprintf(stderr
, "Could not acquire pidfile\n");
7388 signal(SIGTSTP
, SIG_IGN
);
7389 signal(SIGTTOU
, SIG_IGN
);
7390 signal(SIGTTIN
, SIG_IGN
);
7394 if (pid_file
&& create_pidfile(pid_file
) != 0) {
7397 write(fds
[1], &status
, 1);
7399 fprintf(stderr
, "Could not acquire pid file\n");
7407 linux_boot
= (kernel_filename
!= NULL
);
7410 boot_device
!= 'n' &&
7411 hd_filename
[0] == '\0' &&
7412 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7413 fd_filename
[0] == '\0')
7416 /* boot to floppy or the default cd if no hard disk defined yet */
7417 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7418 if (fd_filename
[0] != '\0')
7424 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7434 /* init network clients */
7435 if (nb_net_clients
== 0) {
7436 /* if no clients, we use a default config */
7437 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7439 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7444 for(i
= 0;i
< nb_net_clients
; i
++) {
7445 if (net_client_init(net_clients
[i
]) < 0)
7450 if (boot_device
== 'n') {
7451 for (i
= 0; i
< nb_nics
; i
++) {
7452 const char *model
= nd_table
[i
].model
;
7456 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7457 if (get_image_size(buf
) > 0) {
7458 option_rom
[nb_option_roms
] = strdup(buf
);
7464 fprintf(stderr
, "No valid PXE rom found for network device\n");
7467 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7471 /* init the memory */
7472 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
7474 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7475 if (!phys_ram_base
) {
7476 fprintf(stderr
, "Could not allocate physical memory\n");
7480 /* we always create the cdrom drive, even if no disk is there */
7482 if (cdrom_index
>= 0) {
7483 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7484 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7487 /* open the virtual block devices */
7488 for(i
= 0; i
< MAX_DISKS
; i
++) {
7489 if (hd_filename
[i
]) {
7492 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7493 bs_table
[i
] = bdrv_new(buf
);
7495 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7496 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7500 if (i
== 0 && cyls
!= 0) {
7501 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7502 bdrv_set_translation_hint(bs_table
[i
], translation
);
7507 /* we always create at least one floppy disk */
7508 fd_table
[0] = bdrv_new("fda");
7509 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7511 for(i
= 0; i
< MAX_FD
; i
++) {
7512 if (fd_filename
[i
]) {
7515 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7516 fd_table
[i
] = bdrv_new(buf
);
7517 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7519 if (fd_filename
[i
] != '\0') {
7520 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7521 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7522 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7530 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7531 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7537 dumb_display_init(ds
);
7538 } else if (vnc_display
!= NULL
) {
7539 vnc_display_init(ds
, vnc_display
);
7541 #if defined(CONFIG_SDL)
7542 sdl_display_init(ds
, full_screen
, no_frame
);
7543 #elif defined(CONFIG_COCOA)
7544 cocoa_display_init(ds
, full_screen
);
7546 dumb_display_init(ds
);
7550 /* Maintain compatibility with multiple stdio monitors */
7551 if (!strcmp(monitor_device
,"stdio")) {
7552 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7553 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
7554 monitor_device
[0] = '\0';
7556 } else if (!strcmp(serial_devices
[i
],"stdio")) {
7557 monitor_device
[0] = '\0';
7558 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
7563 if (monitor_device
[0] != '\0') {
7564 monitor_hd
= qemu_chr_open(monitor_device
);
7566 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7569 monitor_init(monitor_hd
, !nographic
);
7572 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7573 const char *devname
= serial_devices
[i
];
7574 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7575 serial_hds
[i
] = qemu_chr_open(devname
);
7576 if (!serial_hds
[i
]) {
7577 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7581 if (!strcmp(devname
, "vc"))
7582 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7586 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7587 const char *devname
= parallel_devices
[i
];
7588 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7589 parallel_hds
[i
] = qemu_chr_open(devname
);
7590 if (!parallel_hds
[i
]) {
7591 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7595 if (!strcmp(devname
, "vc"))
7596 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7600 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7601 ds
, fd_filename
, snapshot
,
7602 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
7604 /* init USB devices */
7606 for(i
= 0; i
< usb_devices_index
; i
++) {
7607 if (usb_device_add(usb_devices
[i
]) < 0) {
7608 fprintf(stderr
, "Warning: could not add USB device %s\n",
7614 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7615 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7617 #ifdef CONFIG_GDBSTUB
7619 /* XXX: use standard host:port notation and modify options
7621 if (gdbserver_start(gdbstub_port
) < 0) {
7622 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
7632 /* XXX: simplify init */
7645 len
= write(fds
[1], &status
, 1);
7646 if (len
== -1 && (errno
== EINTR
))
7652 fd
= open("/dev/null", O_RDWR
);