4 * Copyright (c) 2003-2008 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
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
72 #include <linux/if_tun.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
101 #include <winsock2.h>
102 int inet_aton(const char *cp
, struct in_addr
*ia
);
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
111 #include <sys/timeb.h>
112 #include <mmsystem.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
117 #include "qemu_socket.h"
123 #endif /* CONFIG_SDL */
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
139 #define SMBD_COMMAND "/usr/sbin/smbd"
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
146 #define DEFAULT_RAM_SIZE 144
148 #define DEFAULT_RAM_SIZE 128
151 #define GUI_REFRESH_INTERVAL 30
153 /* Max number of USB devices that can be specified on the commandline. */
154 #define MAX_USB_CMDLINE 8
156 /* XXX: use a two level table to limit memory usage */
157 #define MAX_IOPORTS 65536
159 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
160 const char *bios_name
= NULL
;
161 void *ioport_opaque
[MAX_IOPORTS
];
162 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
163 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
164 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
165 to store the VM snapshots */
166 DriveInfo drives_table
[MAX_DRIVES
+1];
168 /* point to the block driver where the snapshots are managed */
169 BlockDriverState
*bs_snapshots
;
171 static DisplayState display_state
;
174 const char* keyboard_layout
= NULL
;
175 int64_t ticks_per_sec
;
177 int pit_min_timer_count
= 0;
179 NICInfo nd_table
[MAX_NICS
];
181 static int rtc_utc
= 1;
182 static int rtc_date_offset
= -1; /* -1 means no change */
183 int cirrus_vga_enabled
= 1;
184 int vmsvga_enabled
= 0;
186 int graphic_width
= 1024;
187 int graphic_height
= 768;
188 int graphic_depth
= 8;
190 int graphic_width
= 800;
191 int graphic_height
= 600;
192 int graphic_depth
= 15;
197 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
198 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
200 int win2k_install_hack
= 0;
203 static VLANState
*first_vlan
;
205 const char *vnc_display
;
206 #if defined(TARGET_SPARC)
208 #elif defined(TARGET_I386)
213 int acpi_enabled
= 1;
218 int graphic_rotate
= 0;
220 const char *option_rom
[MAX_OPTION_ROMS
];
222 int semihosting_enabled
= 0;
227 const char *qemu_name
;
230 unsigned int nb_prom_envs
= 0;
231 const char *prom_envs
[MAX_PROM_ENVS
];
237 } drives_opt
[MAX_DRIVES
];
239 static CPUState
*cur_cpu
;
240 static CPUState
*next_cpu
;
241 static int event_pending
= 1;
243 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
245 /***********************************************************/
246 /* x86 ISA bus support */
248 target_phys_addr_t isa_mem_base
= 0;
251 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
259 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
261 #ifdef DEBUG_UNUSED_IOPORT
262 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
266 /* default is to make two byte accesses */
267 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
270 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
271 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
272 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
276 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
278 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
279 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
280 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
283 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
285 #ifdef DEBUG_UNUSED_IOPORT
286 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
291 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
293 #ifdef DEBUG_UNUSED_IOPORT
294 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
298 static void init_ioports(void)
302 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
303 ioport_read_table
[0][i
] = default_ioport_readb
;
304 ioport_write_table
[0][i
] = default_ioport_writeb
;
305 ioport_read_table
[1][i
] = default_ioport_readw
;
306 ioport_write_table
[1][i
] = default_ioport_writew
;
307 ioport_read_table
[2][i
] = default_ioport_readl
;
308 ioport_write_table
[2][i
] = default_ioport_writel
;
312 /* size is the word size in byte */
313 int register_ioport_read(int start
, int length
, int size
,
314 IOPortReadFunc
*func
, void *opaque
)
320 } else if (size
== 2) {
322 } else if (size
== 4) {
325 hw_error("register_ioport_read: invalid size");
328 for(i
= start
; i
< start
+ length
; i
+= size
) {
329 ioport_read_table
[bsize
][i
] = func
;
330 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
331 hw_error("register_ioport_read: invalid opaque");
332 ioport_opaque
[i
] = opaque
;
337 /* size is the word size in byte */
338 int register_ioport_write(int start
, int length
, int size
,
339 IOPortWriteFunc
*func
, void *opaque
)
345 } else if (size
== 2) {
347 } else if (size
== 4) {
350 hw_error("register_ioport_write: invalid size");
353 for(i
= start
; i
< start
+ length
; i
+= size
) {
354 ioport_write_table
[bsize
][i
] = func
;
355 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
356 hw_error("register_ioport_write: invalid opaque");
357 ioport_opaque
[i
] = opaque
;
362 void isa_unassign_ioport(int start
, int length
)
366 for(i
= start
; i
< start
+ length
; i
++) {
367 ioport_read_table
[0][i
] = default_ioport_readb
;
368 ioport_read_table
[1][i
] = default_ioport_readw
;
369 ioport_read_table
[2][i
] = default_ioport_readl
;
371 ioport_write_table
[0][i
] = default_ioport_writeb
;
372 ioport_write_table
[1][i
] = default_ioport_writew
;
373 ioport_write_table
[2][i
] = default_ioport_writel
;
377 /***********************************************************/
379 void cpu_outb(CPUState
*env
, int addr
, int val
)
382 if (loglevel
& CPU_LOG_IOPORT
)
383 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
385 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
388 env
->last_io_time
= cpu_get_time_fast();
392 void cpu_outw(CPUState
*env
, int addr
, int val
)
395 if (loglevel
& CPU_LOG_IOPORT
)
396 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
398 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
401 env
->last_io_time
= cpu_get_time_fast();
405 void cpu_outl(CPUState
*env
, int addr
, int val
)
408 if (loglevel
& CPU_LOG_IOPORT
)
409 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
411 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
414 env
->last_io_time
= cpu_get_time_fast();
418 int cpu_inb(CPUState
*env
, int addr
)
421 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
423 if (loglevel
& CPU_LOG_IOPORT
)
424 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
428 env
->last_io_time
= cpu_get_time_fast();
433 int cpu_inw(CPUState
*env
, int addr
)
436 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
438 if (loglevel
& CPU_LOG_IOPORT
)
439 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
443 env
->last_io_time
= cpu_get_time_fast();
448 int cpu_inl(CPUState
*env
, int addr
)
451 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
453 if (loglevel
& CPU_LOG_IOPORT
)
454 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
458 env
->last_io_time
= cpu_get_time_fast();
463 /***********************************************************/
464 void hw_error(const char *fmt
, ...)
470 fprintf(stderr
, "qemu: hardware error: ");
471 vfprintf(stderr
, fmt
, ap
);
472 fprintf(stderr
, "\n");
473 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
474 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
476 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
478 cpu_dump_state(env
, stderr
, fprintf
, 0);
485 /***********************************************************/
488 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
489 static void *qemu_put_kbd_event_opaque
;
490 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
491 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
493 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
495 qemu_put_kbd_event_opaque
= opaque
;
496 qemu_put_kbd_event
= func
;
499 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
500 void *opaque
, int absolute
,
503 QEMUPutMouseEntry
*s
, *cursor
;
505 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
509 s
->qemu_put_mouse_event
= func
;
510 s
->qemu_put_mouse_event_opaque
= opaque
;
511 s
->qemu_put_mouse_event_absolute
= absolute
;
512 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
515 if (!qemu_put_mouse_event_head
) {
516 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
520 cursor
= qemu_put_mouse_event_head
;
521 while (cursor
->next
!= NULL
)
522 cursor
= cursor
->next
;
525 qemu_put_mouse_event_current
= s
;
530 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
532 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
534 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
537 cursor
= qemu_put_mouse_event_head
;
538 while (cursor
!= NULL
&& cursor
!= entry
) {
540 cursor
= cursor
->next
;
543 if (cursor
== NULL
) // does not exist or list empty
545 else if (prev
== NULL
) { // entry is head
546 qemu_put_mouse_event_head
= cursor
->next
;
547 if (qemu_put_mouse_event_current
== entry
)
548 qemu_put_mouse_event_current
= cursor
->next
;
549 qemu_free(entry
->qemu_put_mouse_event_name
);
554 prev
->next
= entry
->next
;
556 if (qemu_put_mouse_event_current
== entry
)
557 qemu_put_mouse_event_current
= prev
;
559 qemu_free(entry
->qemu_put_mouse_event_name
);
563 void kbd_put_keycode(int keycode
)
565 if (qemu_put_kbd_event
) {
566 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
570 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
572 QEMUPutMouseEvent
*mouse_event
;
573 void *mouse_event_opaque
;
576 if (!qemu_put_mouse_event_current
) {
581 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
583 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
586 if (graphic_rotate
) {
587 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
590 width
= graphic_width
- 1;
591 mouse_event(mouse_event_opaque
,
592 width
- dy
, dx
, dz
, buttons_state
);
594 mouse_event(mouse_event_opaque
,
595 dx
, dy
, dz
, buttons_state
);
599 int kbd_mouse_is_absolute(void)
601 if (!qemu_put_mouse_event_current
)
604 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
607 void do_info_mice(void)
609 QEMUPutMouseEntry
*cursor
;
612 if (!qemu_put_mouse_event_head
) {
613 term_printf("No mouse devices connected\n");
617 term_printf("Mouse devices available:\n");
618 cursor
= qemu_put_mouse_event_head
;
619 while (cursor
!= NULL
) {
620 term_printf("%c Mouse #%d: %s\n",
621 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
622 index
, cursor
->qemu_put_mouse_event_name
);
624 cursor
= cursor
->next
;
628 void do_mouse_set(int index
)
630 QEMUPutMouseEntry
*cursor
;
633 if (!qemu_put_mouse_event_head
) {
634 term_printf("No mouse devices connected\n");
638 cursor
= qemu_put_mouse_event_head
;
639 while (cursor
!= NULL
&& index
!= i
) {
641 cursor
= cursor
->next
;
645 qemu_put_mouse_event_current
= cursor
;
647 term_printf("Mouse at given index not found\n");
650 /* compute with 96 bit intermediate result: (a*b)/c */
651 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
656 #ifdef WORDS_BIGENDIAN
666 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
667 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
670 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
674 /***********************************************************/
675 /* real time host monotonic timer */
677 #define QEMU_TIMER_BASE 1000000000LL
681 static int64_t clock_freq
;
683 static void init_get_clock(void)
687 ret
= QueryPerformanceFrequency(&freq
);
689 fprintf(stderr
, "Could not calibrate ticks\n");
692 clock_freq
= freq
.QuadPart
;
695 static int64_t get_clock(void)
698 QueryPerformanceCounter(&ti
);
699 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
704 static int use_rt_clock
;
706 static void init_get_clock(void)
709 #if defined(__linux__)
712 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
719 static int64_t get_clock(void)
721 #if defined(__linux__)
724 clock_gettime(CLOCK_MONOTONIC
, &ts
);
725 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
729 /* XXX: using gettimeofday leads to problems if the date
730 changes, so it should be avoided. */
732 gettimeofday(&tv
, NULL
);
733 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
739 /***********************************************************/
740 /* guest cycle counter */
742 static int64_t cpu_ticks_prev
;
743 static int64_t cpu_ticks_offset
;
744 static int64_t cpu_clock_offset
;
745 static int cpu_ticks_enabled
;
747 /* return the host CPU cycle counter and handle stop/restart */
748 int64_t cpu_get_ticks(void)
750 if (!cpu_ticks_enabled
) {
751 return cpu_ticks_offset
;
754 ticks
= cpu_get_real_ticks();
755 if (cpu_ticks_prev
> ticks
) {
756 /* Note: non increasing ticks may happen if the host uses
758 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
760 cpu_ticks_prev
= ticks
;
761 return ticks
+ cpu_ticks_offset
;
765 /* return the host CPU monotonic timer and handle stop/restart */
766 static int64_t cpu_get_clock(void)
769 if (!cpu_ticks_enabled
) {
770 return cpu_clock_offset
;
773 return ti
+ cpu_clock_offset
;
777 /* enable cpu_get_ticks() */
778 void cpu_enable_ticks(void)
780 if (!cpu_ticks_enabled
) {
781 cpu_ticks_offset
-= cpu_get_real_ticks();
782 cpu_clock_offset
-= get_clock();
783 cpu_ticks_enabled
= 1;
787 /* disable cpu_get_ticks() : the clock is stopped. You must not call
788 cpu_get_ticks() after that. */
789 void cpu_disable_ticks(void)
791 if (cpu_ticks_enabled
) {
792 cpu_ticks_offset
= cpu_get_ticks();
793 cpu_clock_offset
= cpu_get_clock();
794 cpu_ticks_enabled
= 0;
798 /***********************************************************/
801 #define QEMU_TIMER_REALTIME 0
802 #define QEMU_TIMER_VIRTUAL 1
806 /* XXX: add frequency */
814 struct QEMUTimer
*next
;
817 struct qemu_alarm_timer
{
821 int (*start
)(struct qemu_alarm_timer
*t
);
822 void (*stop
)(struct qemu_alarm_timer
*t
);
823 void (*rearm
)(struct qemu_alarm_timer
*t
);
827 #define ALARM_FLAG_DYNTICKS 0x1
828 #define ALARM_FLAG_EXPIRED 0x2
830 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
832 return t
->flags
& ALARM_FLAG_DYNTICKS
;
835 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
837 if (!alarm_has_dynticks(t
))
843 /* TODO: MIN_TIMER_REARM_US should be optimized */
844 #define MIN_TIMER_REARM_US 250
846 static struct qemu_alarm_timer
*alarm_timer
;
850 struct qemu_alarm_win32
{
854 } alarm_win32_data
= {0, NULL
, -1};
856 static int win32_start_timer(struct qemu_alarm_timer
*t
);
857 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
858 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
862 static int unix_start_timer(struct qemu_alarm_timer
*t
);
863 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
867 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
868 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
869 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
871 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
872 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
874 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
875 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
877 #endif /* __linux__ */
881 static struct qemu_alarm_timer alarm_timers
[] = {
884 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
885 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
886 /* HPET - if available - is preferred */
887 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
888 /* ...otherwise try RTC */
889 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
891 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
893 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
894 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
895 {"win32", 0, win32_start_timer
,
896 win32_stop_timer
, NULL
, &alarm_win32_data
},
901 static void show_available_alarms(void)
905 printf("Available alarm timers, in order of precedence:\n");
906 for (i
= 0; alarm_timers
[i
].name
; i
++)
907 printf("%s\n", alarm_timers
[i
].name
);
910 static void configure_alarms(char const *opt
)
914 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
918 if (!strcmp(opt
, "?")) {
919 show_available_alarms();
925 /* Reorder the array */
926 name
= strtok(arg
, ",");
928 struct qemu_alarm_timer tmp
;
930 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
931 if (!strcmp(alarm_timers
[i
].name
, name
))
936 fprintf(stderr
, "Unknown clock %s\n", name
);
945 tmp
= alarm_timers
[i
];
946 alarm_timers
[i
] = alarm_timers
[cur
];
947 alarm_timers
[cur
] = tmp
;
951 name
= strtok(NULL
, ",");
957 /* Disable remaining timers */
958 for (i
= cur
; i
< count
; i
++)
959 alarm_timers
[i
].name
= NULL
;
961 show_available_alarms();
969 static QEMUTimer
*active_timers
[2];
971 static QEMUClock
*qemu_new_clock(int type
)
974 clock
= qemu_mallocz(sizeof(QEMUClock
));
981 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
985 ts
= qemu_mallocz(sizeof(QEMUTimer
));
992 void qemu_free_timer(QEMUTimer
*ts
)
997 /* stop a timer, but do not dealloc it */
998 void qemu_del_timer(QEMUTimer
*ts
)
1002 /* NOTE: this code must be signal safe because
1003 qemu_timer_expired() can be called from a signal. */
1004 pt
= &active_timers
[ts
->clock
->type
];
1017 /* modify the current timer so that it will be fired when current_time
1018 >= expire_time. The corresponding callback will be called. */
1019 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1025 /* add the timer in the sorted list */
1026 /* NOTE: this code must be signal safe because
1027 qemu_timer_expired() can be called from a signal. */
1028 pt
= &active_timers
[ts
->clock
->type
];
1033 if (t
->expire_time
> expire_time
)
1037 ts
->expire_time
= expire_time
;
1041 /* Rearm if necessary */
1042 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0 &&
1043 pt
== &active_timers
[ts
->clock
->type
])
1044 qemu_rearm_alarm_timer(alarm_timer
);
1047 int qemu_timer_pending(QEMUTimer
*ts
)
1050 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1057 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1061 return (timer_head
->expire_time
<= current_time
);
1064 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1070 if (!ts
|| ts
->expire_time
> current_time
)
1072 /* remove timer from the list before calling the callback */
1073 *ptimer_head
= ts
->next
;
1076 /* run the callback (the timer list can be modified) */
1081 int64_t qemu_get_clock(QEMUClock
*clock
)
1083 switch(clock
->type
) {
1084 case QEMU_TIMER_REALTIME
:
1085 return get_clock() / 1000000;
1087 case QEMU_TIMER_VIRTUAL
:
1088 return cpu_get_clock();
1092 static void init_timers(void)
1095 ticks_per_sec
= QEMU_TIMER_BASE
;
1096 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1097 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1101 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1103 uint64_t expire_time
;
1105 if (qemu_timer_pending(ts
)) {
1106 expire_time
= ts
->expire_time
;
1110 qemu_put_be64(f
, expire_time
);
1113 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1115 uint64_t expire_time
;
1117 expire_time
= qemu_get_be64(f
);
1118 if (expire_time
!= -1) {
1119 qemu_mod_timer(ts
, expire_time
);
1125 static void timer_save(QEMUFile
*f
, void *opaque
)
1127 if (cpu_ticks_enabled
) {
1128 hw_error("cannot save state if virtual timers are running");
1130 qemu_put_be64(f
, cpu_ticks_offset
);
1131 qemu_put_be64(f
, ticks_per_sec
);
1132 qemu_put_be64(f
, cpu_clock_offset
);
1135 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1137 if (version_id
!= 1 && version_id
!= 2)
1139 if (cpu_ticks_enabled
) {
1142 cpu_ticks_offset
=qemu_get_be64(f
);
1143 ticks_per_sec
=qemu_get_be64(f
);
1144 if (version_id
== 2) {
1145 cpu_clock_offset
=qemu_get_be64(f
);
1151 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1152 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1154 static void host_alarm_handler(int host_signum
)
1158 #define DISP_FREQ 1000
1160 static int64_t delta_min
= INT64_MAX
;
1161 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1163 ti
= qemu_get_clock(vm_clock
);
1164 if (last_clock
!= 0) {
1165 delta
= ti
- last_clock
;
1166 if (delta
< delta_min
)
1168 if (delta
> delta_max
)
1171 if (++count
== DISP_FREQ
) {
1172 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1173 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1174 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1175 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1176 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1178 delta_min
= INT64_MAX
;
1186 if (alarm_has_dynticks(alarm_timer
) ||
1187 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1188 qemu_get_clock(vm_clock
)) ||
1189 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1190 qemu_get_clock(rt_clock
))) {
1192 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1193 SetEvent(data
->host_alarm
);
1195 CPUState
*env
= next_cpu
;
1197 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1200 /* stop the currently executing cpu because a timer occured */
1201 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1203 if (env
->kqemu_enabled
) {
1204 kqemu_cpu_interrupt(env
);
1212 static uint64_t qemu_next_deadline(void)
1214 int64_t nearest_delta_us
= INT64_MAX
;
1217 if (active_timers
[QEMU_TIMER_REALTIME
])
1218 nearest_delta_us
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1219 qemu_get_clock(rt_clock
))*1000;
1221 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1223 vmdelta_us
= (active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1224 qemu_get_clock(vm_clock
)+999)/1000;
1225 if (vmdelta_us
< nearest_delta_us
)
1226 nearest_delta_us
= vmdelta_us
;
1229 /* Avoid arming the timer to negative, zero, or too low values */
1230 if (nearest_delta_us
<= MIN_TIMER_REARM_US
)
1231 nearest_delta_us
= MIN_TIMER_REARM_US
;
1233 return nearest_delta_us
;
1238 #if defined(__linux__)
1240 #define RTC_FREQ 1024
1242 static void enable_sigio_timer(int fd
)
1244 struct sigaction act
;
1247 sigfillset(&act
.sa_mask
);
1249 act
.sa_handler
= host_alarm_handler
;
1251 sigaction(SIGIO
, &act
, NULL
);
1252 fcntl(fd
, F_SETFL
, O_ASYNC
);
1253 fcntl(fd
, F_SETOWN
, getpid());
1256 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1258 struct hpet_info info
;
1261 fd
= open("/dev/hpet", O_RDONLY
);
1266 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1268 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1269 "error, but for better emulation accuracy type:\n"
1270 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1274 /* Check capabilities */
1275 r
= ioctl(fd
, HPET_INFO
, &info
);
1279 /* Enable periodic mode */
1280 r
= ioctl(fd
, HPET_EPI
, 0);
1281 if (info
.hi_flags
&& (r
< 0))
1284 /* Enable interrupt */
1285 r
= ioctl(fd
, HPET_IE_ON
, 0);
1289 enable_sigio_timer(fd
);
1290 t
->priv
= (void *)(long)fd
;
1298 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1300 int fd
= (long)t
->priv
;
1305 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1308 unsigned long current_rtc_freq
= 0;
1310 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1313 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1314 if (current_rtc_freq
!= RTC_FREQ
&&
1315 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1316 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1317 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1318 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1321 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1327 enable_sigio_timer(rtc_fd
);
1329 t
->priv
= (void *)(long)rtc_fd
;
1334 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1336 int rtc_fd
= (long)t
->priv
;
1341 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1345 struct sigaction act
;
1347 sigfillset(&act
.sa_mask
);
1349 act
.sa_handler
= host_alarm_handler
;
1351 sigaction(SIGALRM
, &act
, NULL
);
1353 ev
.sigev_value
.sival_int
= 0;
1354 ev
.sigev_notify
= SIGEV_SIGNAL
;
1355 ev
.sigev_signo
= SIGALRM
;
1357 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1358 perror("timer_create");
1360 /* disable dynticks */
1361 fprintf(stderr
, "Dynamic Ticks disabled\n");
1366 t
->priv
= (void *)host_timer
;
1371 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1373 timer_t host_timer
= (timer_t
)t
->priv
;
1375 timer_delete(host_timer
);
1378 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1380 timer_t host_timer
= (timer_t
)t
->priv
;
1381 struct itimerspec timeout
;
1382 int64_t nearest_delta_us
= INT64_MAX
;
1385 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1386 !active_timers
[QEMU_TIMER_VIRTUAL
])
1389 nearest_delta_us
= qemu_next_deadline();
1391 /* check whether a timer is already running */
1392 if (timer_gettime(host_timer
, &timeout
)) {
1394 fprintf(stderr
, "Internal timer error: aborting\n");
1397 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1398 if (current_us
&& current_us
<= nearest_delta_us
)
1401 timeout
.it_interval
.tv_sec
= 0;
1402 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1403 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1404 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1405 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1407 fprintf(stderr
, "Internal timer error: aborting\n");
1412 #endif /* defined(__linux__) */
1414 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1416 struct sigaction act
;
1417 struct itimerval itv
;
1421 sigfillset(&act
.sa_mask
);
1423 act
.sa_handler
= host_alarm_handler
;
1425 sigaction(SIGALRM
, &act
, NULL
);
1427 itv
.it_interval
.tv_sec
= 0;
1428 /* for i386 kernel 2.6 to get 1 ms */
1429 itv
.it_interval
.tv_usec
= 999;
1430 itv
.it_value
.tv_sec
= 0;
1431 itv
.it_value
.tv_usec
= 10 * 1000;
1433 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1440 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1442 struct itimerval itv
;
1444 memset(&itv
, 0, sizeof(itv
));
1445 setitimer(ITIMER_REAL
, &itv
, NULL
);
1448 #endif /* !defined(_WIN32) */
1452 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1455 struct qemu_alarm_win32
*data
= t
->priv
;
1458 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1459 if (!data
->host_alarm
) {
1460 perror("Failed CreateEvent");
1464 memset(&tc
, 0, sizeof(tc
));
1465 timeGetDevCaps(&tc
, sizeof(tc
));
1467 if (data
->period
< tc
.wPeriodMin
)
1468 data
->period
= tc
.wPeriodMin
;
1470 timeBeginPeriod(data
->period
);
1472 flags
= TIME_CALLBACK_FUNCTION
;
1473 if (alarm_has_dynticks(t
))
1474 flags
|= TIME_ONESHOT
;
1476 flags
|= TIME_PERIODIC
;
1478 data
->timerId
= timeSetEvent(1, // interval (ms)
1479 data
->period
, // resolution
1480 host_alarm_handler
, // function
1481 (DWORD
)t
, // parameter
1484 if (!data
->timerId
) {
1485 perror("Failed to initialize win32 alarm timer");
1487 timeEndPeriod(data
->period
);
1488 CloseHandle(data
->host_alarm
);
1492 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1497 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1499 struct qemu_alarm_win32
*data
= t
->priv
;
1501 timeKillEvent(data
->timerId
);
1502 timeEndPeriod(data
->period
);
1504 CloseHandle(data
->host_alarm
);
1507 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1509 struct qemu_alarm_win32
*data
= t
->priv
;
1510 uint64_t nearest_delta_us
;
1512 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1513 !active_timers
[QEMU_TIMER_VIRTUAL
])
1516 nearest_delta_us
= qemu_next_deadline();
1517 nearest_delta_us
/= 1000;
1519 timeKillEvent(data
->timerId
);
1521 data
->timerId
= timeSetEvent(1,
1525 TIME_ONESHOT
| TIME_PERIODIC
);
1527 if (!data
->timerId
) {
1528 perror("Failed to re-arm win32 alarm timer");
1530 timeEndPeriod(data
->period
);
1531 CloseHandle(data
->host_alarm
);
1538 static void init_timer_alarm(void)
1540 struct qemu_alarm_timer
*t
;
1543 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1544 t
= &alarm_timers
[i
];
1552 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1553 fprintf(stderr
, "Terminating\n");
1560 static void quit_timers(void)
1562 alarm_timer
->stop(alarm_timer
);
1566 /***********************************************************/
1567 /* host time/date access */
1568 void qemu_get_timedate(struct tm
*tm
, int offset
)
1575 if (rtc_date_offset
== -1) {
1579 ret
= localtime(&ti
);
1581 ti
-= rtc_date_offset
;
1585 memcpy(tm
, ret
, sizeof(struct tm
));
1588 int qemu_timedate_diff(struct tm
*tm
)
1592 if (rtc_date_offset
== -1)
1594 seconds
= mktimegm(tm
);
1596 seconds
= mktime(tm
);
1598 seconds
= mktimegm(tm
) + rtc_date_offset
;
1600 return seconds
- time(NULL
);
1603 /***********************************************************/
1604 /* character device */
1606 static void qemu_chr_event(CharDriverState
*s
, int event
)
1610 s
->chr_event(s
->handler_opaque
, event
);
1613 static void qemu_chr_reset_bh(void *opaque
)
1615 CharDriverState
*s
= opaque
;
1616 qemu_chr_event(s
, CHR_EVENT_RESET
);
1617 qemu_bh_delete(s
->bh
);
1621 void qemu_chr_reset(CharDriverState
*s
)
1623 if (s
->bh
== NULL
) {
1624 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1625 qemu_bh_schedule(s
->bh
);
1629 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1631 return s
->chr_write(s
, buf
, len
);
1634 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1638 return s
->chr_ioctl(s
, cmd
, arg
);
1641 int qemu_chr_can_read(CharDriverState
*s
)
1643 if (!s
->chr_can_read
)
1645 return s
->chr_can_read(s
->handler_opaque
);
1648 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1650 s
->chr_read(s
->handler_opaque
, buf
, len
);
1653 void qemu_chr_accept_input(CharDriverState
*s
)
1655 if (s
->chr_accept_input
)
1656 s
->chr_accept_input(s
);
1659 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1664 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1665 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1669 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1671 if (s
->chr_send_event
)
1672 s
->chr_send_event(s
, event
);
1675 void qemu_chr_add_handlers(CharDriverState
*s
,
1676 IOCanRWHandler
*fd_can_read
,
1677 IOReadHandler
*fd_read
,
1678 IOEventHandler
*fd_event
,
1681 s
->chr_can_read
= fd_can_read
;
1682 s
->chr_read
= fd_read
;
1683 s
->chr_event
= fd_event
;
1684 s
->handler_opaque
= opaque
;
1685 if (s
->chr_update_read_handler
)
1686 s
->chr_update_read_handler(s
);
1689 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1694 static CharDriverState
*qemu_chr_open_null(void)
1696 CharDriverState
*chr
;
1698 chr
= qemu_mallocz(sizeof(CharDriverState
));
1701 chr
->chr_write
= null_chr_write
;
1705 /* MUX driver for serial I/O splitting */
1706 static int term_timestamps
;
1707 static int64_t term_timestamps_start
;
1709 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1710 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1712 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1713 IOReadHandler
*chr_read
[MAX_MUX
];
1714 IOEventHandler
*chr_event
[MAX_MUX
];
1715 void *ext_opaque
[MAX_MUX
];
1716 CharDriverState
*drv
;
1717 unsigned char buffer
[MUX_BUFFER_SIZE
];
1721 int term_got_escape
;
1726 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1728 MuxDriver
*d
= chr
->opaque
;
1730 if (!term_timestamps
) {
1731 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1736 for(i
= 0; i
< len
; i
++) {
1737 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1738 if (buf
[i
] == '\n') {
1744 if (term_timestamps_start
== -1)
1745 term_timestamps_start
= ti
;
1746 ti
-= term_timestamps_start
;
1747 secs
= ti
/ 1000000000;
1748 snprintf(buf1
, sizeof(buf1
),
1749 "[%02d:%02d:%02d.%03d] ",
1753 (int)((ti
/ 1000000) % 1000));
1754 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1761 static char *mux_help
[] = {
1762 "% h print this help\n\r",
1763 "% x exit emulator\n\r",
1764 "% s save disk data back to file (if -snapshot)\n\r",
1765 "% t toggle console timestamps\n\r"
1766 "% b send break (magic sysrq)\n\r",
1767 "% c switch between console and monitor\n\r",
1772 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1773 static void mux_print_help(CharDriverState
*chr
)
1776 char ebuf
[15] = "Escape-Char";
1777 char cbuf
[50] = "\n\r";
1779 if (term_escape_char
> 0 && term_escape_char
< 26) {
1780 sprintf(cbuf
,"\n\r");
1781 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1783 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1786 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1787 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1788 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1789 if (mux_help
[i
][j
] == '%')
1790 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1792 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1797 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1799 if (d
->term_got_escape
) {
1800 d
->term_got_escape
= 0;
1801 if (ch
== term_escape_char
)
1806 mux_print_help(chr
);
1810 char *term
= "QEMU: Terminated\n\r";
1811 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1818 for (i
= 0; i
< nb_drives
; i
++) {
1819 bdrv_commit(drives_table
[i
].bdrv
);
1824 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1827 /* Switch to the next registered device */
1829 if (chr
->focus
>= d
->mux_cnt
)
1833 term_timestamps
= !term_timestamps
;
1834 term_timestamps_start
= -1;
1837 } else if (ch
== term_escape_char
) {
1838 d
->term_got_escape
= 1;
1846 static void mux_chr_accept_input(CharDriverState
*chr
)
1849 MuxDriver
*d
= chr
->opaque
;
1851 while (d
->prod
!= d
->cons
&&
1852 d
->chr_can_read
[m
] &&
1853 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1854 d
->chr_read
[m
](d
->ext_opaque
[m
],
1855 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1859 static int mux_chr_can_read(void *opaque
)
1861 CharDriverState
*chr
= opaque
;
1862 MuxDriver
*d
= chr
->opaque
;
1864 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
1866 if (d
->chr_can_read
[chr
->focus
])
1867 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1871 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1873 CharDriverState
*chr
= opaque
;
1874 MuxDriver
*d
= chr
->opaque
;
1878 mux_chr_accept_input (opaque
);
1880 for(i
= 0; i
< size
; i
++)
1881 if (mux_proc_byte(chr
, d
, buf
[i
])) {
1882 if (d
->prod
== d
->cons
&&
1883 d
->chr_can_read
[m
] &&
1884 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
1885 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
1887 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
1891 static void mux_chr_event(void *opaque
, int event
)
1893 CharDriverState
*chr
= opaque
;
1894 MuxDriver
*d
= chr
->opaque
;
1897 /* Send the event to all registered listeners */
1898 for (i
= 0; i
< d
->mux_cnt
; i
++)
1899 if (d
->chr_event
[i
])
1900 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1903 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1905 MuxDriver
*d
= chr
->opaque
;
1907 if (d
->mux_cnt
>= MAX_MUX
) {
1908 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1911 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1912 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1913 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1914 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1915 /* Fix up the real driver with mux routines */
1916 if (d
->mux_cnt
== 0) {
1917 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1918 mux_chr_event
, chr
);
1920 chr
->focus
= d
->mux_cnt
;
1924 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1926 CharDriverState
*chr
;
1929 chr
= qemu_mallocz(sizeof(CharDriverState
));
1932 d
= qemu_mallocz(sizeof(MuxDriver
));
1941 chr
->chr_write
= mux_chr_write
;
1942 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1943 chr
->chr_accept_input
= mux_chr_accept_input
;
1950 static void socket_cleanup(void)
1955 static int socket_init(void)
1960 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1962 err
= WSAGetLastError();
1963 fprintf(stderr
, "WSAStartup: %d\n", err
);
1966 atexit(socket_cleanup
);
1970 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1976 ret
= send(fd
, buf
, len
, 0);
1979 errno
= WSAGetLastError();
1980 if (errno
!= WSAEWOULDBLOCK
) {
1983 } else if (ret
== 0) {
1993 void socket_set_nonblock(int fd
)
1995 unsigned long opt
= 1;
1996 ioctlsocket(fd
, FIONBIO
, &opt
);
2001 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2007 ret
= write(fd
, buf
, len
);
2009 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2011 } else if (ret
== 0) {
2021 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2023 return unix_write(fd
, buf
, len1
);
2026 void socket_set_nonblock(int fd
)
2028 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2030 #endif /* !_WIN32 */
2039 #define STDIO_MAX_CLIENTS 1
2040 static int stdio_nb_clients
= 0;
2042 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2044 FDCharDriver
*s
= chr
->opaque
;
2045 return unix_write(s
->fd_out
, buf
, len
);
2048 static int fd_chr_read_poll(void *opaque
)
2050 CharDriverState
*chr
= opaque
;
2051 FDCharDriver
*s
= chr
->opaque
;
2053 s
->max_size
= qemu_chr_can_read(chr
);
2057 static void fd_chr_read(void *opaque
)
2059 CharDriverState
*chr
= opaque
;
2060 FDCharDriver
*s
= chr
->opaque
;
2065 if (len
> s
->max_size
)
2069 size
= read(s
->fd_in
, buf
, len
);
2071 /* FD has been closed. Remove it from the active list. */
2072 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2076 qemu_chr_read(chr
, buf
, size
);
2080 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2082 FDCharDriver
*s
= chr
->opaque
;
2084 if (s
->fd_in
>= 0) {
2085 if (nographic
&& s
->fd_in
== 0) {
2087 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2088 fd_chr_read
, NULL
, chr
);
2093 static void fd_chr_close(struct CharDriverState
*chr
)
2095 FDCharDriver
*s
= chr
->opaque
;
2097 if (s
->fd_in
>= 0) {
2098 if (nographic
&& s
->fd_in
== 0) {
2100 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2107 /* open a character device to a unix fd */
2108 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2110 CharDriverState
*chr
;
2113 chr
= qemu_mallocz(sizeof(CharDriverState
));
2116 s
= qemu_mallocz(sizeof(FDCharDriver
));
2124 chr
->chr_write
= fd_chr_write
;
2125 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2126 chr
->chr_close
= fd_chr_close
;
2128 qemu_chr_reset(chr
);
2133 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2137 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2140 return qemu_chr_open_fd(-1, fd_out
);
2143 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2146 char filename_in
[256], filename_out
[256];
2148 snprintf(filename_in
, 256, "%s.in", filename
);
2149 snprintf(filename_out
, 256, "%s.out", filename
);
2150 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2151 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2152 if (fd_in
< 0 || fd_out
< 0) {
2157 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2161 return qemu_chr_open_fd(fd_in
, fd_out
);
2165 /* for STDIO, we handle the case where several clients use it
2168 #define TERM_FIFO_MAX_SIZE 1
2170 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2171 static int term_fifo_size
;
2173 static int stdio_read_poll(void *opaque
)
2175 CharDriverState
*chr
= opaque
;
2177 /* try to flush the queue if needed */
2178 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2179 qemu_chr_read(chr
, term_fifo
, 1);
2182 /* see if we can absorb more chars */
2183 if (term_fifo_size
== 0)
2189 static void stdio_read(void *opaque
)
2193 CharDriverState
*chr
= opaque
;
2195 size
= read(0, buf
, 1);
2197 /* stdin has been closed. Remove it from the active list. */
2198 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2202 if (qemu_chr_can_read(chr
) > 0) {
2203 qemu_chr_read(chr
, buf
, 1);
2204 } else if (term_fifo_size
== 0) {
2205 term_fifo
[term_fifo_size
++] = buf
[0];
2210 /* init terminal so that we can grab keys */
2211 static struct termios oldtty
;
2212 static int old_fd0_flags
;
2213 static int term_atexit_done
;
2215 static void term_exit(void)
2217 tcsetattr (0, TCSANOW
, &oldtty
);
2218 fcntl(0, F_SETFL
, old_fd0_flags
);
2221 static void term_init(void)
2225 tcgetattr (0, &tty
);
2227 old_fd0_flags
= fcntl(0, F_GETFL
);
2229 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2230 |INLCR
|IGNCR
|ICRNL
|IXON
);
2231 tty
.c_oflag
|= OPOST
;
2232 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2233 /* if graphical mode, we allow Ctrl-C handling */
2235 tty
.c_lflag
&= ~ISIG
;
2236 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2239 tty
.c_cc
[VTIME
] = 0;
2241 tcsetattr (0, TCSANOW
, &tty
);
2243 if (!term_atexit_done
++)
2246 fcntl(0, F_SETFL
, O_NONBLOCK
);
2249 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2253 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2257 static CharDriverState
*qemu_chr_open_stdio(void)
2259 CharDriverState
*chr
;
2261 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2263 chr
= qemu_chr_open_fd(0, 1);
2264 chr
->chr_close
= qemu_chr_close_stdio
;
2265 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2272 #if defined(__linux__) || defined(__sun__)
2273 static CharDriverState
*qemu_chr_open_pty(void)
2276 char slave_name
[1024];
2277 int master_fd
, slave_fd
;
2279 #if defined(__linux__)
2280 /* Not satisfying */
2281 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
2286 /* Disabling local echo and line-buffered output */
2287 tcgetattr (master_fd
, &tty
);
2288 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
2290 tty
.c_cc
[VTIME
] = 0;
2291 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
2293 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
2294 return qemu_chr_open_fd(master_fd
, master_fd
);
2297 static void tty_serial_init(int fd
, int speed
,
2298 int parity
, int data_bits
, int stop_bits
)
2304 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2305 speed
, parity
, data_bits
, stop_bits
);
2307 tcgetattr (fd
, &tty
);
2310 if (speed
<= 50 * MARGIN
)
2312 else if (speed
<= 75 * MARGIN
)
2314 else if (speed
<= 300 * MARGIN
)
2316 else if (speed
<= 600 * MARGIN
)
2318 else if (speed
<= 1200 * MARGIN
)
2320 else if (speed
<= 2400 * MARGIN
)
2322 else if (speed
<= 4800 * MARGIN
)
2324 else if (speed
<= 9600 * MARGIN
)
2326 else if (speed
<= 19200 * MARGIN
)
2328 else if (speed
<= 38400 * MARGIN
)
2330 else if (speed
<= 57600 * MARGIN
)
2332 else if (speed
<= 115200 * MARGIN
)
2337 cfsetispeed(&tty
, spd
);
2338 cfsetospeed(&tty
, spd
);
2340 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2341 |INLCR
|IGNCR
|ICRNL
|IXON
);
2342 tty
.c_oflag
|= OPOST
;
2343 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2344 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2365 tty
.c_cflag
|= PARENB
;
2368 tty
.c_cflag
|= PARENB
| PARODD
;
2372 tty
.c_cflag
|= CSTOPB
;
2374 tcsetattr (fd
, TCSANOW
, &tty
);
2377 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2379 FDCharDriver
*s
= chr
->opaque
;
2382 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2384 QEMUSerialSetParams
*ssp
= arg
;
2385 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2386 ssp
->data_bits
, ssp
->stop_bits
);
2389 case CHR_IOCTL_SERIAL_SET_BREAK
:
2391 int enable
= *(int *)arg
;
2393 tcsendbreak(s
->fd_in
, 1);
2402 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2404 CharDriverState
*chr
;
2407 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2408 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2409 tty_serial_init(fd
, 115200, 'N', 8, 1);
2410 chr
= qemu_chr_open_fd(fd
, fd
);
2415 chr
->chr_ioctl
= tty_serial_ioctl
;
2416 qemu_chr_reset(chr
);
2419 #else /* ! __linux__ && ! __sun__ */
2420 static CharDriverState
*qemu_chr_open_pty(void)
2424 #endif /* __linux__ || __sun__ */
2426 #if defined(__linux__)
2430 } ParallelCharDriver
;
2432 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2434 if (s
->mode
!= mode
) {
2436 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2443 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2445 ParallelCharDriver
*drv
= chr
->opaque
;
2450 case CHR_IOCTL_PP_READ_DATA
:
2451 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2453 *(uint8_t *)arg
= b
;
2455 case CHR_IOCTL_PP_WRITE_DATA
:
2456 b
= *(uint8_t *)arg
;
2457 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2460 case CHR_IOCTL_PP_READ_CONTROL
:
2461 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2463 /* Linux gives only the lowest bits, and no way to know data
2464 direction! For better compatibility set the fixed upper
2466 *(uint8_t *)arg
= b
| 0xc0;
2468 case CHR_IOCTL_PP_WRITE_CONTROL
:
2469 b
= *(uint8_t *)arg
;
2470 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2473 case CHR_IOCTL_PP_READ_STATUS
:
2474 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2476 *(uint8_t *)arg
= b
;
2478 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2479 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2480 struct ParallelIOArg
*parg
= arg
;
2481 int n
= read(fd
, parg
->buffer
, parg
->count
);
2482 if (n
!= parg
->count
) {
2487 case CHR_IOCTL_PP_EPP_READ
:
2488 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2489 struct ParallelIOArg
*parg
= arg
;
2490 int n
= read(fd
, parg
->buffer
, parg
->count
);
2491 if (n
!= parg
->count
) {
2496 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2497 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2498 struct ParallelIOArg
*parg
= arg
;
2499 int n
= write(fd
, parg
->buffer
, parg
->count
);
2500 if (n
!= parg
->count
) {
2505 case CHR_IOCTL_PP_EPP_WRITE
:
2506 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2507 struct ParallelIOArg
*parg
= arg
;
2508 int n
= write(fd
, parg
->buffer
, parg
->count
);
2509 if (n
!= parg
->count
) {
2520 static void pp_close(CharDriverState
*chr
)
2522 ParallelCharDriver
*drv
= chr
->opaque
;
2525 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2526 ioctl(fd
, PPRELEASE
);
2531 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2533 CharDriverState
*chr
;
2534 ParallelCharDriver
*drv
;
2537 TFR(fd
= open(filename
, O_RDWR
));
2541 if (ioctl(fd
, PPCLAIM
) < 0) {
2546 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2552 drv
->mode
= IEEE1284_MODE_COMPAT
;
2554 chr
= qemu_mallocz(sizeof(CharDriverState
));
2560 chr
->chr_write
= null_chr_write
;
2561 chr
->chr_ioctl
= pp_ioctl
;
2562 chr
->chr_close
= pp_close
;
2565 qemu_chr_reset(chr
);
2569 #endif /* __linux__ */
2575 HANDLE hcom
, hrecv
, hsend
;
2576 OVERLAPPED orecv
, osend
;
2581 #define NSENDBUF 2048
2582 #define NRECVBUF 2048
2583 #define MAXCONNECT 1
2584 #define NTIMEOUT 5000
2586 static int win_chr_poll(void *opaque
);
2587 static int win_chr_pipe_poll(void *opaque
);
2589 static void win_chr_close(CharDriverState
*chr
)
2591 WinCharState
*s
= chr
->opaque
;
2594 CloseHandle(s
->hsend
);
2598 CloseHandle(s
->hrecv
);
2602 CloseHandle(s
->hcom
);
2606 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2608 qemu_del_polling_cb(win_chr_poll
, chr
);
2611 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2613 WinCharState
*s
= chr
->opaque
;
2615 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2620 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2622 fprintf(stderr
, "Failed CreateEvent\n");
2625 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2627 fprintf(stderr
, "Failed CreateEvent\n");
2631 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2632 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2633 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2634 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2639 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2640 fprintf(stderr
, "Failed SetupComm\n");
2644 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2645 size
= sizeof(COMMCONFIG
);
2646 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2647 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2648 CommConfigDialog(filename
, NULL
, &comcfg
);
2650 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2651 fprintf(stderr
, "Failed SetCommState\n");
2655 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2656 fprintf(stderr
, "Failed SetCommMask\n");
2660 cto
.ReadIntervalTimeout
= MAXDWORD
;
2661 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2662 fprintf(stderr
, "Failed SetCommTimeouts\n");
2666 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2667 fprintf(stderr
, "Failed ClearCommError\n");
2670 qemu_add_polling_cb(win_chr_poll
, chr
);
2678 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2680 WinCharState
*s
= chr
->opaque
;
2681 DWORD len
, ret
, size
, err
;
2684 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2685 s
->osend
.hEvent
= s
->hsend
;
2688 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2690 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2692 err
= GetLastError();
2693 if (err
== ERROR_IO_PENDING
) {
2694 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2712 static int win_chr_read_poll(CharDriverState
*chr
)
2714 WinCharState
*s
= chr
->opaque
;
2716 s
->max_size
= qemu_chr_can_read(chr
);
2720 static void win_chr_readfile(CharDriverState
*chr
)
2722 WinCharState
*s
= chr
->opaque
;
2727 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2728 s
->orecv
.hEvent
= s
->hrecv
;
2729 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2731 err
= GetLastError();
2732 if (err
== ERROR_IO_PENDING
) {
2733 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2738 qemu_chr_read(chr
, buf
, size
);
2742 static void win_chr_read(CharDriverState
*chr
)
2744 WinCharState
*s
= chr
->opaque
;
2746 if (s
->len
> s
->max_size
)
2747 s
->len
= s
->max_size
;
2751 win_chr_readfile(chr
);
2754 static int win_chr_poll(void *opaque
)
2756 CharDriverState
*chr
= opaque
;
2757 WinCharState
*s
= chr
->opaque
;
2761 ClearCommError(s
->hcom
, &comerr
, &status
);
2762 if (status
.cbInQue
> 0) {
2763 s
->len
= status
.cbInQue
;
2764 win_chr_read_poll(chr
);
2771 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2773 CharDriverState
*chr
;
2776 chr
= qemu_mallocz(sizeof(CharDriverState
));
2779 s
= qemu_mallocz(sizeof(WinCharState
));
2785 chr
->chr_write
= win_chr_write
;
2786 chr
->chr_close
= win_chr_close
;
2788 if (win_chr_init(chr
, filename
) < 0) {
2793 qemu_chr_reset(chr
);
2797 static int win_chr_pipe_poll(void *opaque
)
2799 CharDriverState
*chr
= opaque
;
2800 WinCharState
*s
= chr
->opaque
;
2803 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2806 win_chr_read_poll(chr
);
2813 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2815 WinCharState
*s
= chr
->opaque
;
2823 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2825 fprintf(stderr
, "Failed CreateEvent\n");
2828 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2830 fprintf(stderr
, "Failed CreateEvent\n");
2834 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2835 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2836 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2838 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2839 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2840 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2845 ZeroMemory(&ov
, sizeof(ov
));
2846 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2847 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2849 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2853 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2855 fprintf(stderr
, "Failed GetOverlappedResult\n");
2857 CloseHandle(ov
.hEvent
);
2864 CloseHandle(ov
.hEvent
);
2867 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2876 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2878 CharDriverState
*chr
;
2881 chr
= qemu_mallocz(sizeof(CharDriverState
));
2884 s
= qemu_mallocz(sizeof(WinCharState
));
2890 chr
->chr_write
= win_chr_write
;
2891 chr
->chr_close
= win_chr_close
;
2893 if (win_chr_pipe_init(chr
, filename
) < 0) {
2898 qemu_chr_reset(chr
);
2902 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2904 CharDriverState
*chr
;
2907 chr
= qemu_mallocz(sizeof(CharDriverState
));
2910 s
= qemu_mallocz(sizeof(WinCharState
));
2917 chr
->chr_write
= win_chr_write
;
2918 qemu_chr_reset(chr
);
2922 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
2924 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
2927 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2931 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2932 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2933 if (fd_out
== INVALID_HANDLE_VALUE
)
2936 return qemu_chr_open_win_file(fd_out
);
2938 #endif /* !_WIN32 */
2940 /***********************************************************/
2941 /* UDP Net console */
2945 struct sockaddr_in daddr
;
2952 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2954 NetCharDriver
*s
= chr
->opaque
;
2956 return sendto(s
->fd
, buf
, len
, 0,
2957 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2960 static int udp_chr_read_poll(void *opaque
)
2962 CharDriverState
*chr
= opaque
;
2963 NetCharDriver
*s
= chr
->opaque
;
2965 s
->max_size
= qemu_chr_can_read(chr
);
2967 /* If there were any stray characters in the queue process them
2970 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2971 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2973 s
->max_size
= qemu_chr_can_read(chr
);
2978 static void udp_chr_read(void *opaque
)
2980 CharDriverState
*chr
= opaque
;
2981 NetCharDriver
*s
= chr
->opaque
;
2983 if (s
->max_size
== 0)
2985 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2986 s
->bufptr
= s
->bufcnt
;
2991 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2992 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2994 s
->max_size
= qemu_chr_can_read(chr
);
2998 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3000 NetCharDriver
*s
= chr
->opaque
;
3003 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3004 udp_chr_read
, NULL
, chr
);
3008 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3010 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3012 int parse_host_src_port(struct sockaddr_in
*haddr
,
3013 struct sockaddr_in
*saddr
,
3016 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3018 CharDriverState
*chr
= NULL
;
3019 NetCharDriver
*s
= NULL
;
3021 struct sockaddr_in saddr
;
3023 chr
= qemu_mallocz(sizeof(CharDriverState
));
3026 s
= qemu_mallocz(sizeof(NetCharDriver
));
3030 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3032 perror("socket(PF_INET, SOCK_DGRAM)");
3036 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3037 printf("Could not parse: %s\n", def
);
3041 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3051 chr
->chr_write
= udp_chr_write
;
3052 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3065 /***********************************************************/
3066 /* TCP Net console */
3077 static void tcp_chr_accept(void *opaque
);
3079 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3081 TCPCharDriver
*s
= chr
->opaque
;
3083 return send_all(s
->fd
, buf
, len
);
3085 /* XXX: indicate an error ? */
3090 static int tcp_chr_read_poll(void *opaque
)
3092 CharDriverState
*chr
= opaque
;
3093 TCPCharDriver
*s
= chr
->opaque
;
3096 s
->max_size
= qemu_chr_can_read(chr
);
3101 #define IAC_BREAK 243
3102 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3104 uint8_t *buf
, int *size
)
3106 /* Handle any telnet client's basic IAC options to satisfy char by
3107 * char mode with no echo. All IAC options will be removed from
3108 * the buf and the do_telnetopt variable will be used to track the
3109 * state of the width of the IAC information.
3111 * IAC commands come in sets of 3 bytes with the exception of the
3112 * "IAC BREAK" command and the double IAC.
3118 for (i
= 0; i
< *size
; i
++) {
3119 if (s
->do_telnetopt
> 1) {
3120 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3121 /* Double IAC means send an IAC */
3125 s
->do_telnetopt
= 1;
3127 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3128 /* Handle IAC break commands by sending a serial break */
3129 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3134 if (s
->do_telnetopt
>= 4) {
3135 s
->do_telnetopt
= 1;
3138 if ((unsigned char)buf
[i
] == IAC
) {
3139 s
->do_telnetopt
= 2;
3150 static void tcp_chr_read(void *opaque
)
3152 CharDriverState
*chr
= opaque
;
3153 TCPCharDriver
*s
= chr
->opaque
;
3157 if (!s
->connected
|| s
->max_size
<= 0)
3160 if (len
> s
->max_size
)
3162 size
= recv(s
->fd
, buf
, len
, 0);
3164 /* connection closed */
3166 if (s
->listen_fd
>= 0) {
3167 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3169 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3172 } else if (size
> 0) {
3173 if (s
->do_telnetopt
)
3174 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3176 qemu_chr_read(chr
, buf
, size
);
3180 static void tcp_chr_connect(void *opaque
)
3182 CharDriverState
*chr
= opaque
;
3183 TCPCharDriver
*s
= chr
->opaque
;
3186 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3187 tcp_chr_read
, NULL
, chr
);
3188 qemu_chr_reset(chr
);
3191 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3192 static void tcp_chr_telnet_init(int fd
)
3195 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3196 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3197 send(fd
, (char *)buf
, 3, 0);
3198 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3199 send(fd
, (char *)buf
, 3, 0);
3200 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3201 send(fd
, (char *)buf
, 3, 0);
3202 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3203 send(fd
, (char *)buf
, 3, 0);
3206 static void socket_set_nodelay(int fd
)
3209 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3212 static void tcp_chr_accept(void *opaque
)
3214 CharDriverState
*chr
= opaque
;
3215 TCPCharDriver
*s
= chr
->opaque
;
3216 struct sockaddr_in saddr
;
3218 struct sockaddr_un uaddr
;
3220 struct sockaddr
*addr
;
3227 len
= sizeof(uaddr
);
3228 addr
= (struct sockaddr
*)&uaddr
;
3232 len
= sizeof(saddr
);
3233 addr
= (struct sockaddr
*)&saddr
;
3235 fd
= accept(s
->listen_fd
, addr
, &len
);
3236 if (fd
< 0 && errno
!= EINTR
) {
3238 } else if (fd
>= 0) {
3239 if (s
->do_telnetopt
)
3240 tcp_chr_telnet_init(fd
);
3244 socket_set_nonblock(fd
);
3246 socket_set_nodelay(fd
);
3248 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3249 tcp_chr_connect(chr
);
3252 static void tcp_chr_close(CharDriverState
*chr
)
3254 TCPCharDriver
*s
= chr
->opaque
;
3257 if (s
->listen_fd
>= 0)
3258 closesocket(s
->listen_fd
);
3262 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3266 CharDriverState
*chr
= NULL
;
3267 TCPCharDriver
*s
= NULL
;
3268 int fd
= -1, ret
, err
, val
;
3270 int is_waitconnect
= 1;
3273 struct sockaddr_in saddr
;
3275 struct sockaddr_un uaddr
;
3277 struct sockaddr
*addr
;
3282 addr
= (struct sockaddr
*)&uaddr
;
3283 addrlen
= sizeof(uaddr
);
3284 if (parse_unix_path(&uaddr
, host_str
) < 0)
3289 addr
= (struct sockaddr
*)&saddr
;
3290 addrlen
= sizeof(saddr
);
3291 if (parse_host_port(&saddr
, host_str
) < 0)
3296 while((ptr
= strchr(ptr
,','))) {
3298 if (!strncmp(ptr
,"server",6)) {
3300 } else if (!strncmp(ptr
,"nowait",6)) {
3302 } else if (!strncmp(ptr
,"nodelay",6)) {
3305 printf("Unknown option: %s\n", ptr
);
3312 chr
= qemu_mallocz(sizeof(CharDriverState
));
3315 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3321 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3324 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3329 if (!is_waitconnect
)
3330 socket_set_nonblock(fd
);
3335 s
->is_unix
= is_unix
;
3336 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3339 chr
->chr_write
= tcp_chr_write
;
3340 chr
->chr_close
= tcp_chr_close
;
3343 /* allow fast reuse */
3347 strncpy(path
, uaddr
.sun_path
, 108);
3354 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3357 ret
= bind(fd
, addr
, addrlen
);
3361 ret
= listen(fd
, 0);
3366 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3368 s
->do_telnetopt
= 1;
3371 ret
= connect(fd
, addr
, addrlen
);
3373 err
= socket_error();
3374 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3375 } else if (err
== EINPROGRESS
) {
3378 } else if (err
== WSAEALREADY
) {
3390 socket_set_nodelay(fd
);
3392 tcp_chr_connect(chr
);
3394 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3397 if (is_listen
&& is_waitconnect
) {
3398 printf("QEMU waiting for connection on: %s\n", host_str
);
3399 tcp_chr_accept(chr
);
3400 socket_set_nonblock(s
->listen_fd
);
3412 CharDriverState
*qemu_chr_open(const char *filename
)
3416 if (!strcmp(filename
, "vc")) {
3417 return text_console_init(&display_state
, 0);
3418 } else if (strstart(filename
, "vc:", &p
)) {
3419 return text_console_init(&display_state
, p
);
3420 } else if (!strcmp(filename
, "null")) {
3421 return qemu_chr_open_null();
3423 if (strstart(filename
, "tcp:", &p
)) {
3424 return qemu_chr_open_tcp(p
, 0, 0);
3426 if (strstart(filename
, "telnet:", &p
)) {
3427 return qemu_chr_open_tcp(p
, 1, 0);
3429 if (strstart(filename
, "udp:", &p
)) {
3430 return qemu_chr_open_udp(p
);
3432 if (strstart(filename
, "mon:", &p
)) {
3433 CharDriverState
*drv
= qemu_chr_open(p
);
3435 drv
= qemu_chr_open_mux(drv
);
3436 monitor_init(drv
, !nographic
);
3439 printf("Unable to open driver: %s\n", p
);
3443 if (strstart(filename
, "unix:", &p
)) {
3444 return qemu_chr_open_tcp(p
, 0, 1);
3445 } else if (strstart(filename
, "file:", &p
)) {
3446 return qemu_chr_open_file_out(p
);
3447 } else if (strstart(filename
, "pipe:", &p
)) {
3448 return qemu_chr_open_pipe(p
);
3449 } else if (!strcmp(filename
, "pty")) {
3450 return qemu_chr_open_pty();
3451 } else if (!strcmp(filename
, "stdio")) {
3452 return qemu_chr_open_stdio();
3454 #if defined(__linux__)
3455 if (strstart(filename
, "/dev/parport", NULL
)) {
3456 return qemu_chr_open_pp(filename
);
3459 #if defined(__linux__) || defined(__sun__)
3460 if (strstart(filename
, "/dev/", NULL
)) {
3461 return qemu_chr_open_tty(filename
);
3465 if (strstart(filename
, "COM", NULL
)) {
3466 return qemu_chr_open_win(filename
);
3468 if (strstart(filename
, "pipe:", &p
)) {
3469 return qemu_chr_open_win_pipe(p
);
3471 if (strstart(filename
, "con:", NULL
)) {
3472 return qemu_chr_open_win_con(filename
);
3474 if (strstart(filename
, "file:", &p
)) {
3475 return qemu_chr_open_win_file_out(p
);
3478 #ifdef CONFIG_BRLAPI
3479 if (!strcmp(filename
, "braille")) {
3480 return chr_baum_init();
3488 void qemu_chr_close(CharDriverState
*chr
)
3491 chr
->chr_close(chr
);
3495 /***********************************************************/
3496 /* network device redirectors */
3498 __attribute__ (( unused
))
3499 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3503 for(i
=0;i
<size
;i
+=16) {
3507 fprintf(f
, "%08x ", i
);
3510 fprintf(f
, " %02x", buf
[i
+j
]);
3515 for(j
=0;j
<len
;j
++) {
3517 if (c
< ' ' || c
> '~')
3519 fprintf(f
, "%c", c
);
3525 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3532 offset
= strtol(p
, &last_char
, 0);
3533 if (0 == errno
&& '\0' == *last_char
&&
3534 offset
>= 0 && offset
<= 0xFFFFFF) {
3535 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3536 macaddr
[4] = (offset
& 0xFF00) >> 8;
3537 macaddr
[5] = offset
& 0xFF;
3540 for(i
= 0; i
< 6; i
++) {
3541 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3546 if (*p
!= ':' && *p
!= '-')
3557 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3562 p1
= strchr(p
, sep
);
3568 if (len
> buf_size
- 1)
3570 memcpy(buf
, p
, len
);
3577 int parse_host_src_port(struct sockaddr_in
*haddr
,
3578 struct sockaddr_in
*saddr
,
3579 const char *input_str
)
3581 char *str
= strdup(input_str
);
3582 char *host_str
= str
;
3587 * Chop off any extra arguments at the end of the string which
3588 * would start with a comma, then fill in the src port information
3589 * if it was provided else use the "any address" and "any port".
3591 if ((ptr
= strchr(str
,',')))
3594 if ((src_str
= strchr(input_str
,'@'))) {
3599 if (parse_host_port(haddr
, host_str
) < 0)
3602 if (!src_str
|| *src_str
== '\0')
3605 if (parse_host_port(saddr
, src_str
) < 0)
3616 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3624 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3626 saddr
->sin_family
= AF_INET
;
3627 if (buf
[0] == '\0') {
3628 saddr
->sin_addr
.s_addr
= 0;
3630 if (isdigit(buf
[0])) {
3631 if (!inet_aton(buf
, &saddr
->sin_addr
))
3634 if ((he
= gethostbyname(buf
)) == NULL
)
3636 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3639 port
= strtol(p
, (char **)&r
, 0);
3642 saddr
->sin_port
= htons(port
);
3647 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3652 len
= MIN(108, strlen(str
));
3653 p
= strchr(str
, ',');
3655 len
= MIN(len
, p
- str
);
3657 memset(uaddr
, 0, sizeof(*uaddr
));
3659 uaddr
->sun_family
= AF_UNIX
;
3660 memcpy(uaddr
->sun_path
, str
, len
);
3666 /* find or alloc a new VLAN */
3667 VLANState
*qemu_find_vlan(int id
)
3669 VLANState
**pvlan
, *vlan
;
3670 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3674 vlan
= qemu_mallocz(sizeof(VLANState
));
3679 pvlan
= &first_vlan
;
3680 while (*pvlan
!= NULL
)
3681 pvlan
= &(*pvlan
)->next
;
3686 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3687 IOReadHandler
*fd_read
,
3688 IOCanRWHandler
*fd_can_read
,
3691 VLANClientState
*vc
, **pvc
;
3692 vc
= qemu_mallocz(sizeof(VLANClientState
));
3695 vc
->fd_read
= fd_read
;
3696 vc
->fd_can_read
= fd_can_read
;
3697 vc
->opaque
= opaque
;
3701 pvc
= &vlan
->first_client
;
3702 while (*pvc
!= NULL
)
3703 pvc
= &(*pvc
)->next
;
3708 int qemu_can_send_packet(VLANClientState
*vc1
)
3710 VLANState
*vlan
= vc1
->vlan
;
3711 VLANClientState
*vc
;
3713 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3715 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
3722 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3724 VLANState
*vlan
= vc1
->vlan
;
3725 VLANClientState
*vc
;
3728 printf("vlan %d send:\n", vlan
->id
);
3729 hex_dump(stdout
, buf
, size
);
3731 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3733 vc
->fd_read(vc
->opaque
, buf
, size
);
3738 #if defined(CONFIG_SLIRP)
3740 /* slirp network adapter */
3742 static int slirp_inited
;
3743 static VLANClientState
*slirp_vc
;
3745 int slirp_can_output(void)
3747 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3750 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3753 printf("slirp output:\n");
3754 hex_dump(stdout
, pkt
, pkt_len
);
3758 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3761 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3764 printf("slirp input:\n");
3765 hex_dump(stdout
, buf
, size
);
3767 slirp_input(buf
, size
);
3770 static int net_slirp_init(VLANState
*vlan
)
3772 if (!slirp_inited
) {
3776 slirp_vc
= qemu_new_vlan_client(vlan
,
3777 slirp_receive
, NULL
, NULL
);
3778 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3782 static void net_slirp_redir(const char *redir_str
)
3787 struct in_addr guest_addr
;
3788 int host_port
, guest_port
;
3790 if (!slirp_inited
) {
3796 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3798 if (!strcmp(buf
, "tcp")) {
3800 } else if (!strcmp(buf
, "udp")) {
3806 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3808 host_port
= strtol(buf
, &r
, 0);
3812 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3814 if (buf
[0] == '\0') {
3815 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3817 if (!inet_aton(buf
, &guest_addr
))
3820 guest_port
= strtol(p
, &r
, 0);
3824 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3825 fprintf(stderr
, "qemu: could not set up redirection\n");
3830 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3838 static void erase_dir(char *dir_name
)
3842 char filename
[1024];
3844 /* erase all the files in the directory */
3845 if ((d
= opendir(dir_name
)) != 0) {
3850 if (strcmp(de
->d_name
, ".") != 0 &&
3851 strcmp(de
->d_name
, "..") != 0) {
3852 snprintf(filename
, sizeof(filename
), "%s/%s",
3853 smb_dir
, de
->d_name
);
3854 if (unlink(filename
) != 0) /* is it a directory? */
3855 erase_dir(filename
);
3863 /* automatic user mode samba server configuration */
3864 static void smb_exit(void)
3869 /* automatic user mode samba server configuration */
3870 static void net_slirp_smb(const char *exported_dir
)
3872 char smb_conf
[1024];
3873 char smb_cmdline
[1024];
3876 if (!slirp_inited
) {
3881 /* XXX: better tmp dir construction */
3882 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3883 if (mkdir(smb_dir
, 0700) < 0) {
3884 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3887 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3889 f
= fopen(smb_conf
, "w");
3891 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3898 "socket address=127.0.0.1\n"
3899 "pid directory=%s\n"
3900 "lock directory=%s\n"
3901 "log file=%s/log.smbd\n"
3902 "smb passwd file=%s/smbpasswd\n"
3903 "security = share\n"
3918 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3919 SMBD_COMMAND
, smb_conf
);
3921 slirp_add_exec(0, smb_cmdline
, 4, 139);
3924 #endif /* !defined(_WIN32) */
3925 void do_info_slirp(void)
3930 #endif /* CONFIG_SLIRP */
3932 #if !defined(_WIN32)
3934 typedef struct TAPState
{
3935 VLANClientState
*vc
;
3937 char down_script
[1024];
3940 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3942 TAPState
*s
= opaque
;
3945 ret
= write(s
->fd
, buf
, size
);
3946 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3953 static void tap_send(void *opaque
)
3955 TAPState
*s
= opaque
;
3962 sbuf
.maxlen
= sizeof(buf
);
3964 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3966 size
= read(s
->fd
, buf
, sizeof(buf
));
3969 qemu_send_packet(s
->vc
, buf
, size
);
3975 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3979 s
= qemu_mallocz(sizeof(TAPState
));
3983 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3984 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3985 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3989 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3990 static int tap_open(char *ifname
, int ifname_size
)
3996 TFR(fd
= open("/dev/tap", O_RDWR
));
3998 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4003 dev
= devname(s
.st_rdev
, S_IFCHR
);
4004 pstrcpy(ifname
, ifname_size
, dev
);
4006 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4009 #elif defined(__sun__)
4010 #define TUNNEWPPA (('T'<<16) | 0x0001)
4012 * Allocate TAP device, returns opened fd.
4013 * Stores dev name in the first arg(must be large enough).
4015 int tap_alloc(char *dev
)
4017 int tap_fd
, if_fd
, ppa
= -1;
4018 static int ip_fd
= 0;
4021 static int arp_fd
= 0;
4022 int ip_muxid
, arp_muxid
;
4023 struct strioctl strioc_if
, strioc_ppa
;
4024 int link_type
= I_PLINK
;;
4026 char actual_name
[32] = "";
4028 memset(&ifr
, 0x0, sizeof(ifr
));
4032 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4036 /* Check if IP device was opened */
4040 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4042 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4046 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4048 syslog(LOG_ERR
, "Can't open /dev/tap");
4052 /* Assign a new PPA and get its unit number. */
4053 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4054 strioc_ppa
.ic_timout
= 0;
4055 strioc_ppa
.ic_len
= sizeof(ppa
);
4056 strioc_ppa
.ic_dp
= (char *)&ppa
;
4057 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4058 syslog (LOG_ERR
, "Can't assign new interface");
4060 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4062 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4065 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4066 syslog(LOG_ERR
, "Can't push IP module");
4070 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4071 syslog(LOG_ERR
, "Can't get flags\n");
4073 snprintf (actual_name
, 32, "tap%d", ppa
);
4074 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4077 /* Assign ppa according to the unit number returned by tun device */
4079 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4080 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4081 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4082 syslog (LOG_ERR
, "Can't get flags\n");
4083 /* Push arp module to if_fd */
4084 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4085 syslog (LOG_ERR
, "Can't push ARP module (2)");
4087 /* Push arp module to ip_fd */
4088 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4089 syslog (LOG_ERR
, "I_POP failed\n");
4090 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4091 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4093 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4095 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4097 /* Set ifname to arp */
4098 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4099 strioc_if
.ic_timout
= 0;
4100 strioc_if
.ic_len
= sizeof(ifr
);
4101 strioc_if
.ic_dp
= (char *)&ifr
;
4102 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4103 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4106 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4107 syslog(LOG_ERR
, "Can't link TAP device to IP");
4111 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4112 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4116 memset(&ifr
, 0x0, sizeof(ifr
));
4117 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4118 ifr
.lifr_ip_muxid
= ip_muxid
;
4119 ifr
.lifr_arp_muxid
= arp_muxid
;
4121 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4123 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4124 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4125 syslog (LOG_ERR
, "Can't set multiplexor id");
4128 sprintf(dev
, "tap%d", ppa
);
4132 static int tap_open(char *ifname
, int ifname_size
)
4136 if( (fd
= tap_alloc(dev
)) < 0 ){
4137 fprintf(stderr
, "Cannot allocate TAP device\n");
4140 pstrcpy(ifname
, ifname_size
, dev
);
4141 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4145 static int tap_open(char *ifname
, int ifname_size
)
4150 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4152 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4155 memset(&ifr
, 0, sizeof(ifr
));
4156 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4157 if (ifname
[0] != '\0')
4158 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4160 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4161 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4163 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4167 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4168 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4173 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4179 /* try to launch network script */
4183 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4184 for (i
= 0; i
< open_max
; i
++)
4185 if (i
!= STDIN_FILENO
&&
4186 i
!= STDOUT_FILENO
&&
4187 i
!= STDERR_FILENO
&&
4192 *parg
++ = (char *)setup_script
;
4193 *parg
++ = (char *)ifname
;
4195 execv(setup_script
, args
);
4198 while (waitpid(pid
, &status
, 0) != pid
);
4199 if (!WIFEXITED(status
) ||
4200 WEXITSTATUS(status
) != 0) {
4201 fprintf(stderr
, "%s: could not launch network script\n",
4209 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4210 const char *setup_script
, const char *down_script
)
4216 if (ifname1
!= NULL
)
4217 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4220 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4224 if (!setup_script
|| !strcmp(setup_script
, "no"))
4226 if (setup_script
[0] != '\0') {
4227 if (launch_script(setup_script
, ifname
, fd
))
4230 s
= net_tap_fd_init(vlan
, fd
);
4233 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4234 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4235 if (down_script
&& strcmp(down_script
, "no"))
4236 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4240 #endif /* !_WIN32 */
4242 /* network connection */
4243 typedef struct NetSocketState
{
4244 VLANClientState
*vc
;
4246 int state
; /* 0 = getting length, 1 = getting data */
4250 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4253 typedef struct NetSocketListenState
{
4256 } NetSocketListenState
;
4258 /* XXX: we consider we can send the whole packet without blocking */
4259 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4261 NetSocketState
*s
= opaque
;
4265 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4266 send_all(s
->fd
, buf
, size
);
4269 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4271 NetSocketState
*s
= opaque
;
4272 sendto(s
->fd
, buf
, size
, 0,
4273 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4276 static void net_socket_send(void *opaque
)
4278 NetSocketState
*s
= opaque
;
4283 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4285 err
= socket_error();
4286 if (err
!= EWOULDBLOCK
)
4288 } else if (size
== 0) {
4289 /* end of connection */
4291 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4297 /* reassemble a packet from the network */
4303 memcpy(s
->buf
+ s
->index
, buf
, l
);
4307 if (s
->index
== 4) {
4309 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4315 l
= s
->packet_len
- s
->index
;
4318 memcpy(s
->buf
+ s
->index
, buf
, l
);
4322 if (s
->index
>= s
->packet_len
) {
4323 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4332 static void net_socket_send_dgram(void *opaque
)
4334 NetSocketState
*s
= opaque
;
4337 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4341 /* end of connection */
4342 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4345 qemu_send_packet(s
->vc
, s
->buf
, size
);
4348 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4353 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4354 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4355 inet_ntoa(mcastaddr
->sin_addr
),
4356 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4360 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4362 perror("socket(PF_INET, SOCK_DGRAM)");
4367 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4368 (const char *)&val
, sizeof(val
));
4370 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4374 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4380 /* Add host to multicast group */
4381 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4382 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4384 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4385 (const char *)&imr
, sizeof(struct ip_mreq
));
4387 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4391 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4393 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4394 (const char *)&val
, sizeof(val
));
4396 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4400 socket_set_nonblock(fd
);
4408 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4411 struct sockaddr_in saddr
;
4413 socklen_t saddr_len
;
4416 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4417 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4418 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4422 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4424 if (saddr
.sin_addr
.s_addr
==0) {
4425 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4429 /* clone dgram socket */
4430 newfd
= net_socket_mcast_create(&saddr
);
4432 /* error already reported by net_socket_mcast_create() */
4436 /* clone newfd to fd, close newfd */
4441 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4442 fd
, strerror(errno
));
4447 s
= qemu_mallocz(sizeof(NetSocketState
));
4452 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4453 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4455 /* mcast: save bound address as dst */
4456 if (is_connected
) s
->dgram_dst
=saddr
;
4458 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4459 "socket: fd=%d (%s mcast=%s:%d)",
4460 fd
, is_connected
? "cloned" : "",
4461 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4465 static void net_socket_connect(void *opaque
)
4467 NetSocketState
*s
= opaque
;
4468 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4471 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4475 s
= qemu_mallocz(sizeof(NetSocketState
));
4479 s
->vc
= qemu_new_vlan_client(vlan
,
4480 net_socket_receive
, NULL
, s
);
4481 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4482 "socket: fd=%d", fd
);
4484 net_socket_connect(s
);
4486 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4491 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4494 int so_type
=-1, optlen
=sizeof(so_type
);
4496 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4497 (socklen_t
*)&optlen
)< 0) {
4498 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4503 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4505 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4507 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4508 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4509 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4514 static void net_socket_accept(void *opaque
)
4516 NetSocketListenState
*s
= opaque
;
4518 struct sockaddr_in saddr
;
4523 len
= sizeof(saddr
);
4524 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4525 if (fd
< 0 && errno
!= EINTR
) {
4527 } else if (fd
>= 0) {
4531 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4535 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4536 "socket: connection from %s:%d",
4537 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4541 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4543 NetSocketListenState
*s
;
4545 struct sockaddr_in saddr
;
4547 if (parse_host_port(&saddr
, host_str
) < 0)
4550 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4554 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4559 socket_set_nonblock(fd
);
4561 /* allow fast reuse */
4563 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4565 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4570 ret
= listen(fd
, 0);
4577 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4581 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4584 int fd
, connected
, ret
, err
;
4585 struct sockaddr_in saddr
;
4587 if (parse_host_port(&saddr
, host_str
) < 0)
4590 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4595 socket_set_nonblock(fd
);
4599 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4601 err
= socket_error();
4602 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4603 } else if (err
== EINPROGRESS
) {
4606 } else if (err
== WSAEALREADY
) {
4619 s
= net_socket_fd_init(vlan
, fd
, connected
);
4622 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4623 "socket: connect to %s:%d",
4624 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4628 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4632 struct sockaddr_in saddr
;
4634 if (parse_host_port(&saddr
, host_str
) < 0)
4638 fd
= net_socket_mcast_create(&saddr
);
4642 s
= net_socket_fd_init(vlan
, fd
, 0);
4646 s
->dgram_dst
= saddr
;
4648 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4649 "socket: mcast=%s:%d",
4650 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4655 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
4660 while (*p
!= '\0' && *p
!= '=') {
4661 if (q
&& (q
- buf
) < buf_size
- 1)
4671 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
4676 while (*p
!= '\0') {
4678 if (*(p
+ 1) != ',')
4682 if (q
&& (q
- buf
) < buf_size
- 1)
4692 static int get_param_value(char *buf
, int buf_size
,
4693 const char *tag
, const char *str
)
4700 p
= get_opt_name(option
, sizeof(option
), p
);
4704 if (!strcmp(tag
, option
)) {
4705 (void)get_opt_value(buf
, buf_size
, p
);
4708 p
= get_opt_value(NULL
, 0, p
);
4717 static int check_params(char *buf
, int buf_size
,
4718 char **params
, const char *str
)
4725 p
= get_opt_name(buf
, buf_size
, p
);
4729 for(i
= 0; params
[i
] != NULL
; i
++)
4730 if (!strcmp(params
[i
], buf
))
4732 if (params
[i
] == NULL
)
4734 p
= get_opt_value(NULL
, 0, p
);
4743 static int net_client_init(const char *str
)
4754 while (*p
!= '\0' && *p
!= ',') {
4755 if ((q
- device
) < sizeof(device
) - 1)
4763 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4764 vlan_id
= strtol(buf
, NULL
, 0);
4766 vlan
= qemu_find_vlan(vlan_id
);
4768 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4771 if (!strcmp(device
, "nic")) {
4775 if (nb_nics
>= MAX_NICS
) {
4776 fprintf(stderr
, "Too Many NICs\n");
4779 nd
= &nd_table
[nb_nics
];
4780 macaddr
= nd
->macaddr
;
4786 macaddr
[5] = 0x56 + nb_nics
;
4788 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4789 if (parse_macaddr(macaddr
, buf
) < 0) {
4790 fprintf(stderr
, "invalid syntax for ethernet address\n");
4794 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4795 nd
->model
= strdup(buf
);
4799 vlan
->nb_guest_devs
++;
4802 if (!strcmp(device
, "none")) {
4803 /* does nothing. It is needed to signal that no network cards
4808 if (!strcmp(device
, "user")) {
4809 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4810 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4812 vlan
->nb_host_devs
++;
4813 ret
= net_slirp_init(vlan
);
4817 if (!strcmp(device
, "tap")) {
4819 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4820 fprintf(stderr
, "tap: no interface name\n");
4823 vlan
->nb_host_devs
++;
4824 ret
= tap_win32_init(vlan
, ifname
);
4827 if (!strcmp(device
, "tap")) {
4829 char setup_script
[1024], down_script
[1024];
4831 vlan
->nb_host_devs
++;
4832 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4833 fd
= strtol(buf
, NULL
, 0);
4834 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4836 if (net_tap_fd_init(vlan
, fd
))
4839 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4842 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4843 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4845 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
4846 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
4848 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
4852 if (!strcmp(device
, "socket")) {
4853 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4855 fd
= strtol(buf
, NULL
, 0);
4857 if (net_socket_fd_init(vlan
, fd
, 1))
4859 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4860 ret
= net_socket_listen_init(vlan
, buf
);
4861 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4862 ret
= net_socket_connect_init(vlan
, buf
);
4863 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4864 ret
= net_socket_mcast_init(vlan
, buf
);
4866 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4869 vlan
->nb_host_devs
++;
4872 fprintf(stderr
, "Unknown network device: %s\n", device
);
4876 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4882 void do_info_network(void)
4885 VLANClientState
*vc
;
4887 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4888 term_printf("VLAN %d devices:\n", vlan
->id
);
4889 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4890 term_printf(" %s\n", vc
->info_str
);
4894 #define HD_ALIAS "index=%d,media=disk"
4896 #define CDROM_ALIAS "index=1,media=cdrom"
4898 #define CDROM_ALIAS "index=2,media=cdrom"
4900 #define FD_ALIAS "index=%d,if=floppy"
4901 #define PFLASH_ALIAS "if=pflash"
4902 #define MTD_ALIAS "if=mtd"
4903 #define SD_ALIAS "index=0,if=sd"
4905 static int drive_add(const char *file
, const char *fmt
, ...)
4909 if (nb_drives_opt
>= MAX_DRIVES
) {
4910 fprintf(stderr
, "qemu: too many drives\n");
4914 drives_opt
[nb_drives_opt
].file
= file
;
4916 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
4917 sizeof(drives_opt
[0].opt
), fmt
, ap
);
4920 return nb_drives_opt
++;
4923 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
4927 /* seek interface, bus and unit */
4929 for (index
= 0; index
< nb_drives
; index
++)
4930 if (drives_table
[index
].type
== type
&&
4931 drives_table
[index
].bus
== bus
&&
4932 drives_table
[index
].unit
== unit
)
4938 int drive_get_max_bus(BlockInterfaceType type
)
4944 for (index
= 0; index
< nb_drives
; index
++) {
4945 if(drives_table
[index
].type
== type
&&
4946 drives_table
[index
].bus
> max_bus
)
4947 max_bus
= drives_table
[index
].bus
;
4952 static int drive_init(struct drive_opt
*arg
, int snapshot
,
4953 QEMUMachine
*machine
)
4958 const char *mediastr
= "";
4959 BlockInterfaceType type
;
4960 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
4961 int bus_id
, unit_id
;
4962 int cyls
, heads
, secs
, translation
;
4963 BlockDriverState
*bdrv
;
4964 BlockDriver
*drv
= NULL
;
4969 char *str
= arg
->opt
;
4970 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
4971 "secs", "trans", "media", "snapshot", "file",
4972 "cache", "format", NULL
};
4974 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
4975 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
4981 cyls
= heads
= secs
= 0;
4984 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4988 if (!strcmp(machine
->name
, "realview") ||
4989 !strcmp(machine
->name
, "SS-5") ||
4990 !strcmp(machine
->name
, "SS-10") ||
4991 !strcmp(machine
->name
, "SS-600MP") ||
4992 !strcmp(machine
->name
, "versatilepb") ||
4993 !strcmp(machine
->name
, "versatileab")) {
4995 max_devs
= MAX_SCSI_DEVS
;
4996 strcpy(devname
, "scsi");
4999 max_devs
= MAX_IDE_DEVS
;
5000 strcpy(devname
, "ide");
5004 /* extract parameters */
5006 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5007 bus_id
= strtol(buf
, NULL
, 0);
5009 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5014 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5015 unit_id
= strtol(buf
, NULL
, 0);
5017 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5022 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5023 strncpy(devname
, buf
, sizeof(devname
));
5024 if (!strcmp(buf
, "ide")) {
5026 max_devs
= MAX_IDE_DEVS
;
5027 } else if (!strcmp(buf
, "scsi")) {
5029 max_devs
= MAX_SCSI_DEVS
;
5030 } else if (!strcmp(buf
, "floppy")) {
5033 } else if (!strcmp(buf
, "pflash")) {
5036 } else if (!strcmp(buf
, "mtd")) {
5039 } else if (!strcmp(buf
, "sd")) {
5043 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5048 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5049 index
= strtol(buf
, NULL
, 0);
5051 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5056 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5057 cyls
= strtol(buf
, NULL
, 0);
5060 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5061 heads
= strtol(buf
, NULL
, 0);
5064 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5065 secs
= strtol(buf
, NULL
, 0);
5068 if (cyls
|| heads
|| secs
) {
5069 if (cyls
< 1 || cyls
> 16383) {
5070 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5073 if (heads
< 1 || heads
> 16) {
5074 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5077 if (secs
< 1 || secs
> 63) {
5078 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5083 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5086 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5090 if (!strcmp(buf
, "none"))
5091 translation
= BIOS_ATA_TRANSLATION_NONE
;
5092 else if (!strcmp(buf
, "lba"))
5093 translation
= BIOS_ATA_TRANSLATION_LBA
;
5094 else if (!strcmp(buf
, "auto"))
5095 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5097 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5102 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5103 if (!strcmp(buf
, "disk")) {
5105 } else if (!strcmp(buf
, "cdrom")) {
5106 if (cyls
|| secs
|| heads
) {
5108 "qemu: '%s' invalid physical CHS format\n", str
);
5111 media
= MEDIA_CDROM
;
5113 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5118 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5119 if (!strcmp(buf
, "on"))
5121 else if (!strcmp(buf
, "off"))
5124 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5129 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5130 if (!strcmp(buf
, "off"))
5132 else if (!strcmp(buf
, "on"))
5135 fprintf(stderr
, "qemu: invalid cache option\n");
5140 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5141 drv
= bdrv_find_format(buf
);
5143 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5148 if (arg
->file
== NULL
)
5149 get_param_value(file
, sizeof(file
), "file", str
);
5151 pstrcpy(file
, sizeof(file
), arg
->file
);
5153 /* compute bus and unit according index */
5156 if (bus_id
!= 0 || unit_id
!= -1) {
5158 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5166 unit_id
= index
% max_devs
;
5167 bus_id
= index
/ max_devs
;
5171 /* if user doesn't specify a unit_id,
5172 * try to find the first free
5175 if (unit_id
== -1) {
5177 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5179 if (max_devs
&& unit_id
>= max_devs
) {
5180 unit_id
-= max_devs
;
5188 if (max_devs
&& unit_id
>= max_devs
) {
5189 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5190 str
, unit_id
, max_devs
- 1);
5195 * ignore multiple definitions
5198 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5203 if (type
== IF_IDE
|| type
== IF_SCSI
)
5204 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5206 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5207 devname
, bus_id
, mediastr
, unit_id
);
5209 snprintf(buf
, sizeof(buf
), "%s%s%i",
5210 devname
, mediastr
, unit_id
);
5211 bdrv
= bdrv_new(buf
);
5212 drives_table
[nb_drives
].bdrv
= bdrv
;
5213 drives_table
[nb_drives
].type
= type
;
5214 drives_table
[nb_drives
].bus
= bus_id
;
5215 drives_table
[nb_drives
].unit
= unit_id
;
5224 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5225 bdrv_set_translation_hint(bdrv
, translation
);
5229 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5234 /* FIXME: This isn't really a floppy, but it's a reasonable
5237 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5247 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5249 bdrv_flags
|= BDRV_O_DIRECT
;
5250 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5251 fprintf(stderr
, "qemu: could not open disk image %s\n",
5258 /***********************************************************/
5261 static USBPort
*used_usb_ports
;
5262 static USBPort
*free_usb_ports
;
5264 /* ??? Maybe change this to register a hub to keep track of the topology. */
5265 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5266 usb_attachfn attach
)
5268 port
->opaque
= opaque
;
5269 port
->index
= index
;
5270 port
->attach
= attach
;
5271 port
->next
= free_usb_ports
;
5272 free_usb_ports
= port
;
5275 static int usb_device_add(const char *devname
)
5281 if (!free_usb_ports
)
5284 if (strstart(devname
, "host:", &p
)) {
5285 dev
= usb_host_device_open(p
);
5286 } else if (!strcmp(devname
, "mouse")) {
5287 dev
= usb_mouse_init();
5288 } else if (!strcmp(devname
, "tablet")) {
5289 dev
= usb_tablet_init();
5290 } else if (!strcmp(devname
, "keyboard")) {
5291 dev
= usb_keyboard_init();
5292 } else if (strstart(devname
, "disk:", &p
)) {
5293 dev
= usb_msd_init(p
);
5294 } else if (!strcmp(devname
, "wacom-tablet")) {
5295 dev
= usb_wacom_init();
5296 } else if (strstart(devname
, "serial:", &p
)) {
5297 dev
= usb_serial_init(p
);
5298 #ifdef CONFIG_BRLAPI
5299 } else if (!strcmp(devname
, "braille")) {
5300 dev
= usb_baum_init();
5308 /* Find a USB port to add the device to. */
5309 port
= free_usb_ports
;
5313 /* Create a new hub and chain it on. */
5314 free_usb_ports
= NULL
;
5315 port
->next
= used_usb_ports
;
5316 used_usb_ports
= port
;
5318 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5319 usb_attach(port
, hub
);
5320 port
= free_usb_ports
;
5323 free_usb_ports
= port
->next
;
5324 port
->next
= used_usb_ports
;
5325 used_usb_ports
= port
;
5326 usb_attach(port
, dev
);
5330 static int usb_device_del(const char *devname
)
5338 if (!used_usb_ports
)
5341 p
= strchr(devname
, '.');
5344 bus_num
= strtoul(devname
, NULL
, 0);
5345 addr
= strtoul(p
+ 1, NULL
, 0);
5349 lastp
= &used_usb_ports
;
5350 port
= used_usb_ports
;
5351 while (port
&& port
->dev
->addr
!= addr
) {
5352 lastp
= &port
->next
;
5360 *lastp
= port
->next
;
5361 usb_attach(port
, NULL
);
5362 dev
->handle_destroy(dev
);
5363 port
->next
= free_usb_ports
;
5364 free_usb_ports
= port
;
5368 void do_usb_add(const char *devname
)
5371 ret
= usb_device_add(devname
);
5373 term_printf("Could not add USB device '%s'\n", devname
);
5376 void do_usb_del(const char *devname
)
5379 ret
= usb_device_del(devname
);
5381 term_printf("Could not remove USB device '%s'\n", devname
);
5388 const char *speed_str
;
5391 term_printf("USB support not enabled\n");
5395 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5399 switch(dev
->speed
) {
5403 case USB_SPEED_FULL
:
5406 case USB_SPEED_HIGH
:
5413 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5414 0, dev
->addr
, speed_str
, dev
->devname
);
5418 /***********************************************************/
5419 /* PCMCIA/Cardbus */
5421 static struct pcmcia_socket_entry_s
{
5422 struct pcmcia_socket_s
*socket
;
5423 struct pcmcia_socket_entry_s
*next
;
5424 } *pcmcia_sockets
= 0;
5426 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5428 struct pcmcia_socket_entry_s
*entry
;
5430 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5431 entry
->socket
= socket
;
5432 entry
->next
= pcmcia_sockets
;
5433 pcmcia_sockets
= entry
;
5436 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5438 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5440 ptr
= &pcmcia_sockets
;
5441 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5442 if (entry
->socket
== socket
) {
5448 void pcmcia_info(void)
5450 struct pcmcia_socket_entry_s
*iter
;
5451 if (!pcmcia_sockets
)
5452 term_printf("No PCMCIA sockets\n");
5454 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5455 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5456 iter
->socket
->attached
? iter
->socket
->card_string
:
5460 /***********************************************************/
5463 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5467 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5471 static void dumb_refresh(DisplayState
*ds
)
5473 #if defined(CONFIG_SDL)
5478 static void dumb_display_init(DisplayState
*ds
)
5483 ds
->dpy_update
= dumb_update
;
5484 ds
->dpy_resize
= dumb_resize
;
5485 ds
->dpy_refresh
= dumb_refresh
;
5488 /***********************************************************/
5491 #define MAX_IO_HANDLERS 64
5493 typedef struct IOHandlerRecord
{
5495 IOCanRWHandler
*fd_read_poll
;
5497 IOHandler
*fd_write
;
5500 /* temporary data */
5502 struct IOHandlerRecord
*next
;
5505 static IOHandlerRecord
*first_io_handler
;
5507 /* XXX: fd_read_poll should be suppressed, but an API change is
5508 necessary in the character devices to suppress fd_can_read(). */
5509 int qemu_set_fd_handler2(int fd
,
5510 IOCanRWHandler
*fd_read_poll
,
5512 IOHandler
*fd_write
,
5515 IOHandlerRecord
**pioh
, *ioh
;
5517 if (!fd_read
&& !fd_write
) {
5518 pioh
= &first_io_handler
;
5523 if (ioh
->fd
== fd
) {
5530 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5534 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5537 ioh
->next
= first_io_handler
;
5538 first_io_handler
= ioh
;
5541 ioh
->fd_read_poll
= fd_read_poll
;
5542 ioh
->fd_read
= fd_read
;
5543 ioh
->fd_write
= fd_write
;
5544 ioh
->opaque
= opaque
;
5550 int qemu_set_fd_handler(int fd
,
5552 IOHandler
*fd_write
,
5555 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5558 /***********************************************************/
5559 /* Polling handling */
5561 typedef struct PollingEntry
{
5564 struct PollingEntry
*next
;
5567 static PollingEntry
*first_polling_entry
;
5569 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5571 PollingEntry
**ppe
, *pe
;
5572 pe
= qemu_mallocz(sizeof(PollingEntry
));
5576 pe
->opaque
= opaque
;
5577 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5582 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5584 PollingEntry
**ppe
, *pe
;
5585 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5587 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5596 /***********************************************************/
5597 /* Wait objects support */
5598 typedef struct WaitObjects
{
5600 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
5601 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
5602 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
5605 static WaitObjects wait_objects
= {0};
5607 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5609 WaitObjects
*w
= &wait_objects
;
5611 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
5613 w
->events
[w
->num
] = handle
;
5614 w
->func
[w
->num
] = func
;
5615 w
->opaque
[w
->num
] = opaque
;
5620 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5623 WaitObjects
*w
= &wait_objects
;
5626 for (i
= 0; i
< w
->num
; i
++) {
5627 if (w
->events
[i
] == handle
)
5630 w
->events
[i
] = w
->events
[i
+ 1];
5631 w
->func
[i
] = w
->func
[i
+ 1];
5632 w
->opaque
[i
] = w
->opaque
[i
+ 1];
5640 /***********************************************************/
5641 /* savevm/loadvm support */
5643 #define IO_BUF_SIZE 32768
5647 BlockDriverState
*bs
;
5650 int64_t base_offset
;
5651 int64_t buf_offset
; /* start of buffer when writing, end of buffer
5654 int buf_size
; /* 0 when writing */
5655 uint8_t buf
[IO_BUF_SIZE
];
5658 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
5662 f
= qemu_mallocz(sizeof(QEMUFile
));
5665 if (!strcmp(mode
, "wb")) {
5667 } else if (!strcmp(mode
, "rb")) {
5672 f
->outfile
= fopen(filename
, mode
);
5684 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
5688 f
= qemu_mallocz(sizeof(QEMUFile
));
5693 f
->is_writable
= is_writable
;
5694 f
->base_offset
= offset
;
5698 void qemu_fflush(QEMUFile
*f
)
5700 if (!f
->is_writable
)
5702 if (f
->buf_index
> 0) {
5704 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
5705 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
5707 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
5708 f
->buf
, f
->buf_index
);
5710 f
->buf_offset
+= f
->buf_index
;
5715 static void qemu_fill_buffer(QEMUFile
*f
)
5722 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
5723 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
5727 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
5728 f
->buf
, IO_BUF_SIZE
);
5734 f
->buf_offset
+= len
;
5737 void qemu_fclose(QEMUFile
*f
)
5747 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
5751 l
= IO_BUF_SIZE
- f
->buf_index
;
5754 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
5758 if (f
->buf_index
>= IO_BUF_SIZE
)
5763 void qemu_put_byte(QEMUFile
*f
, int v
)
5765 f
->buf
[f
->buf_index
++] = v
;
5766 if (f
->buf_index
>= IO_BUF_SIZE
)
5770 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
5776 l
= f
->buf_size
- f
->buf_index
;
5778 qemu_fill_buffer(f
);
5779 l
= f
->buf_size
- f
->buf_index
;
5785 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
5790 return size1
- size
;
5793 int qemu_get_byte(QEMUFile
*f
)
5795 if (f
->buf_index
>= f
->buf_size
) {
5796 qemu_fill_buffer(f
);
5797 if (f
->buf_index
>= f
->buf_size
)
5800 return f
->buf
[f
->buf_index
++];
5803 int64_t qemu_ftell(QEMUFile
*f
)
5805 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
5808 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
5810 if (whence
== SEEK_SET
) {
5812 } else if (whence
== SEEK_CUR
) {
5813 pos
+= qemu_ftell(f
);
5815 /* SEEK_END not supported */
5818 if (f
->is_writable
) {
5820 f
->buf_offset
= pos
;
5822 f
->buf_offset
= pos
;
5829 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
5831 qemu_put_byte(f
, v
>> 8);
5832 qemu_put_byte(f
, v
);
5835 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
5837 qemu_put_byte(f
, v
>> 24);
5838 qemu_put_byte(f
, v
>> 16);
5839 qemu_put_byte(f
, v
>> 8);
5840 qemu_put_byte(f
, v
);
5843 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
5845 qemu_put_be32(f
, v
>> 32);
5846 qemu_put_be32(f
, v
);
5849 unsigned int qemu_get_be16(QEMUFile
*f
)
5852 v
= qemu_get_byte(f
) << 8;
5853 v
|= qemu_get_byte(f
);
5857 unsigned int qemu_get_be32(QEMUFile
*f
)
5860 v
= qemu_get_byte(f
) << 24;
5861 v
|= qemu_get_byte(f
) << 16;
5862 v
|= qemu_get_byte(f
) << 8;
5863 v
|= qemu_get_byte(f
);
5867 uint64_t qemu_get_be64(QEMUFile
*f
)
5870 v
= (uint64_t)qemu_get_be32(f
) << 32;
5871 v
|= qemu_get_be32(f
);
5875 typedef struct SaveStateEntry
{
5879 SaveStateHandler
*save_state
;
5880 LoadStateHandler
*load_state
;
5882 struct SaveStateEntry
*next
;
5885 static SaveStateEntry
*first_se
;
5887 int register_savevm(const char *idstr
,
5890 SaveStateHandler
*save_state
,
5891 LoadStateHandler
*load_state
,
5894 SaveStateEntry
*se
, **pse
;
5896 se
= qemu_malloc(sizeof(SaveStateEntry
));
5899 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
5900 se
->instance_id
= instance_id
;
5901 se
->version_id
= version_id
;
5902 se
->save_state
= save_state
;
5903 se
->load_state
= load_state
;
5904 se
->opaque
= opaque
;
5907 /* add at the end of list */
5909 while (*pse
!= NULL
)
5910 pse
= &(*pse
)->next
;
5915 #define QEMU_VM_FILE_MAGIC 0x5145564d
5916 #define QEMU_VM_FILE_VERSION 0x00000002
5918 static int qemu_savevm_state(QEMUFile
*f
)
5922 int64_t cur_pos
, len_pos
, total_len_pos
;
5924 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
5925 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
5926 total_len_pos
= qemu_ftell(f
);
5927 qemu_put_be64(f
, 0); /* total size */
5929 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
5931 len
= strlen(se
->idstr
);
5932 qemu_put_byte(f
, len
);
5933 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
5935 qemu_put_be32(f
, se
->instance_id
);
5936 qemu_put_be32(f
, se
->version_id
);
5938 /* record size: filled later */
5939 len_pos
= qemu_ftell(f
);
5940 qemu_put_be32(f
, 0);
5941 se
->save_state(f
, se
->opaque
);
5943 /* fill record size */
5944 cur_pos
= qemu_ftell(f
);
5945 len
= cur_pos
- len_pos
- 4;
5946 qemu_fseek(f
, len_pos
, SEEK_SET
);
5947 qemu_put_be32(f
, len
);
5948 qemu_fseek(f
, cur_pos
, SEEK_SET
);
5950 cur_pos
= qemu_ftell(f
);
5951 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
5952 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
5953 qemu_fseek(f
, cur_pos
, SEEK_SET
);
5959 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
5963 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
5964 if (!strcmp(se
->idstr
, idstr
) &&
5965 instance_id
== se
->instance_id
)
5971 static int qemu_loadvm_state(QEMUFile
*f
)
5974 int len
, ret
, instance_id
, record_len
, version_id
;
5975 int64_t total_len
, end_pos
, cur_pos
;
5979 v
= qemu_get_be32(f
);
5980 if (v
!= QEMU_VM_FILE_MAGIC
)
5982 v
= qemu_get_be32(f
);
5983 if (v
!= QEMU_VM_FILE_VERSION
) {
5988 total_len
= qemu_get_be64(f
);
5989 end_pos
= total_len
+ qemu_ftell(f
);
5991 if (qemu_ftell(f
) >= end_pos
)
5993 len
= qemu_get_byte(f
);
5994 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
5996 instance_id
= qemu_get_be32(f
);
5997 version_id
= qemu_get_be32(f
);
5998 record_len
= qemu_get_be32(f
);
6000 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6001 idstr
, instance_id
, version_id
, record_len
);
6003 cur_pos
= qemu_ftell(f
);
6004 se
= find_se(idstr
, instance_id
);
6006 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6007 instance_id
, idstr
);
6009 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6011 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6012 instance_id
, idstr
);
6015 /* always seek to exact end of record */
6016 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6023 /* device can contain snapshots */
6024 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6027 !bdrv_is_removable(bs
) &&
6028 !bdrv_is_read_only(bs
));
6031 /* device must be snapshots in order to have a reliable snapshot */
6032 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6035 !bdrv_is_removable(bs
) &&
6036 !bdrv_is_read_only(bs
));
6039 static BlockDriverState
*get_bs_snapshots(void)
6041 BlockDriverState
*bs
;
6045 return bs_snapshots
;
6046 for(i
= 0; i
<= nb_drives
; i
++) {
6047 bs
= drives_table
[i
].bdrv
;
6048 if (bdrv_can_snapshot(bs
))
6057 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6060 QEMUSnapshotInfo
*sn_tab
, *sn
;
6064 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6067 for(i
= 0; i
< nb_sns
; i
++) {
6069 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6079 void do_savevm(const char *name
)
6081 BlockDriverState
*bs
, *bs1
;
6082 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6083 int must_delete
, ret
, i
;
6084 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6086 int saved_vm_running
;
6093 bs
= get_bs_snapshots();
6095 term_printf("No block device can accept snapshots\n");
6099 /* ??? Should this occur after vm_stop? */
6102 saved_vm_running
= vm_running
;
6107 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6112 memset(sn
, 0, sizeof(*sn
));
6114 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6115 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6118 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6121 /* fill auxiliary fields */
6124 sn
->date_sec
= tb
.time
;
6125 sn
->date_nsec
= tb
.millitm
* 1000000;
6127 gettimeofday(&tv
, NULL
);
6128 sn
->date_sec
= tv
.tv_sec
;
6129 sn
->date_nsec
= tv
.tv_usec
* 1000;
6131 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6133 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6134 term_printf("Device %s does not support VM state snapshots\n",
6135 bdrv_get_device_name(bs
));
6139 /* save the VM state */
6140 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6142 term_printf("Could not open VM state file\n");
6145 ret
= qemu_savevm_state(f
);
6146 sn
->vm_state_size
= qemu_ftell(f
);
6149 term_printf("Error %d while writing VM\n", ret
);
6153 /* create the snapshots */
6155 for(i
= 0; i
< nb_drives
; i
++) {
6156 bs1
= drives_table
[i
].bdrv
;
6157 if (bdrv_has_snapshot(bs1
)) {
6159 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6161 term_printf("Error while deleting snapshot on '%s'\n",
6162 bdrv_get_device_name(bs1
));
6165 ret
= bdrv_snapshot_create(bs1
, sn
);
6167 term_printf("Error while creating snapshot on '%s'\n",
6168 bdrv_get_device_name(bs1
));
6174 if (saved_vm_running
)
6178 void do_loadvm(const char *name
)
6180 BlockDriverState
*bs
, *bs1
;
6181 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6184 int saved_vm_running
;
6186 bs
= get_bs_snapshots();
6188 term_printf("No block device supports snapshots\n");
6192 /* Flush all IO requests so they don't interfere with the new state. */
6195 saved_vm_running
= vm_running
;
6198 for(i
= 0; i
<= nb_drives
; i
++) {
6199 bs1
= drives_table
[i
].bdrv
;
6200 if (bdrv_has_snapshot(bs1
)) {
6201 ret
= bdrv_snapshot_goto(bs1
, name
);
6204 term_printf("Warning: ");
6207 term_printf("Snapshots not supported on device '%s'\n",
6208 bdrv_get_device_name(bs1
));
6211 term_printf("Could not find snapshot '%s' on device '%s'\n",
6212 name
, bdrv_get_device_name(bs1
));
6215 term_printf("Error %d while activating snapshot on '%s'\n",
6216 ret
, bdrv_get_device_name(bs1
));
6219 /* fatal on snapshot block device */
6226 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6227 term_printf("Device %s does not support VM state snapshots\n",
6228 bdrv_get_device_name(bs
));
6232 /* restore the VM state */
6233 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6235 term_printf("Could not open VM state file\n");
6238 ret
= qemu_loadvm_state(f
);
6241 term_printf("Error %d while loading VM state\n", ret
);
6244 if (saved_vm_running
)
6248 void do_delvm(const char *name
)
6250 BlockDriverState
*bs
, *bs1
;
6253 bs
= get_bs_snapshots();
6255 term_printf("No block device supports snapshots\n");
6259 for(i
= 0; i
<= nb_drives
; i
++) {
6260 bs1
= drives_table
[i
].bdrv
;
6261 if (bdrv_has_snapshot(bs1
)) {
6262 ret
= bdrv_snapshot_delete(bs1
, name
);
6264 if (ret
== -ENOTSUP
)
6265 term_printf("Snapshots not supported on device '%s'\n",
6266 bdrv_get_device_name(bs1
));
6268 term_printf("Error %d while deleting snapshot on '%s'\n",
6269 ret
, bdrv_get_device_name(bs1
));
6275 void do_info_snapshots(void)
6277 BlockDriverState
*bs
, *bs1
;
6278 QEMUSnapshotInfo
*sn_tab
, *sn
;
6282 bs
= get_bs_snapshots();
6284 term_printf("No available block device supports snapshots\n");
6287 term_printf("Snapshot devices:");
6288 for(i
= 0; i
<= nb_drives
; i
++) {
6289 bs1
= drives_table
[i
].bdrv
;
6290 if (bdrv_has_snapshot(bs1
)) {
6292 term_printf(" %s", bdrv_get_device_name(bs1
));
6297 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6299 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6302 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6303 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6304 for(i
= 0; i
< nb_sns
; i
++) {
6306 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6311 /***********************************************************/
6312 /* cpu save/restore */
6314 #if defined(TARGET_I386)
6316 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
6318 qemu_put_be32(f
, dt
->selector
);
6319 qemu_put_betl(f
, dt
->base
);
6320 qemu_put_be32(f
, dt
->limit
);
6321 qemu_put_be32(f
, dt
->flags
);
6324 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
6326 dt
->selector
= qemu_get_be32(f
);
6327 dt
->base
= qemu_get_betl(f
);
6328 dt
->limit
= qemu_get_be32(f
);
6329 dt
->flags
= qemu_get_be32(f
);
6332 void cpu_save(QEMUFile
*f
, void *opaque
)
6334 CPUState
*env
= opaque
;
6335 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
6339 for(i
= 0; i
< CPU_NB_REGS
; i
++)
6340 qemu_put_betls(f
, &env
->regs
[i
]);
6341 qemu_put_betls(f
, &env
->eip
);
6342 qemu_put_betls(f
, &env
->eflags
);
6343 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
6344 qemu_put_be32s(f
, &hflags
);
6348 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
6350 for(i
= 0; i
< 8; i
++) {
6351 fptag
|= ((!env
->fptags
[i
]) << i
);
6354 qemu_put_be16s(f
, &fpuc
);
6355 qemu_put_be16s(f
, &fpus
);
6356 qemu_put_be16s(f
, &fptag
);
6358 #ifdef USE_X86LDOUBLE
6363 qemu_put_be16s(f
, &fpregs_format
);
6365 for(i
= 0; i
< 8; i
++) {
6366 #ifdef USE_X86LDOUBLE
6370 /* we save the real CPU data (in case of MMX usage only 'mant'
6371 contains the MMX register */
6372 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
6373 qemu_put_be64(f
, mant
);
6374 qemu_put_be16(f
, exp
);
6377 /* if we use doubles for float emulation, we save the doubles to
6378 avoid losing information in case of MMX usage. It can give
6379 problems if the image is restored on a CPU where long
6380 doubles are used instead. */
6381 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
6385 for(i
= 0; i
< 6; i
++)
6386 cpu_put_seg(f
, &env
->segs
[i
]);
6387 cpu_put_seg(f
, &env
->ldt
);
6388 cpu_put_seg(f
, &env
->tr
);
6389 cpu_put_seg(f
, &env
->gdt
);
6390 cpu_put_seg(f
, &env
->idt
);
6392 qemu_put_be32s(f
, &env
->sysenter_cs
);
6393 qemu_put_be32s(f
, &env
->sysenter_esp
);
6394 qemu_put_be32s(f
, &env
->sysenter_eip
);
6396 qemu_put_betls(f
, &env
->cr
[0]);
6397 qemu_put_betls(f
, &env
->cr
[2]);
6398 qemu_put_betls(f
, &env
->cr
[3]);
6399 qemu_put_betls(f
, &env
->cr
[4]);
6401 for(i
= 0; i
< 8; i
++)
6402 qemu_put_betls(f
, &env
->dr
[i
]);
6405 qemu_put_be32s(f
, &env
->a20_mask
);
6408 qemu_put_be32s(f
, &env
->mxcsr
);
6409 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
6410 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
6411 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
6414 #ifdef TARGET_X86_64
6415 qemu_put_be64s(f
, &env
->efer
);
6416 qemu_put_be64s(f
, &env
->star
);
6417 qemu_put_be64s(f
, &env
->lstar
);
6418 qemu_put_be64s(f
, &env
->cstar
);
6419 qemu_put_be64s(f
, &env
->fmask
);
6420 qemu_put_be64s(f
, &env
->kernelgsbase
);
6422 qemu_put_be32s(f
, &env
->smbase
);
6425 #ifdef USE_X86LDOUBLE
6426 /* XXX: add that in a FPU generic layer */
6427 union x86_longdouble
{
6432 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6433 #define EXPBIAS1 1023
6434 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6435 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6437 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
6441 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
6442 /* exponent + sign */
6443 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
6444 e
|= SIGND1(temp
) >> 16;
6449 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6451 CPUState
*env
= opaque
;
6454 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
6456 if (version_id
!= 3 && version_id
!= 4)
6458 for(i
= 0; i
< CPU_NB_REGS
; i
++)
6459 qemu_get_betls(f
, &env
->regs
[i
]);
6460 qemu_get_betls(f
, &env
->eip
);
6461 qemu_get_betls(f
, &env
->eflags
);
6462 qemu_get_be32s(f
, &hflags
);
6464 qemu_get_be16s(f
, &fpuc
);
6465 qemu_get_be16s(f
, &fpus
);
6466 qemu_get_be16s(f
, &fptag
);
6467 qemu_get_be16s(f
, &fpregs_format
);
6469 /* NOTE: we cannot always restore the FPU state if the image come
6470 from a host with a different 'USE_X86LDOUBLE' define. We guess
6471 if we are in an MMX state to restore correctly in that case. */
6472 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
6473 for(i
= 0; i
< 8; i
++) {
6477 switch(fpregs_format
) {
6479 mant
= qemu_get_be64(f
);
6480 exp
= qemu_get_be16(f
);
6481 #ifdef USE_X86LDOUBLE
6482 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
6484 /* difficult case */
6486 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
6488 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
6492 mant
= qemu_get_be64(f
);
6493 #ifdef USE_X86LDOUBLE
6495 union x86_longdouble
*p
;
6496 /* difficult case */
6497 p
= (void *)&env
->fpregs
[i
];
6502 fp64_to_fp80(p
, mant
);
6506 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
6515 /* XXX: restore FPU round state */
6516 env
->fpstt
= (fpus
>> 11) & 7;
6517 env
->fpus
= fpus
& ~0x3800;
6519 for(i
= 0; i
< 8; i
++) {
6520 env
->fptags
[i
] = (fptag
>> i
) & 1;
6523 for(i
= 0; i
< 6; i
++)
6524 cpu_get_seg(f
, &env
->segs
[i
]);
6525 cpu_get_seg(f
, &env
->ldt
);
6526 cpu_get_seg(f
, &env
->tr
);
6527 cpu_get_seg(f
, &env
->gdt
);
6528 cpu_get_seg(f
, &env
->idt
);
6530 qemu_get_be32s(f
, &env
->sysenter_cs
);
6531 qemu_get_be32s(f
, &env
->sysenter_esp
);
6532 qemu_get_be32s(f
, &env
->sysenter_eip
);
6534 qemu_get_betls(f
, &env
->cr
[0]);
6535 qemu_get_betls(f
, &env
->cr
[2]);
6536 qemu_get_betls(f
, &env
->cr
[3]);
6537 qemu_get_betls(f
, &env
->cr
[4]);
6539 for(i
= 0; i
< 8; i
++)
6540 qemu_get_betls(f
, &env
->dr
[i
]);
6543 qemu_get_be32s(f
, &env
->a20_mask
);
6545 qemu_get_be32s(f
, &env
->mxcsr
);
6546 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
6547 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
6548 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
6551 #ifdef TARGET_X86_64
6552 qemu_get_be64s(f
, &env
->efer
);
6553 qemu_get_be64s(f
, &env
->star
);
6554 qemu_get_be64s(f
, &env
->lstar
);
6555 qemu_get_be64s(f
, &env
->cstar
);
6556 qemu_get_be64s(f
, &env
->fmask
);
6557 qemu_get_be64s(f
, &env
->kernelgsbase
);
6559 if (version_id
>= 4)
6560 qemu_get_be32s(f
, &env
->smbase
);
6562 /* XXX: compute hflags from scratch, except for CPL and IIF */
6563 env
->hflags
= hflags
;
6568 #elif defined(TARGET_PPC)
6569 void cpu_save(QEMUFile
*f
, void *opaque
)
6573 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6578 #elif defined(TARGET_MIPS)
6579 void cpu_save(QEMUFile
*f
, void *opaque
)
6583 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6588 #elif defined(TARGET_SPARC)
6589 void cpu_save(QEMUFile
*f
, void *opaque
)
6591 CPUState
*env
= opaque
;
6595 for(i
= 0; i
< 8; i
++)
6596 qemu_put_betls(f
, &env
->gregs
[i
]);
6597 for(i
= 0; i
< NWINDOWS
* 16; i
++)
6598 qemu_put_betls(f
, &env
->regbase
[i
]);
6601 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
6607 qemu_put_be32(f
, u
.i
);
6610 qemu_put_betls(f
, &env
->pc
);
6611 qemu_put_betls(f
, &env
->npc
);
6612 qemu_put_betls(f
, &env
->y
);
6614 qemu_put_be32(f
, tmp
);
6615 qemu_put_betls(f
, &env
->fsr
);
6616 qemu_put_betls(f
, &env
->tbr
);
6617 #ifndef TARGET_SPARC64
6618 qemu_put_be32s(f
, &env
->wim
);
6620 for(i
= 0; i
< 16; i
++)
6621 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
6625 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6627 CPUState
*env
= opaque
;
6631 for(i
= 0; i
< 8; i
++)
6632 qemu_get_betls(f
, &env
->gregs
[i
]);
6633 for(i
= 0; i
< NWINDOWS
* 16; i
++)
6634 qemu_get_betls(f
, &env
->regbase
[i
]);
6637 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
6642 u
.i
= qemu_get_be32(f
);
6646 qemu_get_betls(f
, &env
->pc
);
6647 qemu_get_betls(f
, &env
->npc
);
6648 qemu_get_betls(f
, &env
->y
);
6649 tmp
= qemu_get_be32(f
);
6650 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
6651 correctly updated */
6653 qemu_get_betls(f
, &env
->fsr
);
6654 qemu_get_betls(f
, &env
->tbr
);
6655 #ifndef TARGET_SPARC64
6656 qemu_get_be32s(f
, &env
->wim
);
6658 for(i
= 0; i
< 16; i
++)
6659 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
6665 #elif defined(TARGET_ARM)
6667 void cpu_save(QEMUFile
*f
, void *opaque
)
6670 CPUARMState
*env
= (CPUARMState
*)opaque
;
6672 for (i
= 0; i
< 16; i
++) {
6673 qemu_put_be32(f
, env
->regs
[i
]);
6675 qemu_put_be32(f
, cpsr_read(env
));
6676 qemu_put_be32(f
, env
->spsr
);
6677 for (i
= 0; i
< 6; i
++) {
6678 qemu_put_be32(f
, env
->banked_spsr
[i
]);
6679 qemu_put_be32(f
, env
->banked_r13
[i
]);
6680 qemu_put_be32(f
, env
->banked_r14
[i
]);
6682 for (i
= 0; i
< 5; i
++) {
6683 qemu_put_be32(f
, env
->usr_regs
[i
]);
6684 qemu_put_be32(f
, env
->fiq_regs
[i
]);
6686 qemu_put_be32(f
, env
->cp15
.c0_cpuid
);
6687 qemu_put_be32(f
, env
->cp15
.c0_cachetype
);
6688 qemu_put_be32(f
, env
->cp15
.c1_sys
);
6689 qemu_put_be32(f
, env
->cp15
.c1_coproc
);
6690 qemu_put_be32(f
, env
->cp15
.c1_xscaleauxcr
);
6691 qemu_put_be32(f
, env
->cp15
.c2_base0
);
6692 qemu_put_be32(f
, env
->cp15
.c2_base1
);
6693 qemu_put_be32(f
, env
->cp15
.c2_mask
);
6694 qemu_put_be32(f
, env
->cp15
.c2_data
);
6695 qemu_put_be32(f
, env
->cp15
.c2_insn
);
6696 qemu_put_be32(f
, env
->cp15
.c3
);
6697 qemu_put_be32(f
, env
->cp15
.c5_insn
);
6698 qemu_put_be32(f
, env
->cp15
.c5_data
);
6699 for (i
= 0; i
< 8; i
++) {
6700 qemu_put_be32(f
, env
->cp15
.c6_region
[i
]);
6702 qemu_put_be32(f
, env
->cp15
.c6_insn
);
6703 qemu_put_be32(f
, env
->cp15
.c6_data
);
6704 qemu_put_be32(f
, env
->cp15
.c9_insn
);
6705 qemu_put_be32(f
, env
->cp15
.c9_data
);
6706 qemu_put_be32(f
, env
->cp15
.c13_fcse
);
6707 qemu_put_be32(f
, env
->cp15
.c13_context
);
6708 qemu_put_be32(f
, env
->cp15
.c13_tls1
);
6709 qemu_put_be32(f
, env
->cp15
.c13_tls2
);
6710 qemu_put_be32(f
, env
->cp15
.c13_tls3
);
6711 qemu_put_be32(f
, env
->cp15
.c15_cpar
);
6713 qemu_put_be32(f
, env
->features
);
6715 if (arm_feature(env
, ARM_FEATURE_VFP
)) {
6716 for (i
= 0; i
< 16; i
++) {
6718 u
.d
= env
->vfp
.regs
[i
];
6719 qemu_put_be32(f
, u
.l
.upper
);
6720 qemu_put_be32(f
, u
.l
.lower
);
6722 for (i
= 0; i
< 16; i
++) {
6723 qemu_put_be32(f
, env
->vfp
.xregs
[i
]);
6726 /* TODO: Should use proper FPSCR access functions. */
6727 qemu_put_be32(f
, env
->vfp
.vec_len
);
6728 qemu_put_be32(f
, env
->vfp
.vec_stride
);
6730 if (arm_feature(env
, ARM_FEATURE_VFP3
)) {
6731 for (i
= 16; i
< 32; i
++) {
6733 u
.d
= env
->vfp
.regs
[i
];
6734 qemu_put_be32(f
, u
.l
.upper
);
6735 qemu_put_be32(f
, u
.l
.lower
);
6740 if (arm_feature(env
, ARM_FEATURE_IWMMXT
)) {
6741 for (i
= 0; i
< 16; i
++) {
6742 qemu_put_be64(f
, env
->iwmmxt
.regs
[i
]);
6744 for (i
= 0; i
< 16; i
++) {
6745 qemu_put_be32(f
, env
->iwmmxt
.cregs
[i
]);
6749 if (arm_feature(env
, ARM_FEATURE_M
)) {
6750 qemu_put_be32(f
, env
->v7m
.other_sp
);
6751 qemu_put_be32(f
, env
->v7m
.vecbase
);
6752 qemu_put_be32(f
, env
->v7m
.basepri
);
6753 qemu_put_be32(f
, env
->v7m
.control
);
6754 qemu_put_be32(f
, env
->v7m
.current_sp
);
6755 qemu_put_be32(f
, env
->v7m
.exception
);
6759 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6761 CPUARMState
*env
= (CPUARMState
*)opaque
;
6764 if (version_id
!= ARM_CPU_SAVE_VERSION
)
6767 for (i
= 0; i
< 16; i
++) {
6768 env
->regs
[i
] = qemu_get_be32(f
);
6770 cpsr_write(env
, qemu_get_be32(f
), 0xffffffff);
6771 env
->spsr
= qemu_get_be32(f
);
6772 for (i
= 0; i
< 6; i
++) {
6773 env
->banked_spsr
[i
] = qemu_get_be32(f
);
6774 env
->banked_r13
[i
] = qemu_get_be32(f
);
6775 env
->banked_r14
[i
] = qemu_get_be32(f
);
6777 for (i
= 0; i
< 5; i
++) {
6778 env
->usr_regs
[i
] = qemu_get_be32(f
);
6779 env
->fiq_regs
[i
] = qemu_get_be32(f
);
6781 env
->cp15
.c0_cpuid
= qemu_get_be32(f
);
6782 env
->cp15
.c0_cachetype
= qemu_get_be32(f
);
6783 env
->cp15
.c1_sys
= qemu_get_be32(f
);
6784 env
->cp15
.c1_coproc
= qemu_get_be32(f
);
6785 env
->cp15
.c1_xscaleauxcr
= qemu_get_be32(f
);
6786 env
->cp15
.c2_base0
= qemu_get_be32(f
);
6787 env
->cp15
.c2_base1
= qemu_get_be32(f
);
6788 env
->cp15
.c2_mask
= qemu_get_be32(f
);
6789 env
->cp15
.c2_data
= qemu_get_be32(f
);
6790 env
->cp15
.c2_insn
= qemu_get_be32(f
);
6791 env
->cp15
.c3
= qemu_get_be32(f
);
6792 env
->cp15
.c5_insn
= qemu_get_be32(f
);
6793 env
->cp15
.c5_data
= qemu_get_be32(f
);
6794 for (i
= 0; i
< 8; i
++) {
6795 env
->cp15
.c6_region
[i
] = qemu_get_be32(f
);
6797 env
->cp15
.c6_insn
= qemu_get_be32(f
);
6798 env
->cp15
.c6_data
= qemu_get_be32(f
);
6799 env
->cp15
.c9_insn
= qemu_get_be32(f
);
6800 env
->cp15
.c9_data
= qemu_get_be32(f
);
6801 env
->cp15
.c13_fcse
= qemu_get_be32(f
);
6802 env
->cp15
.c13_context
= qemu_get_be32(f
);
6803 env
->cp15
.c13_tls1
= qemu_get_be32(f
);
6804 env
->cp15
.c13_tls2
= qemu_get_be32(f
);
6805 env
->cp15
.c13_tls3
= qemu_get_be32(f
);
6806 env
->cp15
.c15_cpar
= qemu_get_be32(f
);
6808 env
->features
= qemu_get_be32(f
);
6810 if (arm_feature(env
, ARM_FEATURE_VFP
)) {
6811 for (i
= 0; i
< 16; i
++) {
6813 u
.l
.upper
= qemu_get_be32(f
);
6814 u
.l
.lower
= qemu_get_be32(f
);
6815 env
->vfp
.regs
[i
] = u
.d
;
6817 for (i
= 0; i
< 16; i
++) {
6818 env
->vfp
.xregs
[i
] = qemu_get_be32(f
);
6821 /* TODO: Should use proper FPSCR access functions. */
6822 env
->vfp
.vec_len
= qemu_get_be32(f
);
6823 env
->vfp
.vec_stride
= qemu_get_be32(f
);
6825 if (arm_feature(env
, ARM_FEATURE_VFP3
)) {
6826 for (i
= 0; i
< 16; i
++) {
6828 u
.l
.upper
= qemu_get_be32(f
);
6829 u
.l
.lower
= qemu_get_be32(f
);
6830 env
->vfp
.regs
[i
] = u
.d
;
6835 if (arm_feature(env
, ARM_FEATURE_IWMMXT
)) {
6836 for (i
= 0; i
< 16; i
++) {
6837 env
->iwmmxt
.regs
[i
] = qemu_get_be64(f
);
6839 for (i
= 0; i
< 16; i
++) {
6840 env
->iwmmxt
.cregs
[i
] = qemu_get_be32(f
);
6844 if (arm_feature(env
, ARM_FEATURE_M
)) {
6845 env
->v7m
.other_sp
= qemu_get_be32(f
);
6846 env
->v7m
.vecbase
= qemu_get_be32(f
);
6847 env
->v7m
.basepri
= qemu_get_be32(f
);
6848 env
->v7m
.control
= qemu_get_be32(f
);
6849 env
->v7m
.current_sp
= qemu_get_be32(f
);
6850 env
->v7m
.exception
= qemu_get_be32(f
);
6858 //#warning No CPU save/restore functions
6862 /***********************************************************/
6863 /* ram save/restore */
6865 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6869 v
= qemu_get_byte(f
);
6872 if (qemu_get_buffer(f
, buf
, len
) != len
)
6876 v
= qemu_get_byte(f
);
6877 memset(buf
, v
, len
);
6885 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6890 if (qemu_get_be32(f
) != phys_ram_size
)
6892 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6893 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6900 #define BDRV_HASH_BLOCK_SIZE 1024
6901 #define IOBUF_SIZE 4096
6902 #define RAM_CBLOCK_MAGIC 0xfabe
6904 typedef struct RamCompressState
{
6907 uint8_t buf
[IOBUF_SIZE
];
6910 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6913 memset(s
, 0, sizeof(*s
));
6915 ret
= deflateInit2(&s
->zstream
, 1,
6917 9, Z_DEFAULT_STRATEGY
);
6920 s
->zstream
.avail_out
= IOBUF_SIZE
;
6921 s
->zstream
.next_out
= s
->buf
;
6925 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6927 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6928 qemu_put_be16(s
->f
, len
);
6929 qemu_put_buffer(s
->f
, buf
, len
);
6932 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6936 s
->zstream
.avail_in
= len
;
6937 s
->zstream
.next_in
= (uint8_t *)buf
;
6938 while (s
->zstream
.avail_in
> 0) {
6939 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6942 if (s
->zstream
.avail_out
== 0) {
6943 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6944 s
->zstream
.avail_out
= IOBUF_SIZE
;
6945 s
->zstream
.next_out
= s
->buf
;
6951 static void ram_compress_close(RamCompressState
*s
)
6955 /* compress last bytes */
6957 ret
= deflate(&s
->zstream
, Z_FINISH
);
6958 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6959 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6961 ram_put_cblock(s
, s
->buf
, len
);
6963 s
->zstream
.avail_out
= IOBUF_SIZE
;
6964 s
->zstream
.next_out
= s
->buf
;
6965 if (ret
== Z_STREAM_END
)
6972 deflateEnd(&s
->zstream
);
6975 typedef struct RamDecompressState
{
6978 uint8_t buf
[IOBUF_SIZE
];
6979 } RamDecompressState
;
6981 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6984 memset(s
, 0, sizeof(*s
));
6986 ret
= inflateInit(&s
->zstream
);
6992 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6996 s
->zstream
.avail_out
= len
;
6997 s
->zstream
.next_out
= buf
;
6998 while (s
->zstream
.avail_out
> 0) {
6999 if (s
->zstream
.avail_in
== 0) {
7000 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
7002 clen
= qemu_get_be16(s
->f
);
7003 if (clen
> IOBUF_SIZE
)
7005 qemu_get_buffer(s
->f
, s
->buf
, clen
);
7006 s
->zstream
.avail_in
= clen
;
7007 s
->zstream
.next_in
= s
->buf
;
7009 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
7010 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
7017 static void ram_decompress_close(RamDecompressState
*s
)
7019 inflateEnd(&s
->zstream
);
7022 static void ram_save(QEMUFile
*f
, void *opaque
)
7025 RamCompressState s1
, *s
= &s1
;
7028 qemu_put_be32(f
, phys_ram_size
);
7029 if (ram_compress_open(s
, f
) < 0)
7031 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7033 if (tight_savevm_enabled
) {
7037 /* find if the memory block is available on a virtual
7040 for(j
= 0; j
< nb_drives
; j
++) {
7041 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7043 BDRV_HASH_BLOCK_SIZE
);
7044 if (sector_num
>= 0)
7048 goto normal_compress
;
7051 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7052 ram_compress_buf(s
, buf
, 10);
7058 ram_compress_buf(s
, buf
, 1);
7059 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7062 ram_compress_close(s
);
7065 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7067 RamDecompressState s1
, *s
= &s1
;
7071 if (version_id
== 1)
7072 return ram_load_v1(f
, opaque
);
7073 if (version_id
!= 2)
7075 if (qemu_get_be32(f
) != phys_ram_size
)
7077 if (ram_decompress_open(s
, f
) < 0)
7079 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7080 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7081 fprintf(stderr
, "Error while reading ram block header\n");
7085 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7086 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7095 ram_decompress_buf(s
, buf
+ 1, 9);
7097 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7098 if (bs_index
>= nb_drives
) {
7099 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7102 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7104 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7105 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7106 bs_index
, sector_num
);
7113 printf("Error block header\n");
7117 ram_decompress_close(s
);
7121 /***********************************************************/
7122 /* bottom halves (can be seen as timers which expire ASAP) */
7131 static QEMUBH
*first_bh
= NULL
;
7133 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7136 bh
= qemu_mallocz(sizeof(QEMUBH
));
7140 bh
->opaque
= opaque
;
7144 int qemu_bh_poll(void)
7163 void qemu_bh_schedule(QEMUBH
*bh
)
7165 CPUState
*env
= cpu_single_env
;
7169 bh
->next
= first_bh
;
7172 /* stop the currently executing CPU to execute the BH ASAP */
7174 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7178 void qemu_bh_cancel(QEMUBH
*bh
)
7181 if (bh
->scheduled
) {
7184 pbh
= &(*pbh
)->next
;
7190 void qemu_bh_delete(QEMUBH
*bh
)
7196 /***********************************************************/
7197 /* machine registration */
7199 QEMUMachine
*first_machine
= NULL
;
7201 int qemu_register_machine(QEMUMachine
*m
)
7204 pm
= &first_machine
;
7212 static QEMUMachine
*find_machine(const char *name
)
7216 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7217 if (!strcmp(m
->name
, name
))
7223 /***********************************************************/
7224 /* main execution loop */
7226 static void gui_update(void *opaque
)
7228 DisplayState
*ds
= opaque
;
7229 ds
->dpy_refresh(ds
);
7230 qemu_mod_timer(ds
->gui_timer
,
7231 (ds
->gui_timer_interval
?
7232 ds
->gui_timer_interval
:
7233 GUI_REFRESH_INTERVAL
)
7234 + qemu_get_clock(rt_clock
));
7237 struct vm_change_state_entry
{
7238 VMChangeStateHandler
*cb
;
7240 LIST_ENTRY (vm_change_state_entry
) entries
;
7243 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7245 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7248 VMChangeStateEntry
*e
;
7250 e
= qemu_mallocz(sizeof (*e
));
7256 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7260 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7262 LIST_REMOVE (e
, entries
);
7266 static void vm_state_notify(int running
)
7268 VMChangeStateEntry
*e
;
7270 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7271 e
->cb(e
->opaque
, running
);
7275 /* XXX: support several handlers */
7276 static VMStopHandler
*vm_stop_cb
;
7277 static void *vm_stop_opaque
;
7279 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7282 vm_stop_opaque
= opaque
;
7286 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7297 qemu_rearm_alarm_timer(alarm_timer
);
7301 void vm_stop(int reason
)
7304 cpu_disable_ticks();
7308 vm_stop_cb(vm_stop_opaque
, reason
);
7315 /* reset/shutdown handler */
7317 typedef struct QEMUResetEntry
{
7318 QEMUResetHandler
*func
;
7320 struct QEMUResetEntry
*next
;
7323 static QEMUResetEntry
*first_reset_entry
;
7324 static int reset_requested
;
7325 static int shutdown_requested
;
7326 static int powerdown_requested
;
7328 int qemu_shutdown_requested(void)
7330 int r
= shutdown_requested
;
7331 shutdown_requested
= 0;
7335 int qemu_reset_requested(void)
7337 int r
= reset_requested
;
7338 reset_requested
= 0;
7342 int qemu_powerdown_requested(void)
7344 int r
= powerdown_requested
;
7345 powerdown_requested
= 0;
7349 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7351 QEMUResetEntry
**pre
, *re
;
7353 pre
= &first_reset_entry
;
7354 while (*pre
!= NULL
)
7355 pre
= &(*pre
)->next
;
7356 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7358 re
->opaque
= opaque
;
7363 void qemu_system_reset(void)
7367 /* reset all devices */
7368 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7369 re
->func(re
->opaque
);
7373 void qemu_system_reset_request(void)
7376 shutdown_requested
= 1;
7378 reset_requested
= 1;
7381 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7384 void qemu_system_shutdown_request(void)
7386 shutdown_requested
= 1;
7388 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7391 void qemu_system_powerdown_request(void)
7393 powerdown_requested
= 1;
7395 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7398 void main_loop_wait(int timeout
)
7400 IOHandlerRecord
*ioh
;
7401 fd_set rfds
, wfds
, xfds
;
7410 /* XXX: need to suppress polling by better using win32 events */
7412 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7413 ret
|= pe
->func(pe
->opaque
);
7418 WaitObjects
*w
= &wait_objects
;
7420 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7421 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7422 if (w
->func
[ret
- WAIT_OBJECT_0
])
7423 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7425 /* Check for additional signaled events */
7426 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7428 /* Check if event is signaled */
7429 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7430 if(ret2
== WAIT_OBJECT_0
) {
7432 w
->func
[i
](w
->opaque
[i
]);
7433 } else if (ret2
== WAIT_TIMEOUT
) {
7435 err
= GetLastError();
7436 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7439 } else if (ret
== WAIT_TIMEOUT
) {
7441 err
= GetLastError();
7442 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7446 /* poll any events */
7447 /* XXX: separate device handlers from system ones */
7452 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7456 (!ioh
->fd_read_poll
||
7457 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7458 FD_SET(ioh
->fd
, &rfds
);
7462 if (ioh
->fd_write
) {
7463 FD_SET(ioh
->fd
, &wfds
);
7473 tv
.tv_usec
= timeout
* 1000;
7475 #if defined(CONFIG_SLIRP)
7477 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7480 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7482 IOHandlerRecord
**pioh
;
7484 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7485 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7486 ioh
->fd_read(ioh
->opaque
);
7488 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7489 ioh
->fd_write(ioh
->opaque
);
7493 /* remove deleted IO handlers */
7494 pioh
= &first_io_handler
;
7504 #if defined(CONFIG_SLIRP)
7511 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7517 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7518 qemu_get_clock(vm_clock
));
7519 /* run dma transfers, if any */
7523 /* real time timers */
7524 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7525 qemu_get_clock(rt_clock
));
7527 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7528 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7529 qemu_rearm_alarm_timer(alarm_timer
);
7532 /* Check bottom-halves last in case any of the earlier events triggered
7538 static int main_loop(void)
7541 #ifdef CONFIG_PROFILER
7546 cur_cpu
= first_cpu
;
7547 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7554 #ifdef CONFIG_PROFILER
7555 ti
= profile_getclock();
7557 ret
= cpu_exec(env
);
7558 #ifdef CONFIG_PROFILER
7559 qemu_time
+= profile_getclock() - ti
;
7561 next_cpu
= env
->next_cpu
?: first_cpu
;
7562 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7563 ret
= EXCP_INTERRUPT
;
7567 if (ret
== EXCP_HLT
) {
7568 /* Give the next CPU a chance to run. */
7572 if (ret
!= EXCP_HALTED
)
7574 /* all CPUs are halted ? */
7580 if (shutdown_requested
) {
7581 ret
= EXCP_INTERRUPT
;
7589 if (reset_requested
) {
7590 reset_requested
= 0;
7591 qemu_system_reset();
7592 ret
= EXCP_INTERRUPT
;
7594 if (powerdown_requested
) {
7595 powerdown_requested
= 0;
7596 qemu_system_powerdown();
7597 ret
= EXCP_INTERRUPT
;
7599 if (unlikely(ret
== EXCP_DEBUG
)) {
7600 vm_stop(EXCP_DEBUG
);
7602 /* If all cpus are halted then wait until the next IRQ */
7603 /* XXX: use timeout computed from timers */
7604 if (ret
== EXCP_HALTED
)
7611 #ifdef CONFIG_PROFILER
7612 ti
= profile_getclock();
7614 main_loop_wait(timeout
);
7615 #ifdef CONFIG_PROFILER
7616 dev_time
+= profile_getclock() - ti
;
7619 cpu_disable_ticks();
7623 static void help(int exitcode
)
7625 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7626 "usage: %s [options] [disk_image]\n"
7628 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7630 "Standard options:\n"
7631 "-M machine select emulated machine (-M ? for list)\n"
7632 "-cpu cpu select CPU (-cpu ? for list)\n"
7633 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7634 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7635 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7636 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7637 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7638 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7639 " [,cache=on|off]\n"
7640 " use 'file' as a drive image\n"
7641 "-mtdblock file use 'file' as on-board Flash memory image\n"
7642 "-sd file use 'file' as SecureDigital card image\n"
7643 "-pflash file use 'file' as a parallel flash image\n"
7644 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7645 "-snapshot write to temporary files instead of disk image files\n"
7647 "-no-frame open SDL window without a frame and window decorations\n"
7648 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7649 "-no-quit disable SDL window close capability\n"
7652 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7654 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7655 "-smp n set the number of CPUs to 'n' [default=1]\n"
7656 "-nographic disable graphical output and redirect serial I/Os to console\n"
7657 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7659 "-k language use keyboard layout (for example \"fr\" for French)\n"
7662 "-audio-help print list of audio drivers and their options\n"
7663 "-soundhw c1,... enable audio support\n"
7664 " and only specified sound cards (comma separated list)\n"
7665 " use -soundhw ? to get the list of supported cards\n"
7666 " use -soundhw all to enable all of them\n"
7668 "-localtime set the real time clock to local time [default=utc]\n"
7669 "-full-screen start in full screen\n"
7671 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7673 "-usb enable the USB driver (will be the default soon)\n"
7674 "-usbdevice name add the host or guest USB device 'name'\n"
7675 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7676 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7678 "-name string set the name of the guest\n"
7680 "Network options:\n"
7681 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7682 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7684 "-net user[,vlan=n][,hostname=host]\n"
7685 " connect the user mode network stack to VLAN 'n' and send\n"
7686 " hostname 'host' to DHCP clients\n"
7689 "-net tap[,vlan=n],ifname=name\n"
7690 " connect the host TAP network interface to VLAN 'n'\n"
7692 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7693 " connect the host TAP network interface to VLAN 'n' and use the\n"
7694 " network scripts 'file' (default=%s)\n"
7695 " and 'dfile' (default=%s);\n"
7696 " use '[down]script=no' to disable script execution;\n"
7697 " use 'fd=h' to connect to an already opened TAP interface\n"
7699 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7700 " connect the vlan 'n' to another VLAN using a socket connection\n"
7701 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7702 " connect the vlan 'n' to multicast maddr and port\n"
7703 "-net none use it alone to have zero network devices; if no -net option\n"
7704 " is provided, the default is '-net nic -net user'\n"
7707 "-tftp dir allow tftp access to files in dir [-net user]\n"
7708 "-bootp file advertise file in BOOTP replies\n"
7710 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7712 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7713 " redirect TCP or UDP connections from host to guest [-net user]\n"
7716 "Linux boot specific:\n"
7717 "-kernel bzImage use 'bzImage' as kernel image\n"
7718 "-append cmdline use 'cmdline' as kernel command line\n"
7719 "-initrd file use 'file' as initial ram disk\n"
7721 "Debug/Expert options:\n"
7722 "-monitor dev redirect the monitor to char device 'dev'\n"
7723 "-serial dev redirect the serial port to char device 'dev'\n"
7724 "-parallel dev redirect the parallel port to char device 'dev'\n"
7725 "-pidfile file Write PID to 'file'\n"
7726 "-S freeze CPU at startup (use 'c' to start execution)\n"
7727 "-s wait gdb connection to port\n"
7728 "-p port set gdb connection port [default=%s]\n"
7729 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7730 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7731 " translation (t=none or lba) (usually qemu can guess them)\n"
7732 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7734 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7735 "-no-kqemu disable KQEMU kernel module usage\n"
7738 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7739 " (default is CL-GD5446 PCI VGA)\n"
7740 "-no-acpi disable ACPI\n"
7742 #ifdef CONFIG_CURSES
7743 "-curses use a curses/ncurses interface instead of SDL\n"
7745 "-no-reboot exit instead of rebooting\n"
7746 "-no-shutdown stop before shutdown\n"
7747 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7748 "-vnc display start a VNC server on display\n"
7750 "-daemonize daemonize QEMU after initializing\n"
7752 "-option-rom rom load a file, rom, into the option ROM space\n"
7754 "-prom-env variable=value set OpenBIOS nvram variables\n"
7756 "-clock force the use of the given methods for timer alarm.\n"
7757 " To see what timers are available use -clock ?\n"
7758 "-startdate select initial date of the clock\n"
7760 "During emulation, the following keys are useful:\n"
7761 "ctrl-alt-f toggle full screen\n"
7762 "ctrl-alt-n switch to virtual console 'n'\n"
7763 "ctrl-alt toggle mouse and keyboard grab\n"
7765 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7770 DEFAULT_NETWORK_SCRIPT
,
7771 DEFAULT_NETWORK_DOWN_SCRIPT
,
7773 DEFAULT_GDBSTUB_PORT
,
7778 #define HAS_ARG 0x0001
7793 QEMU_OPTION_mtdblock
,
7797 QEMU_OPTION_snapshot
,
7799 QEMU_OPTION_no_fd_bootchk
,
7802 QEMU_OPTION_nographic
,
7803 QEMU_OPTION_portrait
,
7805 QEMU_OPTION_audio_help
,
7806 QEMU_OPTION_soundhw
,
7826 QEMU_OPTION_no_code_copy
,
7828 QEMU_OPTION_localtime
,
7829 QEMU_OPTION_cirrusvga
,
7832 QEMU_OPTION_std_vga
,
7834 QEMU_OPTION_monitor
,
7836 QEMU_OPTION_parallel
,
7838 QEMU_OPTION_full_screen
,
7839 QEMU_OPTION_no_frame
,
7840 QEMU_OPTION_alt_grab
,
7841 QEMU_OPTION_no_quit
,
7842 QEMU_OPTION_pidfile
,
7843 QEMU_OPTION_no_kqemu
,
7844 QEMU_OPTION_kernel_kqemu
,
7845 QEMU_OPTION_win2k_hack
,
7847 QEMU_OPTION_usbdevice
,
7850 QEMU_OPTION_no_acpi
,
7852 QEMU_OPTION_no_reboot
,
7853 QEMU_OPTION_no_shutdown
,
7854 QEMU_OPTION_show_cursor
,
7855 QEMU_OPTION_daemonize
,
7856 QEMU_OPTION_option_rom
,
7857 QEMU_OPTION_semihosting
,
7859 QEMU_OPTION_prom_env
,
7860 QEMU_OPTION_old_param
,
7862 QEMU_OPTION_startdate
,
7865 typedef struct QEMUOption
{
7871 const QEMUOption qemu_options
[] = {
7872 { "h", 0, QEMU_OPTION_h
},
7873 { "help", 0, QEMU_OPTION_h
},
7875 { "M", HAS_ARG
, QEMU_OPTION_M
},
7876 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7877 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7878 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7879 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7880 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7881 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7882 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7883 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7884 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7885 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7886 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7887 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7888 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7889 { "snapshot", 0, QEMU_OPTION_snapshot
},
7891 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7893 { "m", HAS_ARG
, QEMU_OPTION_m
},
7894 { "nographic", 0, QEMU_OPTION_nographic
},
7895 { "portrait", 0, QEMU_OPTION_portrait
},
7896 { "k", HAS_ARG
, QEMU_OPTION_k
},
7898 { "audio-help", 0, QEMU_OPTION_audio_help
},
7899 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7902 { "net", HAS_ARG
, QEMU_OPTION_net
},
7904 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7905 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7907 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7909 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7912 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7913 { "append", HAS_ARG
, QEMU_OPTION_append
},
7914 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7916 { "S", 0, QEMU_OPTION_S
},
7917 { "s", 0, QEMU_OPTION_s
},
7918 { "p", HAS_ARG
, QEMU_OPTION_p
},
7919 { "d", HAS_ARG
, QEMU_OPTION_d
},
7920 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7921 { "L", HAS_ARG
, QEMU_OPTION_L
},
7922 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7923 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
7925 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7926 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7928 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7929 { "g", 1, QEMU_OPTION_g
},
7931 { "localtime", 0, QEMU_OPTION_localtime
},
7932 { "std-vga", 0, QEMU_OPTION_std_vga
},
7933 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7934 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7935 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7936 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7937 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7938 { "full-screen", 0, QEMU_OPTION_full_screen
},
7940 { "no-frame", 0, QEMU_OPTION_no_frame
},
7941 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7942 { "no-quit", 0, QEMU_OPTION_no_quit
},
7944 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7945 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7946 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7947 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7948 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7949 #ifdef CONFIG_CURSES
7950 { "curses", 0, QEMU_OPTION_curses
},
7953 /* temporary options */
7954 { "usb", 0, QEMU_OPTION_usb
},
7955 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7956 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7957 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7958 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7959 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7960 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7961 { "daemonize", 0, QEMU_OPTION_daemonize
},
7962 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7963 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7964 { "semihosting", 0, QEMU_OPTION_semihosting
},
7966 { "name", HAS_ARG
, QEMU_OPTION_name
},
7967 #if defined(TARGET_SPARC)
7968 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7970 #if defined(TARGET_ARM)
7971 { "old-param", 0, QEMU_OPTION_old_param
},
7973 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7974 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7978 /* password input */
7980 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
7985 if (!bdrv_is_encrypted(bs
))
7988 term_printf("%s is encrypted.\n", name
);
7989 for(i
= 0; i
< 3; i
++) {
7990 monitor_readline("Password: ", 1, password
, sizeof(password
));
7991 if (bdrv_set_key(bs
, password
) == 0)
7993 term_printf("invalid password\n");
7998 static BlockDriverState
*get_bdrv(int index
)
8000 if (index
> nb_drives
)
8002 return drives_table
[index
].bdrv
;
8005 static void read_passwords(void)
8007 BlockDriverState
*bs
;
8010 for(i
= 0; i
< 6; i
++) {
8013 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8017 /* XXX: currently we cannot use simultaneously different CPUs */
8018 static void register_machines(void)
8020 #if defined(TARGET_I386)
8021 qemu_register_machine(&pc_machine
);
8022 qemu_register_machine(&isapc_machine
);
8023 #elif defined(TARGET_PPC)
8024 qemu_register_machine(&heathrow_machine
);
8025 qemu_register_machine(&core99_machine
);
8026 qemu_register_machine(&prep_machine
);
8027 qemu_register_machine(&ref405ep_machine
);
8028 qemu_register_machine(&taihu_machine
);
8029 #elif defined(TARGET_MIPS)
8030 qemu_register_machine(&mips_machine
);
8031 qemu_register_machine(&mips_magnum_machine
);
8032 qemu_register_machine(&mips_malta_machine
);
8033 qemu_register_machine(&mips_pica61_machine
);
8034 qemu_register_machine(&mips_mipssim_machine
);
8035 #elif defined(TARGET_SPARC)
8036 #ifdef TARGET_SPARC64
8037 qemu_register_machine(&sun4u_machine
);
8039 qemu_register_machine(&ss5_machine
);
8040 qemu_register_machine(&ss10_machine
);
8041 qemu_register_machine(&ss600mp_machine
);
8042 qemu_register_machine(&ss20_machine
);
8043 qemu_register_machine(&ss2_machine
);
8044 qemu_register_machine(&voyager_machine
);
8045 qemu_register_machine(&ss_lx_machine
);
8046 qemu_register_machine(&ss4_machine
);
8047 qemu_register_machine(&scls_machine
);
8048 qemu_register_machine(&sbook_machine
);
8049 qemu_register_machine(&ss1000_machine
);
8050 qemu_register_machine(&ss2000_machine
);
8052 #elif defined(TARGET_ARM)
8053 qemu_register_machine(&integratorcp_machine
);
8054 qemu_register_machine(&versatilepb_machine
);
8055 qemu_register_machine(&versatileab_machine
);
8056 qemu_register_machine(&realview_machine
);
8057 qemu_register_machine(&akitapda_machine
);
8058 qemu_register_machine(&spitzpda_machine
);
8059 qemu_register_machine(&borzoipda_machine
);
8060 qemu_register_machine(&terrierpda_machine
);
8061 qemu_register_machine(&palmte_machine
);
8062 qemu_register_machine(&n800_machine
);
8063 qemu_register_machine(&lm3s811evb_machine
);
8064 qemu_register_machine(&lm3s6965evb_machine
);
8065 qemu_register_machine(&connex_machine
);
8066 qemu_register_machine(&verdex_machine
);
8067 qemu_register_machine(&mainstone2_machine
);
8068 qemu_register_machine(&musicpal_machine
);
8069 #elif defined(TARGET_SH4)
8070 qemu_register_machine(&shix_machine
);
8071 qemu_register_machine(&r2d_machine
);
8072 #elif defined(TARGET_ALPHA)
8074 #elif defined(TARGET_M68K)
8075 qemu_register_machine(&mcf5208evb_machine
);
8076 qemu_register_machine(&an5206_machine
);
8077 qemu_register_machine(&dummy_m68k_machine
);
8078 #elif defined(TARGET_CRIS)
8079 qemu_register_machine(&bareetraxfs_machine
);
8081 #error unsupported CPU
8086 struct soundhw soundhw
[] = {
8087 #ifdef HAS_AUDIO_CHOICE
8088 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8094 { .init_isa
= pcspk_audio_init
}
8099 "Creative Sound Blaster 16",
8102 { .init_isa
= SB16_init
}
8109 "Yamaha YMF262 (OPL3)",
8111 "Yamaha YM3812 (OPL2)",
8115 { .init_isa
= Adlib_init
}
8122 "Gravis Ultrasound GF1",
8125 { .init_isa
= GUS_init
}
8132 "Intel 82801AA AC97 Audio",
8135 { .init_pci
= ac97_init
}
8141 "ENSONIQ AudioPCI ES1370",
8144 { .init_pci
= es1370_init
}
8148 { NULL
, NULL
, 0, 0, { NULL
} }
8151 static void select_soundhw (const char *optarg
)
8155 if (*optarg
== '?') {
8158 printf ("Valid sound card names (comma separated):\n");
8159 for (c
= soundhw
; c
->name
; ++c
) {
8160 printf ("%-11s %s\n", c
->name
, c
->descr
);
8162 printf ("\n-soundhw all will enable all of the above\n");
8163 exit (*optarg
!= '?');
8171 if (!strcmp (optarg
, "all")) {
8172 for (c
= soundhw
; c
->name
; ++c
) {
8180 e
= strchr (p
, ',');
8181 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8183 for (c
= soundhw
; c
->name
; ++c
) {
8184 if (!strncmp (c
->name
, p
, l
)) {
8193 "Unknown sound card name (too big to show)\n");
8196 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8201 p
+= l
+ (e
!= NULL
);
8205 goto show_valid_cards
;
8211 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8213 exit(STATUS_CONTROL_C_EXIT
);
8218 #define MAX_NET_CLIENTS 32
8220 int main(int argc
, char **argv
)
8222 #ifdef CONFIG_GDBSTUB
8224 const char *gdbstub_port
;
8226 uint32_t boot_devices_bitmap
= 0;
8228 int snapshot
, linux_boot
, net_boot
;
8229 const char *initrd_filename
;
8230 const char *kernel_filename
, *kernel_cmdline
;
8231 const char *boot_devices
= "";
8232 DisplayState
*ds
= &display_state
;
8233 int cyls
, heads
, secs
, translation
;
8234 const char *net_clients
[MAX_NET_CLIENTS
];
8238 const char *r
, *optarg
;
8239 CharDriverState
*monitor_hd
;
8240 const char *monitor_device
;
8241 const char *serial_devices
[MAX_SERIAL_PORTS
];
8242 int serial_device_index
;
8243 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8244 int parallel_device_index
;
8245 const char *loadvm
= NULL
;
8246 QEMUMachine
*machine
;
8247 const char *cpu_model
;
8248 const char *usb_devices
[MAX_USB_CMDLINE
];
8249 int usb_devices_index
;
8251 const char *pid_file
= NULL
;
8254 LIST_INIT (&vm_change_state_head
);
8257 struct sigaction act
;
8258 sigfillset(&act
.sa_mask
);
8260 act
.sa_handler
= SIG_IGN
;
8261 sigaction(SIGPIPE
, &act
, NULL
);
8264 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8265 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8266 QEMU to run on a single CPU */
8271 h
= GetCurrentProcess();
8272 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8273 for(i
= 0; i
< 32; i
++) {
8274 if (mask
& (1 << i
))
8279 SetProcessAffinityMask(h
, mask
);
8285 register_machines();
8286 machine
= first_machine
;
8288 initrd_filename
= NULL
;
8290 vga_ram_size
= VGA_RAM_SIZE
;
8291 #ifdef CONFIG_GDBSTUB
8293 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8298 kernel_filename
= NULL
;
8299 kernel_cmdline
= "";
8300 cyls
= heads
= secs
= 0;
8301 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8302 monitor_device
= "vc";
8304 serial_devices
[0] = "vc";
8305 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8306 serial_devices
[i
] = NULL
;
8307 serial_device_index
= 0;
8309 parallel_devices
[0] = "vc";
8310 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8311 parallel_devices
[i
] = NULL
;
8312 parallel_device_index
= 0;
8314 usb_devices_index
= 0;
8322 /* default mac address of the first network interface */
8330 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8332 const QEMUOption
*popt
;
8335 /* Treat --foo the same as -foo. */
8338 popt
= qemu_options
;
8341 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8345 if (!strcmp(popt
->name
, r
+ 1))
8349 if (popt
->flags
& HAS_ARG
) {
8350 if (optind
>= argc
) {
8351 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8355 optarg
= argv
[optind
++];
8360 switch(popt
->index
) {
8362 machine
= find_machine(optarg
);
8365 printf("Supported machines are:\n");
8366 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8367 printf("%-10s %s%s\n",
8369 m
== first_machine
? " (default)" : "");
8371 exit(*optarg
!= '?');
8374 case QEMU_OPTION_cpu
:
8375 /* hw initialization will check this */
8376 if (*optarg
== '?') {
8377 /* XXX: implement xxx_cpu_list for targets that still miss it */
8378 #if defined(cpu_list)
8379 cpu_list(stdout
, &fprintf
);
8386 case QEMU_OPTION_initrd
:
8387 initrd_filename
= optarg
;
8389 case QEMU_OPTION_hda
:
8391 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8393 hda_index
= drive_add(optarg
, HD_ALIAS
8394 ",cyls=%d,heads=%d,secs=%d%s",
8395 0, cyls
, heads
, secs
,
8396 translation
== BIOS_ATA_TRANSLATION_LBA
?
8398 translation
== BIOS_ATA_TRANSLATION_NONE
?
8399 ",trans=none" : "");
8401 case QEMU_OPTION_hdb
:
8402 case QEMU_OPTION_hdc
:
8403 case QEMU_OPTION_hdd
:
8404 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8406 case QEMU_OPTION_drive
:
8407 drive_add(NULL
, "%s", optarg
);
8409 case QEMU_OPTION_mtdblock
:
8410 drive_add(optarg
, MTD_ALIAS
);
8412 case QEMU_OPTION_sd
:
8413 drive_add(optarg
, SD_ALIAS
);
8415 case QEMU_OPTION_pflash
:
8416 drive_add(optarg
, PFLASH_ALIAS
);
8418 case QEMU_OPTION_snapshot
:
8421 case QEMU_OPTION_hdachs
:
8425 cyls
= strtol(p
, (char **)&p
, 0);
8426 if (cyls
< 1 || cyls
> 16383)
8431 heads
= strtol(p
, (char **)&p
, 0);
8432 if (heads
< 1 || heads
> 16)
8437 secs
= strtol(p
, (char **)&p
, 0);
8438 if (secs
< 1 || secs
> 63)
8442 if (!strcmp(p
, "none"))
8443 translation
= BIOS_ATA_TRANSLATION_NONE
;
8444 else if (!strcmp(p
, "lba"))
8445 translation
= BIOS_ATA_TRANSLATION_LBA
;
8446 else if (!strcmp(p
, "auto"))
8447 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8450 } else if (*p
!= '\0') {
8452 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8455 if (hda_index
!= -1)
8456 snprintf(drives_opt
[hda_index
].opt
,
8457 sizeof(drives_opt
[hda_index
].opt
),
8458 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8459 0, cyls
, heads
, secs
,
8460 translation
== BIOS_ATA_TRANSLATION_LBA
?
8462 translation
== BIOS_ATA_TRANSLATION_NONE
?
8463 ",trans=none" : "");
8466 case QEMU_OPTION_nographic
:
8467 serial_devices
[0] = "stdio";
8468 parallel_devices
[0] = "null";
8469 monitor_device
= "stdio";
8472 #ifdef CONFIG_CURSES
8473 case QEMU_OPTION_curses
:
8477 case QEMU_OPTION_portrait
:
8480 case QEMU_OPTION_kernel
:
8481 kernel_filename
= optarg
;
8483 case QEMU_OPTION_append
:
8484 kernel_cmdline
= optarg
;
8486 case QEMU_OPTION_cdrom
:
8487 drive_add(optarg
, CDROM_ALIAS
);
8489 case QEMU_OPTION_boot
:
8490 boot_devices
= optarg
;
8491 /* We just do some generic consistency checks */
8493 /* Could easily be extended to 64 devices if needed */
8496 boot_devices_bitmap
= 0;
8497 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8498 /* Allowed boot devices are:
8499 * a b : floppy disk drives
8500 * c ... f : IDE disk drives
8501 * g ... m : machine implementation dependant drives
8502 * n ... p : network devices
8503 * It's up to each machine implementation to check
8504 * if the given boot devices match the actual hardware
8505 * implementation and firmware features.
8507 if (*p
< 'a' || *p
> 'q') {
8508 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8511 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8513 "Boot device '%c' was given twice\n",*p
);
8516 boot_devices_bitmap
|= 1 << (*p
- 'a');
8520 case QEMU_OPTION_fda
:
8521 case QEMU_OPTION_fdb
:
8522 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8525 case QEMU_OPTION_no_fd_bootchk
:
8529 case QEMU_OPTION_no_code_copy
:
8530 code_copy_enabled
= 0;
8532 case QEMU_OPTION_net
:
8533 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8534 fprintf(stderr
, "qemu: too many network clients\n");
8537 net_clients
[nb_net_clients
] = optarg
;
8541 case QEMU_OPTION_tftp
:
8542 tftp_prefix
= optarg
;
8544 case QEMU_OPTION_bootp
:
8545 bootp_filename
= optarg
;
8548 case QEMU_OPTION_smb
:
8549 net_slirp_smb(optarg
);
8552 case QEMU_OPTION_redir
:
8553 net_slirp_redir(optarg
);
8557 case QEMU_OPTION_audio_help
:
8561 case QEMU_OPTION_soundhw
:
8562 select_soundhw (optarg
);
8568 case QEMU_OPTION_m
: {
8572 value
= strtoul(optarg
, &ptr
, 10);
8574 case 0: case 'M': case 'm':
8581 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8585 /* On 32-bit hosts, QEMU is limited by virtual address space */
8586 if (value
> (2047 << 20)
8588 && HOST_LONG_BITS
== 32
8591 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8594 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8595 fprintf(stderr
, "qemu: ram size too large\n");
8606 mask
= cpu_str_to_log_mask(optarg
);
8608 printf("Log items (comma separated):\n");
8609 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8610 printf("%-10s %s\n", item
->name
, item
->help
);
8617 #ifdef CONFIG_GDBSTUB
8622 gdbstub_port
= optarg
;
8628 case QEMU_OPTION_bios
:
8635 keyboard_layout
= optarg
;
8637 case QEMU_OPTION_localtime
:
8640 case QEMU_OPTION_cirrusvga
:
8641 cirrus_vga_enabled
= 1;
8644 case QEMU_OPTION_vmsvga
:
8645 cirrus_vga_enabled
= 0;
8648 case QEMU_OPTION_std_vga
:
8649 cirrus_vga_enabled
= 0;
8657 w
= strtol(p
, (char **)&p
, 10);
8660 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8666 h
= strtol(p
, (char **)&p
, 10);
8671 depth
= strtol(p
, (char **)&p
, 10);
8672 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8673 depth
!= 24 && depth
!= 32)
8675 } else if (*p
== '\0') {
8676 depth
= graphic_depth
;
8683 graphic_depth
= depth
;
8686 case QEMU_OPTION_echr
:
8689 term_escape_char
= strtol(optarg
, &r
, 0);
8691 printf("Bad argument to echr\n");
8694 case QEMU_OPTION_monitor
:
8695 monitor_device
= optarg
;
8697 case QEMU_OPTION_serial
:
8698 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8699 fprintf(stderr
, "qemu: too many serial ports\n");
8702 serial_devices
[serial_device_index
] = optarg
;
8703 serial_device_index
++;
8705 case QEMU_OPTION_parallel
:
8706 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8707 fprintf(stderr
, "qemu: too many parallel ports\n");
8710 parallel_devices
[parallel_device_index
] = optarg
;
8711 parallel_device_index
++;
8713 case QEMU_OPTION_loadvm
:
8716 case QEMU_OPTION_full_screen
:
8720 case QEMU_OPTION_no_frame
:
8723 case QEMU_OPTION_alt_grab
:
8726 case QEMU_OPTION_no_quit
:
8730 case QEMU_OPTION_pidfile
:
8734 case QEMU_OPTION_win2k_hack
:
8735 win2k_install_hack
= 1;
8739 case QEMU_OPTION_no_kqemu
:
8742 case QEMU_OPTION_kernel_kqemu
:
8746 case QEMU_OPTION_usb
:
8749 case QEMU_OPTION_usbdevice
:
8751 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8752 fprintf(stderr
, "Too many USB devices\n");
8755 usb_devices
[usb_devices_index
] = optarg
;
8756 usb_devices_index
++;
8758 case QEMU_OPTION_smp
:
8759 smp_cpus
= atoi(optarg
);
8760 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8761 fprintf(stderr
, "Invalid number of CPUs\n");
8765 case QEMU_OPTION_vnc
:
8766 vnc_display
= optarg
;
8768 case QEMU_OPTION_no_acpi
:
8771 case QEMU_OPTION_no_reboot
:
8774 case QEMU_OPTION_no_shutdown
:
8777 case QEMU_OPTION_show_cursor
:
8780 case QEMU_OPTION_daemonize
:
8783 case QEMU_OPTION_option_rom
:
8784 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8785 fprintf(stderr
, "Too many option ROMs\n");
8788 option_rom
[nb_option_roms
] = optarg
;
8791 case QEMU_OPTION_semihosting
:
8792 semihosting_enabled
= 1;
8794 case QEMU_OPTION_name
:
8798 case QEMU_OPTION_prom_env
:
8799 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8800 fprintf(stderr
, "Too many prom variables\n");
8803 prom_envs
[nb_prom_envs
] = optarg
;
8808 case QEMU_OPTION_old_param
:
8812 case QEMU_OPTION_clock
:
8813 configure_alarms(optarg
);
8815 case QEMU_OPTION_startdate
:
8818 time_t rtc_start_date
;
8819 if (!strcmp(optarg
, "now")) {
8820 rtc_date_offset
= -1;
8822 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8830 } else if (sscanf(optarg
, "%d-%d-%d",
8833 &tm
.tm_mday
) == 3) {
8842 rtc_start_date
= mktimegm(&tm
);
8843 if (rtc_start_date
== -1) {
8845 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8846 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8849 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8858 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
8859 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
8866 if (pipe(fds
) == -1)
8877 len
= read(fds
[0], &status
, 1);
8878 if (len
== -1 && (errno
== EINTR
))
8883 else if (status
== 1) {
8884 fprintf(stderr
, "Could not acquire pidfile\n");
8902 signal(SIGTSTP
, SIG_IGN
);
8903 signal(SIGTTOU
, SIG_IGN
);
8904 signal(SIGTTIN
, SIG_IGN
);
8908 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8911 write(fds
[1], &status
, 1);
8913 fprintf(stderr
, "Could not acquire pid file\n");
8921 linux_boot
= (kernel_filename
!= NULL
);
8922 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8924 /* XXX: this should not be: some embedded targets just have flash */
8925 if (!linux_boot
&& net_boot
== 0 &&
8929 /* boot to floppy or the default cd if no hard disk defined yet */
8930 if (!boot_devices
[0]) {
8931 boot_devices
= "cad";
8933 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8943 /* init network clients */
8944 if (nb_net_clients
== 0) {
8945 /* if no clients, we use a default config */
8946 net_clients
[0] = "nic";
8947 net_clients
[1] = "user";
8951 for(i
= 0;i
< nb_net_clients
; i
++) {
8952 if (net_client_init(net_clients
[i
]) < 0)
8955 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8956 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8958 if (vlan
->nb_guest_devs
== 0) {
8959 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
8962 if (vlan
->nb_host_devs
== 0)
8964 "Warning: vlan %d is not connected to host network\n",
8969 /* XXX: this should be moved in the PC machine instantiation code */
8970 if (net_boot
!= 0) {
8972 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8973 const char *model
= nd_table
[i
].model
;
8975 if (net_boot
& (1 << i
)) {
8978 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
8979 if (get_image_size(buf
) > 0) {
8980 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8981 fprintf(stderr
, "Too many option ROMs\n");
8984 option_rom
[nb_option_roms
] = strdup(buf
);
8991 fprintf(stderr
, "No valid PXE rom found for network device\n");
8997 /* init the memory */
8998 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9000 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9002 if (ram_size
< phys_ram_size
) {
9003 fprintf(stderr
, "Machine `%s' requires %i bytes of memory\n",
9004 machine
->name
, phys_ram_size
);
9008 phys_ram_size
= ram_size
;
9010 ram_size
= phys_ram_size
;
9013 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9015 phys_ram_size
+= ram_size
;
9018 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9019 if (!phys_ram_base
) {
9020 fprintf(stderr
, "Could not allocate physical memory\n");
9026 /* we always create the cdrom drive, even if no disk is there */
9028 if (nb_drives_opt
< MAX_DRIVES
)
9029 drive_add(NULL
, CDROM_ALIAS
);
9031 /* we always create at least one floppy */
9033 if (nb_drives_opt
< MAX_DRIVES
)
9034 drive_add(NULL
, FD_ALIAS
, 0);
9036 /* we always create one sd slot, even if no card is in it */
9038 if (nb_drives_opt
< MAX_DRIVES
)
9039 drive_add(NULL
, SD_ALIAS
);
9041 /* open the virtual block devices */
9043 for(i
= 0; i
< nb_drives_opt
; i
++)
9044 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9047 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9048 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9053 memset(&display_state
, 0, sizeof(display_state
));
9056 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9059 /* nearly nothing to do */
9060 dumb_display_init(ds
);
9061 } else if (vnc_display
!= NULL
) {
9062 vnc_display_init(ds
);
9063 if (vnc_display_open(ds
, vnc_display
) < 0)
9066 #if defined(CONFIG_CURSES)
9068 curses_display_init(ds
, full_screen
);
9072 #if defined(CONFIG_SDL)
9073 sdl_display_init(ds
, full_screen
, no_frame
);
9074 #elif defined(CONFIG_COCOA)
9075 cocoa_display_init(ds
, full_screen
);
9077 dumb_display_init(ds
);
9081 /* Maintain compatibility with multiple stdio monitors */
9082 if (!strcmp(monitor_device
,"stdio")) {
9083 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9084 const char *devname
= serial_devices
[i
];
9085 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9086 monitor_device
= NULL
;
9088 } else if (devname
&& !strcmp(devname
,"stdio")) {
9089 monitor_device
= NULL
;
9090 serial_devices
[i
] = "mon:stdio";
9095 if (monitor_device
) {
9096 monitor_hd
= qemu_chr_open(monitor_device
);
9098 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9101 monitor_init(monitor_hd
, !nographic
);
9104 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9105 const char *devname
= serial_devices
[i
];
9106 if (devname
&& strcmp(devname
, "none")) {
9107 serial_hds
[i
] = qemu_chr_open(devname
);
9108 if (!serial_hds
[i
]) {
9109 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9113 if (strstart(devname
, "vc", 0))
9114 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9118 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9119 const char *devname
= parallel_devices
[i
];
9120 if (devname
&& strcmp(devname
, "none")) {
9121 parallel_hds
[i
] = qemu_chr_open(devname
);
9122 if (!parallel_hds
[i
]) {
9123 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9127 if (strstart(devname
, "vc", 0))
9128 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9132 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9133 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9135 /* init USB devices */
9137 for(i
= 0; i
< usb_devices_index
; i
++) {
9138 if (usb_device_add(usb_devices
[i
]) < 0) {
9139 fprintf(stderr
, "Warning: could not add USB device %s\n",
9145 if (display_state
.dpy_refresh
) {
9146 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9147 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9150 #ifdef CONFIG_GDBSTUB
9152 /* XXX: use standard host:port notation and modify options
9154 if (gdbserver_start(gdbstub_port
) < 0) {
9155 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9166 /* XXX: simplify init */
9179 len
= write(fds
[1], &status
, 1);
9180 if (len
== -1 && (errno
== EINTR
))
9186 TFR(fd
= open("/dev/null", O_RDWR
));
9200 #if !defined(_WIN32)
9201 /* close network clients */
9202 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9203 VLANClientState
*vc
;
9205 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9206 if (vc
->fd_read
== tap_receive
) {
9208 TAPState
*s
= vc
->opaque
;
9210 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9212 launch_script(s
->down_script
, ifname
, s
->fd
);