4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
62 #if defined(CONFIG_SLIRP)
68 #include <sys/timeb.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
74 #include "qemu_socket.h"
80 #endif /* CONFIG_SDL */
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
95 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
97 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
99 #define SMBD_COMMAND "/usr/sbin/smbd"
102 //#define DEBUG_UNUSED_IOPORT
103 //#define DEBUG_IOPORT
105 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
108 #define DEFAULT_RAM_SIZE 144
110 #define DEFAULT_RAM_SIZE 128
113 #define GUI_REFRESH_INTERVAL 30
115 /* Max number of USB devices that can be specified on the commandline. */
116 #define MAX_USB_CMDLINE 8
118 /* XXX: use a two level table to limit memory usage */
119 #define MAX_IOPORTS 65536
121 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
122 char phys_ram_file
[1024];
123 void *ioport_opaque
[MAX_IOPORTS
];
124 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
125 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
126 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
127 to store the VM snapshots */
128 BlockDriverState
*bs_table
[MAX_DISKS
+ 1], *fd_table
[MAX_FD
];
129 /* point to the block driver where the snapshots are managed */
130 BlockDriverState
*bs_snapshots
;
133 static DisplayState display_state
;
135 const char* keyboard_layout
= NULL
;
136 int64_t ticks_per_sec
;
137 int boot_device
= 'c';
139 int pit_min_timer_count
= 0;
141 NICInfo nd_table
[MAX_NICS
];
142 QEMUTimer
*gui_timer
;
145 int cirrus_vga_enabled
= 1;
147 int graphic_width
= 1024;
148 int graphic_height
= 768;
150 int graphic_width
= 800;
151 int graphic_height
= 600;
153 int graphic_depth
= 15;
156 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
157 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
159 int win2k_install_hack
= 0;
162 static VLANState
*first_vlan
;
164 const char *vnc_display
;
165 #if defined(TARGET_SPARC)
167 #elif defined(TARGET_I386)
172 int acpi_enabled
= 1;
176 const char *option_rom
[MAX_OPTION_ROMS
];
178 int semihosting_enabled
= 0;
181 /***********************************************************/
182 /* x86 ISA bus support */
184 target_phys_addr_t isa_mem_base
= 0;
187 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
189 #ifdef DEBUG_UNUSED_IOPORT
190 fprintf(stderr
, "inb: port=0x%04x\n", address
);
195 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
197 #ifdef DEBUG_UNUSED_IOPORT
198 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
202 /* default is to make two byte accesses */
203 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
206 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
207 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
208 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
212 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
214 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
215 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
216 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
219 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr
, "inl: port=0x%04x\n", address
);
227 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
229 #ifdef DEBUG_UNUSED_IOPORT
230 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
234 void init_ioports(void)
238 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
239 ioport_read_table
[0][i
] = default_ioport_readb
;
240 ioport_write_table
[0][i
] = default_ioport_writeb
;
241 ioport_read_table
[1][i
] = default_ioport_readw
;
242 ioport_write_table
[1][i
] = default_ioport_writew
;
243 ioport_read_table
[2][i
] = default_ioport_readl
;
244 ioport_write_table
[2][i
] = default_ioport_writel
;
248 /* size is the word size in byte */
249 int register_ioport_read(int start
, int length
, int size
,
250 IOPortReadFunc
*func
, void *opaque
)
256 } else if (size
== 2) {
258 } else if (size
== 4) {
261 hw_error("register_ioport_read: invalid size");
264 for(i
= start
; i
< start
+ length
; i
+= size
) {
265 ioport_read_table
[bsize
][i
] = func
;
266 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
267 hw_error("register_ioport_read: invalid opaque");
268 ioport_opaque
[i
] = opaque
;
273 /* size is the word size in byte */
274 int register_ioport_write(int start
, int length
, int size
,
275 IOPortWriteFunc
*func
, void *opaque
)
281 } else if (size
== 2) {
283 } else if (size
== 4) {
286 hw_error("register_ioport_write: invalid size");
289 for(i
= start
; i
< start
+ length
; i
+= size
) {
290 ioport_write_table
[bsize
][i
] = func
;
291 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
292 hw_error("register_ioport_write: invalid opaque");
293 ioport_opaque
[i
] = opaque
;
298 void isa_unassign_ioport(int start
, int length
)
302 for(i
= start
; i
< start
+ length
; i
++) {
303 ioport_read_table
[0][i
] = default_ioport_readb
;
304 ioport_read_table
[1][i
] = default_ioport_readw
;
305 ioport_read_table
[2][i
] = default_ioport_readl
;
307 ioport_write_table
[0][i
] = default_ioport_writeb
;
308 ioport_write_table
[1][i
] = default_ioport_writew
;
309 ioport_write_table
[2][i
] = default_ioport_writel
;
313 /***********************************************************/
315 void cpu_outb(CPUState
*env
, int addr
, int val
)
318 if (loglevel
& CPU_LOG_IOPORT
)
319 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
321 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
324 env
->last_io_time
= cpu_get_time_fast();
328 void cpu_outw(CPUState
*env
, int addr
, int val
)
331 if (loglevel
& CPU_LOG_IOPORT
)
332 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
334 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
337 env
->last_io_time
= cpu_get_time_fast();
341 void cpu_outl(CPUState
*env
, int addr
, int val
)
344 if (loglevel
& CPU_LOG_IOPORT
)
345 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
347 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
350 env
->last_io_time
= cpu_get_time_fast();
354 int cpu_inb(CPUState
*env
, int addr
)
357 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
359 if (loglevel
& CPU_LOG_IOPORT
)
360 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
364 env
->last_io_time
= cpu_get_time_fast();
369 int cpu_inw(CPUState
*env
, int addr
)
372 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
374 if (loglevel
& CPU_LOG_IOPORT
)
375 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
379 env
->last_io_time
= cpu_get_time_fast();
384 int cpu_inl(CPUState
*env
, int addr
)
387 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
389 if (loglevel
& CPU_LOG_IOPORT
)
390 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
394 env
->last_io_time
= cpu_get_time_fast();
399 /***********************************************************/
400 void hw_error(const char *fmt
, ...)
406 fprintf(stderr
, "qemu: hardware error: ");
407 vfprintf(stderr
, fmt
, ap
);
408 fprintf(stderr
, "\n");
409 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
410 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
412 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
414 cpu_dump_state(env
, stderr
, fprintf
, 0);
421 /***********************************************************/
424 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
425 static void *qemu_put_kbd_event_opaque
;
426 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
427 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
429 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
431 qemu_put_kbd_event_opaque
= opaque
;
432 qemu_put_kbd_event
= func
;
435 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
436 void *opaque
, int absolute
,
439 QEMUPutMouseEntry
*s
, *cursor
;
441 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
445 s
->qemu_put_mouse_event
= func
;
446 s
->qemu_put_mouse_event_opaque
= opaque
;
447 s
->qemu_put_mouse_event_absolute
= absolute
;
448 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
451 if (!qemu_put_mouse_event_head
) {
452 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
456 cursor
= qemu_put_mouse_event_head
;
457 while (cursor
->next
!= NULL
)
458 cursor
= cursor
->next
;
461 qemu_put_mouse_event_current
= s
;
466 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
468 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
470 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
473 cursor
= qemu_put_mouse_event_head
;
474 while (cursor
!= NULL
&& cursor
!= entry
) {
476 cursor
= cursor
->next
;
479 if (cursor
== NULL
) // does not exist or list empty
481 else if (prev
== NULL
) { // entry is head
482 qemu_put_mouse_event_head
= cursor
->next
;
483 if (qemu_put_mouse_event_current
== entry
)
484 qemu_put_mouse_event_current
= cursor
->next
;
485 qemu_free(entry
->qemu_put_mouse_event_name
);
490 prev
->next
= entry
->next
;
492 if (qemu_put_mouse_event_current
== entry
)
493 qemu_put_mouse_event_current
= prev
;
495 qemu_free(entry
->qemu_put_mouse_event_name
);
499 void kbd_put_keycode(int keycode
)
501 if (qemu_put_kbd_event
) {
502 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
506 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
508 QEMUPutMouseEvent
*mouse_event
;
509 void *mouse_event_opaque
;
511 if (!qemu_put_mouse_event_current
) {
516 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
518 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
521 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
525 int kbd_mouse_is_absolute(void)
527 if (!qemu_put_mouse_event_current
)
530 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
533 void do_info_mice(void)
535 QEMUPutMouseEntry
*cursor
;
538 if (!qemu_put_mouse_event_head
) {
539 term_printf("No mouse devices connected\n");
543 term_printf("Mouse devices available:\n");
544 cursor
= qemu_put_mouse_event_head
;
545 while (cursor
!= NULL
) {
546 term_printf("%c Mouse #%d: %s\n",
547 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
548 index
, cursor
->qemu_put_mouse_event_name
);
550 cursor
= cursor
->next
;
554 void do_mouse_set(int index
)
556 QEMUPutMouseEntry
*cursor
;
559 if (!qemu_put_mouse_event_head
) {
560 term_printf("No mouse devices connected\n");
564 cursor
= qemu_put_mouse_event_head
;
565 while (cursor
!= NULL
&& index
!= i
) {
567 cursor
= cursor
->next
;
571 qemu_put_mouse_event_current
= cursor
;
573 term_printf("Mouse at given index not found\n");
576 /* compute with 96 bit intermediate result: (a*b)/c */
577 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
582 #ifdef WORDS_BIGENDIAN
592 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
593 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
596 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
600 /***********************************************************/
601 /* real time host monotonic timer */
603 #define QEMU_TIMER_BASE 1000000000LL
607 static int64_t clock_freq
;
609 static void init_get_clock(void)
613 ret
= QueryPerformanceFrequency(&freq
);
615 fprintf(stderr
, "Could not calibrate ticks\n");
618 clock_freq
= freq
.QuadPart
;
621 static int64_t get_clock(void)
624 QueryPerformanceCounter(&ti
);
625 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
630 static int use_rt_clock
;
632 static void init_get_clock(void)
635 #if defined(__linux__)
638 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
645 static int64_t get_clock(void)
647 #if defined(__linux__)
650 clock_gettime(CLOCK_MONOTONIC
, &ts
);
651 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
655 /* XXX: using gettimeofday leads to problems if the date
656 changes, so it should be avoided. */
658 gettimeofday(&tv
, NULL
);
659 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
665 /***********************************************************/
666 /* guest cycle counter */
668 static int64_t cpu_ticks_prev
;
669 static int64_t cpu_ticks_offset
;
670 static int64_t cpu_clock_offset
;
671 static int cpu_ticks_enabled
;
673 /* return the host CPU cycle counter and handle stop/restart */
674 int64_t cpu_get_ticks(void)
676 if (!cpu_ticks_enabled
) {
677 return cpu_ticks_offset
;
680 ticks
= cpu_get_real_ticks();
681 if (cpu_ticks_prev
> ticks
) {
682 /* Note: non increasing ticks may happen if the host uses
684 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
686 cpu_ticks_prev
= ticks
;
687 return ticks
+ cpu_ticks_offset
;
691 /* return the host CPU monotonic timer and handle stop/restart */
692 static int64_t cpu_get_clock(void)
695 if (!cpu_ticks_enabled
) {
696 return cpu_clock_offset
;
699 return ti
+ cpu_clock_offset
;
703 /* enable cpu_get_ticks() */
704 void cpu_enable_ticks(void)
706 if (!cpu_ticks_enabled
) {
707 cpu_ticks_offset
-= cpu_get_real_ticks();
708 cpu_clock_offset
-= get_clock();
709 cpu_ticks_enabled
= 1;
713 /* disable cpu_get_ticks() : the clock is stopped. You must not call
714 cpu_get_ticks() after that. */
715 void cpu_disable_ticks(void)
717 if (cpu_ticks_enabled
) {
718 cpu_ticks_offset
= cpu_get_ticks();
719 cpu_clock_offset
= cpu_get_clock();
720 cpu_ticks_enabled
= 0;
724 /***********************************************************/
727 #define QEMU_TIMER_REALTIME 0
728 #define QEMU_TIMER_VIRTUAL 1
732 /* XXX: add frequency */
740 struct QEMUTimer
*next
;
746 static QEMUTimer
*active_timers
[2];
748 static MMRESULT timerID
;
749 static HANDLE host_alarm
= NULL
;
750 static unsigned int period
= 1;
752 /* frequency of the times() clock tick */
753 static int timer_freq
;
756 QEMUClock
*qemu_new_clock(int type
)
759 clock
= qemu_mallocz(sizeof(QEMUClock
));
766 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
770 ts
= qemu_mallocz(sizeof(QEMUTimer
));
777 void qemu_free_timer(QEMUTimer
*ts
)
782 /* stop a timer, but do not dealloc it */
783 void qemu_del_timer(QEMUTimer
*ts
)
787 /* NOTE: this code must be signal safe because
788 qemu_timer_expired() can be called from a signal. */
789 pt
= &active_timers
[ts
->clock
->type
];
802 /* modify the current timer so that it will be fired when current_time
803 >= expire_time. The corresponding callback will be called. */
804 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
810 /* add the timer in the sorted list */
811 /* NOTE: this code must be signal safe because
812 qemu_timer_expired() can be called from a signal. */
813 pt
= &active_timers
[ts
->clock
->type
];
818 if (t
->expire_time
> expire_time
)
822 ts
->expire_time
= expire_time
;
827 int qemu_timer_pending(QEMUTimer
*ts
)
830 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
837 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
841 return (timer_head
->expire_time
<= current_time
);
844 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
850 if (!ts
|| ts
->expire_time
> current_time
)
852 /* remove timer from the list before calling the callback */
853 *ptimer_head
= ts
->next
;
856 /* run the callback (the timer list can be modified) */
861 int64_t qemu_get_clock(QEMUClock
*clock
)
863 switch(clock
->type
) {
864 case QEMU_TIMER_REALTIME
:
865 return get_clock() / 1000000;
867 case QEMU_TIMER_VIRTUAL
:
868 return cpu_get_clock();
872 static void init_timers(void)
875 ticks_per_sec
= QEMU_TIMER_BASE
;
876 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
877 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
881 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
883 uint64_t expire_time
;
885 if (qemu_timer_pending(ts
)) {
886 expire_time
= ts
->expire_time
;
890 qemu_put_be64(f
, expire_time
);
893 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
895 uint64_t expire_time
;
897 expire_time
= qemu_get_be64(f
);
898 if (expire_time
!= -1) {
899 qemu_mod_timer(ts
, expire_time
);
905 static void timer_save(QEMUFile
*f
, void *opaque
)
907 if (cpu_ticks_enabled
) {
908 hw_error("cannot save state if virtual timers are running");
910 qemu_put_be64s(f
, &cpu_ticks_offset
);
911 qemu_put_be64s(f
, &ticks_per_sec
);
912 qemu_put_be64s(f
, &cpu_clock_offset
);
915 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
917 if (version_id
!= 1 && version_id
!= 2)
919 if (cpu_ticks_enabled
) {
922 qemu_get_be64s(f
, &cpu_ticks_offset
);
923 qemu_get_be64s(f
, &ticks_per_sec
);
924 if (version_id
== 2) {
925 qemu_get_be64s(f
, &cpu_clock_offset
);
931 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
932 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
934 static void host_alarm_handler(int host_signum
)
938 #define DISP_FREQ 1000
940 static int64_t delta_min
= INT64_MAX
;
941 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
943 ti
= qemu_get_clock(vm_clock
);
944 if (last_clock
!= 0) {
945 delta
= ti
- last_clock
;
946 if (delta
< delta_min
)
948 if (delta
> delta_max
)
951 if (++count
== DISP_FREQ
) {
952 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
953 muldiv64(delta_min
, 1000000, ticks_per_sec
),
954 muldiv64(delta_max
, 1000000, ticks_per_sec
),
955 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
956 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
958 delta_min
= INT64_MAX
;
966 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
967 qemu_get_clock(vm_clock
)) ||
968 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
969 qemu_get_clock(rt_clock
))) {
971 SetEvent(host_alarm
);
973 CPUState
*env
= cpu_single_env
;
975 /* stop the currently executing cpu because a timer occured */
976 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
978 if (env
->kqemu_enabled
) {
979 kqemu_cpu_interrupt(env
);
988 #if defined(__linux__)
990 #define RTC_FREQ 1024
994 static int start_rtc_timer(void)
996 rtc_fd
= open("/dev/rtc", O_RDONLY
);
999 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1000 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1001 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1002 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1005 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1010 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1016 static int start_rtc_timer(void)
1021 #endif /* !defined(__linux__) */
1023 #endif /* !defined(_WIN32) */
1025 static void init_timer_alarm(void)
1032 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1033 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1034 if (period
< tc
.wPeriodMin
)
1035 period
= tc
.wPeriodMin
;
1036 timeBeginPeriod(period
);
1037 timerID
= timeSetEvent(1, // interval (ms)
1038 period
, // resolution
1039 host_alarm_handler
, // function
1040 (DWORD
)&count
, // user parameter
1041 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1043 perror("failed timer alarm");
1046 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1048 perror("failed CreateEvent");
1051 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1053 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1056 struct sigaction act
;
1057 struct itimerval itv
;
1059 /* get times() syscall frequency */
1060 timer_freq
= sysconf(_SC_CLK_TCK
);
1063 sigfillset(&act
.sa_mask
);
1065 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1066 act
.sa_flags
|= SA_ONSTACK
;
1068 act
.sa_handler
= host_alarm_handler
;
1069 sigaction(SIGALRM
, &act
, NULL
);
1071 itv
.it_interval
.tv_sec
= 0;
1072 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1073 itv
.it_value
.tv_sec
= 0;
1074 itv
.it_value
.tv_usec
= 10 * 1000;
1075 setitimer(ITIMER_REAL
, &itv
, NULL
);
1076 /* we probe the tick duration of the kernel to inform the user if
1077 the emulated kernel requested a too high timer frequency */
1078 getitimer(ITIMER_REAL
, &itv
);
1080 #if defined(__linux__)
1081 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1082 have timers with 1 ms resolution. The correct solution will
1083 be to use the POSIX real time timers available in recent
1085 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1086 /* try to use /dev/rtc to have a faster timer */
1087 if (start_rtc_timer() < 0)
1089 /* disable itimer */
1090 itv
.it_interval
.tv_sec
= 0;
1091 itv
.it_interval
.tv_usec
= 0;
1092 itv
.it_value
.tv_sec
= 0;
1093 itv
.it_value
.tv_usec
= 0;
1094 setitimer(ITIMER_REAL
, &itv
, NULL
);
1097 sigaction(SIGIO
, &act
, NULL
);
1098 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1099 fcntl(rtc_fd
, F_SETOWN
, getpid());
1101 #endif /* defined(__linux__) */
1104 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1105 PIT_FREQ
) / 1000000;
1111 void quit_timers(void)
1114 timeKillEvent(timerID
);
1115 timeEndPeriod(period
);
1117 CloseHandle(host_alarm
);
1123 /***********************************************************/
1124 /* character device */
1126 static void qemu_chr_event(CharDriverState
*s
, int event
)
1130 s
->chr_event(s
->handler_opaque
, event
);
1133 static void qemu_chr_reset_bh(void *opaque
)
1135 CharDriverState
*s
= opaque
;
1136 qemu_chr_event(s
, CHR_EVENT_RESET
);
1137 qemu_bh_delete(s
->bh
);
1141 void qemu_chr_reset(CharDriverState
*s
)
1143 if (s
->bh
== NULL
) {
1144 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1145 qemu_bh_schedule(s
->bh
);
1149 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1151 return s
->chr_write(s
, buf
, len
);
1154 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1158 return s
->chr_ioctl(s
, cmd
, arg
);
1161 int qemu_chr_can_read(CharDriverState
*s
)
1163 if (!s
->chr_can_read
)
1165 return s
->chr_can_read(s
->handler_opaque
);
1168 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1170 s
->chr_read(s
->handler_opaque
, buf
, len
);
1174 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1179 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1180 qemu_chr_write(s
, buf
, strlen(buf
));
1184 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1186 if (s
->chr_send_event
)
1187 s
->chr_send_event(s
, event
);
1190 void qemu_chr_add_handlers(CharDriverState
*s
,
1191 IOCanRWHandler
*fd_can_read
,
1192 IOReadHandler
*fd_read
,
1193 IOEventHandler
*fd_event
,
1196 s
->chr_can_read
= fd_can_read
;
1197 s
->chr_read
= fd_read
;
1198 s
->chr_event
= fd_event
;
1199 s
->handler_opaque
= opaque
;
1200 if (s
->chr_update_read_handler
)
1201 s
->chr_update_read_handler(s
);
1204 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1209 static CharDriverState
*qemu_chr_open_null(void)
1211 CharDriverState
*chr
;
1213 chr
= qemu_mallocz(sizeof(CharDriverState
));
1216 chr
->chr_write
= null_chr_write
;
1222 static void socket_cleanup(void)
1227 static int socket_init(void)
1232 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1234 err
= WSAGetLastError();
1235 fprintf(stderr
, "WSAStartup: %d\n", err
);
1238 atexit(socket_cleanup
);
1242 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1248 ret
= send(fd
, buf
, len
, 0);
1251 errno
= WSAGetLastError();
1252 if (errno
!= WSAEWOULDBLOCK
) {
1255 } else if (ret
== 0) {
1265 void socket_set_nonblock(int fd
)
1267 unsigned long opt
= 1;
1268 ioctlsocket(fd
, FIONBIO
, &opt
);
1273 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1279 ret
= write(fd
, buf
, len
);
1281 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1283 } else if (ret
== 0) {
1293 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1295 return unix_write(fd
, buf
, len1
);
1298 void socket_set_nonblock(int fd
)
1300 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1302 #endif /* !_WIN32 */
1311 #define STDIO_MAX_CLIENTS 2
1313 static int stdio_nb_clients
;
1314 static CharDriverState
*stdio_clients
[STDIO_MAX_CLIENTS
];
1316 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1318 FDCharDriver
*s
= chr
->opaque
;
1319 return unix_write(s
->fd_out
, buf
, len
);
1322 static int fd_chr_read_poll(void *opaque
)
1324 CharDriverState
*chr
= opaque
;
1325 FDCharDriver
*s
= chr
->opaque
;
1327 s
->max_size
= qemu_chr_can_read(chr
);
1331 static void fd_chr_read(void *opaque
)
1333 CharDriverState
*chr
= opaque
;
1334 FDCharDriver
*s
= chr
->opaque
;
1339 if (len
> s
->max_size
)
1343 size
= read(s
->fd_in
, buf
, len
);
1345 /* FD has been closed. Remove it from the active list. */
1346 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1350 qemu_chr_read(chr
, buf
, size
);
1354 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1356 FDCharDriver
*s
= chr
->opaque
;
1358 if (s
->fd_in
>= 0) {
1359 if (nographic
&& s
->fd_in
== 0) {
1361 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1362 fd_chr_read
, NULL
, chr
);
1367 /* open a character device to a unix fd */
1368 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1370 CharDriverState
*chr
;
1373 chr
= qemu_mallocz(sizeof(CharDriverState
));
1376 s
= qemu_mallocz(sizeof(FDCharDriver
));
1384 chr
->chr_write
= fd_chr_write
;
1385 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1387 qemu_chr_reset(chr
);
1392 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1396 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1399 return qemu_chr_open_fd(-1, fd_out
);
1402 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1405 char filename_in
[256], filename_out
[256];
1407 snprintf(filename_in
, 256, "%s.in", filename
);
1408 snprintf(filename_out
, 256, "%s.out", filename
);
1409 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1410 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1411 if (fd_in
< 0 || fd_out
< 0) {
1416 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1420 return qemu_chr_open_fd(fd_in
, fd_out
);
1424 /* for STDIO, we handle the case where several clients use it
1427 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1429 #define TERM_FIFO_MAX_SIZE 1
1431 static int term_got_escape
, client_index
;
1432 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1433 static int term_fifo_size
;
1434 static int term_timestamps
;
1435 static int64_t term_timestamps_start
;
1437 void term_print_help(void)
1440 "C-a h print this help\n"
1441 "C-a x exit emulator\n"
1442 "C-a s save disk data back to file (if -snapshot)\n"
1443 "C-a b send break (magic sysrq)\n"
1444 "C-a t toggle console timestamps\n"
1445 "C-a c switch between console and monitor\n"
1446 "C-a C-a send C-a\n"
1450 /* called when a char is received */
1451 static void stdio_received_byte(int ch
)
1453 if (term_got_escape
) {
1454 term_got_escape
= 0;
1465 for (i
= 0; i
< MAX_DISKS
; i
++) {
1467 bdrv_commit(bs_table
[i
]);
1472 if (client_index
< stdio_nb_clients
) {
1473 CharDriverState
*chr
;
1476 chr
= stdio_clients
[client_index
];
1478 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1483 if (client_index
>= stdio_nb_clients
)
1485 if (client_index
== 0) {
1486 /* send a new line in the monitor to get the prompt */
1492 term_timestamps
= !term_timestamps
;
1493 term_timestamps_start
= -1;
1498 } else if (ch
== TERM_ESCAPE
) {
1499 term_got_escape
= 1;
1502 if (client_index
< stdio_nb_clients
) {
1504 CharDriverState
*chr
;
1506 chr
= stdio_clients
[client_index
];
1507 if (qemu_chr_can_read(chr
) > 0) {
1509 qemu_chr_read(chr
, buf
, 1);
1510 } else if (term_fifo_size
== 0) {
1511 term_fifo
[term_fifo_size
++] = ch
;
1517 static int stdio_read_poll(void *opaque
)
1519 CharDriverState
*chr
;
1521 if (client_index
< stdio_nb_clients
) {
1522 chr
= stdio_clients
[client_index
];
1523 /* try to flush the queue if needed */
1524 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1525 qemu_chr_read(chr
, term_fifo
, 1);
1528 /* see if we can absorb more chars */
1529 if (term_fifo_size
== 0)
1538 static void stdio_read(void *opaque
)
1543 size
= read(0, buf
, 1);
1545 /* stdin has been closed. Remove it from the active list. */
1546 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1550 stdio_received_byte(buf
[0]);
1553 static int stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1555 FDCharDriver
*s
= chr
->opaque
;
1556 if (!term_timestamps
) {
1557 return unix_write(s
->fd_out
, buf
, len
);
1562 for(i
= 0; i
< len
; i
++) {
1563 unix_write(s
->fd_out
, buf
+ i
, 1);
1564 if (buf
[i
] == '\n') {
1569 if (term_timestamps_start
== -1)
1570 term_timestamps_start
= ti
;
1571 ti
-= term_timestamps_start
;
1572 secs
= ti
/ 1000000000;
1573 snprintf(buf1
, sizeof(buf1
),
1574 "[%02d:%02d:%02d.%03d] ",
1578 (int)((ti
/ 1000000) % 1000));
1579 unix_write(s
->fd_out
, buf1
, strlen(buf1
));
1586 /* init terminal so that we can grab keys */
1587 static struct termios oldtty
;
1588 static int old_fd0_flags
;
1590 static void term_exit(void)
1592 tcsetattr (0, TCSANOW
, &oldtty
);
1593 fcntl(0, F_SETFL
, old_fd0_flags
);
1596 static void term_init(void)
1600 tcgetattr (0, &tty
);
1602 old_fd0_flags
= fcntl(0, F_GETFL
);
1604 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1605 |INLCR
|IGNCR
|ICRNL
|IXON
);
1606 tty
.c_oflag
|= OPOST
;
1607 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1608 /* if graphical mode, we allow Ctrl-C handling */
1610 tty
.c_lflag
&= ~ISIG
;
1611 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1614 tty
.c_cc
[VTIME
] = 0;
1616 tcsetattr (0, TCSANOW
, &tty
);
1620 fcntl(0, F_SETFL
, O_NONBLOCK
);
1623 static CharDriverState
*qemu_chr_open_stdio(void)
1625 CharDriverState
*chr
;
1628 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1630 chr
= qemu_chr_open_fd(0, 1);
1631 chr
->chr_write
= stdio_write
;
1632 if (stdio_nb_clients
== 0)
1633 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, NULL
);
1634 client_index
= stdio_nb_clients
;
1636 if (stdio_nb_clients
!= 0)
1638 chr
= qemu_chr_open_fd(0, 1);
1640 stdio_clients
[stdio_nb_clients
++] = chr
;
1641 if (stdio_nb_clients
== 1) {
1642 /* set the terminal in raw mode */
1648 #if defined(__linux__)
1649 static CharDriverState
*qemu_chr_open_pty(void)
1652 char slave_name
[1024];
1653 int master_fd
, slave_fd
;
1655 /* Not satisfying */
1656 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1660 /* Disabling local echo and line-buffered output */
1661 tcgetattr (master_fd
, &tty
);
1662 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1664 tty
.c_cc
[VTIME
] = 0;
1665 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1667 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1668 return qemu_chr_open_fd(master_fd
, master_fd
);
1671 static void tty_serial_init(int fd
, int speed
,
1672 int parity
, int data_bits
, int stop_bits
)
1678 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1679 speed
, parity
, data_bits
, stop_bits
);
1681 tcgetattr (fd
, &tty
);
1723 cfsetispeed(&tty
, spd
);
1724 cfsetospeed(&tty
, spd
);
1726 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1727 |INLCR
|IGNCR
|ICRNL
|IXON
);
1728 tty
.c_oflag
|= OPOST
;
1729 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1730 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1751 tty
.c_cflag
|= PARENB
;
1754 tty
.c_cflag
|= PARENB
| PARODD
;
1758 tty
.c_cflag
|= CSTOPB
;
1760 tcsetattr (fd
, TCSANOW
, &tty
);
1763 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1765 FDCharDriver
*s
= chr
->opaque
;
1768 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1770 QEMUSerialSetParams
*ssp
= arg
;
1771 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1772 ssp
->data_bits
, ssp
->stop_bits
);
1775 case CHR_IOCTL_SERIAL_SET_BREAK
:
1777 int enable
= *(int *)arg
;
1779 tcsendbreak(s
->fd_in
, 1);
1788 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1790 CharDriverState
*chr
;
1793 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1796 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1797 tty_serial_init(fd
, 115200, 'N', 8, 1);
1798 chr
= qemu_chr_open_fd(fd
, fd
);
1801 chr
->chr_ioctl
= tty_serial_ioctl
;
1802 qemu_chr_reset(chr
);
1806 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1808 int fd
= (int)chr
->opaque
;
1812 case CHR_IOCTL_PP_READ_DATA
:
1813 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1815 *(uint8_t *)arg
= b
;
1817 case CHR_IOCTL_PP_WRITE_DATA
:
1818 b
= *(uint8_t *)arg
;
1819 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1822 case CHR_IOCTL_PP_READ_CONTROL
:
1823 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1825 *(uint8_t *)arg
= b
;
1827 case CHR_IOCTL_PP_WRITE_CONTROL
:
1828 b
= *(uint8_t *)arg
;
1829 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1832 case CHR_IOCTL_PP_READ_STATUS
:
1833 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1835 *(uint8_t *)arg
= b
;
1843 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
1845 CharDriverState
*chr
;
1848 fd
= open(filename
, O_RDWR
);
1852 if (ioctl(fd
, PPCLAIM
) < 0) {
1857 chr
= qemu_mallocz(sizeof(CharDriverState
));
1862 chr
->opaque
= (void *)fd
;
1863 chr
->chr_write
= null_chr_write
;
1864 chr
->chr_ioctl
= pp_ioctl
;
1866 qemu_chr_reset(chr
);
1872 static CharDriverState
*qemu_chr_open_pty(void)
1878 #endif /* !defined(_WIN32) */
1882 CharDriverState
*chr
;
1884 HANDLE hcom
, hrecv
, hsend
;
1885 OVERLAPPED orecv
, osend
;
1890 #define NSENDBUF 2048
1891 #define NRECVBUF 2048
1892 #define MAXCONNECT 1
1893 #define NTIMEOUT 5000
1895 static int win_chr_poll(void *opaque
);
1896 static int win_chr_pipe_poll(void *opaque
);
1898 static void win_chr_close2(WinCharState
*s
)
1901 CloseHandle(s
->hsend
);
1905 CloseHandle(s
->hrecv
);
1909 CloseHandle(s
->hcom
);
1913 qemu_del_polling_cb(win_chr_pipe_poll
, s
);
1915 qemu_del_polling_cb(win_chr_poll
, s
);
1918 static void win_chr_close(CharDriverState
*chr
)
1920 WinCharState
*s
= chr
->opaque
;
1924 static int win_chr_init(WinCharState
*s
, CharDriverState
*chr
, const char *filename
)
1927 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1932 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1934 fprintf(stderr
, "Failed CreateEvent\n");
1937 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1939 fprintf(stderr
, "Failed CreateEvent\n");
1943 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1944 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1945 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1946 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1951 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1952 fprintf(stderr
, "Failed SetupComm\n");
1956 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1957 size
= sizeof(COMMCONFIG
);
1958 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1959 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1960 CommConfigDialog(filename
, NULL
, &comcfg
);
1962 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1963 fprintf(stderr
, "Failed SetCommState\n");
1967 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1968 fprintf(stderr
, "Failed SetCommMask\n");
1972 cto
.ReadIntervalTimeout
= MAXDWORD
;
1973 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1974 fprintf(stderr
, "Failed SetCommTimeouts\n");
1978 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1979 fprintf(stderr
, "Failed ClearCommError\n");
1983 qemu_add_polling_cb(win_chr_poll
, s
);
1991 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
1993 WinCharState
*s
= chr
->opaque
;
1994 DWORD len
, ret
, size
, err
;
1997 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
1998 s
->osend
.hEvent
= s
->hsend
;
2001 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2003 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2005 err
= GetLastError();
2006 if (err
== ERROR_IO_PENDING
) {
2007 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2025 static int win_chr_read_poll(WinCharState
*s
)
2027 s
->max_size
= qemu_chr_can_read(s
->chr
);
2031 static void win_chr_readfile(WinCharState
*s
)
2037 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2038 s
->orecv
.hEvent
= s
->hrecv
;
2039 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2041 err
= GetLastError();
2042 if (err
== ERROR_IO_PENDING
) {
2043 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2048 qemu_chr_read(s
->chr
, buf
, size
);
2052 static void win_chr_read(WinCharState
*s
)
2054 if (s
->len
> s
->max_size
)
2055 s
->len
= s
->max_size
;
2059 win_chr_readfile(s
);
2062 static int win_chr_poll(void *opaque
)
2064 WinCharState
*s
= opaque
;
2068 ClearCommError(s
->hcom
, &comerr
, &status
);
2069 if (status
.cbInQue
> 0) {
2070 s
->len
= status
.cbInQue
;
2071 win_chr_read_poll(s
);
2078 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2080 CharDriverState
*chr
;
2083 chr
= qemu_mallocz(sizeof(CharDriverState
));
2086 s
= qemu_mallocz(sizeof(WinCharState
));
2092 chr
->chr_write
= win_chr_write
;
2093 chr
->chr_close
= win_chr_close
;
2095 if (win_chr_init(s
, chr
, filename
) < 0) {
2100 qemu_chr_reset(chr
);
2104 static int win_chr_pipe_poll(void *opaque
)
2106 WinCharState
*s
= opaque
;
2109 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2112 win_chr_read_poll(s
);
2119 static int win_chr_pipe_init(WinCharState
*s
, const char *filename
)
2128 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2130 fprintf(stderr
, "Failed CreateEvent\n");
2133 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2135 fprintf(stderr
, "Failed CreateEvent\n");
2139 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2140 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2141 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2143 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2144 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2145 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2150 ZeroMemory(&ov
, sizeof(ov
));
2151 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2152 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2154 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2158 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2160 fprintf(stderr
, "Failed GetOverlappedResult\n");
2162 CloseHandle(ov
.hEvent
);
2169 CloseHandle(ov
.hEvent
);
2172 qemu_add_polling_cb(win_chr_pipe_poll
, s
);
2181 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2183 CharDriverState
*chr
;
2186 chr
= qemu_mallocz(sizeof(CharDriverState
));
2189 s
= qemu_mallocz(sizeof(WinCharState
));
2195 chr
->chr_write
= win_chr_write
;
2196 chr
->chr_close
= win_chr_close
;
2198 if (win_chr_pipe_init(s
, filename
) < 0) {
2203 qemu_chr_reset(chr
);
2207 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2209 CharDriverState
*chr
;
2212 chr
= qemu_mallocz(sizeof(CharDriverState
));
2215 s
= qemu_mallocz(sizeof(WinCharState
));
2222 chr
->chr_write
= win_chr_write
;
2223 qemu_chr_reset(chr
);
2227 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2231 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2232 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2233 if (fd_out
== INVALID_HANDLE_VALUE
)
2236 return qemu_chr_open_win_file(fd_out
);
2240 /***********************************************************/
2241 /* UDP Net console */
2245 struct sockaddr_in daddr
;
2252 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2254 NetCharDriver
*s
= chr
->opaque
;
2256 return sendto(s
->fd
, buf
, len
, 0,
2257 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2260 static int udp_chr_read_poll(void *opaque
)
2262 CharDriverState
*chr
= opaque
;
2263 NetCharDriver
*s
= chr
->opaque
;
2265 s
->max_size
= qemu_chr_can_read(chr
);
2267 /* If there were any stray characters in the queue process them
2270 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2271 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2273 s
->max_size
= qemu_chr_can_read(chr
);
2278 static void udp_chr_read(void *opaque
)
2280 CharDriverState
*chr
= opaque
;
2281 NetCharDriver
*s
= chr
->opaque
;
2283 if (s
->max_size
== 0)
2285 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2286 s
->bufptr
= s
->bufcnt
;
2291 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2292 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2294 s
->max_size
= qemu_chr_can_read(chr
);
2298 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2300 NetCharDriver
*s
= chr
->opaque
;
2303 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2304 udp_chr_read
, NULL
, chr
);
2308 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2310 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2312 int parse_host_src_port(struct sockaddr_in
*haddr
,
2313 struct sockaddr_in
*saddr
,
2316 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2318 CharDriverState
*chr
= NULL
;
2319 NetCharDriver
*s
= NULL
;
2321 struct sockaddr_in saddr
;
2323 chr
= qemu_mallocz(sizeof(CharDriverState
));
2326 s
= qemu_mallocz(sizeof(NetCharDriver
));
2330 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2332 perror("socket(PF_INET, SOCK_DGRAM)");
2336 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2337 printf("Could not parse: %s\n", def
);
2341 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2351 chr
->chr_write
= udp_chr_write
;
2352 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2365 /***********************************************************/
2366 /* TCP Net console */
2377 static void tcp_chr_accept(void *opaque
);
2379 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2381 TCPCharDriver
*s
= chr
->opaque
;
2383 return send_all(s
->fd
, buf
, len
);
2385 /* XXX: indicate an error ? */
2390 static int tcp_chr_read_poll(void *opaque
)
2392 CharDriverState
*chr
= opaque
;
2393 TCPCharDriver
*s
= chr
->opaque
;
2396 s
->max_size
= qemu_chr_can_read(chr
);
2401 #define IAC_BREAK 243
2402 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2404 char *buf
, int *size
)
2406 /* Handle any telnet client's basic IAC options to satisfy char by
2407 * char mode with no echo. All IAC options will be removed from
2408 * the buf and the do_telnetopt variable will be used to track the
2409 * state of the width of the IAC information.
2411 * IAC commands come in sets of 3 bytes with the exception of the
2412 * "IAC BREAK" command and the double IAC.
2418 for (i
= 0; i
< *size
; i
++) {
2419 if (s
->do_telnetopt
> 1) {
2420 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2421 /* Double IAC means send an IAC */
2425 s
->do_telnetopt
= 1;
2427 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2428 /* Handle IAC break commands by sending a serial break */
2429 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2434 if (s
->do_telnetopt
>= 4) {
2435 s
->do_telnetopt
= 1;
2438 if ((unsigned char)buf
[i
] == IAC
) {
2439 s
->do_telnetopt
= 2;
2450 static void tcp_chr_read(void *opaque
)
2452 CharDriverState
*chr
= opaque
;
2453 TCPCharDriver
*s
= chr
->opaque
;
2457 if (!s
->connected
|| s
->max_size
<= 0)
2460 if (len
> s
->max_size
)
2462 size
= recv(s
->fd
, buf
, len
, 0);
2464 /* connection closed */
2466 if (s
->listen_fd
>= 0) {
2467 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2469 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2472 } else if (size
> 0) {
2473 if (s
->do_telnetopt
)
2474 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2476 qemu_chr_read(chr
, buf
, size
);
2480 static void tcp_chr_connect(void *opaque
)
2482 CharDriverState
*chr
= opaque
;
2483 TCPCharDriver
*s
= chr
->opaque
;
2486 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2487 tcp_chr_read
, NULL
, chr
);
2488 qemu_chr_reset(chr
);
2491 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2492 static void tcp_chr_telnet_init(int fd
)
2495 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2496 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2497 send(fd
, (char *)buf
, 3, 0);
2498 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2499 send(fd
, (char *)buf
, 3, 0);
2500 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2501 send(fd
, (char *)buf
, 3, 0);
2502 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2503 send(fd
, (char *)buf
, 3, 0);
2506 static void socket_set_nodelay(int fd
)
2509 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2512 static void tcp_chr_accept(void *opaque
)
2514 CharDriverState
*chr
= opaque
;
2515 TCPCharDriver
*s
= chr
->opaque
;
2516 struct sockaddr_in saddr
;
2518 struct sockaddr_un uaddr
;
2520 struct sockaddr
*addr
;
2527 len
= sizeof(uaddr
);
2528 addr
= (struct sockaddr
*)&uaddr
;
2532 len
= sizeof(saddr
);
2533 addr
= (struct sockaddr
*)&saddr
;
2535 fd
= accept(s
->listen_fd
, addr
, &len
);
2536 if (fd
< 0 && errno
!= EINTR
) {
2538 } else if (fd
>= 0) {
2539 if (s
->do_telnetopt
)
2540 tcp_chr_telnet_init(fd
);
2544 socket_set_nonblock(fd
);
2546 socket_set_nodelay(fd
);
2548 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2549 tcp_chr_connect(chr
);
2552 static void tcp_chr_close(CharDriverState
*chr
)
2554 TCPCharDriver
*s
= chr
->opaque
;
2557 if (s
->listen_fd
>= 0)
2558 closesocket(s
->listen_fd
);
2562 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2566 CharDriverState
*chr
= NULL
;
2567 TCPCharDriver
*s
= NULL
;
2568 int fd
= -1, ret
, err
, val
;
2570 int is_waitconnect
= 1;
2573 struct sockaddr_in saddr
;
2575 struct sockaddr_un uaddr
;
2577 struct sockaddr
*addr
;
2582 addr
= (struct sockaddr
*)&uaddr
;
2583 addrlen
= sizeof(uaddr
);
2584 if (parse_unix_path(&uaddr
, host_str
) < 0)
2589 addr
= (struct sockaddr
*)&saddr
;
2590 addrlen
= sizeof(saddr
);
2591 if (parse_host_port(&saddr
, host_str
) < 0)
2596 while((ptr
= strchr(ptr
,','))) {
2598 if (!strncmp(ptr
,"server",6)) {
2600 } else if (!strncmp(ptr
,"nowait",6)) {
2602 } else if (!strncmp(ptr
,"nodelay",6)) {
2605 printf("Unknown option: %s\n", ptr
);
2612 chr
= qemu_mallocz(sizeof(CharDriverState
));
2615 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2621 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2624 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2629 if (!is_waitconnect
)
2630 socket_set_nonblock(fd
);
2635 s
->is_unix
= is_unix
;
2636 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2639 chr
->chr_write
= tcp_chr_write
;
2640 chr
->chr_close
= tcp_chr_close
;
2643 /* allow fast reuse */
2647 strncpy(path
, uaddr
.sun_path
, 108);
2654 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2657 ret
= bind(fd
, addr
, addrlen
);
2661 ret
= listen(fd
, 0);
2666 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2668 s
->do_telnetopt
= 1;
2671 ret
= connect(fd
, addr
, addrlen
);
2673 err
= socket_error();
2674 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2675 } else if (err
== EINPROGRESS
) {
2686 socket_set_nodelay(fd
);
2688 tcp_chr_connect(chr
);
2690 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2693 if (is_listen
&& is_waitconnect
) {
2694 printf("QEMU waiting for connection on: %s\n", host_str
);
2695 tcp_chr_accept(chr
);
2696 socket_set_nonblock(s
->listen_fd
);
2708 CharDriverState
*qemu_chr_open(const char *filename
)
2712 if (!strcmp(filename
, "vc")) {
2713 return text_console_init(&display_state
);
2714 } else if (!strcmp(filename
, "null")) {
2715 return qemu_chr_open_null();
2717 if (strstart(filename
, "tcp:", &p
)) {
2718 return qemu_chr_open_tcp(p
, 0, 0);
2720 if (strstart(filename
, "telnet:", &p
)) {
2721 return qemu_chr_open_tcp(p
, 1, 0);
2723 if (strstart(filename
, "udp:", &p
)) {
2724 return qemu_chr_open_udp(p
);
2727 if (strstart(filename
, "unix:", &p
)) {
2728 return qemu_chr_open_tcp(p
, 0, 1);
2729 } else if (strstart(filename
, "file:", &p
)) {
2730 return qemu_chr_open_file_out(p
);
2731 } else if (strstart(filename
, "pipe:", &p
)) {
2732 return qemu_chr_open_pipe(p
);
2733 } else if (!strcmp(filename
, "pty")) {
2734 return qemu_chr_open_pty();
2735 } else if (!strcmp(filename
, "stdio")) {
2736 return qemu_chr_open_stdio();
2739 #if defined(__linux__)
2740 if (strstart(filename
, "/dev/parport", NULL
)) {
2741 return qemu_chr_open_pp(filename
);
2743 if (strstart(filename
, "/dev/", NULL
)) {
2744 return qemu_chr_open_tty(filename
);
2748 if (strstart(filename
, "COM", NULL
)) {
2749 return qemu_chr_open_win(filename
);
2751 if (strstart(filename
, "pipe:", &p
)) {
2752 return qemu_chr_open_win_pipe(p
);
2754 if (strstart(filename
, "file:", &p
)) {
2755 return qemu_chr_open_win_file_out(p
);
2763 void qemu_chr_close(CharDriverState
*chr
)
2766 chr
->chr_close(chr
);
2769 /***********************************************************/
2770 /* network device redirectors */
2772 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2776 for(i
=0;i
<size
;i
+=16) {
2780 fprintf(f
, "%08x ", i
);
2783 fprintf(f
, " %02x", buf
[i
+j
]);
2788 for(j
=0;j
<len
;j
++) {
2790 if (c
< ' ' || c
> '~')
2792 fprintf(f
, "%c", c
);
2798 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2801 for(i
= 0; i
< 6; i
++) {
2802 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
2815 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
2820 p1
= strchr(p
, sep
);
2826 if (len
> buf_size
- 1)
2828 memcpy(buf
, p
, len
);
2835 int parse_host_src_port(struct sockaddr_in
*haddr
,
2836 struct sockaddr_in
*saddr
,
2837 const char *input_str
)
2839 char *str
= strdup(input_str
);
2840 char *host_str
= str
;
2845 * Chop off any extra arguments at the end of the string which
2846 * would start with a comma, then fill in the src port information
2847 * if it was provided else use the "any address" and "any port".
2849 if ((ptr
= strchr(str
,',')))
2852 if ((src_str
= strchr(input_str
,'@'))) {
2857 if (parse_host_port(haddr
, host_str
) < 0)
2860 if (!src_str
|| *src_str
== '\0')
2863 if (parse_host_port(saddr
, src_str
) < 0)
2874 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
2882 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2884 saddr
->sin_family
= AF_INET
;
2885 if (buf
[0] == '\0') {
2886 saddr
->sin_addr
.s_addr
= 0;
2888 if (isdigit(buf
[0])) {
2889 if (!inet_aton(buf
, &saddr
->sin_addr
))
2892 if ((he
= gethostbyname(buf
)) == NULL
)
2894 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
2897 port
= strtol(p
, (char **)&r
, 0);
2900 saddr
->sin_port
= htons(port
);
2905 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
2910 len
= MIN(108, strlen(str
));
2911 p
= strchr(str
, ',');
2913 len
= MIN(len
, p
- str
);
2915 memset(uaddr
, 0, sizeof(*uaddr
));
2917 uaddr
->sun_family
= AF_UNIX
;
2918 memcpy(uaddr
->sun_path
, str
, len
);
2924 /* find or alloc a new VLAN */
2925 VLANState
*qemu_find_vlan(int id
)
2927 VLANState
**pvlan
, *vlan
;
2928 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2932 vlan
= qemu_mallocz(sizeof(VLANState
));
2937 pvlan
= &first_vlan
;
2938 while (*pvlan
!= NULL
)
2939 pvlan
= &(*pvlan
)->next
;
2944 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
2945 IOReadHandler
*fd_read
,
2946 IOCanRWHandler
*fd_can_read
,
2949 VLANClientState
*vc
, **pvc
;
2950 vc
= qemu_mallocz(sizeof(VLANClientState
));
2953 vc
->fd_read
= fd_read
;
2954 vc
->fd_can_read
= fd_can_read
;
2955 vc
->opaque
= opaque
;
2959 pvc
= &vlan
->first_client
;
2960 while (*pvc
!= NULL
)
2961 pvc
= &(*pvc
)->next
;
2966 int qemu_can_send_packet(VLANClientState
*vc1
)
2968 VLANState
*vlan
= vc1
->vlan
;
2969 VLANClientState
*vc
;
2971 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2973 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
2980 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
2982 VLANState
*vlan
= vc1
->vlan
;
2983 VLANClientState
*vc
;
2986 printf("vlan %d send:\n", vlan
->id
);
2987 hex_dump(stdout
, buf
, size
);
2989 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2991 vc
->fd_read(vc
->opaque
, buf
, size
);
2996 #if defined(CONFIG_SLIRP)
2998 /* slirp network adapter */
3000 static int slirp_inited
;
3001 static VLANClientState
*slirp_vc
;
3003 int slirp_can_output(void)
3005 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3008 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3011 printf("slirp output:\n");
3012 hex_dump(stdout
, pkt
, pkt_len
);
3016 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3019 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3022 printf("slirp input:\n");
3023 hex_dump(stdout
, buf
, size
);
3025 slirp_input(buf
, size
);
3028 static int net_slirp_init(VLANState
*vlan
)
3030 if (!slirp_inited
) {
3034 slirp_vc
= qemu_new_vlan_client(vlan
,
3035 slirp_receive
, NULL
, NULL
);
3036 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3040 static void net_slirp_redir(const char *redir_str
)
3045 struct in_addr guest_addr
;
3046 int host_port
, guest_port
;
3048 if (!slirp_inited
) {
3054 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3056 if (!strcmp(buf
, "tcp")) {
3058 } else if (!strcmp(buf
, "udp")) {
3064 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3066 host_port
= strtol(buf
, &r
, 0);
3070 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3072 if (buf
[0] == '\0') {
3073 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3075 if (!inet_aton(buf
, &guest_addr
))
3078 guest_port
= strtol(p
, &r
, 0);
3082 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3083 fprintf(stderr
, "qemu: could not set up redirection\n");
3088 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3096 static void smb_exit(void)
3100 char filename
[1024];
3102 /* erase all the files in the directory */
3103 d
= opendir(smb_dir
);
3108 if (strcmp(de
->d_name
, ".") != 0 &&
3109 strcmp(de
->d_name
, "..") != 0) {
3110 snprintf(filename
, sizeof(filename
), "%s/%s",
3111 smb_dir
, de
->d_name
);
3119 /* automatic user mode samba server configuration */
3120 void net_slirp_smb(const char *exported_dir
)
3122 char smb_conf
[1024];
3123 char smb_cmdline
[1024];
3126 if (!slirp_inited
) {
3131 /* XXX: better tmp dir construction */
3132 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3133 if (mkdir(smb_dir
, 0700) < 0) {
3134 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3137 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3139 f
= fopen(smb_conf
, "w");
3141 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3148 "socket address=127.0.0.1\n"
3149 "pid directory=%s\n"
3150 "lock directory=%s\n"
3151 "log file=%s/log.smbd\n"
3152 "smb passwd file=%s/smbpasswd\n"
3153 "security = share\n"
3168 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3169 SMBD_COMMAND
, smb_conf
);
3171 slirp_add_exec(0, smb_cmdline
, 4, 139);
3174 #endif /* !defined(_WIN32) */
3176 #endif /* CONFIG_SLIRP */
3178 #if !defined(_WIN32)
3180 typedef struct TAPState
{
3181 VLANClientState
*vc
;
3185 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3187 TAPState
*s
= opaque
;
3190 ret
= write(s
->fd
, buf
, size
);
3191 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3198 static void tap_send(void *opaque
)
3200 TAPState
*s
= opaque
;
3204 size
= read(s
->fd
, buf
, sizeof(buf
));
3206 qemu_send_packet(s
->vc
, buf
, size
);
3212 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3216 s
= qemu_mallocz(sizeof(TAPState
));
3220 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3221 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3222 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3227 static int tap_open(char *ifname
, int ifname_size
)
3233 fd
= open("/dev/tap", O_RDWR
);
3235 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3240 dev
= devname(s
.st_rdev
, S_IFCHR
);
3241 pstrcpy(ifname
, ifname_size
, dev
);
3243 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3246 #elif defined(__sun__)
3247 static int tap_open(char *ifname
, int ifname_size
)
3249 fprintf(stderr
, "warning: tap_open not yet implemented\n");
3253 static int tap_open(char *ifname
, int ifname_size
)
3258 fd
= open("/dev/net/tun", O_RDWR
);
3260 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3263 memset(&ifr
, 0, sizeof(ifr
));
3264 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3265 if (ifname
[0] != '\0')
3266 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3268 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3269 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3271 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3275 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3276 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3281 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3282 const char *setup_script
)
3285 int pid
, status
, fd
;
3290 if (ifname1
!= NULL
)
3291 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3294 fd
= tap_open(ifname
, sizeof(ifname
));
3298 if (!setup_script
|| !strcmp(setup_script
, "no"))
3300 if (setup_script
[0] != '\0') {
3301 /* try to launch network init script */
3306 *parg
++ = (char *)setup_script
;
3309 execv(setup_script
, args
);
3312 while (waitpid(pid
, &status
, 0) != pid
);
3313 if (!WIFEXITED(status
) ||
3314 WEXITSTATUS(status
) != 0) {
3315 fprintf(stderr
, "%s: could not launch network script\n",
3321 s
= net_tap_fd_init(vlan
, fd
);
3324 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3325 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3329 #endif /* !_WIN32 */
3331 /* network connection */
3332 typedef struct NetSocketState
{
3333 VLANClientState
*vc
;
3335 int state
; /* 0 = getting length, 1 = getting data */
3339 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3342 typedef struct NetSocketListenState
{
3345 } NetSocketListenState
;
3347 /* XXX: we consider we can send the whole packet without blocking */
3348 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3350 NetSocketState
*s
= opaque
;
3354 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3355 send_all(s
->fd
, buf
, size
);
3358 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3360 NetSocketState
*s
= opaque
;
3361 sendto(s
->fd
, buf
, size
, 0,
3362 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3365 static void net_socket_send(void *opaque
)
3367 NetSocketState
*s
= opaque
;
3372 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3374 err
= socket_error();
3375 if (err
!= EWOULDBLOCK
)
3377 } else if (size
== 0) {
3378 /* end of connection */
3380 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3386 /* reassemble a packet from the network */
3392 memcpy(s
->buf
+ s
->index
, buf
, l
);
3396 if (s
->index
== 4) {
3398 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3404 l
= s
->packet_len
- s
->index
;
3407 memcpy(s
->buf
+ s
->index
, buf
, l
);
3411 if (s
->index
>= s
->packet_len
) {
3412 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3421 static void net_socket_send_dgram(void *opaque
)
3423 NetSocketState
*s
= opaque
;
3426 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3430 /* end of connection */
3431 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3434 qemu_send_packet(s
->vc
, s
->buf
, size
);
3437 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3442 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3443 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3444 inet_ntoa(mcastaddr
->sin_addr
),
3445 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3449 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3451 perror("socket(PF_INET, SOCK_DGRAM)");
3456 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3457 (const char *)&val
, sizeof(val
));
3459 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3463 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3469 /* Add host to multicast group */
3470 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3471 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3473 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3474 (const char *)&imr
, sizeof(struct ip_mreq
));
3476 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3480 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3482 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3483 (const char *)&val
, sizeof(val
));
3485 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3489 socket_set_nonblock(fd
);
3497 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3500 struct sockaddr_in saddr
;
3502 socklen_t saddr_len
;
3505 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3506 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3507 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3511 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3513 if (saddr
.sin_addr
.s_addr
==0) {
3514 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3518 /* clone dgram socket */
3519 newfd
= net_socket_mcast_create(&saddr
);
3521 /* error already reported by net_socket_mcast_create() */
3525 /* clone newfd to fd, close newfd */
3530 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3531 fd
, strerror(errno
));
3536 s
= qemu_mallocz(sizeof(NetSocketState
));
3541 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3542 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3544 /* mcast: save bound address as dst */
3545 if (is_connected
) s
->dgram_dst
=saddr
;
3547 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3548 "socket: fd=%d (%s mcast=%s:%d)",
3549 fd
, is_connected
? "cloned" : "",
3550 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3554 static void net_socket_connect(void *opaque
)
3556 NetSocketState
*s
= opaque
;
3557 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3560 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3564 s
= qemu_mallocz(sizeof(NetSocketState
));
3568 s
->vc
= qemu_new_vlan_client(vlan
,
3569 net_socket_receive
, NULL
, s
);
3570 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3571 "socket: fd=%d", fd
);
3573 net_socket_connect(s
);
3575 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3580 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3583 int so_type
=-1, optlen
=sizeof(so_type
);
3585 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3586 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3591 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3593 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3595 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3596 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3597 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3602 static void net_socket_accept(void *opaque
)
3604 NetSocketListenState
*s
= opaque
;
3606 struct sockaddr_in saddr
;
3611 len
= sizeof(saddr
);
3612 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3613 if (fd
< 0 && errno
!= EINTR
) {
3615 } else if (fd
>= 0) {
3619 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3623 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3624 "socket: connection from %s:%d",
3625 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3629 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3631 NetSocketListenState
*s
;
3633 struct sockaddr_in saddr
;
3635 if (parse_host_port(&saddr
, host_str
) < 0)
3638 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3642 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3647 socket_set_nonblock(fd
);
3649 /* allow fast reuse */
3651 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3653 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3658 ret
= listen(fd
, 0);
3665 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3669 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3672 int fd
, connected
, ret
, err
;
3673 struct sockaddr_in saddr
;
3675 if (parse_host_port(&saddr
, host_str
) < 0)
3678 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3683 socket_set_nonblock(fd
);
3687 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3689 err
= socket_error();
3690 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3691 } else if (err
== EINPROGRESS
) {
3703 s
= net_socket_fd_init(vlan
, fd
, connected
);
3706 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3707 "socket: connect to %s:%d",
3708 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3712 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
3716 struct sockaddr_in saddr
;
3718 if (parse_host_port(&saddr
, host_str
) < 0)
3722 fd
= net_socket_mcast_create(&saddr
);
3726 s
= net_socket_fd_init(vlan
, fd
, 0);
3730 s
->dgram_dst
= saddr
;
3732 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3733 "socket: mcast=%s:%d",
3734 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3739 static int get_param_value(char *buf
, int buf_size
,
3740 const char *tag
, const char *str
)
3749 while (*p
!= '\0' && *p
!= '=') {
3750 if ((q
- option
) < sizeof(option
) - 1)
3758 if (!strcmp(tag
, option
)) {
3760 while (*p
!= '\0' && *p
!= ',') {
3761 if ((q
- buf
) < buf_size
- 1)
3768 while (*p
!= '\0' && *p
!= ',') {
3779 static int net_client_init(const char *str
)
3790 while (*p
!= '\0' && *p
!= ',') {
3791 if ((q
- device
) < sizeof(device
) - 1)
3799 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
3800 vlan_id
= strtol(buf
, NULL
, 0);
3802 vlan
= qemu_find_vlan(vlan_id
);
3804 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
3807 if (!strcmp(device
, "nic")) {
3811 if (nb_nics
>= MAX_NICS
) {
3812 fprintf(stderr
, "Too Many NICs\n");
3815 nd
= &nd_table
[nb_nics
];
3816 macaddr
= nd
->macaddr
;
3822 macaddr
[5] = 0x56 + nb_nics
;
3824 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
3825 if (parse_macaddr(macaddr
, buf
) < 0) {
3826 fprintf(stderr
, "invalid syntax for ethernet address\n");
3830 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
3831 nd
->model
= strdup(buf
);
3837 if (!strcmp(device
, "none")) {
3838 /* does nothing. It is needed to signal that no network cards
3843 if (!strcmp(device
, "user")) {
3844 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
3845 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
3847 ret
= net_slirp_init(vlan
);
3851 if (!strcmp(device
, "tap")) {
3853 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3854 fprintf(stderr
, "tap: no interface name\n");
3857 ret
= tap_win32_init(vlan
, ifname
);
3860 if (!strcmp(device
, "tap")) {
3862 char setup_script
[1024];
3864 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3865 fd
= strtol(buf
, NULL
, 0);
3867 if (net_tap_fd_init(vlan
, fd
))
3870 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3873 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
3874 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
3876 ret
= net_tap_init(vlan
, ifname
, setup_script
);
3880 if (!strcmp(device
, "socket")) {
3881 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3883 fd
= strtol(buf
, NULL
, 0);
3885 if (net_socket_fd_init(vlan
, fd
, 1))
3887 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
3888 ret
= net_socket_listen_init(vlan
, buf
);
3889 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
3890 ret
= net_socket_connect_init(vlan
, buf
);
3891 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
3892 ret
= net_socket_mcast_init(vlan
, buf
);
3894 fprintf(stderr
, "Unknown socket options: %s\n", p
);
3899 fprintf(stderr
, "Unknown network device: %s\n", device
);
3903 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
3909 void do_info_network(void)
3912 VLANClientState
*vc
;
3914 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3915 term_printf("VLAN %d devices:\n", vlan
->id
);
3916 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
3917 term_printf(" %s\n", vc
->info_str
);
3921 /***********************************************************/
3924 static USBPort
*used_usb_ports
;
3925 static USBPort
*free_usb_ports
;
3927 /* ??? Maybe change this to register a hub to keep track of the topology. */
3928 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
3929 usb_attachfn attach
)
3931 port
->opaque
= opaque
;
3932 port
->index
= index
;
3933 port
->attach
= attach
;
3934 port
->next
= free_usb_ports
;
3935 free_usb_ports
= port
;
3938 static int usb_device_add(const char *devname
)
3944 if (!free_usb_ports
)
3947 if (strstart(devname
, "host:", &p
)) {
3948 dev
= usb_host_device_open(p
);
3949 } else if (!strcmp(devname
, "mouse")) {
3950 dev
= usb_mouse_init();
3951 } else if (!strcmp(devname
, "tablet")) {
3952 dev
= usb_tablet_init();
3953 } else if (strstart(devname
, "disk:", &p
)) {
3954 dev
= usb_msd_init(p
);
3961 /* Find a USB port to add the device to. */
3962 port
= free_usb_ports
;
3966 /* Create a new hub and chain it on. */
3967 free_usb_ports
= NULL
;
3968 port
->next
= used_usb_ports
;
3969 used_usb_ports
= port
;
3971 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
3972 usb_attach(port
, hub
);
3973 port
= free_usb_ports
;
3976 free_usb_ports
= port
->next
;
3977 port
->next
= used_usb_ports
;
3978 used_usb_ports
= port
;
3979 usb_attach(port
, dev
);
3983 static int usb_device_del(const char *devname
)
3991 if (!used_usb_ports
)
3994 p
= strchr(devname
, '.');
3997 bus_num
= strtoul(devname
, NULL
, 0);
3998 addr
= strtoul(p
+ 1, NULL
, 0);
4002 lastp
= &used_usb_ports
;
4003 port
= used_usb_ports
;
4004 while (port
&& port
->dev
->addr
!= addr
) {
4005 lastp
= &port
->next
;
4013 *lastp
= port
->next
;
4014 usb_attach(port
, NULL
);
4015 dev
->handle_destroy(dev
);
4016 port
->next
= free_usb_ports
;
4017 free_usb_ports
= port
;
4021 void do_usb_add(const char *devname
)
4024 ret
= usb_device_add(devname
);
4026 term_printf("Could not add USB device '%s'\n", devname
);
4029 void do_usb_del(const char *devname
)
4032 ret
= usb_device_del(devname
);
4034 term_printf("Could not remove USB device '%s'\n", devname
);
4041 const char *speed_str
;
4044 term_printf("USB support not enabled\n");
4048 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4052 switch(dev
->speed
) {
4056 case USB_SPEED_FULL
:
4059 case USB_SPEED_HIGH
:
4066 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4067 0, dev
->addr
, speed_str
, dev
->devname
);
4071 /***********************************************************/
4074 static char *pid_filename
;
4076 /* Remove PID file. Called on normal exit */
4078 static void remove_pidfile(void)
4080 unlink (pid_filename
);
4083 static void create_pidfile(const char *filename
)
4085 struct stat pidstat
;
4088 /* Try to write our PID to the named file */
4089 if (stat(filename
, &pidstat
) < 0) {
4090 if (errno
== ENOENT
) {
4091 if ((f
= fopen (filename
, "w")) == NULL
) {
4092 perror("Opening pidfile");
4095 fprintf(f
, "%d\n", getpid());
4097 pid_filename
= qemu_strdup(filename
);
4098 if (!pid_filename
) {
4099 fprintf(stderr
, "Could not save PID filename");
4102 atexit(remove_pidfile
);
4105 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4111 /***********************************************************/
4114 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4118 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4122 static void dumb_refresh(DisplayState
*ds
)
4127 void dumb_display_init(DisplayState
*ds
)
4132 ds
->dpy_update
= dumb_update
;
4133 ds
->dpy_resize
= dumb_resize
;
4134 ds
->dpy_refresh
= dumb_refresh
;
4137 /***********************************************************/
4140 #define MAX_IO_HANDLERS 64
4142 typedef struct IOHandlerRecord
{
4144 IOCanRWHandler
*fd_read_poll
;
4146 IOHandler
*fd_write
;
4148 /* temporary data */
4150 struct IOHandlerRecord
*next
;
4153 static IOHandlerRecord
*first_io_handler
;
4155 /* XXX: fd_read_poll should be suppressed, but an API change is
4156 necessary in the character devices to suppress fd_can_read(). */
4157 int qemu_set_fd_handler2(int fd
,
4158 IOCanRWHandler
*fd_read_poll
,
4160 IOHandler
*fd_write
,
4163 IOHandlerRecord
**pioh
, *ioh
;
4165 if (!fd_read
&& !fd_write
) {
4166 pioh
= &first_io_handler
;
4171 if (ioh
->fd
== fd
) {
4179 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4183 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4186 ioh
->next
= first_io_handler
;
4187 first_io_handler
= ioh
;
4190 ioh
->fd_read_poll
= fd_read_poll
;
4191 ioh
->fd_read
= fd_read
;
4192 ioh
->fd_write
= fd_write
;
4193 ioh
->opaque
= opaque
;
4198 int qemu_set_fd_handler(int fd
,
4200 IOHandler
*fd_write
,
4203 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4206 /***********************************************************/
4207 /* Polling handling */
4209 typedef struct PollingEntry
{
4212 struct PollingEntry
*next
;
4215 static PollingEntry
*first_polling_entry
;
4217 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4219 PollingEntry
**ppe
, *pe
;
4220 pe
= qemu_mallocz(sizeof(PollingEntry
));
4224 pe
->opaque
= opaque
;
4225 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4230 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4232 PollingEntry
**ppe
, *pe
;
4233 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4235 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4244 /***********************************************************/
4245 /* Wait objects support */
4246 typedef struct WaitObjects
{
4248 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4249 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4250 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4253 static WaitObjects wait_objects
= {0};
4255 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4257 WaitObjects
*w
= &wait_objects
;
4259 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4261 w
->events
[w
->num
] = handle
;
4262 w
->func
[w
->num
] = func
;
4263 w
->opaque
[w
->num
] = opaque
;
4268 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4271 WaitObjects
*w
= &wait_objects
;
4274 for (i
= 0; i
< w
->num
; i
++) {
4275 if (w
->events
[i
] == handle
)
4278 w
->events
[i
] = w
->events
[i
+ 1];
4279 w
->func
[i
] = w
->func
[i
+ 1];
4280 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4288 /***********************************************************/
4289 /* savevm/loadvm support */
4291 #define IO_BUF_SIZE 32768
4295 BlockDriverState
*bs
;
4298 int64_t base_offset
;
4299 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4302 int buf_size
; /* 0 when writing */
4303 uint8_t buf
[IO_BUF_SIZE
];
4306 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
4310 f
= qemu_mallocz(sizeof(QEMUFile
));
4313 if (!strcmp(mode
, "wb")) {
4315 } else if (!strcmp(mode
, "rb")) {
4320 f
->outfile
= fopen(filename
, mode
);
4332 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4336 f
= qemu_mallocz(sizeof(QEMUFile
));
4341 f
->is_writable
= is_writable
;
4342 f
->base_offset
= offset
;
4346 void qemu_fflush(QEMUFile
*f
)
4348 if (!f
->is_writable
)
4350 if (f
->buf_index
> 0) {
4352 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4353 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
4355 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4356 f
->buf
, f
->buf_index
);
4358 f
->buf_offset
+= f
->buf_index
;
4363 static void qemu_fill_buffer(QEMUFile
*f
)
4370 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
4371 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
4375 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
4376 f
->buf
, IO_BUF_SIZE
);
4382 f
->buf_offset
+= len
;
4385 void qemu_fclose(QEMUFile
*f
)
4395 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4399 l
= IO_BUF_SIZE
- f
->buf_index
;
4402 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4406 if (f
->buf_index
>= IO_BUF_SIZE
)
4411 void qemu_put_byte(QEMUFile
*f
, int v
)
4413 f
->buf
[f
->buf_index
++] = v
;
4414 if (f
->buf_index
>= IO_BUF_SIZE
)
4418 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4424 l
= f
->buf_size
- f
->buf_index
;
4426 qemu_fill_buffer(f
);
4427 l
= f
->buf_size
- f
->buf_index
;
4433 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4438 return size1
- size
;
4441 int qemu_get_byte(QEMUFile
*f
)
4443 if (f
->buf_index
>= f
->buf_size
) {
4444 qemu_fill_buffer(f
);
4445 if (f
->buf_index
>= f
->buf_size
)
4448 return f
->buf
[f
->buf_index
++];
4451 int64_t qemu_ftell(QEMUFile
*f
)
4453 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4456 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4458 if (whence
== SEEK_SET
) {
4460 } else if (whence
== SEEK_CUR
) {
4461 pos
+= qemu_ftell(f
);
4463 /* SEEK_END not supported */
4466 if (f
->is_writable
) {
4468 f
->buf_offset
= pos
;
4470 f
->buf_offset
= pos
;
4477 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4479 qemu_put_byte(f
, v
>> 8);
4480 qemu_put_byte(f
, v
);
4483 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4485 qemu_put_byte(f
, v
>> 24);
4486 qemu_put_byte(f
, v
>> 16);
4487 qemu_put_byte(f
, v
>> 8);
4488 qemu_put_byte(f
, v
);
4491 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4493 qemu_put_be32(f
, v
>> 32);
4494 qemu_put_be32(f
, v
);
4497 unsigned int qemu_get_be16(QEMUFile
*f
)
4500 v
= qemu_get_byte(f
) << 8;
4501 v
|= qemu_get_byte(f
);
4505 unsigned int qemu_get_be32(QEMUFile
*f
)
4508 v
= qemu_get_byte(f
) << 24;
4509 v
|= qemu_get_byte(f
) << 16;
4510 v
|= qemu_get_byte(f
) << 8;
4511 v
|= qemu_get_byte(f
);
4515 uint64_t qemu_get_be64(QEMUFile
*f
)
4518 v
= (uint64_t)qemu_get_be32(f
) << 32;
4519 v
|= qemu_get_be32(f
);
4523 typedef struct SaveStateEntry
{
4527 SaveStateHandler
*save_state
;
4528 LoadStateHandler
*load_state
;
4530 struct SaveStateEntry
*next
;
4533 static SaveStateEntry
*first_se
;
4535 int register_savevm(const char *idstr
,
4538 SaveStateHandler
*save_state
,
4539 LoadStateHandler
*load_state
,
4542 SaveStateEntry
*se
, **pse
;
4544 se
= qemu_malloc(sizeof(SaveStateEntry
));
4547 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4548 se
->instance_id
= instance_id
;
4549 se
->version_id
= version_id
;
4550 se
->save_state
= save_state
;
4551 se
->load_state
= load_state
;
4552 se
->opaque
= opaque
;
4555 /* add at the end of list */
4557 while (*pse
!= NULL
)
4558 pse
= &(*pse
)->next
;
4563 #define QEMU_VM_FILE_MAGIC 0x5145564d
4564 #define QEMU_VM_FILE_VERSION 0x00000002
4566 int qemu_savevm_state(QEMUFile
*f
)
4570 int64_t cur_pos
, len_pos
, total_len_pos
;
4572 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4573 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4574 total_len_pos
= qemu_ftell(f
);
4575 qemu_put_be64(f
, 0); /* total size */
4577 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4579 len
= strlen(se
->idstr
);
4580 qemu_put_byte(f
, len
);
4581 qemu_put_buffer(f
, se
->idstr
, len
);
4583 qemu_put_be32(f
, se
->instance_id
);
4584 qemu_put_be32(f
, se
->version_id
);
4586 /* record size: filled later */
4587 len_pos
= qemu_ftell(f
);
4588 qemu_put_be32(f
, 0);
4590 se
->save_state(f
, se
->opaque
);
4592 /* fill record size */
4593 cur_pos
= qemu_ftell(f
);
4594 len
= cur_pos
- len_pos
- 4;
4595 qemu_fseek(f
, len_pos
, SEEK_SET
);
4596 qemu_put_be32(f
, len
);
4597 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4599 cur_pos
= qemu_ftell(f
);
4600 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4601 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4602 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4608 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4612 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4613 if (!strcmp(se
->idstr
, idstr
) &&
4614 instance_id
== se
->instance_id
)
4620 int qemu_loadvm_state(QEMUFile
*f
)
4623 int len
, ret
, instance_id
, record_len
, version_id
;
4624 int64_t total_len
, end_pos
, cur_pos
;
4628 v
= qemu_get_be32(f
);
4629 if (v
!= QEMU_VM_FILE_MAGIC
)
4631 v
= qemu_get_be32(f
);
4632 if (v
!= QEMU_VM_FILE_VERSION
) {
4637 total_len
= qemu_get_be64(f
);
4638 end_pos
= total_len
+ qemu_ftell(f
);
4640 if (qemu_ftell(f
) >= end_pos
)
4642 len
= qemu_get_byte(f
);
4643 qemu_get_buffer(f
, idstr
, len
);
4645 instance_id
= qemu_get_be32(f
);
4646 version_id
= qemu_get_be32(f
);
4647 record_len
= qemu_get_be32(f
);
4649 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4650 idstr
, instance_id
, version_id
, record_len
);
4652 cur_pos
= qemu_ftell(f
);
4653 se
= find_se(idstr
, instance_id
);
4655 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4656 instance_id
, idstr
);
4658 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4660 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4661 instance_id
, idstr
);
4664 /* always seek to exact end of record */
4665 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4672 /* device can contain snapshots */
4673 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4676 !bdrv_is_removable(bs
) &&
4677 !bdrv_is_read_only(bs
));
4680 /* device must be snapshots in order to have a reliable snapshot */
4681 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4684 !bdrv_is_removable(bs
) &&
4685 !bdrv_is_read_only(bs
));
4688 static BlockDriverState
*get_bs_snapshots(void)
4690 BlockDriverState
*bs
;
4694 return bs_snapshots
;
4695 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4697 if (bdrv_can_snapshot(bs
))
4706 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
4709 QEMUSnapshotInfo
*sn_tab
, *sn
;
4713 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
4716 for(i
= 0; i
< nb_sns
; i
++) {
4718 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
4728 void do_savevm(const char *name
)
4730 BlockDriverState
*bs
, *bs1
;
4731 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
4732 int must_delete
, ret
, i
;
4733 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
4735 int saved_vm_running
;
4742 bs
= get_bs_snapshots();
4744 term_printf("No block device can accept snapshots\n");
4748 /* ??? Should this occur after vm_stop? */
4751 saved_vm_running
= vm_running
;
4756 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
4761 memset(sn
, 0, sizeof(*sn
));
4763 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
4764 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
4767 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
4770 /* fill auxiliary fields */
4773 sn
->date_sec
= tb
.time
;
4774 sn
->date_nsec
= tb
.millitm
* 1000000;
4776 gettimeofday(&tv
, NULL
);
4777 sn
->date_sec
= tv
.tv_sec
;
4778 sn
->date_nsec
= tv
.tv_usec
* 1000;
4780 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
4782 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
4783 term_printf("Device %s does not support VM state snapshots\n",
4784 bdrv_get_device_name(bs
));
4788 /* save the VM state */
4789 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
4791 term_printf("Could not open VM state file\n");
4794 ret
= qemu_savevm_state(f
);
4795 sn
->vm_state_size
= qemu_ftell(f
);
4798 term_printf("Error %d while writing VM\n", ret
);
4802 /* create the snapshots */
4804 for(i
= 0; i
< MAX_DISKS
; i
++) {
4806 if (bdrv_has_snapshot(bs1
)) {
4808 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
4810 term_printf("Error while deleting snapshot on '%s'\n",
4811 bdrv_get_device_name(bs1
));
4814 ret
= bdrv_snapshot_create(bs1
, sn
);
4816 term_printf("Error while creating snapshot on '%s'\n",
4817 bdrv_get_device_name(bs1
));
4823 if (saved_vm_running
)
4827 void do_loadvm(const char *name
)
4829 BlockDriverState
*bs
, *bs1
;
4830 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
4833 int saved_vm_running
;
4835 bs
= get_bs_snapshots();
4837 term_printf("No block device supports snapshots\n");
4841 /* Flush all IO requests so they don't interfere with the new state. */
4844 saved_vm_running
= vm_running
;
4847 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4849 if (bdrv_has_snapshot(bs1
)) {
4850 ret
= bdrv_snapshot_goto(bs1
, name
);
4853 term_printf("Warning: ");
4856 term_printf("Snapshots not supported on device '%s'\n",
4857 bdrv_get_device_name(bs1
));
4860 term_printf("Could not find snapshot '%s' on device '%s'\n",
4861 name
, bdrv_get_device_name(bs1
));
4864 term_printf("Error %d while activating snapshot on '%s'\n",
4865 ret
, bdrv_get_device_name(bs1
));
4868 /* fatal on snapshot block device */
4875 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
4876 term_printf("Device %s does not support VM state snapshots\n",
4877 bdrv_get_device_name(bs
));
4881 /* restore the VM state */
4882 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
4884 term_printf("Could not open VM state file\n");
4887 ret
= qemu_loadvm_state(f
);
4890 term_printf("Error %d while loading VM state\n", ret
);
4893 if (saved_vm_running
)
4897 void do_delvm(const char *name
)
4899 BlockDriverState
*bs
, *bs1
;
4902 bs
= get_bs_snapshots();
4904 term_printf("No block device supports snapshots\n");
4908 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4910 if (bdrv_has_snapshot(bs1
)) {
4911 ret
= bdrv_snapshot_delete(bs1
, name
);
4913 if (ret
== -ENOTSUP
)
4914 term_printf("Snapshots not supported on device '%s'\n",
4915 bdrv_get_device_name(bs1
));
4917 term_printf("Error %d while deleting snapshot on '%s'\n",
4918 ret
, bdrv_get_device_name(bs1
));
4924 void do_info_snapshots(void)
4926 BlockDriverState
*bs
, *bs1
;
4927 QEMUSnapshotInfo
*sn_tab
, *sn
;
4931 bs
= get_bs_snapshots();
4933 term_printf("No available block device supports snapshots\n");
4936 term_printf("Snapshot devices:");
4937 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4939 if (bdrv_has_snapshot(bs1
)) {
4941 term_printf(" %s", bdrv_get_device_name(bs1
));
4946 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
4948 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
4951 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
4952 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
4953 for(i
= 0; i
< nb_sns
; i
++) {
4955 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
4960 /***********************************************************/
4961 /* cpu save/restore */
4963 #if defined(TARGET_I386)
4965 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
4967 qemu_put_be32(f
, dt
->selector
);
4968 qemu_put_betl(f
, dt
->base
);
4969 qemu_put_be32(f
, dt
->limit
);
4970 qemu_put_be32(f
, dt
->flags
);
4973 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
4975 dt
->selector
= qemu_get_be32(f
);
4976 dt
->base
= qemu_get_betl(f
);
4977 dt
->limit
= qemu_get_be32(f
);
4978 dt
->flags
= qemu_get_be32(f
);
4981 void cpu_save(QEMUFile
*f
, void *opaque
)
4983 CPUState
*env
= opaque
;
4984 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
4990 kvm_save_registers(env
);
4993 for(i
= 0; i
< CPU_NB_REGS
; i
++)
4994 qemu_put_betls(f
, &env
->regs
[i
]);
4995 qemu_put_betls(f
, &env
->eip
);
4996 qemu_put_betls(f
, &env
->eflags
);
4997 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
4998 qemu_put_be32s(f
, &hflags
);
5002 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5004 for(i
= 0; i
< 8; i
++) {
5005 fptag
|= ((!env
->fptags
[i
]) << i
);
5008 qemu_put_be16s(f
, &fpuc
);
5009 qemu_put_be16s(f
, &fpus
);
5010 qemu_put_be16s(f
, &fptag
);
5012 #ifdef USE_X86LDOUBLE
5017 qemu_put_be16s(f
, &fpregs_format
);
5019 for(i
= 0; i
< 8; i
++) {
5020 #ifdef USE_X86LDOUBLE
5024 /* we save the real CPU data (in case of MMX usage only 'mant'
5025 contains the MMX register */
5026 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5027 qemu_put_be64(f
, mant
);
5028 qemu_put_be16(f
, exp
);
5031 /* if we use doubles for float emulation, we save the doubles to
5032 avoid losing information in case of MMX usage. It can give
5033 problems if the image is restored on a CPU where long
5034 doubles are used instead. */
5035 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5039 for(i
= 0; i
< 6; i
++)
5040 cpu_put_seg(f
, &env
->segs
[i
]);
5041 cpu_put_seg(f
, &env
->ldt
);
5042 cpu_put_seg(f
, &env
->tr
);
5043 cpu_put_seg(f
, &env
->gdt
);
5044 cpu_put_seg(f
, &env
->idt
);
5046 qemu_put_be32s(f
, &env
->sysenter_cs
);
5047 qemu_put_be32s(f
, &env
->sysenter_esp
);
5048 qemu_put_be32s(f
, &env
->sysenter_eip
);
5050 qemu_put_betls(f
, &env
->cr
[0]);
5051 qemu_put_betls(f
, &env
->cr
[2]);
5052 qemu_put_betls(f
, &env
->cr
[3]);
5053 qemu_put_betls(f
, &env
->cr
[4]);
5055 for(i
= 0; i
< 8; i
++)
5056 qemu_put_betls(f
, &env
->dr
[i
]);
5059 qemu_put_be32s(f
, &env
->a20_mask
);
5062 qemu_put_be32s(f
, &env
->mxcsr
);
5063 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5064 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5065 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5068 #ifdef TARGET_X86_64
5069 qemu_put_be64s(f
, &env
->efer
);
5070 qemu_put_be64s(f
, &env
->star
);
5071 qemu_put_be64s(f
, &env
->lstar
);
5072 qemu_put_be64s(f
, &env
->cstar
);
5073 qemu_put_be64s(f
, &env
->fmask
);
5074 qemu_put_be64s(f
, &env
->kernelgsbase
);
5076 qemu_put_be32s(f
, &env
->smbase
);
5079 #ifdef USE_X86LDOUBLE
5080 /* XXX: add that in a FPU generic layer */
5081 union x86_longdouble
{
5086 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5087 #define EXPBIAS1 1023
5088 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5089 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5091 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5095 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5096 /* exponent + sign */
5097 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5098 e
|= SIGND1(temp
) >> 16;
5103 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5105 CPUState
*env
= opaque
;
5108 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5110 if (version_id
!= 3 && version_id
!= 4)
5112 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5113 qemu_get_betls(f
, &env
->regs
[i
]);
5114 qemu_get_betls(f
, &env
->eip
);
5115 qemu_get_betls(f
, &env
->eflags
);
5116 qemu_get_be32s(f
, &hflags
);
5118 qemu_get_be16s(f
, &fpuc
);
5119 qemu_get_be16s(f
, &fpus
);
5120 qemu_get_be16s(f
, &fptag
);
5121 qemu_get_be16s(f
, &fpregs_format
);
5123 /* NOTE: we cannot always restore the FPU state if the image come
5124 from a host with a different 'USE_X86LDOUBLE' define. We guess
5125 if we are in an MMX state to restore correctly in that case. */
5126 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5127 for(i
= 0; i
< 8; i
++) {
5131 switch(fpregs_format
) {
5133 mant
= qemu_get_be64(f
);
5134 exp
= qemu_get_be16(f
);
5135 #ifdef USE_X86LDOUBLE
5136 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5138 /* difficult case */
5140 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5142 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5146 mant
= qemu_get_be64(f
);
5147 #ifdef USE_X86LDOUBLE
5149 union x86_longdouble
*p
;
5150 /* difficult case */
5151 p
= (void *)&env
->fpregs
[i
];
5156 fp64_to_fp80(p
, mant
);
5160 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5169 /* XXX: restore FPU round state */
5170 env
->fpstt
= (fpus
>> 11) & 7;
5171 env
->fpus
= fpus
& ~0x3800;
5173 for(i
= 0; i
< 8; i
++) {
5174 env
->fptags
[i
] = (fptag
>> i
) & 1;
5177 for(i
= 0; i
< 6; i
++)
5178 cpu_get_seg(f
, &env
->segs
[i
]);
5179 cpu_get_seg(f
, &env
->ldt
);
5180 cpu_get_seg(f
, &env
->tr
);
5181 cpu_get_seg(f
, &env
->gdt
);
5182 cpu_get_seg(f
, &env
->idt
);
5184 qemu_get_be32s(f
, &env
->sysenter_cs
);
5185 qemu_get_be32s(f
, &env
->sysenter_esp
);
5186 qemu_get_be32s(f
, &env
->sysenter_eip
);
5188 qemu_get_betls(f
, &env
->cr
[0]);
5189 qemu_get_betls(f
, &env
->cr
[2]);
5190 qemu_get_betls(f
, &env
->cr
[3]);
5191 qemu_get_betls(f
, &env
->cr
[4]);
5193 for(i
= 0; i
< 8; i
++)
5194 qemu_get_betls(f
, &env
->dr
[i
]);
5197 qemu_get_be32s(f
, &env
->a20_mask
);
5199 qemu_get_be32s(f
, &env
->mxcsr
);
5200 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5201 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5202 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5205 #ifdef TARGET_X86_64
5206 qemu_get_be64s(f
, &env
->efer
);
5207 qemu_get_be64s(f
, &env
->star
);
5208 qemu_get_be64s(f
, &env
->lstar
);
5209 qemu_get_be64s(f
, &env
->cstar
);
5210 qemu_get_be64s(f
, &env
->fmask
);
5211 qemu_get_be64s(f
, &env
->kernelgsbase
);
5213 if (version_id
>= 4)
5214 qemu_get_be32s(f
, &env
->smbase
);
5216 /* XXX: compute hflags from scratch, except for CPL and IIF */
5217 env
->hflags
= hflags
;
5221 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5222 qemu_get_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
5224 qemu_get_be64s(f
, &env
->tsc
);
5225 kvm_load_registers(env
);
5231 #elif defined(TARGET_PPC)
5232 void cpu_save(QEMUFile
*f
, void *opaque
)
5236 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5241 #elif defined(TARGET_MIPS)
5242 void cpu_save(QEMUFile
*f
, void *opaque
)
5246 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5251 #elif defined(TARGET_SPARC)
5252 void cpu_save(QEMUFile
*f
, void *opaque
)
5254 CPUState
*env
= opaque
;
5258 for(i
= 0; i
< 8; i
++)
5259 qemu_put_betls(f
, &env
->gregs
[i
]);
5260 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5261 qemu_put_betls(f
, &env
->regbase
[i
]);
5264 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5270 qemu_put_be32(f
, u
.i
);
5273 qemu_put_betls(f
, &env
->pc
);
5274 qemu_put_betls(f
, &env
->npc
);
5275 qemu_put_betls(f
, &env
->y
);
5277 qemu_put_be32(f
, tmp
);
5278 qemu_put_betls(f
, &env
->fsr
);
5279 qemu_put_betls(f
, &env
->tbr
);
5280 #ifndef TARGET_SPARC64
5281 qemu_put_be32s(f
, &env
->wim
);
5283 for(i
= 0; i
< 16; i
++)
5284 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5289 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5290 qemu_put_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
5292 qemu_put_be64s(f
, &env
->tsc
);
5297 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5299 CPUState
*env
= opaque
;
5303 for(i
= 0; i
< 8; i
++)
5304 qemu_get_betls(f
, &env
->gregs
[i
]);
5305 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5306 qemu_get_betls(f
, &env
->regbase
[i
]);
5309 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5314 u
.i
= qemu_get_be32(f
);
5318 qemu_get_betls(f
, &env
->pc
);
5319 qemu_get_betls(f
, &env
->npc
);
5320 qemu_get_betls(f
, &env
->y
);
5321 tmp
= qemu_get_be32(f
);
5322 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5323 correctly updated */
5325 qemu_get_betls(f
, &env
->fsr
);
5326 qemu_get_betls(f
, &env
->tbr
);
5327 #ifndef TARGET_SPARC64
5328 qemu_get_be32s(f
, &env
->wim
);
5330 for(i
= 0; i
< 16; i
++)
5331 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5337 #elif defined(TARGET_ARM)
5339 /* ??? Need to implement these. */
5340 void cpu_save(QEMUFile
*f
, void *opaque
)
5344 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5351 #warning No CPU save/restore functions
5355 /***********************************************************/
5356 /* ram save/restore */
5358 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5362 v
= qemu_get_byte(f
);
5365 if (qemu_get_buffer(f
, buf
, len
) != len
)
5369 v
= qemu_get_byte(f
);
5370 memset(buf
, v
, len
);
5378 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5382 if (qemu_get_be32(f
) != phys_ram_size
)
5384 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5385 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5392 #define BDRV_HASH_BLOCK_SIZE 1024
5393 #define IOBUF_SIZE 4096
5394 #define RAM_CBLOCK_MAGIC 0xfabe
5396 typedef struct RamCompressState
{
5399 uint8_t buf
[IOBUF_SIZE
];
5402 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5405 memset(s
, 0, sizeof(*s
));
5407 ret
= deflateInit2(&s
->zstream
, 1,
5409 9, Z_DEFAULT_STRATEGY
);
5412 s
->zstream
.avail_out
= IOBUF_SIZE
;
5413 s
->zstream
.next_out
= s
->buf
;
5417 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5419 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5420 qemu_put_be16(s
->f
, len
);
5421 qemu_put_buffer(s
->f
, buf
, len
);
5424 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5428 s
->zstream
.avail_in
= len
;
5429 s
->zstream
.next_in
= (uint8_t *)buf
;
5430 while (s
->zstream
.avail_in
> 0) {
5431 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5434 if (s
->zstream
.avail_out
== 0) {
5435 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5436 s
->zstream
.avail_out
= IOBUF_SIZE
;
5437 s
->zstream
.next_out
= s
->buf
;
5443 static void ram_compress_close(RamCompressState
*s
)
5447 /* compress last bytes */
5449 ret
= deflate(&s
->zstream
, Z_FINISH
);
5450 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5451 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5453 ram_put_cblock(s
, s
->buf
, len
);
5455 s
->zstream
.avail_out
= IOBUF_SIZE
;
5456 s
->zstream
.next_out
= s
->buf
;
5457 if (ret
== Z_STREAM_END
)
5464 deflateEnd(&s
->zstream
);
5467 typedef struct RamDecompressState
{
5470 uint8_t buf
[IOBUF_SIZE
];
5471 } RamDecompressState
;
5473 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5476 memset(s
, 0, sizeof(*s
));
5478 ret
= inflateInit(&s
->zstream
);
5484 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5488 s
->zstream
.avail_out
= len
;
5489 s
->zstream
.next_out
= buf
;
5490 while (s
->zstream
.avail_out
> 0) {
5491 if (s
->zstream
.avail_in
== 0) {
5492 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5494 clen
= qemu_get_be16(s
->f
);
5495 if (clen
> IOBUF_SIZE
)
5497 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5498 s
->zstream
.avail_in
= clen
;
5499 s
->zstream
.next_in
= s
->buf
;
5501 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5502 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5509 static void ram_decompress_close(RamDecompressState
*s
)
5511 inflateEnd(&s
->zstream
);
5514 static void ram_save(QEMUFile
*f
, void *opaque
)
5517 RamCompressState s1
, *s
= &s1
;
5520 qemu_put_be32(f
, phys_ram_size
);
5521 if (ram_compress_open(s
, f
) < 0)
5523 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5525 if (tight_savevm_enabled
) {
5529 /* find if the memory block is available on a virtual
5532 for(j
= 0; j
< MAX_DISKS
; j
++) {
5534 sector_num
= bdrv_hash_find(bs_table
[j
],
5535 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5536 if (sector_num
>= 0)
5541 goto normal_compress
;
5544 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5545 ram_compress_buf(s
, buf
, 10);
5551 ram_compress_buf(s
, buf
, 1);
5552 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5555 ram_compress_close(s
);
5558 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5560 RamDecompressState s1
, *s
= &s1
;
5564 if (version_id
== 1)
5565 return ram_load_v1(f
, opaque
);
5566 if (version_id
!= 2)
5568 if (qemu_get_be32(f
) != phys_ram_size
)
5570 if (ram_decompress_open(s
, f
) < 0)
5572 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5573 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5574 fprintf(stderr
, "Error while reading ram block header\n");
5578 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5579 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5588 ram_decompress_buf(s
, buf
+ 1, 9);
5590 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5591 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5592 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5595 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5596 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5597 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5598 bs_index
, sector_num
);
5605 printf("Error block header\n");
5609 ram_decompress_close(s
);
5613 /***********************************************************/
5614 /* bottom halves (can be seen as timers which expire ASAP) */
5623 static QEMUBH
*first_bh
= NULL
;
5625 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5628 bh
= qemu_mallocz(sizeof(QEMUBH
));
5632 bh
->opaque
= opaque
;
5636 int qemu_bh_poll(void)
5655 void qemu_bh_schedule(QEMUBH
*bh
)
5657 CPUState
*env
= cpu_single_env
;
5661 bh
->next
= first_bh
;
5664 /* stop the currently executing CPU to execute the BH ASAP */
5666 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5670 void qemu_bh_cancel(QEMUBH
*bh
)
5673 if (bh
->scheduled
) {
5676 pbh
= &(*pbh
)->next
;
5682 void qemu_bh_delete(QEMUBH
*bh
)
5688 /***********************************************************/
5689 /* machine registration */
5691 QEMUMachine
*first_machine
= NULL
;
5693 int qemu_register_machine(QEMUMachine
*m
)
5696 pm
= &first_machine
;
5704 QEMUMachine
*find_machine(const char *name
)
5708 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5709 if (!strcmp(m
->name
, name
))
5715 /***********************************************************/
5716 /* main execution loop */
5718 void gui_update(void *opaque
)
5720 display_state
.dpy_refresh(&display_state
);
5721 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
5724 struct vm_change_state_entry
{
5725 VMChangeStateHandler
*cb
;
5727 LIST_ENTRY (vm_change_state_entry
) entries
;
5730 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
5732 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
5735 VMChangeStateEntry
*e
;
5737 e
= qemu_mallocz(sizeof (*e
));
5743 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
5747 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
5749 LIST_REMOVE (e
, entries
);
5753 static void vm_state_notify(int running
)
5755 VMChangeStateEntry
*e
;
5757 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
5758 e
->cb(e
->opaque
, running
);
5762 /* XXX: support several handlers */
5763 static VMStopHandler
*vm_stop_cb
;
5764 static void *vm_stop_opaque
;
5766 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
5769 vm_stop_opaque
= opaque
;
5773 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
5787 void vm_stop(int reason
)
5790 cpu_disable_ticks();
5794 vm_stop_cb(vm_stop_opaque
, reason
);
5801 /* reset/shutdown handler */
5803 typedef struct QEMUResetEntry
{
5804 QEMUResetHandler
*func
;
5806 struct QEMUResetEntry
*next
;
5809 static QEMUResetEntry
*first_reset_entry
;
5810 static int reset_requested
;
5811 static int shutdown_requested
;
5812 static int powerdown_requested
;
5814 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
5816 QEMUResetEntry
**pre
, *re
;
5818 pre
= &first_reset_entry
;
5819 while (*pre
!= NULL
)
5820 pre
= &(*pre
)->next
;
5821 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
5823 re
->opaque
= opaque
;
5828 static void qemu_system_reset(void)
5832 /* reset all devices */
5833 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
5834 re
->func(re
->opaque
);
5838 void qemu_system_reset_request(void)
5841 shutdown_requested
= 1;
5843 reset_requested
= 1;
5846 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5849 void qemu_system_shutdown_request(void)
5851 shutdown_requested
= 1;
5853 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5856 void qemu_system_powerdown_request(void)
5858 powerdown_requested
= 1;
5860 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
5863 void main_loop_wait(int timeout
)
5865 IOHandlerRecord
*ioh
, *ioh_next
;
5866 fd_set rfds
, wfds
, xfds
;
5872 /* XXX: need to suppress polling by better using win32 events */
5874 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
5875 ret
|= pe
->func(pe
->opaque
);
5878 if (ret
== 0 && timeout
> 0) {
5880 WaitObjects
*w
= &wait_objects
;
5882 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
5883 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
5884 if (w
->func
[ret
- WAIT_OBJECT_0
])
5885 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
5886 } else if (ret
== WAIT_TIMEOUT
) {
5888 err
= GetLastError();
5889 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
5893 /* poll any events */
5894 /* XXX: separate device handlers from system ones */
5899 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5901 (!ioh
->fd_read_poll
||
5902 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
5903 FD_SET(ioh
->fd
, &rfds
);
5907 if (ioh
->fd_write
) {
5908 FD_SET(ioh
->fd
, &wfds
);
5918 tv
.tv_usec
= timeout
* 1000;
5920 #if defined(CONFIG_SLIRP)
5922 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
5925 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
5927 /* XXX: better handling of removal */
5928 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh_next
) {
5929 ioh_next
= ioh
->next
;
5930 if (FD_ISSET(ioh
->fd
, &rfds
)) {
5931 ioh
->fd_read(ioh
->opaque
);
5933 if (FD_ISSET(ioh
->fd
, &wfds
)) {
5934 ioh
->fd_write(ioh
->opaque
);
5938 #if defined(CONFIG_SLIRP)
5945 slirp_select_poll(&rfds
, &wfds
, &xfds
);
5952 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
5953 qemu_get_clock(vm_clock
));
5954 /* run dma transfers, if any */
5958 /* real time timers */
5959 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
5960 qemu_get_clock(rt_clock
));
5963 static CPUState
*cur_cpu
;
5968 #ifdef CONFIG_PROFILER
5973 cur_cpu
= first_cpu
;
5980 env
= env
->next_cpu
;
5983 #ifdef CONFIG_PROFILER
5984 ti
= profile_getclock();
5986 ret
= cpu_exec(env
);
5987 #ifdef CONFIG_PROFILER
5988 qemu_time
+= profile_getclock() - ti
;
5990 if (ret
!= EXCP_HALTED
)
5992 /* all CPUs are halted ? */
5993 if (env
== cur_cpu
) {
6000 if (shutdown_requested
) {
6001 ret
= EXCP_INTERRUPT
;
6004 if (reset_requested
) {
6005 reset_requested
= 0;
6006 qemu_system_reset();
6009 kvm_load_registers(env
);
6011 ret
= EXCP_INTERRUPT
;
6013 if (powerdown_requested
) {
6014 powerdown_requested
= 0;
6015 qemu_system_powerdown();
6016 ret
= EXCP_INTERRUPT
;
6018 if (ret
== EXCP_DEBUG
) {
6019 vm_stop(EXCP_DEBUG
);
6021 /* if hlt instruction, we wait until the next IRQ */
6022 /* XXX: use timeout computed from timers */
6023 if (ret
== EXCP_HLT
)
6030 #ifdef CONFIG_PROFILER
6031 ti
= profile_getclock();
6033 main_loop_wait(timeout
);
6034 #ifdef CONFIG_PROFILER
6035 dev_time
+= profile_getclock() - ti
;
6038 cpu_disable_ticks();
6044 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6045 "usage: %s [options] [disk_image]\n"
6047 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6049 "Standard options:\n"
6050 "-M machine select emulated machine (-M ? for list)\n"
6051 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6052 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6053 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6054 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6055 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6056 "-snapshot write to temporary files instead of disk image files\n"
6058 "-no-quit disable SDL window close capability\n"
6061 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6063 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6064 "-smp n set the number of CPUs to 'n' [default=1]\n"
6065 "-nographic disable graphical output and redirect serial I/Os to console\n"
6067 "-k language use keyboard layout (for example \"fr\" for French)\n"
6070 "-audio-help print list of audio drivers and their options\n"
6071 "-soundhw c1,... enable audio support\n"
6072 " and only specified sound cards (comma separated list)\n"
6073 " use -soundhw ? to get the list of supported cards\n"
6074 " use -soundhw all to enable all of them\n"
6076 "-localtime set the real time clock to local time [default=utc]\n"
6077 "-full-screen start in full screen\n"
6079 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6081 "-usb enable the USB driver (will be the default soon)\n"
6082 "-usbdevice name add the host or guest USB device 'name'\n"
6083 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6084 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6087 "Network options:\n"
6088 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6089 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6091 "-net user[,vlan=n][,hostname=host]\n"
6092 " connect the user mode network stack to VLAN 'n' and send\n"
6093 " hostname 'host' to DHCP clients\n"
6096 "-net tap[,vlan=n],ifname=name\n"
6097 " connect the host TAP network interface to VLAN 'n'\n"
6099 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6100 " connect the host TAP network interface to VLAN 'n' and use\n"
6101 " the network script 'file' (default=%s);\n"
6102 " use 'script=no' to disable script execution;\n"
6103 " use 'fd=h' to connect to an already opened TAP interface\n"
6105 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6106 " connect the vlan 'n' to another VLAN using a socket connection\n"
6107 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6108 " connect the vlan 'n' to multicast maddr and port\n"
6109 "-net none use it alone to have zero network devices; if no -net option\n"
6110 " is provided, the default is '-net nic -net user'\n"
6113 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6115 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6117 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6118 " redirect TCP or UDP connections from host to guest [-net user]\n"
6121 "Linux boot specific:\n"
6122 "-kernel bzImage use 'bzImage' as kernel image\n"
6123 "-append cmdline use 'cmdline' as kernel command line\n"
6124 "-initrd file use 'file' as initial ram disk\n"
6126 "Debug/Expert options:\n"
6127 "-monitor dev redirect the monitor to char device 'dev'\n"
6128 "-serial dev redirect the serial port to char device 'dev'\n"
6129 "-parallel dev redirect the parallel port to char device 'dev'\n"
6130 "-pidfile file Write PID to 'file'\n"
6131 "-S freeze CPU at startup (use 'c' to start execution)\n"
6132 "-s wait gdb connection to port %d\n"
6133 "-p port change gdb connection port\n"
6134 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6135 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6136 " translation (t=none or lba) (usually qemu can guess them)\n"
6137 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6139 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6140 "-no-kqemu disable KQEMU kernel module usage\n"
6143 "-no-kvm disable KVM hardware virtualization\n"
6145 #ifdef USE_CODE_COPY
6146 "-no-code-copy disable code copy acceleration\n"
6149 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6150 " (default is CL-GD5446 PCI VGA)\n"
6151 "-no-acpi disable ACPI\n"
6153 "-no-reboot exit instead of rebooting\n"
6154 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6155 "-vnc display start a VNC server on display\n"
6157 "-daemonize daemonize QEMU after initializing\n"
6159 "-option-rom rom load a file, rom, into the option ROM space\n"
6161 "During emulation, the following keys are useful:\n"
6162 "ctrl-alt-f toggle full screen\n"
6163 "ctrl-alt-n switch to virtual console 'n'\n"
6164 "ctrl-alt toggle mouse and keyboard grab\n"
6166 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6171 DEFAULT_NETWORK_SCRIPT
,
6173 DEFAULT_GDBSTUB_PORT
,
6178 #define HAS_ARG 0x0001
6192 QEMU_OPTION_snapshot
,
6194 QEMU_OPTION_no_fd_bootchk
,
6197 QEMU_OPTION_nographic
,
6199 QEMU_OPTION_audio_help
,
6200 QEMU_OPTION_soundhw
,
6218 QEMU_OPTION_no_code_copy
,
6220 QEMU_OPTION_localtime
,
6221 QEMU_OPTION_cirrusvga
,
6223 QEMU_OPTION_std_vga
,
6224 QEMU_OPTION_monitor
,
6225 QEMU_OPTION_vmchannel
,
6227 QEMU_OPTION_parallel
,
6229 QEMU_OPTION_full_screen
,
6230 QEMU_OPTION_no_quit
,
6231 QEMU_OPTION_pidfile
,
6232 QEMU_OPTION_no_kqemu
,
6233 QEMU_OPTION_kernel_kqemu
,
6234 QEMU_OPTION_win2k_hack
,
6236 QEMU_OPTION_usbdevice
,
6239 QEMU_OPTION_no_acpi
,
6241 QEMU_OPTION_no_reboot
,
6242 QEMU_OPTION_daemonize
,
6243 QEMU_OPTION_option_rom
,
6244 QEMU_OPTION_semihosting
6247 typedef struct QEMUOption
{
6253 const QEMUOption qemu_options
[] = {
6254 { "h", 0, QEMU_OPTION_h
},
6255 { "help", 0, QEMU_OPTION_h
},
6257 { "M", HAS_ARG
, QEMU_OPTION_M
},
6258 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6259 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6260 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6261 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6262 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6263 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6264 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6265 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6266 { "snapshot", 0, QEMU_OPTION_snapshot
},
6268 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6270 { "m", HAS_ARG
, QEMU_OPTION_m
},
6271 { "nographic", 0, QEMU_OPTION_nographic
},
6272 { "k", HAS_ARG
, QEMU_OPTION_k
},
6274 { "audio-help", 0, QEMU_OPTION_audio_help
},
6275 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6278 { "net", HAS_ARG
, QEMU_OPTION_net
},
6280 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6282 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6284 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6287 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6288 { "append", HAS_ARG
, QEMU_OPTION_append
},
6289 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6291 { "S", 0, QEMU_OPTION_S
},
6292 { "s", 0, QEMU_OPTION_s
},
6293 { "p", HAS_ARG
, QEMU_OPTION_p
},
6294 { "d", HAS_ARG
, QEMU_OPTION_d
},
6295 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6296 { "L", HAS_ARG
, QEMU_OPTION_L
},
6297 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6299 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6300 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6303 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
6305 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6306 { "g", 1, QEMU_OPTION_g
},
6308 { "localtime", 0, QEMU_OPTION_localtime
},
6309 { "std-vga", 0, QEMU_OPTION_std_vga
},
6310 { "monitor", 1, QEMU_OPTION_monitor
},
6311 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
6312 { "serial", 1, QEMU_OPTION_serial
},
6313 { "parallel", 1, QEMU_OPTION_parallel
},
6314 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6315 { "full-screen", 0, QEMU_OPTION_full_screen
},
6317 { "no-quit", 0, QEMU_OPTION_no_quit
},
6319 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6320 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6321 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6322 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6323 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6325 /* temporary options */
6326 { "usb", 0, QEMU_OPTION_usb
},
6327 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6328 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6329 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6330 { "daemonize", 0, QEMU_OPTION_daemonize
},
6331 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6332 #if defined(TARGET_ARM)
6333 { "semihosting", 0, QEMU_OPTION_semihosting
},
6338 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6340 /* this stack is only used during signal handling */
6341 #define SIGNAL_STACK_SIZE 32768
6343 static uint8_t *signal_stack
;
6347 /* password input */
6349 static BlockDriverState
*get_bdrv(int index
)
6351 BlockDriverState
*bs
;
6354 bs
= bs_table
[index
];
6355 } else if (index
< 6) {
6356 bs
= fd_table
[index
- 4];
6363 static void read_passwords(void)
6365 BlockDriverState
*bs
;
6369 for(i
= 0; i
< 6; i
++) {
6371 if (bs
&& bdrv_is_encrypted(bs
)) {
6372 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6373 for(j
= 0; j
< 3; j
++) {
6374 monitor_readline("Password: ",
6375 1, password
, sizeof(password
));
6376 if (bdrv_set_key(bs
, password
) == 0)
6378 term_printf("invalid password\n");
6384 /* XXX: currently we cannot use simultaneously different CPUs */
6385 void register_machines(void)
6387 #if defined(TARGET_I386)
6388 qemu_register_machine(&pc_machine
);
6389 qemu_register_machine(&isapc_machine
);
6390 #elif defined(TARGET_PPC)
6391 qemu_register_machine(&heathrow_machine
);
6392 qemu_register_machine(&core99_machine
);
6393 qemu_register_machine(&prep_machine
);
6394 #elif defined(TARGET_MIPS)
6395 qemu_register_machine(&mips_machine
);
6396 qemu_register_machine(&mips_malta_machine
);
6397 #elif defined(TARGET_SPARC)
6398 #ifdef TARGET_SPARC64
6399 qemu_register_machine(&sun4u_machine
);
6401 qemu_register_machine(&sun4m_machine
);
6403 #elif defined(TARGET_ARM)
6404 qemu_register_machine(&integratorcp926_machine
);
6405 qemu_register_machine(&integratorcp1026_machine
);
6406 qemu_register_machine(&versatilepb_machine
);
6407 qemu_register_machine(&versatileab_machine
);
6408 qemu_register_machine(&realview_machine
);
6409 #elif defined(TARGET_SH4)
6410 qemu_register_machine(&shix_machine
);
6412 #error unsupported CPU
6417 struct soundhw soundhw
[] = {
6424 { .init_isa
= pcspk_audio_init
}
6429 "Creative Sound Blaster 16",
6432 { .init_isa
= SB16_init
}
6439 "Yamaha YMF262 (OPL3)",
6441 "Yamaha YM3812 (OPL2)",
6445 { .init_isa
= Adlib_init
}
6452 "Gravis Ultrasound GF1",
6455 { .init_isa
= GUS_init
}
6461 "ENSONIQ AudioPCI ES1370",
6464 { .init_pci
= es1370_init
}
6467 { NULL
, NULL
, 0, 0, { NULL
} }
6470 static void select_soundhw (const char *optarg
)
6474 if (*optarg
== '?') {
6477 printf ("Valid sound card names (comma separated):\n");
6478 for (c
= soundhw
; c
->name
; ++c
) {
6479 printf ("%-11s %s\n", c
->name
, c
->descr
);
6481 printf ("\n-soundhw all will enable all of the above\n");
6482 exit (*optarg
!= '?');
6490 if (!strcmp (optarg
, "all")) {
6491 for (c
= soundhw
; c
->name
; ++c
) {
6499 e
= strchr (p
, ',');
6500 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6502 for (c
= soundhw
; c
->name
; ++c
) {
6503 if (!strncmp (c
->name
, p
, l
)) {
6512 "Unknown sound card name (too big to show)\n");
6515 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6520 p
+= l
+ (e
!= NULL
);
6524 goto show_valid_cards
;
6530 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6532 exit(STATUS_CONTROL_C_EXIT
);
6537 #define MAX_NET_CLIENTS 32
6539 int main(int argc
, char **argv
)
6541 #ifdef CONFIG_GDBSTUB
6542 int use_gdbstub
, gdbstub_port
;
6545 int snapshot
, linux_boot
;
6546 const char *initrd_filename
;
6547 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6548 const char *kernel_filename
, *kernel_cmdline
;
6549 DisplayState
*ds
= &display_state
;
6550 int cyls
, heads
, secs
, translation
;
6551 char net_clients
[MAX_NET_CLIENTS
][256];
6554 const char *r
, *optarg
;
6555 CharDriverState
*monitor_hd
;
6556 char monitor_device
[128];
6557 CharDriverState
*vmchannel_hd
;
6558 char vmchannel_device
[128];
6559 char serial_devices
[MAX_SERIAL_PORTS
][128];
6560 int serial_device_index
;
6561 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6562 int parallel_device_index
;
6563 const char *loadvm
= NULL
;
6564 QEMUMachine
*machine
;
6565 char usb_devices
[MAX_USB_CMDLINE
][128];
6566 int usb_devices_index
;
6569 LIST_INIT (&vm_change_state_head
);
6572 struct sigaction act
;
6573 sigfillset(&act
.sa_mask
);
6575 act
.sa_handler
= SIG_IGN
;
6576 sigaction(SIGPIPE
, &act
, NULL
);
6579 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6580 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6581 QEMU to run on a single CPU */
6586 h
= GetCurrentProcess();
6587 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6588 for(i
= 0; i
< 32; i
++) {
6589 if (mask
& (1 << i
))
6594 SetProcessAffinityMask(h
, mask
);
6600 register_machines();
6601 machine
= first_machine
;
6602 initrd_filename
= NULL
;
6603 for(i
= 0; i
< MAX_FD
; i
++)
6604 fd_filename
[i
] = NULL
;
6605 for(i
= 0; i
< MAX_DISKS
; i
++)
6606 hd_filename
[i
] = NULL
;
6607 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6608 vga_ram_size
= VGA_RAM_SIZE
;
6609 bios_size
= BIOS_SIZE
;
6610 #ifdef CONFIG_GDBSTUB
6612 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6616 kernel_filename
= NULL
;
6617 kernel_cmdline
= "";
6623 cyls
= heads
= secs
= 0;
6624 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6625 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6627 vmchannel_device
[0] = '\0';
6629 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6630 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6631 serial_devices
[i
][0] = '\0';
6632 serial_device_index
= 0;
6634 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6635 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6636 parallel_devices
[i
][0] = '\0';
6637 parallel_device_index
= 0;
6639 usb_devices_index
= 0;
6644 /* default mac address of the first network interface */
6652 hd_filename
[0] = argv
[optind
++];
6654 const QEMUOption
*popt
;
6657 /* Treat --foo the same as -foo. */
6660 popt
= qemu_options
;
6663 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6667 if (!strcmp(popt
->name
, r
+ 1))
6671 if (popt
->flags
& HAS_ARG
) {
6672 if (optind
>= argc
) {
6673 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6677 optarg
= argv
[optind
++];
6682 switch(popt
->index
) {
6684 machine
= find_machine(optarg
);
6687 printf("Supported machines are:\n");
6688 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6689 printf("%-10s %s%s\n",
6691 m
== first_machine
? " (default)" : "");
6696 case QEMU_OPTION_initrd
:
6697 initrd_filename
= optarg
;
6699 case QEMU_OPTION_hda
:
6700 case QEMU_OPTION_hdb
:
6701 case QEMU_OPTION_hdc
:
6702 case QEMU_OPTION_hdd
:
6705 hd_index
= popt
->index
- QEMU_OPTION_hda
;
6706 hd_filename
[hd_index
] = optarg
;
6707 if (hd_index
== cdrom_index
)
6711 case QEMU_OPTION_snapshot
:
6714 case QEMU_OPTION_hdachs
:
6718 cyls
= strtol(p
, (char **)&p
, 0);
6719 if (cyls
< 1 || cyls
> 16383)
6724 heads
= strtol(p
, (char **)&p
, 0);
6725 if (heads
< 1 || heads
> 16)
6730 secs
= strtol(p
, (char **)&p
, 0);
6731 if (secs
< 1 || secs
> 63)
6735 if (!strcmp(p
, "none"))
6736 translation
= BIOS_ATA_TRANSLATION_NONE
;
6737 else if (!strcmp(p
, "lba"))
6738 translation
= BIOS_ATA_TRANSLATION_LBA
;
6739 else if (!strcmp(p
, "auto"))
6740 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6743 } else if (*p
!= '\0') {
6745 fprintf(stderr
, "qemu: invalid physical CHS format\n");
6750 case QEMU_OPTION_nographic
:
6751 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
6752 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
6755 case QEMU_OPTION_kernel
:
6756 kernel_filename
= optarg
;
6758 case QEMU_OPTION_append
:
6759 kernel_cmdline
= optarg
;
6761 case QEMU_OPTION_cdrom
:
6762 if (cdrom_index
>= 0) {
6763 hd_filename
[cdrom_index
] = optarg
;
6766 case QEMU_OPTION_boot
:
6767 boot_device
= optarg
[0];
6768 if (boot_device
!= 'a' &&
6769 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6771 boot_device
!= 'n' &&
6773 boot_device
!= 'c' && boot_device
!= 'd') {
6774 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
6778 case QEMU_OPTION_fda
:
6779 fd_filename
[0] = optarg
;
6781 case QEMU_OPTION_fdb
:
6782 fd_filename
[1] = optarg
;
6785 case QEMU_OPTION_no_fd_bootchk
:
6789 case QEMU_OPTION_no_code_copy
:
6790 code_copy_enabled
= 0;
6792 case QEMU_OPTION_net
:
6793 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
6794 fprintf(stderr
, "qemu: too many network clients\n");
6797 pstrcpy(net_clients
[nb_net_clients
],
6798 sizeof(net_clients
[0]),
6803 case QEMU_OPTION_tftp
:
6804 tftp_prefix
= optarg
;
6807 case QEMU_OPTION_smb
:
6808 net_slirp_smb(optarg
);
6811 case QEMU_OPTION_redir
:
6812 net_slirp_redir(optarg
);
6816 case QEMU_OPTION_audio_help
:
6820 case QEMU_OPTION_soundhw
:
6821 select_soundhw (optarg
);
6828 ram_size
= atoi(optarg
) * 1024 * 1024;
6831 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
6832 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
6833 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
6842 mask
= cpu_str_to_log_mask(optarg
);
6844 printf("Log items (comma separated):\n");
6845 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
6846 printf("%-10s %s\n", item
->name
, item
->help
);
6853 #ifdef CONFIG_GDBSTUB
6858 gdbstub_port
= atoi(optarg
);
6868 keyboard_layout
= optarg
;
6870 case QEMU_OPTION_localtime
:
6873 case QEMU_OPTION_cirrusvga
:
6874 cirrus_vga_enabled
= 1;
6876 case QEMU_OPTION_std_vga
:
6877 cirrus_vga_enabled
= 0;
6884 w
= strtol(p
, (char **)&p
, 10);
6887 fprintf(stderr
, "qemu: invalid resolution or depth\n");
6893 h
= strtol(p
, (char **)&p
, 10);
6898 depth
= strtol(p
, (char **)&p
, 10);
6899 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
6900 depth
!= 24 && depth
!= 32)
6902 } else if (*p
== '\0') {
6903 depth
= graphic_depth
;
6910 graphic_depth
= depth
;
6913 case QEMU_OPTION_monitor
:
6914 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
6916 case QEMU_OPTION_vmchannel
:
6917 pstrcpy(vmchannel_device
, sizeof(vmchannel_device
), optarg
);
6919 case QEMU_OPTION_serial
:
6920 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
6921 fprintf(stderr
, "qemu: too many serial ports\n");
6924 pstrcpy(serial_devices
[serial_device_index
],
6925 sizeof(serial_devices
[0]), optarg
);
6926 serial_device_index
++;
6928 case QEMU_OPTION_parallel
:
6929 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
6930 fprintf(stderr
, "qemu: too many parallel ports\n");
6933 pstrcpy(parallel_devices
[parallel_device_index
],
6934 sizeof(parallel_devices
[0]), optarg
);
6935 parallel_device_index
++;
6937 case QEMU_OPTION_loadvm
:
6940 case QEMU_OPTION_full_screen
:
6944 case QEMU_OPTION_no_quit
:
6948 case QEMU_OPTION_pidfile
:
6949 create_pidfile(optarg
);
6952 case QEMU_OPTION_win2k_hack
:
6953 win2k_install_hack
= 1;
6957 case QEMU_OPTION_no_kqemu
:
6960 case QEMU_OPTION_kernel_kqemu
:
6965 case QEMU_OPTION_no_kvm
:
6969 case QEMU_OPTION_usb
:
6972 case QEMU_OPTION_usbdevice
:
6974 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
6975 fprintf(stderr
, "Too many USB devices\n");
6978 pstrcpy(usb_devices
[usb_devices_index
],
6979 sizeof(usb_devices
[usb_devices_index
]),
6981 usb_devices_index
++;
6983 case QEMU_OPTION_smp
:
6984 smp_cpus
= atoi(optarg
);
6985 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
6986 fprintf(stderr
, "Invalid number of CPUs\n");
6990 case QEMU_OPTION_vnc
:
6991 vnc_display
= optarg
;
6993 case QEMU_OPTION_no_acpi
:
6996 case QEMU_OPTION_no_reboot
:
6999 case QEMU_OPTION_daemonize
:
7002 case QEMU_OPTION_option_rom
:
7003 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7004 fprintf(stderr
, "Too many option ROMs\n");
7007 option_rom
[nb_option_roms
] = optarg
;
7010 case QEMU_OPTION_semihosting
:
7011 semihosting_enabled
= 1;
7018 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
7019 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
7026 if (pipe(fds
) == -1)
7037 len
= read(fds
[0], &status
, 1);
7038 if (len
== -1 && (errno
== EINTR
))
7041 if (len
!= 1 || status
!= 0)
7059 signal(SIGTSTP
, SIG_IGN
);
7060 signal(SIGTTOU
, SIG_IGN
);
7061 signal(SIGTTIN
, SIG_IGN
);
7067 if (kvm_qemu_init() < 0) {
7068 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
7078 linux_boot
= (kernel_filename
!= NULL
);
7081 hd_filename
[0] == '\0' &&
7082 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7083 fd_filename
[0] == '\0')
7086 /* boot to floppy or the default cd if no hard disk defined yet */
7087 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7088 if (fd_filename
[0] != '\0')
7094 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7104 /* init network clients */
7105 if (nb_net_clients
== 0) {
7106 /* if no clients, we use a default config */
7107 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7109 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7114 for(i
= 0;i
< nb_net_clients
; i
++) {
7115 if (net_client_init(net_clients
[i
]) < 0)
7120 if (boot_device
== 'n') {
7121 for (i
= 0; i
< nb_nics
; i
++) {
7122 const char *model
= nd_table
[i
].model
;
7126 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7127 if (get_image_size(buf
) > 0) {
7128 option_rom
[nb_option_roms
] = strdup(buf
);
7134 fprintf(stderr
, "No valid PXE rom found for network device\n");
7137 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7141 /* init the memory */
7142 phys_ram_size
= ram_size
+ vga_ram_size
+ bios_size
;
7145 for (i
= 0; i
< nb_option_roms
; i
++) {
7146 int ret
= get_image_size(option_rom
[i
]);
7148 fprintf(stderr
, "Could not load option rom '%s'\n", option_rom
[i
]);
7151 phys_ram_size
+= ret
;
7155 /* Initialize kvm */
7157 phys_ram_size
+= KVM_EXTRA_PAGES
* 4096;
7158 if (kvm_qemu_create_context() < 0) {
7159 fprintf(stderr
, "Could not create KVM context\n");
7163 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7164 if (!phys_ram_base
) {
7165 fprintf(stderr
, "Could not allocate physical memory\n");
7170 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7171 if (!phys_ram_base
) {
7172 fprintf(stderr
, "Could not allocate physical memory\n");
7177 /* we always create the cdrom drive, even if no disk is there */
7179 if (cdrom_index
>= 0) {
7180 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7181 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7184 /* open the virtual block devices */
7185 for(i
= 0; i
< MAX_DISKS
; i
++) {
7186 if (hd_filename
[i
]) {
7189 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7190 bs_table
[i
] = bdrv_new(buf
);
7192 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7193 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7197 if (i
== 0 && cyls
!= 0) {
7198 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7199 bdrv_set_translation_hint(bs_table
[i
], translation
);
7204 /* we always create at least one floppy disk */
7205 fd_table
[0] = bdrv_new("fda");
7206 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7208 for(i
= 0; i
< MAX_FD
; i
++) {
7209 if (fd_filename
[i
]) {
7212 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7213 fd_table
[i
] = bdrv_new(buf
);
7214 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7216 if (fd_filename
[i
] != '\0') {
7217 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7218 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7219 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7227 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7228 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
7234 dumb_display_init(ds
);
7235 } else if (vnc_display
!= NULL
) {
7236 vnc_display_init(ds
, vnc_display
);
7238 #if defined(CONFIG_SDL)
7239 sdl_display_init(ds
, full_screen
);
7240 #elif defined(CONFIG_COCOA)
7241 cocoa_display_init(ds
, full_screen
);
7243 dumb_display_init(ds
);
7247 monitor_hd
= qemu_chr_open(monitor_device
);
7249 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7252 monitor_init(monitor_hd
, !nographic
);
7254 if (*vmchannel_device
) {
7255 vmchannel_hd
= qemu_chr_open(vmchannel_device
);
7256 if (!vmchannel_hd
) {
7257 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n", vmchannel_device
);
7260 vmchannel_init(vmchannel_hd
);
7263 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7264 const char *devname
= serial_devices
[i
];
7265 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7266 serial_hds
[i
] = qemu_chr_open(devname
);
7267 if (!serial_hds
[i
]) {
7268 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7272 if (!strcmp(devname
, "vc"))
7273 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7277 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7278 const char *devname
= parallel_devices
[i
];
7279 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7280 parallel_hds
[i
] = qemu_chr_open(devname
);
7281 if (!parallel_hds
[i
]) {
7282 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7286 if (!strcmp(devname
, "vc"))
7287 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7291 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7292 ds
, fd_filename
, snapshot
,
7293 kernel_filename
, kernel_cmdline
, initrd_filename
);
7295 /* init USB devices */
7297 for(i
= 0; i
< usb_devices_index
; i
++) {
7298 if (usb_device_add(usb_devices
[i
]) < 0) {
7299 fprintf(stderr
, "Warning: could not add USB device %s\n",
7305 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7306 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7308 #ifdef CONFIG_GDBSTUB
7310 /* XXX: use standard host:port notation and modify options
7312 if (gdbserver_start_port(gdbstub_port
) < 0) {
7313 fprintf(stderr
, "qemu: could not open gdbstub device on port '%d'\n",
7323 /* XXX: simplify init */
7336 len
= write(fds
[1], &status
, 1);
7337 if (len
== -1 && (errno
== EINTR
))
7343 fd
= open("/dev/null", O_RDWR
);