4 * Copyright (c) 2003-2005 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
34 #include <sys/times.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
54 #include <linux/if_ether.h>
57 #include <linux/rtc.h>
58 #include <linux/ppdev.h>
63 #if defined(CONFIG_SLIRP)
69 #include <sys/timeb.h>
71 #define getopt_long_only getopt_long
72 #define memalign(align, size) malloc(size)
75 #include "qemu_socket.h"
81 #endif /* CONFIG_SDL */
85 #define main qemu_main
86 #endif /* CONFIG_COCOA */
96 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
98 //#define DEBUG_UNUSED_IOPORT
99 //#define DEBUG_IOPORT
101 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
104 #define DEFAULT_RAM_SIZE 144
106 #define DEFAULT_RAM_SIZE 128
109 #define GUI_REFRESH_INTERVAL 30
111 /* Max number of USB devices that can be specified on the commandline. */
112 #define MAX_USB_CMDLINE 8
114 /* XXX: use a two level table to limit memory usage */
115 #define MAX_IOPORTS 65536
117 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
118 char phys_ram_file
[1024];
119 void *ioport_opaque
[MAX_IOPORTS
];
120 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
121 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
122 BlockDriverState
*bs_table
[MAX_DISKS
], *fd_table
[MAX_FD
];
125 static DisplayState display_state
;
127 const char* keyboard_layout
= NULL
;
128 int64_t ticks_per_sec
;
129 int boot_device
= 'c';
131 int pit_min_timer_count
= 0;
133 NICInfo nd_table
[MAX_NICS
];
134 QEMUTimer
*gui_timer
;
137 int cirrus_vga_enabled
= 1;
139 int graphic_width
= 1024;
140 int graphic_height
= 768;
142 int graphic_width
= 800;
143 int graphic_height
= 600;
145 int graphic_depth
= 15;
147 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
148 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
150 int win2k_install_hack
= 0;
153 static VLANState
*first_vlan
;
155 int vnc_display
= -1;
156 #if defined(TARGET_SPARC)
158 #elif defined(TARGET_I386)
163 int acpi_enabled
= 1;
166 /***********************************************************/
167 /* x86 ISA bus support */
169 target_phys_addr_t isa_mem_base
= 0;
172 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
174 #ifdef DEBUG_UNUSED_IOPORT
175 fprintf(stderr
, "inb: port=0x%04x\n", address
);
180 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
182 #ifdef DEBUG_UNUSED_IOPORT
183 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
187 /* default is to make two byte accesses */
188 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
191 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
192 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
193 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
197 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
199 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
200 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
201 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
204 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr
, "inl: port=0x%04x\n", address
);
212 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
214 #ifdef DEBUG_UNUSED_IOPORT
215 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
219 void init_ioports(void)
223 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
224 ioport_read_table
[0][i
] = default_ioport_readb
;
225 ioport_write_table
[0][i
] = default_ioport_writeb
;
226 ioport_read_table
[1][i
] = default_ioport_readw
;
227 ioport_write_table
[1][i
] = default_ioport_writew
;
228 ioport_read_table
[2][i
] = default_ioport_readl
;
229 ioport_write_table
[2][i
] = default_ioport_writel
;
233 /* size is the word size in byte */
234 int register_ioport_read(int start
, int length
, int size
,
235 IOPortReadFunc
*func
, void *opaque
)
241 } else if (size
== 2) {
243 } else if (size
== 4) {
246 hw_error("register_ioport_read: invalid size");
249 for(i
= start
; i
< start
+ length
; i
+= size
) {
250 ioport_read_table
[bsize
][i
] = func
;
251 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
252 hw_error("register_ioport_read: invalid opaque");
253 ioport_opaque
[i
] = opaque
;
258 /* size is the word size in byte */
259 int register_ioport_write(int start
, int length
, int size
,
260 IOPortWriteFunc
*func
, void *opaque
)
266 } else if (size
== 2) {
268 } else if (size
== 4) {
271 hw_error("register_ioport_write: invalid size");
274 for(i
= start
; i
< start
+ length
; i
+= size
) {
275 ioport_write_table
[bsize
][i
] = func
;
276 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
277 hw_error("register_ioport_read: invalid opaque");
278 ioport_opaque
[i
] = opaque
;
283 void isa_unassign_ioport(int start
, int length
)
287 for(i
= start
; i
< start
+ length
; i
++) {
288 ioport_read_table
[0][i
] = default_ioport_readb
;
289 ioport_read_table
[1][i
] = default_ioport_readw
;
290 ioport_read_table
[2][i
] = default_ioport_readl
;
292 ioport_write_table
[0][i
] = default_ioport_writeb
;
293 ioport_write_table
[1][i
] = default_ioport_writew
;
294 ioport_write_table
[2][i
] = default_ioport_writel
;
298 /***********************************************************/
300 void pstrcpy(char *buf
, int buf_size
, const char *str
)
310 if (c
== 0 || q
>= buf
+ buf_size
- 1)
317 /* strcat and truncate. */
318 char *pstrcat(char *buf
, int buf_size
, const char *s
)
323 pstrcpy(buf
+ len
, buf_size
- len
, s
);
327 int strstart(const char *str
, const char *val
, const char **ptr
)
343 void cpu_outb(CPUState
*env
, int addr
, int val
)
346 if (loglevel
& CPU_LOG_IOPORT
)
347 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
349 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
352 env
->last_io_time
= cpu_get_time_fast();
356 void cpu_outw(CPUState
*env
, int addr
, int val
)
359 if (loglevel
& CPU_LOG_IOPORT
)
360 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
362 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
365 env
->last_io_time
= cpu_get_time_fast();
369 void cpu_outl(CPUState
*env
, int addr
, int val
)
372 if (loglevel
& CPU_LOG_IOPORT
)
373 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
375 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
378 env
->last_io_time
= cpu_get_time_fast();
382 int cpu_inb(CPUState
*env
, int addr
)
385 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
387 if (loglevel
& CPU_LOG_IOPORT
)
388 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
392 env
->last_io_time
= cpu_get_time_fast();
397 int cpu_inw(CPUState
*env
, int addr
)
400 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
402 if (loglevel
& CPU_LOG_IOPORT
)
403 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
407 env
->last_io_time
= cpu_get_time_fast();
412 int cpu_inl(CPUState
*env
, int addr
)
415 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
417 if (loglevel
& CPU_LOG_IOPORT
)
418 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
422 env
->last_io_time
= cpu_get_time_fast();
427 /***********************************************************/
428 void hw_error(const char *fmt
, ...)
434 fprintf(stderr
, "qemu: hardware error: ");
435 vfprintf(stderr
, fmt
, ap
);
436 fprintf(stderr
, "\n");
437 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
438 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
440 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
442 cpu_dump_state(env
, stderr
, fprintf
, 0);
449 /***********************************************************/
452 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
453 static void *qemu_put_kbd_event_opaque
;
454 static QEMUPutMouseEvent
*qemu_put_mouse_event
;
455 static void *qemu_put_mouse_event_opaque
;
456 static int qemu_put_mouse_event_absolute
;
458 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
460 qemu_put_kbd_event_opaque
= opaque
;
461 qemu_put_kbd_event
= func
;
464 void qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
, void *opaque
, int absolute
)
466 qemu_put_mouse_event_opaque
= opaque
;
467 qemu_put_mouse_event
= func
;
468 qemu_put_mouse_event_absolute
= absolute
;
471 void kbd_put_keycode(int keycode
)
473 if (qemu_put_kbd_event
) {
474 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
478 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
480 if (qemu_put_mouse_event
) {
481 qemu_put_mouse_event(qemu_put_mouse_event_opaque
,
482 dx
, dy
, dz
, buttons_state
);
486 int kbd_mouse_is_absolute(void)
488 return qemu_put_mouse_event_absolute
;
491 /* compute with 96 bit intermediate result: (a*b)/c */
492 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
497 #ifdef WORDS_BIGENDIAN
507 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
508 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
511 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
515 /***********************************************************/
516 /* real time host monotonic timer */
518 #define QEMU_TIMER_BASE 1000000000LL
522 static int64_t clock_freq
;
524 static void init_get_clock(void)
528 ret
= QueryPerformanceFrequency(&freq
);
530 fprintf(stderr
, "Could not calibrate ticks\n");
533 clock_freq
= freq
.QuadPart
;
536 static int64_t get_clock(void)
539 QueryPerformanceCounter(&ti
);
540 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
545 static int use_rt_clock
;
547 static void init_get_clock(void)
550 #if defined(__linux__)
553 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
560 static int64_t get_clock(void)
562 #if defined(__linux__)
565 clock_gettime(CLOCK_MONOTONIC
, &ts
);
566 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
570 /* XXX: using gettimeofday leads to problems if the date
571 changes, so it should be avoided. */
573 gettimeofday(&tv
, NULL
);
574 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
580 /***********************************************************/
581 /* guest cycle counter */
583 static int64_t cpu_ticks_prev
;
584 static int64_t cpu_ticks_offset
;
585 static int64_t cpu_clock_offset
;
586 static int cpu_ticks_enabled
;
588 /* return the host CPU cycle counter and handle stop/restart */
589 int64_t cpu_get_ticks(void)
591 if (!cpu_ticks_enabled
) {
592 return cpu_ticks_offset
;
595 ticks
= cpu_get_real_ticks();
596 if (cpu_ticks_prev
> ticks
) {
597 /* Note: non increasing ticks may happen if the host uses
599 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
601 cpu_ticks_prev
= ticks
;
602 return ticks
+ cpu_ticks_offset
;
606 /* return the host CPU monotonic timer and handle stop/restart */
607 static int64_t cpu_get_clock(void)
610 if (!cpu_ticks_enabled
) {
611 return cpu_clock_offset
;
614 return ti
+ cpu_clock_offset
;
618 /* enable cpu_get_ticks() */
619 void cpu_enable_ticks(void)
621 if (!cpu_ticks_enabled
) {
622 cpu_ticks_offset
-= cpu_get_real_ticks();
623 cpu_clock_offset
-= get_clock();
624 cpu_ticks_enabled
= 1;
628 /* disable cpu_get_ticks() : the clock is stopped. You must not call
629 cpu_get_ticks() after that. */
630 void cpu_disable_ticks(void)
632 if (cpu_ticks_enabled
) {
633 cpu_ticks_offset
= cpu_get_ticks();
634 cpu_clock_offset
= cpu_get_clock();
635 cpu_ticks_enabled
= 0;
639 /***********************************************************/
642 #define QEMU_TIMER_REALTIME 0
643 #define QEMU_TIMER_VIRTUAL 1
647 /* XXX: add frequency */
655 struct QEMUTimer
*next
;
661 static QEMUTimer
*active_timers
[2];
663 static MMRESULT timerID
;
664 static HANDLE host_alarm
= NULL
;
665 static unsigned int period
= 1;
667 /* frequency of the times() clock tick */
668 static int timer_freq
;
671 QEMUClock
*qemu_new_clock(int type
)
674 clock
= qemu_mallocz(sizeof(QEMUClock
));
681 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
685 ts
= qemu_mallocz(sizeof(QEMUTimer
));
692 void qemu_free_timer(QEMUTimer
*ts
)
697 /* stop a timer, but do not dealloc it */
698 void qemu_del_timer(QEMUTimer
*ts
)
702 /* NOTE: this code must be signal safe because
703 qemu_timer_expired() can be called from a signal. */
704 pt
= &active_timers
[ts
->clock
->type
];
717 /* modify the current timer so that it will be fired when current_time
718 >= expire_time. The corresponding callback will be called. */
719 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
725 /* add the timer in the sorted list */
726 /* NOTE: this code must be signal safe because
727 qemu_timer_expired() can be called from a signal. */
728 pt
= &active_timers
[ts
->clock
->type
];
733 if (t
->expire_time
> expire_time
)
737 ts
->expire_time
= expire_time
;
742 int qemu_timer_pending(QEMUTimer
*ts
)
745 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
752 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
756 return (timer_head
->expire_time
<= current_time
);
759 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
765 if (!ts
|| ts
->expire_time
> current_time
)
767 /* remove timer from the list before calling the callback */
768 *ptimer_head
= ts
->next
;
771 /* run the callback (the timer list can be modified) */
776 int64_t qemu_get_clock(QEMUClock
*clock
)
778 switch(clock
->type
) {
779 case QEMU_TIMER_REALTIME
:
780 return get_clock() / 1000000;
782 case QEMU_TIMER_VIRTUAL
:
783 return cpu_get_clock();
787 static void init_timers(void)
790 ticks_per_sec
= QEMU_TIMER_BASE
;
791 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
792 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
796 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
798 uint64_t expire_time
;
800 if (qemu_timer_pending(ts
)) {
801 expire_time
= ts
->expire_time
;
805 qemu_put_be64(f
, expire_time
);
808 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
810 uint64_t expire_time
;
812 expire_time
= qemu_get_be64(f
);
813 if (expire_time
!= -1) {
814 qemu_mod_timer(ts
, expire_time
);
820 static void timer_save(QEMUFile
*f
, void *opaque
)
822 if (cpu_ticks_enabled
) {
823 hw_error("cannot save state if virtual timers are running");
825 qemu_put_be64s(f
, &cpu_ticks_offset
);
826 qemu_put_be64s(f
, &ticks_per_sec
);
827 qemu_put_be64s(f
, &cpu_clock_offset
);
830 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
834 if (cpu_ticks_enabled
) {
837 qemu_get_be64s(f
, &cpu_ticks_offset
);
838 qemu_get_be64s(f
, &ticks_per_sec
);
839 qemu_get_be64s(f
, &cpu_clock_offset
);
844 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
845 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
847 static void host_alarm_handler(int host_signum
)
851 #define DISP_FREQ 1000
853 static int64_t delta_min
= INT64_MAX
;
854 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
856 ti
= qemu_get_clock(vm_clock
);
857 if (last_clock
!= 0) {
858 delta
= ti
- last_clock
;
859 if (delta
< delta_min
)
861 if (delta
> delta_max
)
864 if (++count
== DISP_FREQ
) {
865 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
866 muldiv64(delta_min
, 1000000, ticks_per_sec
),
867 muldiv64(delta_max
, 1000000, ticks_per_sec
),
868 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
869 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
871 delta_min
= INT64_MAX
;
879 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
880 qemu_get_clock(vm_clock
)) ||
881 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
882 qemu_get_clock(rt_clock
))) {
884 SetEvent(host_alarm
);
886 CPUState
*env
= cpu_single_env
;
888 /* stop the currently executing cpu because a timer occured */
889 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
891 if (env
->kqemu_enabled
) {
892 kqemu_cpu_interrupt(env
);
901 #if defined(__linux__)
903 #define RTC_FREQ 1024
907 static int start_rtc_timer(void)
909 rtc_fd
= open("/dev/rtc", O_RDONLY
);
912 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
913 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
914 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
915 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
918 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
923 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
929 static int start_rtc_timer(void)
934 #endif /* !defined(__linux__) */
936 #endif /* !defined(_WIN32) */
938 static void init_timer_alarm(void)
945 ZeroMemory(&tc
, sizeof(TIMECAPS
));
946 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
947 if (period
< tc
.wPeriodMin
)
948 period
= tc
.wPeriodMin
;
949 timeBeginPeriod(period
);
950 timerID
= timeSetEvent(1, // interval (ms)
951 period
, // resolution
952 host_alarm_handler
, // function
953 (DWORD
)&count
, // user parameter
954 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
956 perror("failed timer alarm");
959 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
961 perror("failed CreateEvent");
964 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
966 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
969 struct sigaction act
;
970 struct itimerval itv
;
972 /* get times() syscall frequency */
973 timer_freq
= sysconf(_SC_CLK_TCK
);
976 sigfillset(&act
.sa_mask
);
978 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
979 act
.sa_flags
|= SA_ONSTACK
;
981 act
.sa_handler
= host_alarm_handler
;
982 sigaction(SIGALRM
, &act
, NULL
);
984 itv
.it_interval
.tv_sec
= 0;
985 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
986 itv
.it_value
.tv_sec
= 0;
987 itv
.it_value
.tv_usec
= 10 * 1000;
988 setitimer(ITIMER_REAL
, &itv
, NULL
);
989 /* we probe the tick duration of the kernel to inform the user if
990 the emulated kernel requested a too high timer frequency */
991 getitimer(ITIMER_REAL
, &itv
);
993 #if defined(__linux__)
994 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
995 have timers with 1 ms resolution. The correct solution will
996 be to use the POSIX real time timers available in recent
998 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
999 /* try to use /dev/rtc to have a faster timer */
1000 if (start_rtc_timer() < 0)
1002 /* disable itimer */
1003 itv
.it_interval
.tv_sec
= 0;
1004 itv
.it_interval
.tv_usec
= 0;
1005 itv
.it_value
.tv_sec
= 0;
1006 itv
.it_value
.tv_usec
= 0;
1007 setitimer(ITIMER_REAL
, &itv
, NULL
);
1010 sigaction(SIGIO
, &act
, NULL
);
1011 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1012 fcntl(rtc_fd
, F_SETOWN
, getpid());
1014 #endif /* defined(__linux__) */
1017 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1018 PIT_FREQ
) / 1000000;
1024 void quit_timers(void)
1027 timeKillEvent(timerID
);
1028 timeEndPeriod(period
);
1030 CloseHandle(host_alarm
);
1036 /***********************************************************/
1037 /* character device */
1039 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1041 return s
->chr_write(s
, buf
, len
);
1044 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1048 return s
->chr_ioctl(s
, cmd
, arg
);
1051 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1056 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1057 qemu_chr_write(s
, buf
, strlen(buf
));
1061 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1063 if (s
->chr_send_event
)
1064 s
->chr_send_event(s
, event
);
1067 void qemu_chr_add_read_handler(CharDriverState
*s
,
1068 IOCanRWHandler
*fd_can_read
,
1069 IOReadHandler
*fd_read
, void *opaque
)
1071 s
->chr_add_read_handler(s
, fd_can_read
, fd_read
, opaque
);
1074 void qemu_chr_add_event_handler(CharDriverState
*s
, IOEventHandler
*chr_event
)
1076 s
->chr_event
= chr_event
;
1079 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1084 static void null_chr_add_read_handler(CharDriverState
*chr
,
1085 IOCanRWHandler
*fd_can_read
,
1086 IOReadHandler
*fd_read
, void *opaque
)
1090 CharDriverState
*qemu_chr_open_null(void)
1092 CharDriverState
*chr
;
1094 chr
= qemu_mallocz(sizeof(CharDriverState
));
1097 chr
->chr_write
= null_chr_write
;
1098 chr
->chr_add_read_handler
= null_chr_add_read_handler
;
1104 static void socket_cleanup(void)
1109 static int socket_init(void)
1114 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1116 err
= WSAGetLastError();
1117 fprintf(stderr
, "WSAStartup: %d\n", err
);
1120 atexit(socket_cleanup
);
1124 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1130 ret
= send(fd
, buf
, len
, 0);
1133 errno
= WSAGetLastError();
1134 if (errno
!= WSAEWOULDBLOCK
) {
1137 } else if (ret
== 0) {
1147 void socket_set_nonblock(int fd
)
1149 unsigned long opt
= 1;
1150 ioctlsocket(fd
, FIONBIO
, &opt
);
1155 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1161 ret
= write(fd
, buf
, len
);
1163 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1165 } else if (ret
== 0) {
1175 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1177 return unix_write(fd
, buf
, len1
);
1180 void socket_set_nonblock(int fd
)
1182 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1184 #endif /* !_WIN32 */
1190 IOCanRWHandler
*fd_can_read
;
1191 IOReadHandler
*fd_read
;
1196 #define STDIO_MAX_CLIENTS 2
1198 static int stdio_nb_clients
;
1199 static CharDriverState
*stdio_clients
[STDIO_MAX_CLIENTS
];
1201 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1203 FDCharDriver
*s
= chr
->opaque
;
1204 return unix_write(s
->fd_out
, buf
, len
);
1207 static int fd_chr_read_poll(void *opaque
)
1209 CharDriverState
*chr
= opaque
;
1210 FDCharDriver
*s
= chr
->opaque
;
1212 s
->max_size
= s
->fd_can_read(s
->fd_opaque
);
1216 static void fd_chr_read(void *opaque
)
1218 CharDriverState
*chr
= opaque
;
1219 FDCharDriver
*s
= chr
->opaque
;
1224 if (len
> s
->max_size
)
1228 size
= read(s
->fd_in
, buf
, len
);
1230 s
->fd_read(s
->fd_opaque
, buf
, size
);
1234 static void fd_chr_add_read_handler(CharDriverState
*chr
,
1235 IOCanRWHandler
*fd_can_read
,
1236 IOReadHandler
*fd_read
, void *opaque
)
1238 FDCharDriver
*s
= chr
->opaque
;
1240 if (s
->fd_in
>= 0) {
1241 s
->fd_can_read
= fd_can_read
;
1242 s
->fd_read
= fd_read
;
1243 s
->fd_opaque
= opaque
;
1244 if (nographic
&& s
->fd_in
== 0) {
1246 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1247 fd_chr_read
, NULL
, chr
);
1252 /* open a character device to a unix fd */
1253 CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1255 CharDriverState
*chr
;
1258 chr
= qemu_mallocz(sizeof(CharDriverState
));
1261 s
= qemu_mallocz(sizeof(FDCharDriver
));
1269 chr
->chr_write
= fd_chr_write
;
1270 chr
->chr_add_read_handler
= fd_chr_add_read_handler
;
1274 CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1278 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1281 return qemu_chr_open_fd(-1, fd_out
);
1284 CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1288 fd
= open(filename
, O_RDWR
| O_BINARY
);
1291 return qemu_chr_open_fd(fd
, fd
);
1295 /* for STDIO, we handle the case where several clients use it
1298 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1300 #define TERM_FIFO_MAX_SIZE 1
1302 static int term_got_escape
, client_index
;
1303 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1304 static int term_fifo_size
;
1305 static int term_timestamps
;
1306 static int64_t term_timestamps_start
;
1308 void term_print_help(void)
1311 "C-a h print this help\n"
1312 "C-a x exit emulator\n"
1313 "C-a s save disk data back to file (if -snapshot)\n"
1314 "C-a b send break (magic sysrq)\n"
1315 "C-a t toggle console timestamps\n"
1316 "C-a c switch between console and monitor\n"
1317 "C-a C-a send C-a\n"
1321 /* called when a char is received */
1322 static void stdio_received_byte(int ch
)
1324 if (term_got_escape
) {
1325 term_got_escape
= 0;
1336 for (i
= 0; i
< MAX_DISKS
; i
++) {
1338 bdrv_commit(bs_table
[i
]);
1343 if (client_index
< stdio_nb_clients
) {
1344 CharDriverState
*chr
;
1347 chr
= stdio_clients
[client_index
];
1349 chr
->chr_event(s
->fd_opaque
, CHR_EVENT_BREAK
);
1354 if (client_index
>= stdio_nb_clients
)
1356 if (client_index
== 0) {
1357 /* send a new line in the monitor to get the prompt */
1363 term_timestamps
= !term_timestamps
;
1364 term_timestamps_start
= -1;
1369 } else if (ch
== TERM_ESCAPE
) {
1370 term_got_escape
= 1;
1373 if (client_index
< stdio_nb_clients
) {
1375 CharDriverState
*chr
;
1378 chr
= stdio_clients
[client_index
];
1380 if (s
->fd_can_read(s
->fd_opaque
) > 0) {
1382 s
->fd_read(s
->fd_opaque
, buf
, 1);
1383 } else if (term_fifo_size
== 0) {
1384 term_fifo
[term_fifo_size
++] = ch
;
1390 static int stdio_read_poll(void *opaque
)
1392 CharDriverState
*chr
;
1395 if (client_index
< stdio_nb_clients
) {
1396 chr
= stdio_clients
[client_index
];
1398 /* try to flush the queue if needed */
1399 if (term_fifo_size
!= 0 && s
->fd_can_read(s
->fd_opaque
) > 0) {
1400 s
->fd_read(s
->fd_opaque
, term_fifo
, 1);
1403 /* see if we can absorb more chars */
1404 if (term_fifo_size
== 0)
1413 static void stdio_read(void *opaque
)
1418 size
= read(0, buf
, 1);
1420 stdio_received_byte(buf
[0]);
1423 static int stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1425 FDCharDriver
*s
= chr
->opaque
;
1426 if (!term_timestamps
) {
1427 return unix_write(s
->fd_out
, buf
, len
);
1432 for(i
= 0; i
< len
; i
++) {
1433 unix_write(s
->fd_out
, buf
+ i
, 1);
1434 if (buf
[i
] == '\n') {
1439 if (term_timestamps_start
== -1)
1440 term_timestamps_start
= ti
;
1441 ti
-= term_timestamps_start
;
1442 secs
= ti
/ 1000000000;
1443 snprintf(buf1
, sizeof(buf1
),
1444 "[%02d:%02d:%02d.%03d] ",
1448 (int)((ti
/ 1000000) % 1000));
1449 unix_write(s
->fd_out
, buf1
, strlen(buf1
));
1456 /* init terminal so that we can grab keys */
1457 static struct termios oldtty
;
1458 static int old_fd0_flags
;
1460 static void term_exit(void)
1462 tcsetattr (0, TCSANOW
, &oldtty
);
1463 fcntl(0, F_SETFL
, old_fd0_flags
);
1466 static void term_init(void)
1470 tcgetattr (0, &tty
);
1472 old_fd0_flags
= fcntl(0, F_GETFL
);
1474 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1475 |INLCR
|IGNCR
|ICRNL
|IXON
);
1476 tty
.c_oflag
|= OPOST
;
1477 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1478 /* if graphical mode, we allow Ctrl-C handling */
1480 tty
.c_lflag
&= ~ISIG
;
1481 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1484 tty
.c_cc
[VTIME
] = 0;
1486 tcsetattr (0, TCSANOW
, &tty
);
1490 fcntl(0, F_SETFL
, O_NONBLOCK
);
1493 CharDriverState
*qemu_chr_open_stdio(void)
1495 CharDriverState
*chr
;
1498 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1500 chr
= qemu_chr_open_fd(0, 1);
1501 chr
->chr_write
= stdio_write
;
1502 if (stdio_nb_clients
== 0)
1503 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, NULL
);
1504 client_index
= stdio_nb_clients
;
1506 if (stdio_nb_clients
!= 0)
1508 chr
= qemu_chr_open_fd(0, 1);
1510 stdio_clients
[stdio_nb_clients
++] = chr
;
1511 if (stdio_nb_clients
== 1) {
1512 /* set the terminal in raw mode */
1518 #if defined(__linux__)
1519 CharDriverState
*qemu_chr_open_pty(void)
1522 char slave_name
[1024];
1523 int master_fd
, slave_fd
;
1525 /* Not satisfying */
1526 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1530 /* Disabling local echo and line-buffered output */
1531 tcgetattr (master_fd
, &tty
);
1532 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1534 tty
.c_cc
[VTIME
] = 0;
1535 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1537 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1538 return qemu_chr_open_fd(master_fd
, master_fd
);
1541 static void tty_serial_init(int fd
, int speed
,
1542 int parity
, int data_bits
, int stop_bits
)
1548 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1549 speed
, parity
, data_bits
, stop_bits
);
1551 tcgetattr (fd
, &tty
);
1593 cfsetispeed(&tty
, spd
);
1594 cfsetospeed(&tty
, spd
);
1596 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1597 |INLCR
|IGNCR
|ICRNL
|IXON
);
1598 tty
.c_oflag
|= OPOST
;
1599 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1600 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
);
1621 tty
.c_cflag
|= PARENB
;
1624 tty
.c_cflag
|= PARENB
| PARODD
;
1628 tcsetattr (fd
, TCSANOW
, &tty
);
1631 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1633 FDCharDriver
*s
= chr
->opaque
;
1636 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1638 QEMUSerialSetParams
*ssp
= arg
;
1639 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1640 ssp
->data_bits
, ssp
->stop_bits
);
1643 case CHR_IOCTL_SERIAL_SET_BREAK
:
1645 int enable
= *(int *)arg
;
1647 tcsendbreak(s
->fd_in
, 1);
1656 CharDriverState
*qemu_chr_open_tty(const char *filename
)
1658 CharDriverState
*chr
;
1661 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1664 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1665 tty_serial_init(fd
, 115200, 'N', 8, 1);
1666 chr
= qemu_chr_open_fd(fd
, fd
);
1669 chr
->chr_ioctl
= tty_serial_ioctl
;
1673 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1675 int fd
= (int)chr
->opaque
;
1679 case CHR_IOCTL_PP_READ_DATA
:
1680 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1682 *(uint8_t *)arg
= b
;
1684 case CHR_IOCTL_PP_WRITE_DATA
:
1685 b
= *(uint8_t *)arg
;
1686 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1689 case CHR_IOCTL_PP_READ_CONTROL
:
1690 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1692 *(uint8_t *)arg
= b
;
1694 case CHR_IOCTL_PP_WRITE_CONTROL
:
1695 b
= *(uint8_t *)arg
;
1696 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1699 case CHR_IOCTL_PP_READ_STATUS
:
1700 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1702 *(uint8_t *)arg
= b
;
1710 CharDriverState
*qemu_chr_open_pp(const char *filename
)
1712 CharDriverState
*chr
;
1715 fd
= open(filename
, O_RDWR
);
1719 if (ioctl(fd
, PPCLAIM
) < 0) {
1724 chr
= qemu_mallocz(sizeof(CharDriverState
));
1729 chr
->opaque
= (void *)fd
;
1730 chr
->chr_write
= null_chr_write
;
1731 chr
->chr_add_read_handler
= null_chr_add_read_handler
;
1732 chr
->chr_ioctl
= pp_ioctl
;
1737 CharDriverState
*qemu_chr_open_pty(void)
1743 #endif /* !defined(_WIN32) */
1747 IOCanRWHandler
*fd_can_read
;
1748 IOReadHandler
*fd_read
;
1751 HANDLE hcom
, hrecv
, hsend
;
1752 OVERLAPPED orecv
, osend
;
1757 #define NSENDBUF 2048
1758 #define NRECVBUF 2048
1759 #define MAXCONNECT 1
1760 #define NTIMEOUT 5000
1762 static int win_chr_poll(void *opaque
);
1763 static int win_chr_pipe_poll(void *opaque
);
1765 static void win_chr_close2(WinCharState
*s
)
1768 CloseHandle(s
->hsend
);
1772 CloseHandle(s
->hrecv
);
1776 CloseHandle(s
->hcom
);
1780 qemu_del_polling_cb(win_chr_pipe_poll
, s
);
1782 qemu_del_polling_cb(win_chr_poll
, s
);
1785 static void win_chr_close(CharDriverState
*chr
)
1787 WinCharState
*s
= chr
->opaque
;
1791 static int win_chr_init(WinCharState
*s
, const char *filename
)
1794 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1799 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1801 fprintf(stderr
, "Failed CreateEvent\n");
1804 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1806 fprintf(stderr
, "Failed CreateEvent\n");
1810 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1811 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1812 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1813 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1818 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1819 fprintf(stderr
, "Failed SetupComm\n");
1823 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1824 size
= sizeof(COMMCONFIG
);
1825 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1826 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1827 CommConfigDialog(filename
, NULL
, &comcfg
);
1829 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1830 fprintf(stderr
, "Failed SetCommState\n");
1834 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1835 fprintf(stderr
, "Failed SetCommMask\n");
1839 cto
.ReadIntervalTimeout
= MAXDWORD
;
1840 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1841 fprintf(stderr
, "Failed SetCommTimeouts\n");
1845 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1846 fprintf(stderr
, "Failed ClearCommError\n");
1849 qemu_add_polling_cb(win_chr_poll
, s
);
1857 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
1859 WinCharState
*s
= chr
->opaque
;
1860 DWORD len
, ret
, size
, err
;
1863 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
1864 s
->osend
.hEvent
= s
->hsend
;
1867 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
1869 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
1871 err
= GetLastError();
1872 if (err
== ERROR_IO_PENDING
) {
1873 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
1891 static int win_chr_read_poll(WinCharState
*s
)
1893 s
->max_size
= s
->fd_can_read(s
->win_opaque
);
1897 static void win_chr_readfile(WinCharState
*s
)
1903 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
1904 s
->orecv
.hEvent
= s
->hrecv
;
1905 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
1907 err
= GetLastError();
1908 if (err
== ERROR_IO_PENDING
) {
1909 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
1914 s
->fd_read(s
->win_opaque
, buf
, size
);
1918 static void win_chr_read(WinCharState
*s
)
1920 if (s
->len
> s
->max_size
)
1921 s
->len
= s
->max_size
;
1925 win_chr_readfile(s
);
1928 static int win_chr_poll(void *opaque
)
1930 WinCharState
*s
= opaque
;
1934 ClearCommError(s
->hcom
, &comerr
, &status
);
1935 if (status
.cbInQue
> 0) {
1936 s
->len
= status
.cbInQue
;
1937 win_chr_read_poll(s
);
1944 static void win_chr_add_read_handler(CharDriverState
*chr
,
1945 IOCanRWHandler
*fd_can_read
,
1946 IOReadHandler
*fd_read
, void *opaque
)
1948 WinCharState
*s
= chr
->opaque
;
1950 s
->fd_can_read
= fd_can_read
;
1951 s
->fd_read
= fd_read
;
1952 s
->win_opaque
= opaque
;
1955 CharDriverState
*qemu_chr_open_win(const char *filename
)
1957 CharDriverState
*chr
;
1960 chr
= qemu_mallocz(sizeof(CharDriverState
));
1963 s
= qemu_mallocz(sizeof(WinCharState
));
1969 chr
->chr_write
= win_chr_write
;
1970 chr
->chr_add_read_handler
= win_chr_add_read_handler
;
1971 chr
->chr_close
= win_chr_close
;
1973 if (win_chr_init(s
, filename
) < 0) {
1981 static int win_chr_pipe_poll(void *opaque
)
1983 WinCharState
*s
= opaque
;
1986 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
1989 win_chr_read_poll(s
);
1996 static int win_chr_pipe_init(WinCharState
*s
, const char *filename
)
2005 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2007 fprintf(stderr
, "Failed CreateEvent\n");
2010 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2012 fprintf(stderr
, "Failed CreateEvent\n");
2016 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2017 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2018 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2020 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2021 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2022 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2027 ZeroMemory(&ov
, sizeof(ov
));
2028 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2029 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2031 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2035 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2037 fprintf(stderr
, "Failed GetOverlappedResult\n");
2039 CloseHandle(ov
.hEvent
);
2046 CloseHandle(ov
.hEvent
);
2049 qemu_add_polling_cb(win_chr_pipe_poll
, s
);
2058 CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2060 CharDriverState
*chr
;
2063 chr
= qemu_mallocz(sizeof(CharDriverState
));
2066 s
= qemu_mallocz(sizeof(WinCharState
));
2072 chr
->chr_write
= win_chr_write
;
2073 chr
->chr_add_read_handler
= win_chr_add_read_handler
;
2074 chr
->chr_close
= win_chr_close
;
2076 if (win_chr_pipe_init(s
, filename
) < 0) {
2084 CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2086 CharDriverState
*chr
;
2089 chr
= qemu_mallocz(sizeof(CharDriverState
));
2092 s
= qemu_mallocz(sizeof(WinCharState
));
2099 chr
->chr_write
= win_chr_write
;
2100 chr
->chr_add_read_handler
= win_chr_add_read_handler
;
2104 CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2108 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2109 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2110 if (fd_out
== INVALID_HANDLE_VALUE
)
2113 return qemu_chr_open_win_file(fd_out
);
2117 /***********************************************************/
2118 /* UDP Net console */
2121 IOCanRWHandler
*fd_can_read
;
2122 IOReadHandler
*fd_read
;
2125 struct sockaddr_in daddr
;
2132 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2134 NetCharDriver
*s
= chr
->opaque
;
2136 return sendto(s
->fd
, buf
, len
, 0,
2137 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2140 static int udp_chr_read_poll(void *opaque
)
2142 CharDriverState
*chr
= opaque
;
2143 NetCharDriver
*s
= chr
->opaque
;
2145 s
->max_size
= s
->fd_can_read(s
->fd_opaque
);
2147 /* If there were any stray characters in the queue process them
2150 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2151 s
->fd_read(s
->fd_opaque
, &s
->buf
[s
->bufptr
], 1);
2153 s
->max_size
= s
->fd_can_read(s
->fd_opaque
);
2158 static void udp_chr_read(void *opaque
)
2160 CharDriverState
*chr
= opaque
;
2161 NetCharDriver
*s
= chr
->opaque
;
2163 if (s
->max_size
== 0)
2165 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2166 s
->bufptr
= s
->bufcnt
;
2171 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2172 s
->fd_read(s
->fd_opaque
, &s
->buf
[s
->bufptr
], 1);
2174 s
->max_size
= s
->fd_can_read(s
->fd_opaque
);
2178 static void udp_chr_add_read_handler(CharDriverState
*chr
,
2179 IOCanRWHandler
*fd_can_read
,
2180 IOReadHandler
*fd_read
, void *opaque
)
2182 NetCharDriver
*s
= chr
->opaque
;
2185 s
->fd_can_read
= fd_can_read
;
2186 s
->fd_read
= fd_read
;
2187 s
->fd_opaque
= opaque
;
2188 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2189 udp_chr_read
, NULL
, chr
);
2193 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2194 int parse_host_unix_path(struct sockaddr_un
*uaddr
,
2197 int parse_host_src_port(struct sockaddr_in
*haddr
,
2198 struct sockaddr_in
*saddr
,
2201 CharDriverState
*qemu_chr_open_udp(const char *def
)
2203 CharDriverState
*chr
= NULL
;
2204 NetCharDriver
*s
= NULL
;
2206 struct sockaddr_in saddr
;
2208 chr
= qemu_mallocz(sizeof(CharDriverState
));
2211 s
= qemu_mallocz(sizeof(NetCharDriver
));
2215 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2217 perror("socket(PF_INET, SOCK_DGRAM)");
2221 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2222 printf("Could not parse: %s\n", def
);
2226 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2236 chr
->chr_write
= udp_chr_write
;
2237 chr
->chr_add_read_handler
= udp_chr_add_read_handler
;
2250 /***********************************************************/
2251 /* TCP Net console */
2254 IOCanRWHandler
*fd_can_read
;
2255 IOReadHandler
*fd_read
;
2263 static void tcp_chr_accept(void *opaque
);
2265 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2267 TCPCharDriver
*s
= chr
->opaque
;
2269 return send_all(s
->fd
, buf
, len
);
2271 /* XXX: indicate an error ? */
2276 static int tcp_chr_read_poll(void *opaque
)
2278 CharDriverState
*chr
= opaque
;
2279 TCPCharDriver
*s
= chr
->opaque
;
2282 s
->max_size
= s
->fd_can_read(s
->fd_opaque
);
2287 #define IAC_BREAK 243
2288 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2290 char *buf
, int *size
)
2292 /* Handle any telnet client's basic IAC options to satisfy char by
2293 * char mode with no echo. All IAC options will be removed from
2294 * the buf and the do_telnetopt variable will be used to track the
2295 * state of the width of the IAC information.
2297 * IAC commands come in sets of 3 bytes with the exception of the
2298 * "IAC BREAK" command and the double IAC.
2304 for (i
= 0; i
< *size
; i
++) {
2305 if (s
->do_telnetopt
> 1) {
2306 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2307 /* Double IAC means send an IAC */
2311 s
->do_telnetopt
= 1;
2313 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2314 /* Handle IAC break commands by sending a serial break */
2315 chr
->chr_event(s
->fd_opaque
, CHR_EVENT_BREAK
);
2320 if (s
->do_telnetopt
>= 4) {
2321 s
->do_telnetopt
= 1;
2324 if ((unsigned char)buf
[i
] == IAC
) {
2325 s
->do_telnetopt
= 2;
2336 static void tcp_chr_read(void *opaque
)
2338 CharDriverState
*chr
= opaque
;
2339 TCPCharDriver
*s
= chr
->opaque
;
2343 if (!s
->connected
|| s
->max_size
<= 0)
2346 if (len
> s
->max_size
)
2348 size
= recv(s
->fd
, buf
, len
, 0);
2350 /* connection closed */
2352 if (s
->listen_fd
>= 0) {
2353 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2355 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2358 } else if (size
> 0) {
2359 if (s
->do_telnetopt
)
2360 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2362 s
->fd_read(s
->fd_opaque
, buf
, size
);
2366 static void tcp_chr_add_read_handler(CharDriverState
*chr
,
2367 IOCanRWHandler
*fd_can_read
,
2368 IOReadHandler
*fd_read
, void *opaque
)
2370 TCPCharDriver
*s
= chr
->opaque
;
2372 s
->fd_can_read
= fd_can_read
;
2373 s
->fd_read
= fd_read
;
2374 s
->fd_opaque
= opaque
;
2377 static void tcp_chr_connect(void *opaque
)
2379 CharDriverState
*chr
= opaque
;
2380 TCPCharDriver
*s
= chr
->opaque
;
2383 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2384 tcp_chr_read
, NULL
, chr
);
2387 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2388 static void tcp_chr_telnet_init(int fd
)
2391 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2392 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2393 send(fd
, (char *)buf
, 3, 0);
2394 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2395 send(fd
, (char *)buf
, 3, 0);
2396 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2397 send(fd
, (char *)buf
, 3, 0);
2398 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2399 send(fd
, (char *)buf
, 3, 0);
2402 static void tcp_chr_accept(void *opaque
)
2404 CharDriverState
*chr
= opaque
;
2405 TCPCharDriver
*s
= chr
->opaque
;
2406 struct sockaddr_in saddr
;
2411 len
= sizeof(saddr
);
2412 fd
= accept(s
->listen_fd
, (struct sockaddr
*)&saddr
, &len
);
2413 if (fd
< 0 && errno
!= EINTR
) {
2415 } else if (fd
>= 0) {
2416 if (s
->do_telnetopt
)
2417 tcp_chr_telnet_init(fd
);
2421 socket_set_nonblock(fd
);
2423 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2424 tcp_chr_connect(chr
);
2427 static void tcp_chr_close(CharDriverState
*chr
)
2429 TCPCharDriver
*s
= chr
->opaque
;
2432 if (s
->listen_fd
>= 0)
2433 closesocket(s
->listen_fd
);
2437 static CharDriverState
*qemu_chr_open_stream(const char *host_str
,
2441 CharDriverState
*chr
= NULL
;
2442 TCPCharDriver
*s
= NULL
;
2443 int fd
= -1, ret
, err
, val
;
2445 int is_waitconnect
= 1;
2447 struct sockaddr
* addr
;
2448 struct sockaddr_in saddr
;
2449 struct sockaddr_un uaddr
;
2453 if (is_unix_domain
) {
2454 parse_host_unix_path(&uaddr
, host_str
, ',');
2455 addr
= (struct sockaddr
*)&uaddr
;
2456 addrlen
= sizeof(uaddr
);
2457 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2461 if (parse_host_port(&saddr
, host_str
) < 0)
2463 addr
= (struct sockaddr
*)&saddr
;
2464 addrlen
= sizeof(saddr
);
2465 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2471 while((ptr
= strchr(ptr
,','))) {
2473 if (!strncmp(ptr
,"server",6)) {
2475 } else if (!strncmp(ptr
,"nowait",6)) {
2478 printf("Unknown option: %s\n", ptr
);
2485 chr
= qemu_mallocz(sizeof(CharDriverState
));
2488 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2492 if (!is_waitconnect
)
2493 socket_set_nonblock(fd
);
2499 /* allow fast reuse */
2501 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2502 ret
= bind(fd
, (struct sockaddr
*)addr
, addrlen
);
2505 ret
= listen(fd
, 0);
2509 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2511 s
->do_telnetopt
= 1;
2514 ret
= connect(fd
, (struct sockaddr
*)addr
, addrlen
);
2516 err
= socket_error();
2517 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2518 } else if (err
== EINPROGRESS
) {
2530 tcp_chr_connect(chr
);
2532 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2536 chr
->chr_write
= tcp_chr_write
;
2537 chr
->chr_add_read_handler
= tcp_chr_add_read_handler
;
2538 chr
->chr_close
= tcp_chr_close
;
2539 if (is_listen
&& is_waitconnect
) {
2540 printf("QEMU waiting for connection on: %s\n", host_str
);
2541 tcp_chr_accept(chr
);
2542 socket_set_nonblock(s
->listen_fd
);
2554 CharDriverState
*qemu_chr_open(const char *filename
)
2558 if (!strcmp(filename
, "vc")) {
2559 return text_console_init(&display_state
);
2560 } else if (!strcmp(filename
, "null")) {
2561 return qemu_chr_open_null();
2563 if (strstart(filename
, "tcp:", &p
)) {
2564 return qemu_chr_open_stream(p
, 0, 0);
2566 if (strstart(filename
, "telnet:", &p
)) {
2567 return qemu_chr_open_stream(p
, 1, 0);
2569 if (strstart(filename
, "udp:", &p
)) {
2570 return qemu_chr_open_udp(p
);
2573 if (strstart(filename
, "file:", &p
)) {
2574 return qemu_chr_open_file_out(p
);
2575 } else if (strstart(filename
, "pipe:", &p
)) {
2576 return qemu_chr_open_pipe(p
);
2577 } else if (!strcmp(filename
, "pty")) {
2578 return qemu_chr_open_pty();
2579 } else if (!strcmp(filename
, "stdio")) {
2580 return qemu_chr_open_stdio();
2581 } else if (strstart(filename
, "unix:", &p
)) {
2582 return qemu_chr_open_stream(p
, 0, 1);
2585 #if defined(__linux__)
2586 if (strstart(filename
, "/dev/parport", NULL
)) {
2587 return qemu_chr_open_pp(filename
);
2589 if (strstart(filename
, "/dev/", NULL
)) {
2590 return qemu_chr_open_tty(filename
);
2594 if (strstart(filename
, "COM", NULL
)) {
2595 return qemu_chr_open_win(filename
);
2597 if (strstart(filename
, "pipe:", &p
)) {
2598 return qemu_chr_open_win_pipe(p
);
2600 if (strstart(filename
, "file:", &p
)) {
2601 return qemu_chr_open_win_file_out(p
);
2609 void qemu_chr_close(CharDriverState
*chr
)
2612 chr
->chr_close(chr
);
2615 /***********************************************************/
2616 /* network device redirectors */
2618 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2622 for(i
=0;i
<size
;i
+=16) {
2626 fprintf(f
, "%08x ", i
);
2629 fprintf(f
, " %02x", buf
[i
+j
]);
2634 for(j
=0;j
<len
;j
++) {
2636 if (c
< ' ' || c
> '~')
2638 fprintf(f
, "%c", c
);
2644 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2647 for(i
= 0; i
< 6; i
++) {
2648 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
2661 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
2666 p1
= strchr(p
, sep
);
2672 if (len
> buf_size
- 1)
2674 memcpy(buf
, p
, len
);
2681 int parse_host_src_port(struct sockaddr_in
*haddr
,
2682 struct sockaddr_in
*saddr
,
2683 const char *input_str
)
2685 char *str
= strdup(input_str
);
2686 char *host_str
= str
;
2691 * Chop off any extra arguments at the end of the string which
2692 * would start with a comma, then fill in the src port information
2693 * if it was provided else use the "any address" and "any port".
2695 if ((ptr
= strchr(str
,',')))
2698 if ((src_str
= strchr(input_str
,'@'))) {
2703 if (parse_host_port(haddr
, host_str
) < 0)
2706 if (!src_str
|| *src_str
== '\0')
2709 if (parse_host_port(saddr
, src_str
) < 0)
2720 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
2728 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2730 saddr
->sin_family
= AF_INET
;
2731 if (buf
[0] == '\0') {
2732 saddr
->sin_addr
.s_addr
= 0;
2734 if (isdigit(buf
[0])) {
2735 if (!inet_aton(buf
, &saddr
->sin_addr
))
2738 if ((he
= gethostbyname(buf
)) == NULL
)
2740 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
2743 port
= strtol(p
, (char **)&r
, 0);
2746 saddr
->sin_port
= htons(port
);
2750 int parse_host_unix_path(struct sockaddr_un
*uaddr
, const char *str
, int sep
)
2754 p
= strchrnul(str
, sep
);
2755 uaddr
->sun_family
= AF_UNIX
;
2756 memcpy(uaddr
->sun_path
, str
, p
- str
);
2757 uaddr
->sun_path
[p
-str
] = '\0';
2758 unlink(uaddr
->sun_path
);
2764 /* find or alloc a new VLAN */
2765 VLANState
*qemu_find_vlan(int id
)
2767 VLANState
**pvlan
, *vlan
;
2768 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2772 vlan
= qemu_mallocz(sizeof(VLANState
));
2777 pvlan
= &first_vlan
;
2778 while (*pvlan
!= NULL
)
2779 pvlan
= &(*pvlan
)->next
;
2784 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
2785 IOReadHandler
*fd_read
,
2786 IOCanRWHandler
*fd_can_read
,
2789 VLANClientState
*vc
, **pvc
;
2790 vc
= qemu_mallocz(sizeof(VLANClientState
));
2793 vc
->fd_read
= fd_read
;
2794 vc
->fd_can_read
= fd_can_read
;
2795 vc
->opaque
= opaque
;
2799 pvc
= &vlan
->first_client
;
2800 while (*pvc
!= NULL
)
2801 pvc
= &(*pvc
)->next
;
2806 int qemu_can_send_packet(VLANClientState
*vc1
)
2808 VLANState
*vlan
= vc1
->vlan
;
2809 VLANClientState
*vc
;
2811 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2813 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
2820 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
2822 VLANState
*vlan
= vc1
->vlan
;
2823 VLANClientState
*vc
;
2826 printf("vlan %d send:\n", vlan
->id
);
2827 hex_dump(stdout
, buf
, size
);
2829 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2831 vc
->fd_read(vc
->opaque
, buf
, size
);
2836 #if defined(CONFIG_SLIRP)
2838 /* slirp network adapter */
2840 static int slirp_inited
;
2841 static VLANClientState
*slirp_vc
;
2843 int slirp_can_output(void)
2845 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
2848 void slirp_output(const uint8_t *pkt
, int pkt_len
)
2851 printf("slirp output:\n");
2852 hex_dump(stdout
, pkt
, pkt_len
);
2856 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
2859 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
2862 printf("slirp input:\n");
2863 hex_dump(stdout
, buf
, size
);
2865 slirp_input(buf
, size
);
2868 static int net_slirp_init(VLANState
*vlan
)
2870 if (!slirp_inited
) {
2874 slirp_vc
= qemu_new_vlan_client(vlan
,
2875 slirp_receive
, NULL
, NULL
);
2876 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
2880 static void net_slirp_redir(const char *redir_str
)
2885 struct in_addr guest_addr
;
2886 int host_port
, guest_port
;
2888 if (!slirp_inited
) {
2894 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2896 if (!strcmp(buf
, "tcp")) {
2898 } else if (!strcmp(buf
, "udp")) {
2904 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2906 host_port
= strtol(buf
, &r
, 0);
2910 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2912 if (buf
[0] == '\0') {
2913 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
2915 if (!inet_aton(buf
, &guest_addr
))
2918 guest_port
= strtol(p
, &r
, 0);
2922 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
2923 fprintf(stderr
, "qemu: could not set up redirection\n");
2928 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2936 static void smb_exit(void)
2940 char filename
[1024];
2942 /* erase all the files in the directory */
2943 d
= opendir(smb_dir
);
2948 if (strcmp(de
->d_name
, ".") != 0 &&
2949 strcmp(de
->d_name
, "..") != 0) {
2950 snprintf(filename
, sizeof(filename
), "%s/%s",
2951 smb_dir
, de
->d_name
);
2959 /* automatic user mode samba server configuration */
2960 void net_slirp_smb(const char *exported_dir
)
2962 char smb_conf
[1024];
2963 char smb_cmdline
[1024];
2966 if (!slirp_inited
) {
2971 /* XXX: better tmp dir construction */
2972 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
2973 if (mkdir(smb_dir
, 0700) < 0) {
2974 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
2977 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
2979 f
= fopen(smb_conf
, "w");
2981 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
2988 "socket address=127.0.0.1\n"
2989 "pid directory=%s\n"
2990 "lock directory=%s\n"
2991 "log file=%s/log.smbd\n"
2992 "smb passwd file=%s/smbpasswd\n"
2993 "security = share\n"
3008 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "/usr/sbin/smbd -s %s",
3011 slirp_add_exec(0, smb_cmdline
, 4, 139);
3014 #endif /* !defined(_WIN32) */
3016 #endif /* CONFIG_SLIRP */
3018 #if !defined(_WIN32)
3020 typedef struct TAPState
{
3021 VLANClientState
*vc
;
3025 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3027 TAPState
*s
= opaque
;
3030 ret
= write(s
->fd
, buf
, size
);
3031 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3038 static void tap_send(void *opaque
)
3040 TAPState
*s
= opaque
;
3044 size
= read(s
->fd
, buf
, sizeof(buf
));
3046 qemu_send_packet(s
->vc
, buf
, size
);
3052 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3056 s
= qemu_mallocz(sizeof(TAPState
));
3060 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3061 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3062 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3067 static int tap_open(char *ifname
, int ifname_size
)
3073 fd
= open("/dev/tap", O_RDWR
);
3075 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3080 dev
= devname(s
.st_rdev
, S_IFCHR
);
3081 pstrcpy(ifname
, ifname_size
, dev
);
3083 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3086 #elif defined(__sun__)
3087 static int tap_open(char *ifname
, int ifname_size
)
3089 fprintf(stderr
, "warning: tap_open not yet implemented\n");
3093 static int tap_open(char *ifname
, int ifname_size
)
3098 fd
= open("/dev/net/tun", O_RDWR
);
3100 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3103 memset(&ifr
, 0, sizeof(ifr
));
3104 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3105 if (ifname
[0] != '\0')
3106 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3108 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3109 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3111 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3115 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3116 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3121 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3122 const char *setup_script
)
3125 int pid
, status
, fd
;
3130 if (ifname1
!= NULL
)
3131 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3134 fd
= tap_open(ifname
, sizeof(ifname
));
3140 if (setup_script
[0] != '\0') {
3141 /* try to launch network init script */
3146 *parg
++ = (char *)setup_script
;
3149 execv(setup_script
, args
);
3152 while (waitpid(pid
, &status
, 0) != pid
);
3153 if (!WIFEXITED(status
) ||
3154 WEXITSTATUS(status
) != 0) {
3155 fprintf(stderr
, "%s: could not launch network script\n",
3161 s
= net_tap_fd_init(vlan
, fd
);
3164 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3165 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3169 #endif /* !_WIN32 */
3171 /* network connection */
3172 typedef struct NetSocketState
{
3173 VLANClientState
*vc
;
3175 int state
; /* 0 = getting length, 1 = getting data */
3179 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3182 typedef struct NetSocketListenState
{
3185 } NetSocketListenState
;
3187 /* XXX: we consider we can send the whole packet without blocking */
3188 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3190 NetSocketState
*s
= opaque
;
3194 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3195 send_all(s
->fd
, buf
, size
);
3198 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3200 NetSocketState
*s
= opaque
;
3201 sendto(s
->fd
, buf
, size
, 0,
3202 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3205 static void net_socket_send(void *opaque
)
3207 NetSocketState
*s
= opaque
;
3212 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3214 err
= socket_error();
3215 if (err
!= EWOULDBLOCK
)
3217 } else if (size
== 0) {
3218 /* end of connection */
3220 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3226 /* reassemble a packet from the network */
3232 memcpy(s
->buf
+ s
->index
, buf
, l
);
3236 if (s
->index
== 4) {
3238 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3244 l
= s
->packet_len
- s
->index
;
3247 memcpy(s
->buf
+ s
->index
, buf
, l
);
3251 if (s
->index
>= s
->packet_len
) {
3252 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3261 static void net_socket_send_dgram(void *opaque
)
3263 NetSocketState
*s
= opaque
;
3266 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3270 /* end of connection */
3271 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3274 qemu_send_packet(s
->vc
, s
->buf
, size
);
3277 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3282 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3283 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3284 inet_ntoa(mcastaddr
->sin_addr
),
3285 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3289 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3291 perror("socket(PF_INET, SOCK_DGRAM)");
3296 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3297 (const char *)&val
, sizeof(val
));
3299 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3303 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3309 /* Add host to multicast group */
3310 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3311 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3313 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3314 (const char *)&imr
, sizeof(struct ip_mreq
));
3316 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3320 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3322 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3323 (const char *)&val
, sizeof(val
));
3325 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3329 socket_set_nonblock(fd
);
3337 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3340 struct sockaddr_in saddr
;
3342 socklen_t saddr_len
;
3345 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3346 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3347 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3351 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3353 if (saddr
.sin_addr
.s_addr
==0) {
3354 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3358 /* clone dgram socket */
3359 newfd
= net_socket_mcast_create(&saddr
);
3361 /* error already reported by net_socket_mcast_create() */
3365 /* clone newfd to fd, close newfd */
3370 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3371 fd
, strerror(errno
));
3376 s
= qemu_mallocz(sizeof(NetSocketState
));
3381 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3382 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3384 /* mcast: save bound address as dst */
3385 if (is_connected
) s
->dgram_dst
=saddr
;
3387 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3388 "socket: fd=%d (%s mcast=%s:%d)",
3389 fd
, is_connected
? "cloned" : "",
3390 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3394 static void net_socket_connect(void *opaque
)
3396 NetSocketState
*s
= opaque
;
3397 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3400 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3404 s
= qemu_mallocz(sizeof(NetSocketState
));
3408 s
->vc
= qemu_new_vlan_client(vlan
,
3409 net_socket_receive
, NULL
, s
);
3410 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3411 "socket: fd=%d", fd
);
3413 net_socket_connect(s
);
3415 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3420 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3423 int so_type
=-1, optlen
=sizeof(so_type
);
3425 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3426 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3431 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3433 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3435 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3436 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3437 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3442 static void net_socket_accept(void *opaque
)
3444 NetSocketListenState
*s
= opaque
;
3446 struct sockaddr_in saddr
;
3451 len
= sizeof(saddr
);
3452 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3453 if (fd
< 0 && errno
!= EINTR
) {
3455 } else if (fd
>= 0) {
3459 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3463 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3464 "socket: connection from %s:%d",
3465 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3469 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3471 NetSocketListenState
*s
;
3473 struct sockaddr_in saddr
;
3475 if (parse_host_port(&saddr
, host_str
) < 0)
3478 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3482 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3487 socket_set_nonblock(fd
);
3489 /* allow fast reuse */
3491 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3493 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3498 ret
= listen(fd
, 0);
3505 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3509 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3512 int fd
, connected
, ret
, err
;
3513 struct sockaddr_in saddr
;
3515 if (parse_host_port(&saddr
, host_str
) < 0)
3518 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3523 socket_set_nonblock(fd
);
3527 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3529 err
= socket_error();
3530 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3531 } else if (err
== EINPROGRESS
) {
3543 s
= net_socket_fd_init(vlan
, fd
, connected
);
3546 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3547 "socket: connect to %s:%d",
3548 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3552 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
3556 struct sockaddr_in saddr
;
3558 if (parse_host_port(&saddr
, host_str
) < 0)
3562 fd
= net_socket_mcast_create(&saddr
);
3566 s
= net_socket_fd_init(vlan
, fd
, 0);
3570 s
->dgram_dst
= saddr
;
3572 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3573 "socket: mcast=%s:%d",
3574 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3579 static int get_param_value(char *buf
, int buf_size
,
3580 const char *tag
, const char *str
)
3589 while (*p
!= '\0' && *p
!= '=') {
3590 if ((q
- option
) < sizeof(option
) - 1)
3598 if (!strcmp(tag
, option
)) {
3600 while (*p
!= '\0' && *p
!= ',') {
3601 if ((q
- buf
) < buf_size
- 1)
3608 while (*p
!= '\0' && *p
!= ',') {
3619 int net_client_init(const char *str
)
3630 while (*p
!= '\0' && *p
!= ',') {
3631 if ((q
- device
) < sizeof(device
) - 1)
3639 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
3640 vlan_id
= strtol(buf
, NULL
, 0);
3642 vlan
= qemu_find_vlan(vlan_id
);
3644 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
3647 if (!strcmp(device
, "nic")) {
3651 if (nb_nics
>= MAX_NICS
) {
3652 fprintf(stderr
, "Too Many NICs\n");
3655 nd
= &nd_table
[nb_nics
];
3656 macaddr
= nd
->macaddr
;
3662 macaddr
[5] = 0x56 + nb_nics
;
3664 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
3665 if (parse_macaddr(macaddr
, buf
) < 0) {
3666 fprintf(stderr
, "invalid syntax for ethernet address\n");
3670 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
3671 nd
->model
= strdup(buf
);
3677 if (!strcmp(device
, "none")) {
3678 /* does nothing. It is needed to signal that no network cards
3683 if (!strcmp(device
, "user")) {
3684 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
3685 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
3687 ret
= net_slirp_init(vlan
);
3691 if (!strcmp(device
, "tap")) {
3693 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3694 fprintf(stderr
, "tap: no interface name\n");
3697 ret
= tap_win32_init(vlan
, ifname
);
3700 if (!strcmp(device
, "tap")) {
3702 char setup_script
[1024];
3704 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3705 fd
= strtol(buf
, NULL
, 0);
3707 if (net_tap_fd_init(vlan
, fd
))
3710 get_param_value(ifname
, sizeof(ifname
), "ifname", p
);
3711 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
3712 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
3714 ret
= net_tap_init(vlan
, ifname
, setup_script
);
3718 if (!strcmp(device
, "socket")) {
3719 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3721 fd
= strtol(buf
, NULL
, 0);
3723 if (net_socket_fd_init(vlan
, fd
, 1))
3725 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
3726 ret
= net_socket_listen_init(vlan
, buf
);
3727 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
3728 ret
= net_socket_connect_init(vlan
, buf
);
3729 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
3730 ret
= net_socket_mcast_init(vlan
, buf
);
3732 fprintf(stderr
, "Unknown socket options: %s\n", p
);
3737 fprintf(stderr
, "Unknown network device: %s\n", device
);
3741 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
3747 void do_info_network(void)
3750 VLANClientState
*vc
;
3752 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3753 term_printf("VLAN %d devices:\n", vlan
->id
);
3754 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
3755 term_printf(" %s\n", vc
->info_str
);
3759 #if defined(__linux__)
3760 #define SELF_ANNOUNCE_ROUNDS 5
3761 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
3762 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
3763 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
3764 int announce_self_create(unsigned char *buf
,
3765 unsigned char mac_addr
[ETH_ALEN
])
3767 struct ethhdr
*eh
= (struct ethhdr
*)buf
;
3768 uint32_t *magic
= (uint32_t*)(eh
+1);
3769 unsigned char *p
= (unsigned char*)(magic
+ 1);
3771 /* FIXME: should we send a different packet (arp/rarp/ping)? */
3773 /* ethernet header */
3774 memset(eh
->h_dest
, 0xff, ETH_ALEN
);
3775 memcpy(eh
->h_source
, mac_addr
, ETH_ALEN
);
3776 eh
->h_proto
= htons(ETH_P_EXPERIMENTAL
);
3779 *magic
= EXPERIMENTAL_MAGIC
;
3781 return p
- buf
; /* sizeof(*eh) + sizeof(*magic) */
3784 void qemu_tap_announce_self(void)
3788 VLANClientState
*vc
;
3791 for (i
=0; i
<nb_nics
; i
++) { /* for all nics */
3792 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
3793 vlan
= nd_table
[i
].vlan
;
3794 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3795 if (vc
->fd_read
== tap_receive
) { /* send only if tap */
3796 for (j
=0; j
<SELF_ANNOUNCE_ROUNDS
; j
++) {
3797 vc
->fd_read(vc
->opaque
, buf
, len
);
3800 } /* for vc -- look for tap_receive */
3801 } /* for i -- all nics */
3804 void qemu_tap_announce_self(void) {}
3806 /***********************************************************/
3809 static USBPort
*used_usb_ports
;
3810 static USBPort
*free_usb_ports
;
3812 /* ??? Maybe change this to register a hub to keep track of the topology. */
3813 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
3814 usb_attachfn attach
)
3816 port
->opaque
= opaque
;
3817 port
->index
= index
;
3818 port
->attach
= attach
;
3819 port
->next
= free_usb_ports
;
3820 free_usb_ports
= port
;
3823 static int usb_device_add(const char *devname
)
3829 if (!free_usb_ports
)
3832 if (strstart(devname
, "host:", &p
)) {
3833 dev
= usb_host_device_open(p
);
3834 } else if (!strcmp(devname
, "mouse")) {
3835 dev
= usb_mouse_init();
3836 } else if (!strcmp(devname
, "tablet")) {
3837 dev
= usb_tablet_init();
3838 } else if (strstart(devname
, "disk:", &p
)) {
3839 dev
= usb_msd_init(p
);
3846 /* Find a USB port to add the device to. */
3847 port
= free_usb_ports
;
3851 /* Create a new hub and chain it on. */
3852 free_usb_ports
= NULL
;
3853 port
->next
= used_usb_ports
;
3854 used_usb_ports
= port
;
3856 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
3857 usb_attach(port
, hub
);
3858 port
= free_usb_ports
;
3861 free_usb_ports
= port
->next
;
3862 port
->next
= used_usb_ports
;
3863 used_usb_ports
= port
;
3864 usb_attach(port
, dev
);
3868 static int usb_device_del(const char *devname
)
3876 if (!used_usb_ports
)
3879 p
= strchr(devname
, '.');
3882 bus_num
= strtoul(devname
, NULL
, 0);
3883 addr
= strtoul(p
+ 1, NULL
, 0);
3887 lastp
= &used_usb_ports
;
3888 port
= used_usb_ports
;
3889 while (port
&& port
->dev
->addr
!= addr
) {
3890 lastp
= &port
->next
;
3898 *lastp
= port
->next
;
3899 usb_attach(port
, NULL
);
3900 dev
->handle_destroy(dev
);
3901 port
->next
= free_usb_ports
;
3902 free_usb_ports
= port
;
3906 void do_usb_add(const char *devname
)
3909 ret
= usb_device_add(devname
);
3911 term_printf("Could not add USB device '%s'\n", devname
);
3914 void do_usb_del(const char *devname
)
3917 ret
= usb_device_del(devname
);
3919 term_printf("Could not remove USB device '%s'\n", devname
);
3926 const char *speed_str
;
3929 term_printf("USB support not enabled\n");
3933 for (port
= used_usb_ports
; port
; port
= port
->next
) {
3937 switch(dev
->speed
) {
3941 case USB_SPEED_FULL
:
3944 case USB_SPEED_HIGH
:
3951 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3952 0, dev
->addr
, speed_str
, dev
->devname
);
3956 /***********************************************************/
3959 static char *pid_filename
;
3961 /* Remove PID file. Called on normal exit */
3963 static void remove_pidfile(void)
3965 unlink (pid_filename
);
3968 static void create_pidfile(const char *filename
)
3970 struct stat pidstat
;
3973 /* Try to write our PID to the named file */
3974 if (stat(filename
, &pidstat
) < 0) {
3975 if (errno
== ENOENT
) {
3976 if ((f
= fopen (filename
, "w")) == NULL
) {
3977 perror("Opening pidfile");
3980 fprintf(f
, "%d\n", getpid());
3982 pid_filename
= qemu_strdup(filename
);
3983 if (!pid_filename
) {
3984 fprintf(stderr
, "Could not save PID filename");
3987 atexit(remove_pidfile
);
3990 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
3996 /***********************************************************/
3999 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4003 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4007 static void dumb_refresh(DisplayState
*ds
)
4012 void dumb_display_init(DisplayState
*ds
)
4017 ds
->dpy_update
= dumb_update
;
4018 ds
->dpy_resize
= dumb_resize
;
4019 ds
->dpy_refresh
= dumb_refresh
;
4022 /***********************************************************/
4025 #define MAX_IO_HANDLERS 64
4027 typedef struct IOHandlerRecord
{
4029 IOCanRWHandler
*fd_read_poll
;
4031 IOHandler
*fd_write
;
4033 /* temporary data */
4035 struct IOHandlerRecord
*next
;
4038 static IOHandlerRecord
*first_io_handler
;
4040 /* XXX: fd_read_poll should be suppressed, but an API change is
4041 necessary in the character devices to suppress fd_can_read(). */
4042 int qemu_set_fd_handler2(int fd
,
4043 IOCanRWHandler
*fd_read_poll
,
4045 IOHandler
*fd_write
,
4048 IOHandlerRecord
**pioh
, *ioh
;
4050 if (!fd_read
&& !fd_write
) {
4051 pioh
= &first_io_handler
;
4056 if (ioh
->fd
== fd
) {
4064 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4068 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4071 ioh
->next
= first_io_handler
;
4072 first_io_handler
= ioh
;
4075 ioh
->fd_read_poll
= fd_read_poll
;
4076 ioh
->fd_read
= fd_read
;
4077 ioh
->fd_write
= fd_write
;
4078 ioh
->opaque
= opaque
;
4083 int qemu_set_fd_handler(int fd
,
4085 IOHandler
*fd_write
,
4088 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4091 /***********************************************************/
4092 /* Polling handling */
4094 typedef struct PollingEntry
{
4097 struct PollingEntry
*next
;
4100 static PollingEntry
*first_polling_entry
;
4102 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4104 PollingEntry
**ppe
, *pe
;
4105 pe
= qemu_mallocz(sizeof(PollingEntry
));
4109 pe
->opaque
= opaque
;
4110 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4115 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4117 PollingEntry
**ppe
, *pe
;
4118 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4120 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4129 /***********************************************************/
4130 /* Wait objects support */
4131 typedef struct WaitObjects
{
4133 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4134 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4135 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4138 static WaitObjects wait_objects
= {0};
4140 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4142 WaitObjects
*w
= &wait_objects
;
4144 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4146 w
->events
[w
->num
] = handle
;
4147 w
->func
[w
->num
] = func
;
4148 w
->opaque
[w
->num
] = opaque
;
4153 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4156 WaitObjects
*w
= &wait_objects
;
4159 for (i
= 0; i
< w
->num
; i
++) {
4160 if (w
->events
[i
] == handle
)
4163 w
->events
[i
] = w
->events
[i
+ 1];
4164 w
->func
[i
] = w
->func
[i
+ 1];
4165 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4173 /***********************************************************/
4174 /* savevm/loadvm support */
4176 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4178 f
->put_buffer(f
, buf
, size
);
4181 void qemu_put_byte(QEMUFile
*f
, int v
)
4186 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4188 qemu_put_byte(f
, v
>> 8);
4189 qemu_put_byte(f
, v
);
4192 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4194 qemu_put_byte(f
, v
>> 24);
4195 qemu_put_byte(f
, v
>> 16);
4196 qemu_put_byte(f
, v
>> 8);
4197 qemu_put_byte(f
, v
);
4200 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4202 qemu_put_be32(f
, v
>> 32);
4203 qemu_put_be32(f
, v
);
4206 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size
)
4208 return f
->get_buffer(f
, buf
, size
);
4211 int qemu_get_byte(QEMUFile
*f
)
4213 return f
->get_byte(f
);
4216 unsigned int qemu_get_be16(QEMUFile
*f
)
4219 v
= qemu_get_byte(f
) << 8;
4220 v
|= qemu_get_byte(f
);
4224 unsigned int qemu_get_be32(QEMUFile
*f
)
4227 v
= qemu_get_byte(f
) << 24;
4228 v
|= qemu_get_byte(f
) << 16;
4229 v
|= qemu_get_byte(f
) << 8;
4230 v
|= qemu_get_byte(f
);
4234 uint64_t qemu_get_be64(QEMUFile
*f
)
4237 v
= (uint64_t)qemu_get_be32(f
) << 32;
4238 v
|= qemu_get_be32(f
);
4242 int64_t qemu_ftell(QEMUFile
*f
)
4247 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4249 return f
->seek(f
, pos
, whence
);
4252 typedef struct SaveStateEntry
{
4256 SaveStateHandler
*save_state
;
4257 LoadStateHandler
*load_state
;
4259 struct SaveStateEntry
*next
;
4262 static SaveStateEntry
*first_se
;
4264 int register_savevm(const char *idstr
,
4267 SaveStateHandler
*save_state
,
4268 LoadStateHandler
*load_state
,
4271 SaveStateEntry
*se
, **pse
;
4273 se
= qemu_malloc(sizeof(SaveStateEntry
));
4276 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4277 se
->instance_id
= instance_id
;
4278 se
->version_id
= version_id
;
4279 se
->save_state
= save_state
;
4280 se
->load_state
= load_state
;
4281 se
->opaque
= opaque
;
4284 /* add at the end of list */
4286 while (*pse
!= NULL
)
4287 pse
= &(*pse
)->next
;
4292 #define QEMU_VM_FILE_MAGIC 0x5145564d
4293 #define QEMU_VM_FILE_VERSION 0x00000001
4296 static int qemu_savevm_method_file_open(QEMUFile
*f
, const char *filename
,
4299 FILE *fp
= fopen(filename
, flags
);
4300 f
->opaque
= (void*)fp
;
4306 static void qemu_savevm_method_file_close(QEMUFile
*f
)
4308 FILE *fp
= (FILE*)f
->opaque
;
4313 static void qemu_savevm_method_file_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4315 FILE *fp
= (FILE*)f
->opaque
;
4316 fwrite(buf
, 1, size
, fp
);
4319 static void qemu_savevm_method_file_put_byte(QEMUFile
*f
, int v
)
4321 FILE *fp
= (FILE*)f
->opaque
;
4325 static int qemu_savevm_method_file_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size
)
4327 FILE *fp
= (FILE*)f
->opaque
;
4328 return fread(buf
, 1, size
, fp
);
4331 static int qemu_savevm_method_file_get_byte(QEMUFile
*f
)
4333 FILE *fp
= (FILE*)f
->opaque
;
4343 static int64_t qemu_savevm_method_file_tell(QEMUFile
*f
)
4345 FILE *fp
= (FILE*)f
->opaque
;
4349 static int64_t qemu_savevm_method_file_seek(QEMUFile
*f
, int64_t pos
, int whence
)
4351 FILE *fp
= (FILE*)f
->opaque
;
4352 if (fseek(fp
, pos
, whence
) < 0)
4357 static int qemu_savevm_method_file_eof(QEMUFile
*f
)
4359 FILE *fp
= (FILE*)f
->opaque
;
4363 QEMUFile qemu_savevm_method_file
= {
4365 .open
= qemu_savevm_method_file_open
,
4366 .close
= qemu_savevm_method_file_close
,
4367 .put_byte
= qemu_savevm_method_file_put_byte
,
4368 .get_byte
= qemu_savevm_method_file_get_byte
,
4369 .put_buffer
= qemu_savevm_method_file_put_buffer
,
4370 .get_buffer
= qemu_savevm_method_file_get_buffer
,
4371 .tell
= qemu_savevm_method_file_tell
,
4372 .seek
= qemu_savevm_method_file_seek
,
4373 .eof
= qemu_savevm_method_file_eof
4377 int qemu_savevm(const char *filename
, QEMUFile
*f
)
4380 int len
, len_pos
, cur_pos
, saved_vm_running
, ret
;
4382 saved_vm_running
= vm_running
;
4385 if (f
->open(f
, filename
, "wb")) {
4390 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4391 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4393 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4395 len
= strlen(se
->idstr
);
4396 qemu_put_byte(f
, len
);
4397 qemu_put_buffer(f
, se
->idstr
, len
);
4399 qemu_put_be32(f
, se
->instance_id
);
4400 qemu_put_be32(f
, se
->version_id
);
4402 /* record size: filled later */
4403 len_pos
= qemu_ftell(f
);
4404 qemu_put_be32(f
, 0);
4406 se
->save_state(f
, se
->opaque
);
4408 /* fill record size */
4409 cur_pos
= qemu_ftell(f
);
4410 len
= qemu_ftell(f
) - len_pos
- 4;
4411 qemu_fseek(f
, len_pos
, SEEK_SET
);
4412 qemu_put_be32(f
, len
);
4413 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4415 qemu_put_byte(f
, 0); /* len==0 represents end of state */
4419 if (saved_vm_running
)
4424 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4428 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4429 if (!strcmp(se
->idstr
, idstr
) &&
4430 instance_id
== se
->instance_id
)
4436 int qemu_loadvm(const char *filename
, QEMUFile
*f
)
4439 int len
, cur_pos
, ret
, instance_id
, record_len
, version_id
;
4440 int saved_vm_running
;
4444 saved_vm_running
= vm_running
;
4447 if (f
->open(f
, filename
, "rb")) {
4452 v
= qemu_get_be32(f
);
4453 if (v
!= QEMU_VM_FILE_MAGIC
)
4455 v
= qemu_get_be32(f
);
4456 if (v
!= QEMU_VM_FILE_VERSION
) {
4463 len
= qemu_get_byte(f
);
4464 if (f
->eof(f
) || len
==0)
4466 qemu_get_buffer(f
, idstr
, len
);
4468 instance_id
= qemu_get_be32(f
);
4469 version_id
= qemu_get_be32(f
);
4470 record_len
= qemu_get_be32(f
);
4472 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4473 idstr
, instance_id
, version_id
, record_len
);
4475 cur_pos
= qemu_ftell(f
);
4476 se
= find_se(idstr
, instance_id
);
4478 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4479 instance_id
, idstr
);
4481 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4483 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4484 instance_id
, idstr
);
4487 /* always seek to exact end of record */
4488 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4491 qemu_tap_announce_self(); /* FIXME: should this move to vm_start? */
4494 if (saved_vm_running
)
4499 /***********************************************************/
4500 /* cpu save/restore */
4502 #if defined(TARGET_I386)
4504 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
4506 qemu_put_be32(f
, dt
->selector
);
4507 qemu_put_betl(f
, dt
->base
);
4508 qemu_put_be32(f
, dt
->limit
);
4509 qemu_put_be32(f
, dt
->flags
);
4512 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
4514 dt
->selector
= qemu_get_be32(f
);
4515 dt
->base
= qemu_get_betl(f
);
4516 dt
->limit
= qemu_get_be32(f
);
4517 dt
->flags
= qemu_get_be32(f
);
4520 void cpu_save(QEMUFile
*f
, void *opaque
)
4522 CPUState
*env
= opaque
;
4523 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
4529 kvm_save_registers(env
);
4532 for(i
= 0; i
< CPU_NB_REGS
; i
++)
4533 qemu_put_betls(f
, &env
->regs
[i
]);
4534 qemu_put_betls(f
, &env
->eip
);
4535 qemu_put_betls(f
, &env
->eflags
);
4536 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
4537 qemu_put_be32s(f
, &hflags
);
4541 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
4543 for(i
= 0; i
< 8; i
++) {
4544 fptag
|= ((!env
->fptags
[i
]) << i
);
4547 qemu_put_be16s(f
, &fpuc
);
4548 qemu_put_be16s(f
, &fpus
);
4549 qemu_put_be16s(f
, &fptag
);
4551 #ifdef USE_X86LDOUBLE
4556 qemu_put_be16s(f
, &fpregs_format
);
4558 for(i
= 0; i
< 8; i
++) {
4559 #ifdef USE_X86LDOUBLE
4563 /* we save the real CPU data (in case of MMX usage only 'mant'
4564 contains the MMX register */
4565 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
4566 qemu_put_be64(f
, mant
);
4567 qemu_put_be16(f
, exp
);
4570 /* if we use doubles for float emulation, we save the doubles to
4571 avoid losing information in case of MMX usage. It can give
4572 problems if the image is restored on a CPU where long
4573 doubles are used instead. */
4574 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
4578 for(i
= 0; i
< 6; i
++)
4579 cpu_put_seg(f
, &env
->segs
[i
]);
4580 cpu_put_seg(f
, &env
->ldt
);
4581 cpu_put_seg(f
, &env
->tr
);
4582 cpu_put_seg(f
, &env
->gdt
);
4583 cpu_put_seg(f
, &env
->idt
);
4585 qemu_put_be32s(f
, &env
->sysenter_cs
);
4586 qemu_put_be32s(f
, &env
->sysenter_esp
);
4587 qemu_put_be32s(f
, &env
->sysenter_eip
);
4589 qemu_put_betls(f
, &env
->cr
[0]);
4590 qemu_put_betls(f
, &env
->cr
[2]);
4591 qemu_put_betls(f
, &env
->cr
[3]);
4592 qemu_put_betls(f
, &env
->cr
[4]);
4594 for(i
= 0; i
< 8; i
++)
4595 qemu_put_betls(f
, &env
->dr
[i
]);
4598 qemu_put_be32s(f
, &env
->a20_mask
);
4601 qemu_put_be32s(f
, &env
->mxcsr
);
4602 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
4603 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
4604 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
4607 #ifdef TARGET_X86_64
4608 qemu_put_be64s(f
, &env
->efer
);
4609 qemu_put_be64s(f
, &env
->star
);
4610 qemu_put_be64s(f
, &env
->lstar
);
4611 qemu_put_be64s(f
, &env
->cstar
);
4612 qemu_put_be64s(f
, &env
->fmask
);
4613 qemu_put_be64s(f
, &env
->kernelgsbase
);
4618 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
4619 qemu_put_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
4621 qemu_put_be64s(f
, &env
->tsc
);
4626 #ifdef USE_X86LDOUBLE
4627 /* XXX: add that in a FPU generic layer */
4628 union x86_longdouble
{
4633 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4634 #define EXPBIAS1 1023
4635 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4636 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4638 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
4642 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
4643 /* exponent + sign */
4644 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
4645 e
|= SIGND1(temp
) >> 16;
4650 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
4652 CPUState
*env
= opaque
;
4655 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
4657 if (version_id
!= 3)
4659 for(i
= 0; i
< CPU_NB_REGS
; i
++)
4660 qemu_get_betls(f
, &env
->regs
[i
]);
4661 qemu_get_betls(f
, &env
->eip
);
4662 qemu_get_betls(f
, &env
->eflags
);
4663 qemu_get_be32s(f
, &hflags
);
4665 qemu_get_be16s(f
, &fpuc
);
4666 qemu_get_be16s(f
, &fpus
);
4667 qemu_get_be16s(f
, &fptag
);
4668 qemu_get_be16s(f
, &fpregs_format
);
4670 /* NOTE: we cannot always restore the FPU state if the image come
4671 from a host with a different 'USE_X86LDOUBLE' define. We guess
4672 if we are in an MMX state to restore correctly in that case. */
4673 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
4674 for(i
= 0; i
< 8; i
++) {
4678 switch(fpregs_format
) {
4680 mant
= qemu_get_be64(f
);
4681 exp
= qemu_get_be16(f
);
4682 #ifdef USE_X86LDOUBLE
4683 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
4685 /* difficult case */
4687 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
4689 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
4693 mant
= qemu_get_be64(f
);
4694 #ifdef USE_X86LDOUBLE
4696 union x86_longdouble
*p
;
4697 /* difficult case */
4698 p
= (void *)&env
->fpregs
[i
];
4703 fp64_to_fp80(p
, mant
);
4707 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
4716 /* XXX: restore FPU round state */
4717 env
->fpstt
= (fpus
>> 11) & 7;
4718 env
->fpus
= fpus
& ~0x3800;
4720 for(i
= 0; i
< 8; i
++) {
4721 env
->fptags
[i
] = (fptag
>> i
) & 1;
4724 for(i
= 0; i
< 6; i
++)
4725 cpu_get_seg(f
, &env
->segs
[i
]);
4726 cpu_get_seg(f
, &env
->ldt
);
4727 cpu_get_seg(f
, &env
->tr
);
4728 cpu_get_seg(f
, &env
->gdt
);
4729 cpu_get_seg(f
, &env
->idt
);
4731 qemu_get_be32s(f
, &env
->sysenter_cs
);
4732 qemu_get_be32s(f
, &env
->sysenter_esp
);
4733 qemu_get_be32s(f
, &env
->sysenter_eip
);
4735 qemu_get_betls(f
, &env
->cr
[0]);
4736 qemu_get_betls(f
, &env
->cr
[2]);
4737 qemu_get_betls(f
, &env
->cr
[3]);
4738 qemu_get_betls(f
, &env
->cr
[4]);
4740 for(i
= 0; i
< 8; i
++)
4741 qemu_get_betls(f
, &env
->dr
[i
]);
4744 qemu_get_be32s(f
, &env
->a20_mask
);
4746 qemu_get_be32s(f
, &env
->mxcsr
);
4747 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
4748 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
4749 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
4752 #ifdef TARGET_X86_64
4753 qemu_get_be64s(f
, &env
->efer
);
4754 qemu_get_be64s(f
, &env
->star
);
4755 qemu_get_be64s(f
, &env
->lstar
);
4756 qemu_get_be64s(f
, &env
->cstar
);
4757 qemu_get_be64s(f
, &env
->fmask
);
4758 qemu_get_be64s(f
, &env
->kernelgsbase
);
4761 /* XXX: compute hflags from scratch, except for CPL and IIF */
4762 env
->hflags
= hflags
;
4766 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
4767 qemu_get_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
4769 qemu_get_be64s(f
, &env
->tsc
);
4770 kvm_load_registers(env
);
4776 #elif defined(TARGET_PPC)
4777 void cpu_save(QEMUFile
*f
, void *opaque
)
4781 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
4786 #elif defined(TARGET_MIPS)
4787 void cpu_save(QEMUFile
*f
, void *opaque
)
4791 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
4796 #elif defined(TARGET_SPARC)
4797 void cpu_save(QEMUFile
*f
, void *opaque
)
4799 CPUState
*env
= opaque
;
4803 for(i
= 0; i
< 8; i
++)
4804 qemu_put_betls(f
, &env
->gregs
[i
]);
4805 for(i
= 0; i
< NWINDOWS
* 16; i
++)
4806 qemu_put_betls(f
, &env
->regbase
[i
]);
4809 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
4815 qemu_put_be32(f
, u
.i
);
4818 qemu_put_betls(f
, &env
->pc
);
4819 qemu_put_betls(f
, &env
->npc
);
4820 qemu_put_betls(f
, &env
->y
);
4822 qemu_put_be32(f
, tmp
);
4823 qemu_put_betls(f
, &env
->fsr
);
4824 qemu_put_betls(f
, &env
->tbr
);
4825 #ifndef TARGET_SPARC64
4826 qemu_put_be32s(f
, &env
->wim
);
4828 for(i
= 0; i
< 16; i
++)
4829 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
4833 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
4835 CPUState
*env
= opaque
;
4839 for(i
= 0; i
< 8; i
++)
4840 qemu_get_betls(f
, &env
->gregs
[i
]);
4841 for(i
= 0; i
< NWINDOWS
* 16; i
++)
4842 qemu_get_betls(f
, &env
->regbase
[i
]);
4845 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
4850 u
.i
= qemu_get_be32(f
);
4854 qemu_get_betls(f
, &env
->pc
);
4855 qemu_get_betls(f
, &env
->npc
);
4856 qemu_get_betls(f
, &env
->y
);
4857 tmp
= qemu_get_be32(f
);
4858 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
4859 correctly updated */
4861 qemu_get_betls(f
, &env
->fsr
);
4862 qemu_get_betls(f
, &env
->tbr
);
4863 #ifndef TARGET_SPARC64
4864 qemu_get_be32s(f
, &env
->wim
);
4866 for(i
= 0; i
< 16; i
++)
4867 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
4873 #elif defined(TARGET_ARM)
4875 /* ??? Need to implement these. */
4876 void cpu_save(QEMUFile
*f
, void *opaque
)
4880 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
4887 #warning No CPU save/restore functions
4891 /***********************************************************/
4892 /* ram save/restore */
4894 /* we just avoid storing empty pages */
4895 static void ram_put_page(QEMUFile
*f
, const uint8_t *buf
, int len
)
4900 for(i
= 1; i
< len
; i
++) {
4904 qemu_put_byte(f
, 1);
4905 qemu_put_byte(f
, v
);
4908 qemu_put_byte(f
, 0);
4909 qemu_put_buffer(f
, buf
, len
);
4912 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
4916 v
= qemu_get_byte(f
);
4919 if (qemu_get_buffer(f
, buf
, len
) != len
)
4923 v
= qemu_get_byte(f
);
4924 memset(buf
, v
, len
);
4932 static void ram_save(QEMUFile
*f
, void *opaque
)
4935 qemu_put_be32(f
, phys_ram_size
);
4936 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
4938 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
4941 ram_put_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
4945 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
4948 if (version_id
!= 1)
4950 if (qemu_get_be32(f
) != phys_ram_size
)
4952 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
4954 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
4957 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
4964 /***********************************************************/
4965 /* machine registration */
4967 QEMUMachine
*first_machine
= NULL
;
4969 int qemu_register_machine(QEMUMachine
*m
)
4972 pm
= &first_machine
;
4980 QEMUMachine
*find_machine(const char *name
)
4984 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
4985 if (!strcmp(m
->name
, name
))
4991 /***********************************************************/
4992 /* main execution loop */
4994 void gui_update(void *opaque
)
4996 display_state
.dpy_refresh(&display_state
);
4997 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
5000 struct vm_change_state_entry
{
5001 VMChangeStateHandler
*cb
;
5003 LIST_ENTRY (vm_change_state_entry
) entries
;
5006 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
5008 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
5011 VMChangeStateEntry
*e
;
5013 e
= qemu_mallocz(sizeof (*e
));
5019 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
5023 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
5025 LIST_REMOVE (e
, entries
);
5029 static void vm_state_notify(int running
)
5031 VMChangeStateEntry
*e
;
5033 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
5034 e
->cb(e
->opaque
, running
);
5038 /* XXX: support several handlers */
5039 static VMStopHandler
*vm_stop_cb
;
5040 static void *vm_stop_opaque
;
5042 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
5045 vm_stop_opaque
= opaque
;
5049 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
5060 console_select(0); /* focus on guest's display */
5064 void vm_stop(int reason
)
5067 cpu_disable_ticks();
5071 vm_stop_cb(vm_stop_opaque
, reason
);
5078 /* reset/shutdown handler */
5080 typedef struct QEMUResetEntry
{
5081 QEMUResetHandler
*func
;
5083 struct QEMUResetEntry
*next
;
5086 static QEMUResetEntry
*first_reset_entry
;
5087 static int reset_requested
;
5088 static int shutdown_requested
;
5089 static int powerdown_requested
;
5091 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
5093 QEMUResetEntry
**pre
, *re
;
5095 pre
= &first_reset_entry
;
5096 while (*pre
!= NULL
)
5097 pre
= &(*pre
)->next
;
5098 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
5100 re
->opaque
= opaque
;
5105 void qemu_system_reset(void)
5109 /* reset all devices */
5110 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
5111 re
->func(re
->opaque
);
5115 void qemu_system_reset_request(void)
5117 reset_requested
= 1;
5119 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5122 void qemu_system_shutdown_request(void)
5124 shutdown_requested
= 1;
5126 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5129 void qemu_system_powerdown_request(void)
5131 powerdown_requested
= 1;
5133 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5136 void main_loop_wait(int timeout
)
5138 IOHandlerRecord
*ioh
, *ioh_next
;
5139 fd_set rfds
, wfds
, xfds
;
5145 /* XXX: need to suppress polling by better using win32 events */
5147 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
5148 ret
|= pe
->func(pe
->opaque
);
5151 if (ret
== 0 && timeout
> 0) {
5153 WaitObjects
*w
= &wait_objects
;
5155 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
5156 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
5157 if (w
->func
[ret
- WAIT_OBJECT_0
])
5158 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
5159 } else if (ret
== WAIT_TIMEOUT
) {
5161 err
= GetLastError();
5162 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
5166 /* poll any events */
5167 /* XXX: separate device handlers from system ones */
5172 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5174 (!ioh
->fd_read_poll
||
5175 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
5176 FD_SET(ioh
->fd
, &rfds
);
5180 if (ioh
->fd_write
) {
5181 FD_SET(ioh
->fd
, &wfds
);
5191 tv
.tv_usec
= timeout
* 1000;
5193 #if defined(CONFIG_SLIRP)
5195 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
5198 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
5200 /* XXX: better handling of removal */
5201 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh_next
) {
5202 ioh_next
= ioh
->next
;
5203 if (FD_ISSET(ioh
->fd
, &rfds
)) {
5204 ioh
->fd_read(ioh
->opaque
);
5207 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh_next
) {
5208 ioh_next
= ioh
->next
;
5209 if (FD_ISSET(ioh
->fd
, &wfds
)) {
5210 ioh
->fd_write(ioh
->opaque
);
5214 #if defined(CONFIG_SLIRP)
5221 slirp_select_poll(&rfds
, &wfds
, &xfds
);
5229 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
5230 qemu_get_clock(vm_clock
));
5231 /* run dma transfers, if any */
5235 /* real time timers */
5236 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
5237 qemu_get_clock(rt_clock
));
5240 static CPUState
*cur_cpu
;
5245 #ifdef CONFIG_PROFILER
5250 cur_cpu
= first_cpu
;
5257 env
= env
->next_cpu
;
5260 #ifdef CONFIG_PROFILER
5261 ti
= profile_getclock();
5263 ret
= cpu_exec(env
);
5264 #ifdef CONFIG_PROFILER
5265 qemu_time
+= profile_getclock() - ti
;
5267 if (ret
!= EXCP_HALTED
)
5269 /* all CPUs are halted ? */
5270 if (env
== cur_cpu
) {
5277 if (shutdown_requested
) {
5278 ret
= EXCP_INTERRUPT
;
5281 if (reset_requested
) {
5282 reset_requested
= 0;
5283 qemu_system_reset();
5284 ret
= EXCP_INTERRUPT
;
5286 if (powerdown_requested
) {
5287 powerdown_requested
= 0;
5288 qemu_system_powerdown();
5289 ret
= EXCP_INTERRUPT
;
5291 if (ret
== EXCP_DEBUG
) {
5292 vm_stop(EXCP_DEBUG
);
5294 /* if hlt instruction, we wait until the next IRQ */
5295 /* XXX: use timeout computed from timers */
5296 if (ret
== EXCP_HLT
)
5303 #ifdef CONFIG_PROFILER
5304 ti
= profile_getclock();
5306 main_loop_wait(timeout
);
5307 #ifdef CONFIG_PROFILER
5308 dev_time
+= profile_getclock() - ti
;
5311 cpu_disable_ticks();
5317 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2005 Fabrice Bellard\n"
5318 "usage: %s [options] [disk_image]\n"
5320 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5322 "Standard options:\n"
5323 "-M machine select emulated machine (-M ? for list)\n"
5324 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5325 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5326 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5327 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5328 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5329 "-snapshot write to temporary files instead of disk image files\n"
5331 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5333 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5334 "-smp n set the number of CPUs to 'n' [default=1]\n"
5335 "-nographic disable graphical output and redirect serial I/Os to console\n"
5337 "-k language use keyboard layout (for example \"fr\" for French)\n"
5340 "-audio-help print list of audio drivers and their options\n"
5341 "-soundhw c1,... enable audio support\n"
5342 " and only specified sound cards (comma separated list)\n"
5343 " use -soundhw ? to get the list of supported cards\n"
5344 " use -soundhw all to enable all of them\n"
5346 "-localtime set the real time clock to local time [default=utc]\n"
5347 "-full-screen start in full screen\n"
5349 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5351 "-usb enable the USB driver (will be the default soon)\n"
5352 "-usbdevice name add the host or guest USB device 'name'\n"
5353 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5354 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5357 "Network options:\n"
5358 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5359 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5361 "-net user[,vlan=n][,hostname=host]\n"
5362 " connect the user mode network stack to VLAN 'n' and send\n"
5363 " hostname 'host' to DHCP clients\n"
5366 "-net tap[,vlan=n],ifname=name\n"
5367 " connect the host TAP network interface to VLAN 'n'\n"
5369 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5370 " connect the host TAP network interface to VLAN 'n' and use\n"
5371 " the network script 'file' (default=%s);\n"
5372 " use 'fd=h' to connect to an already opened TAP interface\n"
5374 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5375 " connect the vlan 'n' to another VLAN using a socket connection\n"
5376 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5377 " connect the vlan 'n' to multicast maddr and port\n"
5378 "-net none use it alone to have zero network devices; if no -net option\n"
5379 " is provided, the default is '-net nic -net user'\n"
5382 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5384 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5386 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5387 " redirect TCP or UDP connections from host to guest [-net user]\n"
5390 "Linux boot specific:\n"
5391 "-kernel bzImage use 'bzImage' as kernel image\n"
5392 "-append cmdline use 'cmdline' as kernel command line\n"
5393 "-initrd file use 'file' as initial ram disk\n"
5395 "Debug/Expert options:\n"
5396 "-monitor dev redirect the monitor to char device 'dev'\n"
5397 "-serial dev redirect the serial port to char device 'dev'\n"
5398 "-parallel dev redirect the parallel port to char device 'dev'\n"
5399 "-pidfile file Write PID to 'file'\n"
5400 "-S freeze CPU at startup (use 'c' to start execution)\n"
5401 "-s wait gdb connection to port %d\n"
5402 "-p port change gdb connection port\n"
5403 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5404 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5405 " translation (t=none or lba) (usually qemu can guess them)\n"
5406 "-L path set the directory for the BIOS and VGA BIOS\n"
5408 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5409 "-no-kqemu disable KQEMU kernel module usage\n"
5412 "-no-kvm disable KVM hardware virtualization\n"
5414 #ifdef USE_CODE_COPY
5415 "-no-code-copy disable code copy acceleration\n"
5418 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5419 " (default is CL-GD5446 PCI VGA)\n"
5420 "-no-acpi disable ACPI\n"
5422 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5423 "-vnc display start a VNC server on display\n"
5425 "During emulation, the following keys are useful:\n"
5426 "ctrl-alt-f toggle full screen\n"
5427 "ctrl-alt-n switch to virtual console 'n'\n"
5428 "ctrl-alt toggle mouse and keyboard grab\n"
5430 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5435 DEFAULT_NETWORK_SCRIPT
,
5437 DEFAULT_GDBSTUB_PORT
,
5442 #define HAS_ARG 0x0001
5456 QEMU_OPTION_snapshot
,
5458 QEMU_OPTION_no_fd_bootchk
,
5461 QEMU_OPTION_nographic
,
5463 QEMU_OPTION_audio_help
,
5464 QEMU_OPTION_soundhw
,
5482 QEMU_OPTION_no_code_copy
,
5484 QEMU_OPTION_localtime
,
5485 QEMU_OPTION_cirrusvga
,
5487 QEMU_OPTION_std_vga
,
5488 QEMU_OPTION_monitor
,
5489 QEMU_OPTION_vmchannel
,
5491 QEMU_OPTION_parallel
,
5493 QEMU_OPTION_full_screen
,
5494 QEMU_OPTION_pidfile
,
5495 QEMU_OPTION_no_kqemu
,
5496 QEMU_OPTION_kernel_kqemu
,
5497 QEMU_OPTION_win2k_hack
,
5499 QEMU_OPTION_usbdevice
,
5502 QEMU_OPTION_no_acpi
,
5506 typedef struct QEMUOption
{
5512 const QEMUOption qemu_options
[] = {
5513 { "h", 0, QEMU_OPTION_h
},
5515 { "M", HAS_ARG
, QEMU_OPTION_M
},
5516 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
5517 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
5518 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
5519 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
5520 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
5521 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
5522 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
5523 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
5524 { "snapshot", 0, QEMU_OPTION_snapshot
},
5526 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
5528 { "m", HAS_ARG
, QEMU_OPTION_m
},
5529 { "nographic", 0, QEMU_OPTION_nographic
},
5530 { "k", HAS_ARG
, QEMU_OPTION_k
},
5532 { "audio-help", 0, QEMU_OPTION_audio_help
},
5533 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
5536 { "net", HAS_ARG
, QEMU_OPTION_net
},
5538 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
5540 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
5542 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
5545 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
5546 { "append", HAS_ARG
, QEMU_OPTION_append
},
5547 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
5549 { "S", 0, QEMU_OPTION_S
},
5550 { "s", 0, QEMU_OPTION_s
},
5551 { "p", HAS_ARG
, QEMU_OPTION_p
},
5552 { "d", HAS_ARG
, QEMU_OPTION_d
},
5553 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
5554 { "L", HAS_ARG
, QEMU_OPTION_L
},
5555 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
5557 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
5558 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
5561 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
5563 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5564 { "g", 1, QEMU_OPTION_g
},
5566 { "localtime", 0, QEMU_OPTION_localtime
},
5567 { "std-vga", 0, QEMU_OPTION_std_vga
},
5568 { "monitor", 1, QEMU_OPTION_monitor
},
5569 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
5570 { "serial", 1, QEMU_OPTION_serial
},
5571 { "parallel", 1, QEMU_OPTION_parallel
},
5572 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
5573 { "full-screen", 0, QEMU_OPTION_full_screen
},
5574 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
5575 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
5576 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
5577 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
5578 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
5580 /* temporary options */
5581 { "usb", 0, QEMU_OPTION_usb
},
5582 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
5583 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
5587 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5589 /* this stack is only used during signal handling */
5590 #define SIGNAL_STACK_SIZE 32768
5592 static uint8_t *signal_stack
;
5596 /* password input */
5598 static BlockDriverState
*get_bdrv(int index
)
5600 BlockDriverState
*bs
;
5603 bs
= bs_table
[index
];
5604 } else if (index
< 6) {
5605 bs
= fd_table
[index
- 4];
5612 static void read_passwords(void)
5614 BlockDriverState
*bs
;
5618 for(i
= 0; i
< 6; i
++) {
5620 if (bs
&& bdrv_is_encrypted(bs
)) {
5621 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
5622 for(j
= 0; j
< 3; j
++) {
5623 monitor_readline("Password: ",
5624 1, password
, sizeof(password
));
5625 if (bdrv_set_key(bs
, password
) == 0)
5627 term_printf("invalid password\n");
5633 /* XXX: currently we cannot use simultaneously different CPUs */
5634 void register_machines(void)
5636 #if defined(TARGET_I386)
5637 qemu_register_machine(&pc_machine
);
5638 qemu_register_machine(&isapc_machine
);
5639 #elif defined(TARGET_PPC)
5640 qemu_register_machine(&heathrow_machine
);
5641 qemu_register_machine(&core99_machine
);
5642 qemu_register_machine(&prep_machine
);
5643 #elif defined(TARGET_MIPS)
5644 qemu_register_machine(&mips_machine
);
5645 #elif defined(TARGET_SPARC)
5646 #ifdef TARGET_SPARC64
5647 qemu_register_machine(&sun4u_machine
);
5649 qemu_register_machine(&sun4m_machine
);
5651 #elif defined(TARGET_ARM)
5652 qemu_register_machine(&integratorcp926_machine
);
5653 qemu_register_machine(&integratorcp1026_machine
);
5654 qemu_register_machine(&versatilepb_machine
);
5655 qemu_register_machine(&versatileab_machine
);
5656 #elif defined(TARGET_SH4)
5657 qemu_register_machine(&shix_machine
);
5659 #error unsupported CPU
5664 struct soundhw soundhw
[] = {
5671 { .init_isa
= pcspk_audio_init
}
5676 "Creative Sound Blaster 16",
5679 { .init_isa
= SB16_init
}
5686 "Yamaha YMF262 (OPL3)",
5688 "Yamaha YM3812 (OPL2)",
5692 { .init_isa
= Adlib_init
}
5699 "Gravis Ultrasound GF1",
5702 { .init_isa
= GUS_init
}
5708 "ENSONIQ AudioPCI ES1370",
5711 { .init_pci
= es1370_init
}
5714 { NULL
, NULL
, 0, 0, { NULL
} }
5717 static void select_soundhw (const char *optarg
)
5721 if (*optarg
== '?') {
5724 printf ("Valid sound card names (comma separated):\n");
5725 for (c
= soundhw
; c
->name
; ++c
) {
5726 printf ("%-11s %s\n", c
->name
, c
->descr
);
5728 printf ("\n-soundhw all will enable all of the above\n");
5729 exit (*optarg
!= '?');
5737 if (!strcmp (optarg
, "all")) {
5738 for (c
= soundhw
; c
->name
; ++c
) {
5746 e
= strchr (p
, ',');
5747 l
= !e
? strlen (p
) : (size_t) (e
- p
);
5749 for (c
= soundhw
; c
->name
; ++c
) {
5750 if (!strncmp (c
->name
, p
, l
)) {
5759 "Unknown sound card name (too big to show)\n");
5762 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
5767 p
+= l
+ (e
!= NULL
);
5771 goto show_valid_cards
;
5777 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
5779 exit(STATUS_CONTROL_C_EXIT
);
5784 #define MAX_NET_CLIENTS 32
5786 int main(int argc
, char **argv
)
5788 #ifdef CONFIG_GDBSTUB
5789 int use_gdbstub
, gdbstub_port
;
5792 int snapshot
, linux_boot
;
5793 const char *initrd_filename
;
5794 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
5795 const char *kernel_filename
, *kernel_cmdline
;
5796 DisplayState
*ds
= &display_state
;
5797 int cyls
, heads
, secs
, translation
;
5798 int start_emulation
= 1;
5799 char net_clients
[MAX_NET_CLIENTS
][256];
5802 const char *r
, *optarg
;
5803 CharDriverState
*monitor_hd
;
5804 char monitor_device
[128];
5805 CharDriverState
*vmchannel_hd
;
5806 char vmchannel_device
[128];
5807 char serial_devices
[MAX_SERIAL_PORTS
][128];
5808 int serial_device_index
;
5809 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
5810 int parallel_device_index
;
5811 const char *loadvm
= NULL
;
5812 QEMUMachine
*machine
;
5813 char usb_devices
[MAX_USB_CMDLINE
][128];
5814 int usb_devices_index
;
5816 LIST_INIT (&vm_change_state_head
);
5819 struct sigaction act
;
5820 sigfillset(&act
.sa_mask
);
5822 act
.sa_handler
= SIG_IGN
;
5823 sigaction(SIGPIPE
, &act
, NULL
);
5826 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
5827 /* Note: cpu_interrupt() is currently not SMP safe, so we force
5828 QEMU to run on a single CPU */
5833 h
= GetCurrentProcess();
5834 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
5835 for(i
= 0; i
< 32; i
++) {
5836 if (mask
& (1 << i
))
5841 SetProcessAffinityMask(h
, mask
);
5847 register_machines();
5848 machine
= first_machine
;
5849 initrd_filename
= NULL
;
5850 for(i
= 0; i
< MAX_FD
; i
++)
5851 fd_filename
[i
] = NULL
;
5852 for(i
= 0; i
< MAX_DISKS
; i
++)
5853 hd_filename
[i
] = NULL
;
5854 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
5855 vga_ram_size
= VGA_RAM_SIZE
;
5856 bios_size
= BIOS_SIZE
;
5857 #ifdef CONFIG_GDBSTUB
5859 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
5863 kernel_filename
= NULL
;
5864 kernel_cmdline
= "";
5870 cyls
= heads
= secs
= 0;
5871 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5872 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
5874 vmchannel_device
[0] = '\0';
5876 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
5877 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
5878 serial_devices
[i
][0] = '\0';
5879 serial_device_index
= 0;
5881 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
5882 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
5883 parallel_devices
[i
][0] = '\0';
5884 parallel_device_index
= 0;
5886 usb_devices_index
= 0;
5891 /* default mac address of the first network interface */
5899 hd_filename
[0] = argv
[optind
++];
5901 const QEMUOption
*popt
;
5904 popt
= qemu_options
;
5907 fprintf(stderr
, "%s: invalid option -- '%s'\n",
5911 if (!strcmp(popt
->name
, r
+ 1))
5915 if (popt
->flags
& HAS_ARG
) {
5916 if (optind
>= argc
) {
5917 fprintf(stderr
, "%s: option '%s' requires an argument\n",
5921 optarg
= argv
[optind
++];
5926 switch(popt
->index
) {
5928 machine
= find_machine(optarg
);
5931 printf("Supported machines are:\n");
5932 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5933 printf("%-10s %s%s\n",
5935 m
== first_machine
? " (default)" : "");
5940 case QEMU_OPTION_initrd
:
5941 initrd_filename
= optarg
;
5943 case QEMU_OPTION_hda
:
5944 case QEMU_OPTION_hdb
:
5945 case QEMU_OPTION_hdc
:
5946 case QEMU_OPTION_hdd
:
5949 hd_index
= popt
->index
- QEMU_OPTION_hda
;
5950 hd_filename
[hd_index
] = optarg
;
5951 if (hd_index
== cdrom_index
)
5955 case QEMU_OPTION_snapshot
:
5958 case QEMU_OPTION_hdachs
:
5962 cyls
= strtol(p
, (char **)&p
, 0);
5963 if (cyls
< 1 || cyls
> 16383)
5968 heads
= strtol(p
, (char **)&p
, 0);
5969 if (heads
< 1 || heads
> 16)
5974 secs
= strtol(p
, (char **)&p
, 0);
5975 if (secs
< 1 || secs
> 63)
5979 if (!strcmp(p
, "none"))
5980 translation
= BIOS_ATA_TRANSLATION_NONE
;
5981 else if (!strcmp(p
, "lba"))
5982 translation
= BIOS_ATA_TRANSLATION_LBA
;
5983 else if (!strcmp(p
, "auto"))
5984 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5987 } else if (*p
!= '\0') {
5989 fprintf(stderr
, "qemu: invalid physical CHS format\n");
5994 case QEMU_OPTION_nographic
:
5995 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
5996 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
5999 case QEMU_OPTION_kernel
:
6000 kernel_filename
= optarg
;
6002 case QEMU_OPTION_append
:
6003 kernel_cmdline
= optarg
;
6005 case QEMU_OPTION_cdrom
:
6006 if (cdrom_index
>= 0) {
6007 hd_filename
[cdrom_index
] = optarg
;
6010 case QEMU_OPTION_boot
:
6011 boot_device
= optarg
[0];
6012 if (boot_device
!= 'a' &&
6015 boot_device
!= 'n' &&
6017 boot_device
!= 'c' && boot_device
!= 'd') {
6018 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
6022 case QEMU_OPTION_fda
:
6023 fd_filename
[0] = optarg
;
6025 case QEMU_OPTION_fdb
:
6026 fd_filename
[1] = optarg
;
6029 case QEMU_OPTION_no_fd_bootchk
:
6033 case QEMU_OPTION_no_code_copy
:
6034 code_copy_enabled
= 0;
6036 case QEMU_OPTION_net
:
6037 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
6038 fprintf(stderr
, "qemu: too many network clients\n");
6041 pstrcpy(net_clients
[nb_net_clients
],
6042 sizeof(net_clients
[0]),
6047 case QEMU_OPTION_tftp
:
6048 tftp_prefix
= optarg
;
6051 case QEMU_OPTION_smb
:
6052 net_slirp_smb(optarg
);
6055 case QEMU_OPTION_redir
:
6056 net_slirp_redir(optarg
);
6060 case QEMU_OPTION_audio_help
:
6064 case QEMU_OPTION_soundhw
:
6065 select_soundhw (optarg
);
6072 ram_size
= atoi(optarg
) * 1024 * 1024;
6075 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
6076 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
6077 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
6086 mask
= cpu_str_to_log_mask(optarg
);
6088 printf("Log items (comma separated):\n");
6089 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
6090 printf("%-10s %s\n", item
->name
, item
->help
);
6097 #ifdef CONFIG_GDBSTUB
6102 gdbstub_port
= atoi(optarg
);
6109 start_emulation
= 0;
6112 keyboard_layout
= optarg
;
6114 case QEMU_OPTION_localtime
:
6117 case QEMU_OPTION_cirrusvga
:
6118 cirrus_vga_enabled
= 1;
6120 case QEMU_OPTION_std_vga
:
6121 cirrus_vga_enabled
= 0;
6128 w
= strtol(p
, (char **)&p
, 10);
6131 fprintf(stderr
, "qemu: invalid resolution or depth\n");
6137 h
= strtol(p
, (char **)&p
, 10);
6142 depth
= strtol(p
, (char **)&p
, 10);
6143 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
6144 depth
!= 24 && depth
!= 32)
6146 } else if (*p
== '\0') {
6147 depth
= graphic_depth
;
6154 graphic_depth
= depth
;
6157 case QEMU_OPTION_monitor
:
6158 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
6160 case QEMU_OPTION_vmchannel
:
6161 pstrcpy(vmchannel_device
, sizeof(vmchannel_device
), optarg
);
6163 case QEMU_OPTION_serial
:
6164 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
6165 fprintf(stderr
, "qemu: too many serial ports\n");
6168 pstrcpy(serial_devices
[serial_device_index
],
6169 sizeof(serial_devices
[0]), optarg
);
6170 serial_device_index
++;
6172 case QEMU_OPTION_parallel
:
6173 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
6174 fprintf(stderr
, "qemu: too many parallel ports\n");
6177 pstrcpy(parallel_devices
[parallel_device_index
],
6178 sizeof(parallel_devices
[0]), optarg
);
6179 parallel_device_index
++;
6181 case QEMU_OPTION_loadvm
:
6184 case QEMU_OPTION_full_screen
:
6187 case QEMU_OPTION_pidfile
:
6188 create_pidfile(optarg
);
6191 case QEMU_OPTION_win2k_hack
:
6192 win2k_install_hack
= 1;
6196 case QEMU_OPTION_no_kqemu
:
6199 case QEMU_OPTION_kernel_kqemu
:
6204 case QEMU_OPTION_no_kvm
:
6208 case QEMU_OPTION_usb
:
6211 case QEMU_OPTION_usbdevice
:
6213 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
6214 fprintf(stderr
, "Too many USB devices\n");
6217 pstrcpy(usb_devices
[usb_devices_index
],
6218 sizeof(usb_devices
[usb_devices_index
]),
6220 usb_devices_index
++;
6222 case QEMU_OPTION_smp
:
6223 smp_cpus
= atoi(optarg
);
6224 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
6225 fprintf(stderr
, "Invalid number of CPUs\n");
6229 case QEMU_OPTION_vnc
:
6230 vnc_display
= atoi(optarg
);
6231 if (vnc_display
< 0) {
6232 fprintf(stderr
, "Invalid VNC display\n");
6236 case QEMU_OPTION_no_acpi
:
6245 if (kvm_qemu_init() < 0) {
6246 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
6256 linux_boot
= (kernel_filename
!= NULL
);
6259 hd_filename
[0] == '\0' &&
6260 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
6261 fd_filename
[0] == '\0')
6264 /* boot to cd by default if no hard disk */
6265 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
6266 if (fd_filename
[0] != '\0')
6272 setvbuf(stdout
, NULL
, _IOLBF
, 0);
6281 /* init network clients */
6282 if (nb_net_clients
== 0) {
6283 /* if no clients, we use a default config */
6284 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
6286 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
6291 for(i
= 0;i
< nb_net_clients
; i
++) {
6292 if (net_client_init(net_clients
[i
]) < 0)
6296 /* init the memory */
6297 phys_ram_size
= ram_size
+ vga_ram_size
+ bios_size
;
6299 /* Initialize kvm */
6301 phys_ram_size
+= KVM_EXTRA_PAGES
* 4096;
6302 if (kvm_qemu_create_context() < 0) {
6303 fprintf(stderr
, "Could not create KVM context\n");
6307 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
6308 if (!phys_ram_base
) {
6309 fprintf(stderr
, "Could not allocate physical memory\n");
6314 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
6315 if (!phys_ram_base
) {
6316 fprintf(stderr
, "Could not allocate physical memory\n");
6321 /* we always create the cdrom drive, even if no disk is there */
6323 if (cdrom_index
>= 0) {
6324 bs_table
[cdrom_index
] = bdrv_new("cdrom");
6325 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
6328 /* open the virtual block devices */
6329 for(i
= 0; i
< MAX_DISKS
; i
++) {
6330 if (hd_filename
[i
]) {
6333 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
6334 bs_table
[i
] = bdrv_new(buf
);
6336 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
) < 0) {
6337 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
6341 if (i
== 0 && cyls
!= 0) {
6342 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
6343 bdrv_set_translation_hint(bs_table
[i
], translation
);
6348 /* we always create at least one floppy disk */
6349 fd_table
[0] = bdrv_new("fda");
6350 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
6352 for(i
= 0; i
< MAX_FD
; i
++) {
6353 if (fd_filename
[i
]) {
6356 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
6357 fd_table
[i
] = bdrv_new(buf
);
6358 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
6360 if (fd_filename
[i
] != '\0') {
6361 if (bdrv_open(fd_table
[i
], fd_filename
[i
], snapshot
) < 0) {
6362 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
6370 register_savevm("timer", 0, 1, timer_save
, timer_load
, NULL
);
6371 register_savevm("ram", 0, 1, ram_save
, ram_load
, NULL
);
6377 dumb_display_init(ds
);
6378 } else if (vnc_display
!= -1) {
6379 vnc_display_init(ds
, vnc_display
);
6381 #if defined(CONFIG_SDL)
6382 sdl_display_init(ds
, full_screen
);
6383 #elif defined(CONFIG_COCOA)
6384 cocoa_display_init(ds
, full_screen
);
6386 dumb_display_init(ds
);
6390 monitor_hd
= qemu_chr_open(monitor_device
);
6392 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
6395 monitor_init(monitor_hd
, !nographic
);
6397 if (*vmchannel_device
) {
6398 vmchannel_hd
= qemu_chr_open(vmchannel_device
);
6399 if (!vmchannel_hd
) {
6400 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n", vmchannel_device
);
6403 vmchannel_init(vmchannel_hd
);
6406 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
6407 if (serial_devices
[i
][0] != '\0') {
6408 serial_hds
[i
] = qemu_chr_open(serial_devices
[i
]);
6409 if (!serial_hds
[i
]) {
6410 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
6414 if (!strcmp(serial_devices
[i
], "vc"))
6415 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
6419 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
6420 if (parallel_devices
[i
][0] != '\0') {
6421 parallel_hds
[i
] = qemu_chr_open(parallel_devices
[i
]);
6422 if (!parallel_hds
[i
]) {
6423 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
6424 parallel_devices
[i
]);
6427 if (!strcmp(parallel_devices
[i
], "vc"))
6428 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
6432 machine
->init(ram_size
, vga_ram_size
, boot_device
,
6433 ds
, fd_filename
, snapshot
,
6434 kernel_filename
, kernel_cmdline
, initrd_filename
);
6436 /* init USB devices */
6438 for(i
= 0; i
< usb_devices_index
; i
++) {
6439 if (usb_device_add(usb_devices
[i
]) < 0) {
6440 fprintf(stderr
, "Warning: could not add USB device %s\n",
6446 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
6447 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
6449 #ifdef CONFIG_GDBSTUB
6451 if (gdbserver_start(gdbstub_port
) < 0) {
6452 fprintf(stderr
, "Could not open gdbserver socket on port %d\n",
6456 printf("Waiting gdb connection on port %d\n", gdbstub_port
);
6461 qemu_loadvm(loadvm
, &qemu_savevm_method_file
);
6464 /* XXX: simplify init */
6466 if (start_emulation
) {
6470 console_select(1); /* focus on monitor */