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 #if HOST_LONG_BITS < 64
106 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
108 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024 * 1024ULL)
112 #define DEFAULT_RAM_SIZE 144
114 #define DEFAULT_RAM_SIZE 128
117 #define GUI_REFRESH_INTERVAL 30
119 /* Max number of USB devices that can be specified on the commandline. */
120 #define MAX_USB_CMDLINE 8
122 /* XXX: use a two level table to limit memory usage */
123 #define MAX_IOPORTS 65536
125 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
126 char phys_ram_file
[1024];
127 void *ioport_opaque
[MAX_IOPORTS
];
128 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
129 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
130 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
131 to store the VM snapshots */
132 BlockDriverState
*bs_table
[MAX_DISKS
+ 1], *fd_table
[MAX_FD
];
133 /* point to the block driver where the snapshots are managed */
134 BlockDriverState
*bs_snapshots
;
137 static DisplayState display_state
;
139 const char* keyboard_layout
= NULL
;
140 int64_t ticks_per_sec
;
141 int boot_device
= 'c';
143 int pit_min_timer_count
= 0;
145 NICInfo nd_table
[MAX_NICS
];
146 QEMUTimer
*gui_timer
;
149 int cirrus_vga_enabled
= 1;
151 int graphic_width
= 1024;
152 int graphic_height
= 768;
154 int graphic_width
= 800;
155 int graphic_height
= 600;
157 int graphic_depth
= 15;
160 int balloon_used
= 0;
161 CharDriverState
*vmchannel_hds
[MAX_VMCHANNEL_DEVICES
];
162 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
163 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
165 int win2k_install_hack
= 0;
168 static VLANState
*first_vlan
;
170 const char *vnc_display
;
171 #if defined(TARGET_SPARC)
173 #elif defined(TARGET_I386)
178 int acpi_enabled
= 1;
182 const char *incoming
;
183 const char *option_rom
[MAX_OPTION_ROMS
];
185 int semihosting_enabled
= 0;
187 int time_drift_fix
= 0;
188 const char *cpu_vendor_string
;
190 /***********************************************************/
191 /* x86 ISA bus support */
193 target_phys_addr_t isa_mem_base
= 0;
196 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr
, "inb: port=0x%04x\n", address
);
204 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
211 /* default is to make two byte accesses */
212 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
215 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
216 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
217 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
221 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
223 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
224 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
225 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
228 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
230 #ifdef DEBUG_UNUSED_IOPORT
231 fprintf(stderr
, "inl: port=0x%04x\n", address
);
236 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
238 #ifdef DEBUG_UNUSED_IOPORT
239 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
243 void init_ioports(void)
247 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
248 ioport_read_table
[0][i
] = default_ioport_readb
;
249 ioport_write_table
[0][i
] = default_ioport_writeb
;
250 ioport_read_table
[1][i
] = default_ioport_readw
;
251 ioport_write_table
[1][i
] = default_ioport_writew
;
252 ioport_read_table
[2][i
] = default_ioport_readl
;
253 ioport_write_table
[2][i
] = default_ioport_writel
;
257 /* size is the word size in byte */
258 int register_ioport_read(int start
, int length
, int size
,
259 IOPortReadFunc
*func
, void *opaque
)
265 } else if (size
== 2) {
267 } else if (size
== 4) {
270 hw_error("register_ioport_read: invalid size");
273 for(i
= start
; i
< start
+ length
; i
+= size
) {
274 ioport_read_table
[bsize
][i
] = func
;
275 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
276 hw_error("register_ioport_read: invalid opaque");
277 ioport_opaque
[i
] = opaque
;
282 /* size is the word size in byte */
283 int register_ioport_write(int start
, int length
, int size
,
284 IOPortWriteFunc
*func
, void *opaque
)
290 } else if (size
== 2) {
292 } else if (size
== 4) {
295 hw_error("register_ioport_write: invalid size");
298 for(i
= start
; i
< start
+ length
; i
+= size
) {
299 ioport_write_table
[bsize
][i
] = func
;
300 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
301 hw_error("register_ioport_write: invalid opaque");
302 ioport_opaque
[i
] = opaque
;
307 void isa_unassign_ioport(int start
, int length
)
311 for(i
= start
; i
< start
+ length
; i
++) {
312 ioport_read_table
[0][i
] = default_ioport_readb
;
313 ioport_read_table
[1][i
] = default_ioport_readw
;
314 ioport_read_table
[2][i
] = default_ioport_readl
;
316 ioport_write_table
[0][i
] = default_ioport_writeb
;
317 ioport_write_table
[1][i
] = default_ioport_writew
;
318 ioport_write_table
[2][i
] = default_ioport_writel
;
322 /***********************************************************/
324 void cpu_outb(CPUState
*env
, int addr
, int val
)
327 if (loglevel
& CPU_LOG_IOPORT
)
328 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
330 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
333 env
->last_io_time
= cpu_get_time_fast();
337 void cpu_outw(CPUState
*env
, int addr
, int val
)
340 if (loglevel
& CPU_LOG_IOPORT
)
341 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
343 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
346 env
->last_io_time
= cpu_get_time_fast();
350 void cpu_outl(CPUState
*env
, int addr
, int val
)
353 if (loglevel
& CPU_LOG_IOPORT
)
354 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
356 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
359 env
->last_io_time
= cpu_get_time_fast();
363 int cpu_inb(CPUState
*env
, int addr
)
366 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
368 if (loglevel
& CPU_LOG_IOPORT
)
369 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
373 env
->last_io_time
= cpu_get_time_fast();
378 int cpu_inw(CPUState
*env
, int addr
)
381 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
383 if (loglevel
& CPU_LOG_IOPORT
)
384 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
388 env
->last_io_time
= cpu_get_time_fast();
393 int cpu_inl(CPUState
*env
, int addr
)
396 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
398 if (loglevel
& CPU_LOG_IOPORT
)
399 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
403 env
->last_io_time
= cpu_get_time_fast();
408 /***********************************************************/
409 void hw_error(const char *fmt
, ...)
415 fprintf(stderr
, "qemu: hardware error: ");
416 vfprintf(stderr
, fmt
, ap
);
417 fprintf(stderr
, "\n");
418 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
419 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
421 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
423 cpu_dump_state(env
, stderr
, fprintf
, 0);
430 /***********************************************************/
433 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
434 static void *qemu_put_kbd_event_opaque
;
435 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
436 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
438 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
440 qemu_put_kbd_event_opaque
= opaque
;
441 qemu_put_kbd_event
= func
;
444 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
445 void *opaque
, int absolute
,
448 QEMUPutMouseEntry
*s
, *cursor
;
450 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
454 s
->qemu_put_mouse_event
= func
;
455 s
->qemu_put_mouse_event_opaque
= opaque
;
456 s
->qemu_put_mouse_event_absolute
= absolute
;
457 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
460 if (!qemu_put_mouse_event_head
) {
461 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
465 cursor
= qemu_put_mouse_event_head
;
466 while (cursor
->next
!= NULL
)
467 cursor
= cursor
->next
;
470 qemu_put_mouse_event_current
= s
;
475 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
477 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
479 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
482 cursor
= qemu_put_mouse_event_head
;
483 while (cursor
!= NULL
&& cursor
!= entry
) {
485 cursor
= cursor
->next
;
488 if (cursor
== NULL
) // does not exist or list empty
490 else if (prev
== NULL
) { // entry is head
491 qemu_put_mouse_event_head
= cursor
->next
;
492 if (qemu_put_mouse_event_current
== entry
)
493 qemu_put_mouse_event_current
= cursor
->next
;
494 qemu_free(entry
->qemu_put_mouse_event_name
);
499 prev
->next
= entry
->next
;
501 if (qemu_put_mouse_event_current
== entry
)
502 qemu_put_mouse_event_current
= prev
;
504 qemu_free(entry
->qemu_put_mouse_event_name
);
508 void kbd_put_keycode(int keycode
)
510 if (qemu_put_kbd_event
) {
511 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
515 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
517 QEMUPutMouseEvent
*mouse_event
;
518 void *mouse_event_opaque
;
520 if (!qemu_put_mouse_event_current
) {
525 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
527 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
530 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
534 int kbd_mouse_is_absolute(void)
536 if (!qemu_put_mouse_event_current
)
539 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
542 void do_info_mice(void)
544 QEMUPutMouseEntry
*cursor
;
547 if (!qemu_put_mouse_event_head
) {
548 term_printf("No mouse devices connected\n");
552 term_printf("Mouse devices available:\n");
553 cursor
= qemu_put_mouse_event_head
;
554 while (cursor
!= NULL
) {
555 term_printf("%c Mouse #%d: %s\n",
556 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
557 index
, cursor
->qemu_put_mouse_event_name
);
559 cursor
= cursor
->next
;
563 void do_mouse_set(int index
)
565 QEMUPutMouseEntry
*cursor
;
568 if (!qemu_put_mouse_event_head
) {
569 term_printf("No mouse devices connected\n");
573 cursor
= qemu_put_mouse_event_head
;
574 while (cursor
!= NULL
&& index
!= i
) {
576 cursor
= cursor
->next
;
580 qemu_put_mouse_event_current
= cursor
;
582 term_printf("Mouse at given index not found\n");
585 /* compute with 96 bit intermediate result: (a*b)/c */
586 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
591 #ifdef WORDS_BIGENDIAN
601 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
602 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
605 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
609 /***********************************************************/
610 /* real time host monotonic timer */
612 #define QEMU_TIMER_BASE 1000000000LL
616 static int64_t clock_freq
;
618 static void init_get_clock(void)
622 ret
= QueryPerformanceFrequency(&freq
);
624 fprintf(stderr
, "Could not calibrate ticks\n");
627 clock_freq
= freq
.QuadPart
;
630 static int64_t get_clock(void)
633 QueryPerformanceCounter(&ti
);
634 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
639 static int use_rt_clock
;
641 static void init_get_clock(void)
644 #if defined(__linux__)
647 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
654 static int64_t get_clock(void)
656 #if defined(__linux__)
659 clock_gettime(CLOCK_MONOTONIC
, &ts
);
660 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
664 /* XXX: using gettimeofday leads to problems if the date
665 changes, so it should be avoided. */
667 gettimeofday(&tv
, NULL
);
668 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
674 /***********************************************************/
675 /* guest cycle counter */
677 static int64_t cpu_ticks_prev
;
678 static int64_t cpu_ticks_offset
;
679 static int64_t cpu_clock_offset
;
680 static int cpu_ticks_enabled
;
682 /* return the host CPU cycle counter and handle stop/restart */
683 int64_t cpu_get_ticks(void)
685 if (!cpu_ticks_enabled
) {
686 return cpu_ticks_offset
;
689 ticks
= cpu_get_real_ticks();
690 if (cpu_ticks_prev
> ticks
) {
691 /* Note: non increasing ticks may happen if the host uses
693 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
695 cpu_ticks_prev
= ticks
;
696 return ticks
+ cpu_ticks_offset
;
700 /* return the host CPU monotonic timer and handle stop/restart */
701 static int64_t cpu_get_clock(void)
704 if (!cpu_ticks_enabled
) {
705 return cpu_clock_offset
;
708 return ti
+ cpu_clock_offset
;
712 /* enable cpu_get_ticks() */
713 void cpu_enable_ticks(void)
715 if (!cpu_ticks_enabled
) {
716 cpu_ticks_offset
-= cpu_get_real_ticks();
717 cpu_clock_offset
-= get_clock();
718 cpu_ticks_enabled
= 1;
722 /* disable cpu_get_ticks() : the clock is stopped. You must not call
723 cpu_get_ticks() after that. */
724 void cpu_disable_ticks(void)
726 if (cpu_ticks_enabled
) {
727 cpu_ticks_offset
= cpu_get_ticks();
728 cpu_clock_offset
= cpu_get_clock();
729 cpu_ticks_enabled
= 0;
733 /***********************************************************/
736 #define QEMU_TIMER_REALTIME 0
737 #define QEMU_TIMER_VIRTUAL 1
741 /* XXX: add frequency */
749 struct QEMUTimer
*next
;
755 static QEMUTimer
*active_timers
[2];
757 static MMRESULT timerID
;
758 static HANDLE host_alarm
= NULL
;
759 static unsigned int period
= 1;
761 /* frequency of the times() clock tick */
762 static int timer_freq
;
765 QEMUClock
*qemu_new_clock(int type
)
768 clock
= qemu_mallocz(sizeof(QEMUClock
));
775 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
779 ts
= qemu_mallocz(sizeof(QEMUTimer
));
786 void qemu_free_timer(QEMUTimer
*ts
)
791 /* stop a timer, but do not dealloc it */
792 void qemu_del_timer(QEMUTimer
*ts
)
796 /* NOTE: this code must be signal safe because
797 qemu_timer_expired() can be called from a signal. */
798 pt
= &active_timers
[ts
->clock
->type
];
811 /* modify the current timer so that it will be fired when current_time
812 >= expire_time. The corresponding callback will be called. */
813 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
819 /* add the timer in the sorted list */
820 /* NOTE: this code must be signal safe because
821 qemu_timer_expired() can be called from a signal. */
822 pt
= &active_timers
[ts
->clock
->type
];
827 if (t
->expire_time
> expire_time
)
831 ts
->expire_time
= expire_time
;
836 int qemu_timer_pending(QEMUTimer
*ts
)
839 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
846 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
850 return (timer_head
->expire_time
<= current_time
);
853 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
859 if (!ts
|| ts
->expire_time
> current_time
)
861 /* remove timer from the list before calling the callback */
862 *ptimer_head
= ts
->next
;
865 /* run the callback (the timer list can be modified) */
870 int64_t qemu_get_clock(QEMUClock
*clock
)
872 switch(clock
->type
) {
873 case QEMU_TIMER_REALTIME
:
874 return get_clock() / 1000000;
876 case QEMU_TIMER_VIRTUAL
:
877 return cpu_get_clock();
881 static void init_timers(void)
884 ticks_per_sec
= QEMU_TIMER_BASE
;
885 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
886 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
890 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
892 uint64_t expire_time
;
894 if (qemu_timer_pending(ts
)) {
895 expire_time
= ts
->expire_time
;
899 qemu_put_be64(f
, expire_time
);
902 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
904 uint64_t expire_time
;
906 expire_time
= qemu_get_be64(f
);
907 if (expire_time
!= -1) {
908 qemu_mod_timer(ts
, expire_time
);
914 static void timer_save(QEMUFile
*f
, void *opaque
)
916 if (cpu_ticks_enabled
) {
917 hw_error("cannot save state if virtual timers are running");
919 qemu_put_be64s(f
, &cpu_ticks_offset
);
920 qemu_put_be64s(f
, &ticks_per_sec
);
921 qemu_put_be64s(f
, &cpu_clock_offset
);
924 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
926 if (version_id
!= 1 && version_id
!= 2)
928 if (cpu_ticks_enabled
) {
931 qemu_get_be64s(f
, &cpu_ticks_offset
);
932 qemu_get_be64s(f
, &ticks_per_sec
);
933 if (version_id
== 2) {
934 qemu_get_be64s(f
, &cpu_clock_offset
);
940 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
941 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
943 static void host_alarm_handler(int host_signum
)
947 #define DISP_FREQ 1000
949 static int64_t delta_min
= INT64_MAX
;
950 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
952 ti
= qemu_get_clock(vm_clock
);
953 if (last_clock
!= 0) {
954 delta
= ti
- last_clock
;
955 if (delta
< delta_min
)
957 if (delta
> delta_max
)
960 if (++count
== DISP_FREQ
) {
961 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
962 muldiv64(delta_min
, 1000000, ticks_per_sec
),
963 muldiv64(delta_max
, 1000000, ticks_per_sec
),
964 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
965 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
967 delta_min
= INT64_MAX
;
975 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
976 qemu_get_clock(vm_clock
)) ||
977 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
978 qemu_get_clock(rt_clock
))) {
980 SetEvent(host_alarm
);
982 CPUState
*env
= cpu_single_env
;
984 /* stop the currently executing cpu because a timer occured */
985 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
987 if (env
->kqemu_enabled
) {
988 kqemu_cpu_interrupt(env
);
997 #if defined(__linux__)
999 #define RTC_FREQ 1024
1001 static int use_rtc
= 1;
1004 static int start_rtc_timer(void)
1006 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1009 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1010 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1011 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1012 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1015 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1020 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1026 static int start_rtc_timer(void)
1031 #endif /* !defined(__linux__) */
1033 #endif /* !defined(_WIN32) */
1035 static void init_timer_alarm(void)
1042 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1043 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1044 if (period
< tc
.wPeriodMin
)
1045 period
= tc
.wPeriodMin
;
1046 timeBeginPeriod(period
);
1047 timerID
= timeSetEvent(1, // interval (ms)
1048 period
, // resolution
1049 host_alarm_handler
, // function
1050 (DWORD
)&count
, // user parameter
1051 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1053 perror("failed timer alarm");
1056 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1058 perror("failed CreateEvent");
1061 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1063 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1066 struct sigaction act
;
1067 struct itimerval itv
;
1069 /* get times() syscall frequency */
1070 timer_freq
= sysconf(_SC_CLK_TCK
);
1073 sigfillset(&act
.sa_mask
);
1075 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1076 act
.sa_flags
|= SA_ONSTACK
;
1078 act
.sa_handler
= host_alarm_handler
;
1079 sigaction(SIGALRM
, &act
, NULL
);
1081 itv
.it_interval
.tv_sec
= 0;
1082 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1083 itv
.it_value
.tv_sec
= 0;
1084 itv
.it_value
.tv_usec
= 10 * 1000;
1085 setitimer(ITIMER_REAL
, &itv
, NULL
);
1086 /* we probe the tick duration of the kernel to inform the user if
1087 the emulated kernel requested a too high timer frequency */
1088 getitimer(ITIMER_REAL
, &itv
);
1090 #if defined(__linux__)
1091 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1092 have timers with 1 ms resolution. The correct solution will
1093 be to use the POSIX real time timers available in recent
1095 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1096 /* try to use /dev/rtc to have a faster timer */
1097 if (!use_rtc
|| (start_rtc_timer() < 0))
1099 /* disable itimer */
1100 itv
.it_interval
.tv_sec
= 0;
1101 itv
.it_interval
.tv_usec
= 0;
1102 itv
.it_value
.tv_sec
= 0;
1103 itv
.it_value
.tv_usec
= 0;
1104 setitimer(ITIMER_REAL
, &itv
, NULL
);
1107 sigaction(SIGIO
, &act
, NULL
);
1108 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1109 fcntl(rtc_fd
, F_SETOWN
, getpid());
1111 #endif /* defined(__linux__) */
1114 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1115 PIT_FREQ
) / 1000000;
1121 void quit_timers(void)
1124 timeKillEvent(timerID
);
1125 timeEndPeriod(period
);
1127 CloseHandle(host_alarm
);
1133 /***********************************************************/
1134 /* character device */
1136 static void qemu_chr_event(CharDriverState
*s
, int event
)
1140 s
->chr_event(s
->handler_opaque
, event
);
1143 static void qemu_chr_reset_bh(void *opaque
)
1145 CharDriverState
*s
= opaque
;
1146 qemu_chr_event(s
, CHR_EVENT_RESET
);
1147 qemu_bh_delete(s
->bh
);
1151 void qemu_chr_reset(CharDriverState
*s
)
1153 if (s
->bh
== NULL
) {
1154 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1155 qemu_bh_schedule(s
->bh
);
1159 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1161 return s
->chr_write(s
, buf
, len
);
1164 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1168 return s
->chr_ioctl(s
, cmd
, arg
);
1171 int qemu_chr_can_read(CharDriverState
*s
)
1173 if (!s
->chr_can_read
)
1175 return s
->chr_can_read(s
->handler_opaque
);
1178 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1180 s
->chr_read(s
->handler_opaque
, buf
, len
);
1184 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1189 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1190 qemu_chr_write(s
, buf
, strlen(buf
));
1194 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1196 if (s
->chr_send_event
)
1197 s
->chr_send_event(s
, event
);
1200 void qemu_chr_add_handlers(CharDriverState
*s
,
1201 IOCanRWHandler
*fd_can_read
,
1202 IOReadHandler
*fd_read
,
1203 IOEventHandler
*fd_event
,
1206 s
->chr_can_read
= fd_can_read
;
1207 s
->chr_read
= fd_read
;
1208 s
->chr_event
= fd_event
;
1209 s
->handler_opaque
= opaque
;
1210 if (s
->chr_update_read_handler
)
1211 s
->chr_update_read_handler(s
);
1214 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1219 static CharDriverState
*qemu_chr_open_null(void)
1221 CharDriverState
*chr
;
1223 chr
= qemu_mallocz(sizeof(CharDriverState
));
1226 chr
->chr_write
= null_chr_write
;
1232 static void socket_cleanup(void)
1237 static int socket_init(void)
1242 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1244 err
= WSAGetLastError();
1245 fprintf(stderr
, "WSAStartup: %d\n", err
);
1248 atexit(socket_cleanup
);
1252 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1258 ret
= send(fd
, buf
, len
, 0);
1261 errno
= WSAGetLastError();
1262 if (errno
!= WSAEWOULDBLOCK
) {
1265 } else if (ret
== 0) {
1275 void socket_set_nonblock(int fd
)
1277 unsigned long opt
= 1;
1278 ioctlsocket(fd
, FIONBIO
, &opt
);
1283 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1289 ret
= write(fd
, buf
, len
);
1291 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1293 } else if (ret
== 0) {
1303 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1305 return unix_write(fd
, buf
, len1
);
1308 void socket_set_nonblock(int fd
)
1310 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1312 #endif /* !_WIN32 */
1321 #define STDIO_MAX_CLIENTS 2
1323 static int stdio_nb_clients
;
1324 static CharDriverState
*stdio_clients
[STDIO_MAX_CLIENTS
];
1326 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1328 FDCharDriver
*s
= chr
->opaque
;
1329 return unix_write(s
->fd_out
, buf
, len
);
1332 static int fd_chr_read_poll(void *opaque
)
1334 CharDriverState
*chr
= opaque
;
1335 FDCharDriver
*s
= chr
->opaque
;
1337 s
->max_size
= qemu_chr_can_read(chr
);
1341 static void fd_chr_read(void *opaque
)
1343 CharDriverState
*chr
= opaque
;
1344 FDCharDriver
*s
= chr
->opaque
;
1349 if (len
> s
->max_size
)
1353 size
= read(s
->fd_in
, buf
, len
);
1355 /* FD has been closed. Remove it from the active list. */
1356 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1360 qemu_chr_read(chr
, buf
, size
);
1364 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1366 FDCharDriver
*s
= chr
->opaque
;
1368 if (s
->fd_in
>= 0) {
1369 if (nographic
&& s
->fd_in
== 0) {
1371 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1372 fd_chr_read
, NULL
, chr
);
1377 /* open a character device to a unix fd */
1378 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1380 CharDriverState
*chr
;
1383 chr
= qemu_mallocz(sizeof(CharDriverState
));
1386 s
= qemu_mallocz(sizeof(FDCharDriver
));
1394 chr
->chr_write
= fd_chr_write
;
1395 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1397 qemu_chr_reset(chr
);
1402 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1406 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1409 return qemu_chr_open_fd(-1, fd_out
);
1412 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1415 char filename_in
[256], filename_out
[256];
1417 snprintf(filename_in
, 256, "%s.in", filename
);
1418 snprintf(filename_out
, 256, "%s.out", filename
);
1419 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1420 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1421 if (fd_in
< 0 || fd_out
< 0) {
1426 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1430 return qemu_chr_open_fd(fd_in
, fd_out
);
1434 /* for STDIO, we handle the case where several clients use it
1437 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1439 #define TERM_FIFO_MAX_SIZE 1
1441 static int term_got_escape
, client_index
;
1442 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1443 static int term_fifo_size
;
1444 static int term_timestamps
;
1445 static int64_t term_timestamps_start
;
1447 void term_print_help(void)
1450 "C-a h print this help\n"
1451 "C-a x exit emulator\n"
1452 "C-a s save disk data back to file (if -snapshot)\n"
1453 "C-a b send break (magic sysrq)\n"
1454 "C-a t toggle console timestamps\n"
1455 "C-a c switch between console and monitor\n"
1456 "C-a C-a send C-a\n"
1460 /* called when a char is received */
1461 static void stdio_received_byte(int ch
)
1463 if (term_got_escape
) {
1464 term_got_escape
= 0;
1475 for (i
= 0; i
< MAX_DISKS
; i
++) {
1477 bdrv_commit(bs_table
[i
]);
1482 if (client_index
< stdio_nb_clients
) {
1483 CharDriverState
*chr
;
1486 chr
= stdio_clients
[client_index
];
1488 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1493 if (client_index
>= stdio_nb_clients
)
1495 if (client_index
== 0) {
1496 /* send a new line in the monitor to get the prompt */
1502 term_timestamps
= !term_timestamps
;
1503 term_timestamps_start
= -1;
1508 } else if (ch
== TERM_ESCAPE
) {
1509 term_got_escape
= 1;
1512 if (client_index
< stdio_nb_clients
) {
1514 CharDriverState
*chr
;
1516 chr
= stdio_clients
[client_index
];
1517 if (qemu_chr_can_read(chr
) > 0) {
1519 qemu_chr_read(chr
, buf
, 1);
1520 } else if (term_fifo_size
== 0) {
1521 term_fifo
[term_fifo_size
++] = ch
;
1527 static int stdio_read_poll(void *opaque
)
1529 CharDriverState
*chr
;
1531 if (client_index
< stdio_nb_clients
) {
1532 chr
= stdio_clients
[client_index
];
1533 /* try to flush the queue if needed */
1534 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1535 qemu_chr_read(chr
, term_fifo
, 1);
1538 /* see if we can absorb more chars */
1539 if (term_fifo_size
== 0)
1548 static void stdio_read(void *opaque
)
1553 size
= read(0, buf
, 1);
1555 /* stdin has been closed. Remove it from the active list. */
1556 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1560 stdio_received_byte(buf
[0]);
1563 static int stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1565 FDCharDriver
*s
= chr
->opaque
;
1566 if (!term_timestamps
) {
1567 return unix_write(s
->fd_out
, buf
, len
);
1572 for(i
= 0; i
< len
; i
++) {
1573 unix_write(s
->fd_out
, buf
+ i
, 1);
1574 if (buf
[i
] == '\n') {
1579 if (term_timestamps_start
== -1)
1580 term_timestamps_start
= ti
;
1581 ti
-= term_timestamps_start
;
1582 secs
= ti
/ 1000000000;
1583 snprintf(buf1
, sizeof(buf1
),
1584 "[%02d:%02d:%02d.%03d] ",
1588 (int)((ti
/ 1000000) % 1000));
1589 unix_write(s
->fd_out
, buf1
, strlen(buf1
));
1596 /* init terminal so that we can grab keys */
1597 static struct termios oldtty
;
1598 static int old_fd0_flags
;
1600 static void term_exit(void)
1602 tcsetattr (0, TCSANOW
, &oldtty
);
1603 fcntl(0, F_SETFL
, old_fd0_flags
);
1606 static void term_init(void)
1610 tcgetattr (0, &tty
);
1612 old_fd0_flags
= fcntl(0, F_GETFL
);
1614 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1615 |INLCR
|IGNCR
|ICRNL
|IXON
);
1616 tty
.c_oflag
|= OPOST
;
1617 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1618 /* if graphical mode, we allow Ctrl-C handling */
1620 tty
.c_lflag
&= ~ISIG
;
1621 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1624 tty
.c_cc
[VTIME
] = 0;
1626 tcsetattr (0, TCSANOW
, &tty
);
1630 fcntl(0, F_SETFL
, O_NONBLOCK
);
1633 static CharDriverState
*qemu_chr_open_stdio(void)
1635 CharDriverState
*chr
;
1638 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1640 chr
= qemu_chr_open_fd(0, 1);
1641 chr
->chr_write
= stdio_write
;
1642 if (stdio_nb_clients
== 0)
1643 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, NULL
);
1644 client_index
= stdio_nb_clients
;
1646 if (stdio_nb_clients
!= 0)
1648 chr
= qemu_chr_open_fd(0, 1);
1650 stdio_clients
[stdio_nb_clients
++] = chr
;
1651 if (stdio_nb_clients
== 1) {
1652 /* set the terminal in raw mode */
1658 #if defined(__linux__)
1659 static CharDriverState
*qemu_chr_open_pty(void)
1662 char slave_name
[1024];
1663 int master_fd
, slave_fd
;
1665 /* Not satisfying */
1666 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1670 /* Disabling local echo and line-buffered output */
1671 tcgetattr (master_fd
, &tty
);
1672 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1674 tty
.c_cc
[VTIME
] = 0;
1675 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1677 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1678 return qemu_chr_open_fd(master_fd
, master_fd
);
1681 static void tty_serial_init(int fd
, int speed
,
1682 int parity
, int data_bits
, int stop_bits
)
1688 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1689 speed
, parity
, data_bits
, stop_bits
);
1691 tcgetattr (fd
, &tty
);
1733 cfsetispeed(&tty
, spd
);
1734 cfsetospeed(&tty
, spd
);
1736 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1737 |INLCR
|IGNCR
|ICRNL
|IXON
);
1738 tty
.c_oflag
|= OPOST
;
1739 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1740 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1761 tty
.c_cflag
|= PARENB
;
1764 tty
.c_cflag
|= PARENB
| PARODD
;
1768 tty
.c_cflag
|= CSTOPB
;
1770 tcsetattr (fd
, TCSANOW
, &tty
);
1773 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1775 FDCharDriver
*s
= chr
->opaque
;
1778 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1780 QEMUSerialSetParams
*ssp
= arg
;
1781 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1782 ssp
->data_bits
, ssp
->stop_bits
);
1785 case CHR_IOCTL_SERIAL_SET_BREAK
:
1787 int enable
= *(int *)arg
;
1789 tcsendbreak(s
->fd_in
, 1);
1798 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1800 CharDriverState
*chr
;
1803 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1806 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1807 tty_serial_init(fd
, 115200, 'N', 8, 1);
1808 chr
= qemu_chr_open_fd(fd
, fd
);
1811 chr
->chr_ioctl
= tty_serial_ioctl
;
1812 qemu_chr_reset(chr
);
1816 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1818 int fd
= (int)chr
->opaque
;
1822 case CHR_IOCTL_PP_READ_DATA
:
1823 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1825 *(uint8_t *)arg
= b
;
1827 case CHR_IOCTL_PP_WRITE_DATA
:
1828 b
= *(uint8_t *)arg
;
1829 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1832 case CHR_IOCTL_PP_READ_CONTROL
:
1833 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1835 *(uint8_t *)arg
= b
;
1837 case CHR_IOCTL_PP_WRITE_CONTROL
:
1838 b
= *(uint8_t *)arg
;
1839 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1842 case CHR_IOCTL_PP_READ_STATUS
:
1843 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1845 *(uint8_t *)arg
= b
;
1853 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
1855 CharDriverState
*chr
;
1858 fd
= open(filename
, O_RDWR
);
1862 if (ioctl(fd
, PPCLAIM
) < 0) {
1867 chr
= qemu_mallocz(sizeof(CharDriverState
));
1872 chr
->opaque
= (void *)fd
;
1873 chr
->chr_write
= null_chr_write
;
1874 chr
->chr_ioctl
= pp_ioctl
;
1876 qemu_chr_reset(chr
);
1882 static CharDriverState
*qemu_chr_open_pty(void)
1888 #endif /* !defined(_WIN32) */
1892 CharDriverState
*chr
;
1894 HANDLE hcom
, hrecv
, hsend
;
1895 OVERLAPPED orecv
, osend
;
1900 #define NSENDBUF 2048
1901 #define NRECVBUF 2048
1902 #define MAXCONNECT 1
1903 #define NTIMEOUT 5000
1905 static int win_chr_poll(void *opaque
);
1906 static int win_chr_pipe_poll(void *opaque
);
1908 static void win_chr_close2(WinCharState
*s
)
1911 CloseHandle(s
->hsend
);
1915 CloseHandle(s
->hrecv
);
1919 CloseHandle(s
->hcom
);
1923 qemu_del_polling_cb(win_chr_pipe_poll
, s
);
1925 qemu_del_polling_cb(win_chr_poll
, s
);
1928 static void win_chr_close(CharDriverState
*chr
)
1930 WinCharState
*s
= chr
->opaque
;
1934 static int win_chr_init(WinCharState
*s
, CharDriverState
*chr
, const char *filename
)
1937 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1942 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1944 fprintf(stderr
, "Failed CreateEvent\n");
1947 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1949 fprintf(stderr
, "Failed CreateEvent\n");
1953 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1954 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1955 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1956 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1961 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1962 fprintf(stderr
, "Failed SetupComm\n");
1966 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1967 size
= sizeof(COMMCONFIG
);
1968 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1969 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1970 CommConfigDialog(filename
, NULL
, &comcfg
);
1972 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1973 fprintf(stderr
, "Failed SetCommState\n");
1977 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1978 fprintf(stderr
, "Failed SetCommMask\n");
1982 cto
.ReadIntervalTimeout
= MAXDWORD
;
1983 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1984 fprintf(stderr
, "Failed SetCommTimeouts\n");
1988 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1989 fprintf(stderr
, "Failed ClearCommError\n");
1993 qemu_add_polling_cb(win_chr_poll
, s
);
2001 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2003 WinCharState
*s
= chr
->opaque
;
2004 DWORD len
, ret
, size
, err
;
2007 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2008 s
->osend
.hEvent
= s
->hsend
;
2011 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2013 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2015 err
= GetLastError();
2016 if (err
== ERROR_IO_PENDING
) {
2017 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2035 static int win_chr_read_poll(WinCharState
*s
)
2037 s
->max_size
= qemu_chr_can_read(s
->chr
);
2041 static void win_chr_readfile(WinCharState
*s
)
2047 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2048 s
->orecv
.hEvent
= s
->hrecv
;
2049 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2051 err
= GetLastError();
2052 if (err
== ERROR_IO_PENDING
) {
2053 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2058 qemu_chr_read(s
->chr
, buf
, size
);
2062 static void win_chr_read(WinCharState
*s
)
2064 if (s
->len
> s
->max_size
)
2065 s
->len
= s
->max_size
;
2069 win_chr_readfile(s
);
2072 static int win_chr_poll(void *opaque
)
2074 WinCharState
*s
= opaque
;
2078 ClearCommError(s
->hcom
, &comerr
, &status
);
2079 if (status
.cbInQue
> 0) {
2080 s
->len
= status
.cbInQue
;
2081 win_chr_read_poll(s
);
2088 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2090 CharDriverState
*chr
;
2093 chr
= qemu_mallocz(sizeof(CharDriverState
));
2096 s
= qemu_mallocz(sizeof(WinCharState
));
2102 chr
->chr_write
= win_chr_write
;
2103 chr
->chr_close
= win_chr_close
;
2105 if (win_chr_init(s
, chr
, filename
) < 0) {
2110 qemu_chr_reset(chr
);
2114 static int win_chr_pipe_poll(void *opaque
)
2116 WinCharState
*s
= opaque
;
2119 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2122 win_chr_read_poll(s
);
2129 static int win_chr_pipe_init(WinCharState
*s
, const char *filename
)
2138 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2140 fprintf(stderr
, "Failed CreateEvent\n");
2143 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2145 fprintf(stderr
, "Failed CreateEvent\n");
2149 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2150 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2151 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2153 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2154 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2155 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2160 ZeroMemory(&ov
, sizeof(ov
));
2161 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2162 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2164 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2168 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2170 fprintf(stderr
, "Failed GetOverlappedResult\n");
2172 CloseHandle(ov
.hEvent
);
2179 CloseHandle(ov
.hEvent
);
2182 qemu_add_polling_cb(win_chr_pipe_poll
, s
);
2191 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2193 CharDriverState
*chr
;
2196 chr
= qemu_mallocz(sizeof(CharDriverState
));
2199 s
= qemu_mallocz(sizeof(WinCharState
));
2205 chr
->chr_write
= win_chr_write
;
2206 chr
->chr_close
= win_chr_close
;
2208 if (win_chr_pipe_init(s
, filename
) < 0) {
2213 qemu_chr_reset(chr
);
2217 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2219 CharDriverState
*chr
;
2222 chr
= qemu_mallocz(sizeof(CharDriverState
));
2225 s
= qemu_mallocz(sizeof(WinCharState
));
2232 chr
->chr_write
= win_chr_write
;
2233 qemu_chr_reset(chr
);
2237 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2241 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2242 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2243 if (fd_out
== INVALID_HANDLE_VALUE
)
2246 return qemu_chr_open_win_file(fd_out
);
2250 /***********************************************************/
2251 /* UDP Net console */
2255 struct sockaddr_in daddr
;
2262 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2264 NetCharDriver
*s
= chr
->opaque
;
2266 return sendto(s
->fd
, buf
, len
, 0,
2267 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2270 static int udp_chr_read_poll(void *opaque
)
2272 CharDriverState
*chr
= opaque
;
2273 NetCharDriver
*s
= chr
->opaque
;
2275 s
->max_size
= qemu_chr_can_read(chr
);
2277 /* If there were any stray characters in the queue process them
2280 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2281 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2283 s
->max_size
= qemu_chr_can_read(chr
);
2288 static void udp_chr_read(void *opaque
)
2290 CharDriverState
*chr
= opaque
;
2291 NetCharDriver
*s
= chr
->opaque
;
2293 if (s
->max_size
== 0)
2295 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2296 s
->bufptr
= s
->bufcnt
;
2301 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2302 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2304 s
->max_size
= qemu_chr_can_read(chr
);
2308 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2310 NetCharDriver
*s
= chr
->opaque
;
2313 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2314 udp_chr_read
, NULL
, chr
);
2319 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2321 int parse_host_src_port(struct sockaddr_in
*haddr
,
2322 struct sockaddr_in
*saddr
,
2325 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2327 CharDriverState
*chr
= NULL
;
2328 NetCharDriver
*s
= NULL
;
2330 struct sockaddr_in saddr
;
2332 chr
= qemu_mallocz(sizeof(CharDriverState
));
2335 s
= qemu_mallocz(sizeof(NetCharDriver
));
2339 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2341 perror("socket(PF_INET, SOCK_DGRAM)");
2345 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2346 printf("Could not parse: %s\n", def
);
2350 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2360 chr
->chr_write
= udp_chr_write
;
2361 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2374 /***********************************************************/
2375 /* TCP Net console */
2386 static void tcp_chr_accept(void *opaque
);
2388 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2390 TCPCharDriver
*s
= chr
->opaque
;
2392 return send_all(s
->fd
, buf
, len
);
2394 /* XXX: indicate an error ? */
2399 static int tcp_chr_read_poll(void *opaque
)
2401 CharDriverState
*chr
= opaque
;
2402 TCPCharDriver
*s
= chr
->opaque
;
2405 s
->max_size
= qemu_chr_can_read(chr
);
2410 #define IAC_BREAK 243
2411 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2413 char *buf
, int *size
)
2415 /* Handle any telnet client's basic IAC options to satisfy char by
2416 * char mode with no echo. All IAC options will be removed from
2417 * the buf and the do_telnetopt variable will be used to track the
2418 * state of the width of the IAC information.
2420 * IAC commands come in sets of 3 bytes with the exception of the
2421 * "IAC BREAK" command and the double IAC.
2427 for (i
= 0; i
< *size
; i
++) {
2428 if (s
->do_telnetopt
> 1) {
2429 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2430 /* Double IAC means send an IAC */
2434 s
->do_telnetopt
= 1;
2436 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2437 /* Handle IAC break commands by sending a serial break */
2438 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2443 if (s
->do_telnetopt
>= 4) {
2444 s
->do_telnetopt
= 1;
2447 if ((unsigned char)buf
[i
] == IAC
) {
2448 s
->do_telnetopt
= 2;
2459 static void tcp_chr_read(void *opaque
)
2461 CharDriverState
*chr
= opaque
;
2462 TCPCharDriver
*s
= chr
->opaque
;
2466 if (!s
->connected
|| s
->max_size
<= 0)
2469 if (len
> s
->max_size
)
2471 size
= recv(s
->fd
, buf
, len
, 0);
2473 /* connection closed */
2475 if (s
->listen_fd
>= 0) {
2476 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2478 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2481 } else if (size
> 0) {
2482 if (s
->do_telnetopt
)
2483 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2485 qemu_chr_read(chr
, buf
, size
);
2489 static void tcp_chr_connect(void *opaque
)
2491 CharDriverState
*chr
= opaque
;
2492 TCPCharDriver
*s
= chr
->opaque
;
2495 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2496 tcp_chr_read
, NULL
, chr
);
2497 qemu_chr_reset(chr
);
2500 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2501 static void tcp_chr_telnet_init(int fd
)
2504 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2505 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2506 send(fd
, (char *)buf
, 3, 0);
2507 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2508 send(fd
, (char *)buf
, 3, 0);
2509 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2510 send(fd
, (char *)buf
, 3, 0);
2511 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2512 send(fd
, (char *)buf
, 3, 0);
2515 static void socket_set_nodelay(int fd
)
2518 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2521 static void tcp_chr_accept(void *opaque
)
2523 CharDriverState
*chr
= opaque
;
2524 TCPCharDriver
*s
= chr
->opaque
;
2525 struct sockaddr_in saddr
;
2527 struct sockaddr_un uaddr
;
2529 struct sockaddr
*addr
;
2536 len
= sizeof(uaddr
);
2537 addr
= (struct sockaddr
*)&uaddr
;
2541 len
= sizeof(saddr
);
2542 addr
= (struct sockaddr
*)&saddr
;
2544 fd
= accept(s
->listen_fd
, addr
, &len
);
2545 if (fd
< 0 && errno
!= EINTR
) {
2547 } else if (fd
>= 0) {
2548 if (s
->do_telnetopt
)
2549 tcp_chr_telnet_init(fd
);
2553 socket_set_nonblock(fd
);
2555 socket_set_nodelay(fd
);
2557 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2558 tcp_chr_connect(chr
);
2561 static void tcp_chr_close(CharDriverState
*chr
)
2563 TCPCharDriver
*s
= chr
->opaque
;
2566 if (s
->listen_fd
>= 0)
2567 closesocket(s
->listen_fd
);
2571 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2575 CharDriverState
*chr
= NULL
;
2576 TCPCharDriver
*s
= NULL
;
2577 int fd
= -1, ret
, err
, val
;
2579 int is_waitconnect
= 1;
2582 struct sockaddr_in saddr
;
2584 struct sockaddr_un uaddr
;
2586 struct sockaddr
*addr
;
2591 addr
= (struct sockaddr
*)&uaddr
;
2592 addrlen
= sizeof(uaddr
);
2593 if (parse_unix_path(&uaddr
, host_str
) < 0)
2598 addr
= (struct sockaddr
*)&saddr
;
2599 addrlen
= sizeof(saddr
);
2600 if (parse_host_port(&saddr
, host_str
) < 0)
2605 while((ptr
= strchr(ptr
,','))) {
2607 if (!strncmp(ptr
,"server",6)) {
2609 } else if (!strncmp(ptr
,"nowait",6)) {
2611 } else if (!strncmp(ptr
,"nodelay",6)) {
2614 printf("Unknown option: %s\n", ptr
);
2621 chr
= qemu_mallocz(sizeof(CharDriverState
));
2624 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2630 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2633 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2638 if (!is_waitconnect
)
2639 socket_set_nonblock(fd
);
2644 s
->is_unix
= is_unix
;
2645 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2648 chr
->chr_write
= tcp_chr_write
;
2649 chr
->chr_close
= tcp_chr_close
;
2652 /* allow fast reuse */
2656 strncpy(path
, uaddr
.sun_path
, 108);
2663 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2666 ret
= bind(fd
, addr
, addrlen
);
2670 ret
= listen(fd
, 0);
2675 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2677 s
->do_telnetopt
= 1;
2680 ret
= connect(fd
, addr
, addrlen
);
2682 err
= socket_error();
2683 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2684 } else if (err
== EINPROGRESS
) {
2695 socket_set_nodelay(fd
);
2697 tcp_chr_connect(chr
);
2699 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2702 if (is_listen
&& is_waitconnect
) {
2703 printf("QEMU waiting for connection on: %s\n", host_str
);
2704 tcp_chr_accept(chr
);
2705 socket_set_nonblock(s
->listen_fd
);
2717 CharDriverState
*qemu_chr_open(const char *filename
)
2721 if (!strcmp(filename
, "vc")) {
2722 return text_console_init(&display_state
);
2723 } else if (!strcmp(filename
, "null")) {
2724 return qemu_chr_open_null();
2726 if (strstart(filename
, "tcp:", &p
)) {
2727 return qemu_chr_open_tcp(p
, 0, 0);
2729 if (strstart(filename
, "telnet:", &p
)) {
2730 return qemu_chr_open_tcp(p
, 1, 0);
2732 if (strstart(filename
, "udp:", &p
)) {
2733 return qemu_chr_open_udp(p
);
2736 if (strstart(filename
, "unix:", &p
)) {
2737 return qemu_chr_open_tcp(p
, 0, 1);
2738 } else if (strstart(filename
, "file:", &p
)) {
2739 return qemu_chr_open_file_out(p
);
2740 } else if (strstart(filename
, "pipe:", &p
)) {
2741 return qemu_chr_open_pipe(p
);
2742 } else if (!strcmp(filename
, "pty")) {
2743 return qemu_chr_open_pty();
2744 } else if (!strcmp(filename
, "stdio")) {
2745 return qemu_chr_open_stdio();
2748 #if defined(__linux__)
2749 if (strstart(filename
, "/dev/parport", NULL
)) {
2750 return qemu_chr_open_pp(filename
);
2752 if (strstart(filename
, "/dev/", NULL
)) {
2753 return qemu_chr_open_tty(filename
);
2757 if (strstart(filename
, "COM", NULL
)) {
2758 return qemu_chr_open_win(filename
);
2760 if (strstart(filename
, "pipe:", &p
)) {
2761 return qemu_chr_open_win_pipe(p
);
2763 if (strstart(filename
, "file:", &p
)) {
2764 return qemu_chr_open_win_file_out(p
);
2772 void qemu_chr_close(CharDriverState
*chr
)
2775 chr
->chr_close(chr
);
2778 /***********************************************************/
2779 /* network device redirectors */
2781 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2785 for(i
=0;i
<size
;i
+=16) {
2789 fprintf(f
, "%08x ", i
);
2792 fprintf(f
, " %02x", buf
[i
+j
]);
2797 for(j
=0;j
<len
;j
++) {
2799 if (c
< ' ' || c
> '~')
2801 fprintf(f
, "%c", c
);
2807 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2810 for(i
= 0; i
< 6; i
++) {
2811 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
2824 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
2829 p1
= strchr(p
, sep
);
2835 if (len
> buf_size
- 1)
2837 memcpy(buf
, p
, len
);
2844 int parse_host_src_port(struct sockaddr_in
*haddr
,
2845 struct sockaddr_in
*saddr
,
2846 const char *input_str
)
2848 char *str
= strdup(input_str
);
2849 char *host_str
= str
;
2854 * Chop off any extra arguments at the end of the string which
2855 * would start with a comma, then fill in the src port information
2856 * if it was provided else use the "any address" and "any port".
2858 if ((ptr
= strchr(str
,',')))
2861 if ((src_str
= strchr(input_str
,'@'))) {
2866 if (parse_host_port(haddr
, host_str
) < 0)
2869 if (!src_str
|| *src_str
== '\0')
2872 if (parse_host_port(saddr
, src_str
) < 0)
2883 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
2891 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2893 saddr
->sin_family
= AF_INET
;
2894 if (buf
[0] == '\0') {
2895 saddr
->sin_addr
.s_addr
= 0;
2897 if (isdigit(buf
[0])) {
2898 if (!inet_aton(buf
, &saddr
->sin_addr
))
2901 if ((he
= gethostbyname(buf
)) == NULL
)
2903 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
2906 port
= strtol(p
, (char **)&r
, 0);
2909 saddr
->sin_port
= htons(port
);
2914 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
2919 len
= MIN(108, strlen(str
));
2920 p
= strchr(str
, ',');
2922 len
= MIN(len
, p
- str
);
2924 memset(uaddr
, 0, sizeof(*uaddr
));
2926 uaddr
->sun_family
= AF_UNIX
;
2927 memcpy(uaddr
->sun_path
, str
, len
);
2933 /* find or alloc a new VLAN */
2934 VLANState
*qemu_find_vlan(int id
)
2936 VLANState
**pvlan
, *vlan
;
2937 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2941 vlan
= qemu_mallocz(sizeof(VLANState
));
2946 pvlan
= &first_vlan
;
2947 while (*pvlan
!= NULL
)
2948 pvlan
= &(*pvlan
)->next
;
2953 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
2954 IOReadHandler
*fd_read
,
2955 IOCanRWHandler
*fd_can_read
,
2958 VLANClientState
*vc
, **pvc
;
2959 vc
= qemu_mallocz(sizeof(VLANClientState
));
2962 vc
->fd_read
= fd_read
;
2963 vc
->fd_can_read
= fd_can_read
;
2964 vc
->opaque
= opaque
;
2968 pvc
= &vlan
->first_client
;
2969 while (*pvc
!= NULL
)
2970 pvc
= &(*pvc
)->next
;
2975 int qemu_can_send_packet(VLANClientState
*vc1
)
2977 VLANState
*vlan
= vc1
->vlan
;
2978 VLANClientState
*vc
;
2980 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2982 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
2989 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
2991 VLANState
*vlan
= vc1
->vlan
;
2992 VLANClientState
*vc
;
2995 printf("vlan %d send:\n", vlan
->id
);
2996 hex_dump(stdout
, buf
, size
);
2998 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3000 vc
->fd_read(vc
->opaque
, buf
, size
);
3005 #if defined(CONFIG_SLIRP)
3007 /* slirp network adapter */
3009 static int slirp_inited
;
3010 static VLANClientState
*slirp_vc
;
3012 int slirp_can_output(void)
3014 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3017 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3020 printf("slirp output:\n");
3021 hex_dump(stdout
, pkt
, pkt_len
);
3025 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3028 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3031 printf("slirp input:\n");
3032 hex_dump(stdout
, buf
, size
);
3034 slirp_input(buf
, size
);
3037 static int net_slirp_init(VLANState
*vlan
)
3039 if (!slirp_inited
) {
3043 slirp_vc
= qemu_new_vlan_client(vlan
,
3044 slirp_receive
, NULL
, NULL
);
3045 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3049 static void net_slirp_redir(const char *redir_str
)
3054 struct in_addr guest_addr
;
3055 int host_port
, guest_port
;
3057 if (!slirp_inited
) {
3063 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3065 if (!strcmp(buf
, "tcp")) {
3067 } else if (!strcmp(buf
, "udp")) {
3073 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3075 host_port
= strtol(buf
, &r
, 0);
3079 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3081 if (buf
[0] == '\0') {
3082 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3084 if (!inet_aton(buf
, &guest_addr
))
3087 guest_port
= strtol(p
, &r
, 0);
3091 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3092 fprintf(stderr
, "qemu: could not set up redirection\n");
3097 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3105 static void smb_exit(void)
3109 char filename
[1024];
3111 /* erase all the files in the directory */
3112 d
= opendir(smb_dir
);
3117 if (strcmp(de
->d_name
, ".") != 0 &&
3118 strcmp(de
->d_name
, "..") != 0) {
3119 snprintf(filename
, sizeof(filename
), "%s/%s",
3120 smb_dir
, de
->d_name
);
3128 /* automatic user mode samba server configuration */
3129 void net_slirp_smb(const char *exported_dir
)
3131 char smb_conf
[1024];
3132 char smb_cmdline
[1024];
3135 if (!slirp_inited
) {
3140 /* XXX: better tmp dir construction */
3141 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3142 if (mkdir(smb_dir
, 0700) < 0) {
3143 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3146 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3148 f
= fopen(smb_conf
, "w");
3150 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3157 "socket address=127.0.0.1\n"
3158 "pid directory=%s\n"
3159 "lock directory=%s\n"
3160 "log file=%s/log.smbd\n"
3161 "smb passwd file=%s/smbpasswd\n"
3162 "security = share\n"
3177 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3178 SMBD_COMMAND
, smb_conf
);
3180 slirp_add_exec(0, smb_cmdline
, 4, 139);
3183 #endif /* !defined(_WIN32) */
3185 #endif /* CONFIG_SLIRP */
3187 #if !defined(_WIN32)
3189 typedef struct TAPState
{
3190 VLANClientState
*vc
;
3194 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3196 TAPState
*s
= opaque
;
3199 ret
= write(s
->fd
, buf
, size
);
3200 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3207 static void tap_send(void *opaque
)
3209 TAPState
*s
= opaque
;
3213 size
= read(s
->fd
, buf
, sizeof(buf
));
3215 qemu_send_packet(s
->vc
, buf
, size
);
3221 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3225 s
= qemu_mallocz(sizeof(TAPState
));
3229 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3230 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3231 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3236 static int tap_open(char *ifname
, int ifname_size
)
3242 fd
= open("/dev/tap", O_RDWR
);
3244 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3249 dev
= devname(s
.st_rdev
, S_IFCHR
);
3250 pstrcpy(ifname
, ifname_size
, dev
);
3252 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3255 #elif defined(__sun__)
3256 static int tap_open(char *ifname
, int ifname_size
)
3258 fprintf(stderr
, "warning: tap_open not yet implemented\n");
3262 static int tap_open(char *ifname
, int ifname_size
)
3267 fd
= open("/dev/net/tun", O_RDWR
);
3269 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3272 memset(&ifr
, 0, sizeof(ifr
));
3273 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3274 if (ifname
[0] != '\0')
3275 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3277 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3278 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3280 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3284 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3285 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3290 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3291 const char *setup_script
)
3294 int pid
, status
, fd
;
3299 if (ifname1
!= NULL
)
3300 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3303 fd
= tap_open(ifname
, sizeof(ifname
));
3307 if (!setup_script
|| !strcmp(setup_script
, "no"))
3309 if (setup_script
[0] != '\0') {
3310 /* try to launch network init script */
3315 *parg
++ = (char *)setup_script
;
3318 execv(setup_script
, args
);
3321 while (waitpid(pid
, &status
, 0) != pid
);
3322 if (!WIFEXITED(status
) ||
3323 WEXITSTATUS(status
) != 0) {
3324 fprintf(stderr
, "%s: could not launch network script\n",
3330 s
= net_tap_fd_init(vlan
, fd
);
3333 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3334 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3338 #endif /* !_WIN32 */
3340 /* network connection */
3341 typedef struct NetSocketState
{
3342 VLANClientState
*vc
;
3344 int state
; /* 0 = getting length, 1 = getting data */
3348 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3351 typedef struct NetSocketListenState
{
3354 } NetSocketListenState
;
3356 /* XXX: we consider we can send the whole packet without blocking */
3357 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3359 NetSocketState
*s
= opaque
;
3363 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3364 send_all(s
->fd
, buf
, size
);
3367 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3369 NetSocketState
*s
= opaque
;
3370 sendto(s
->fd
, buf
, size
, 0,
3371 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3374 static void net_socket_send(void *opaque
)
3376 NetSocketState
*s
= opaque
;
3381 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3383 err
= socket_error();
3384 if (err
!= EWOULDBLOCK
)
3386 } else if (size
== 0) {
3387 /* end of connection */
3389 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3395 /* reassemble a packet from the network */
3401 memcpy(s
->buf
+ s
->index
, buf
, l
);
3405 if (s
->index
== 4) {
3407 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3413 l
= s
->packet_len
- s
->index
;
3416 memcpy(s
->buf
+ s
->index
, buf
, l
);
3420 if (s
->index
>= s
->packet_len
) {
3421 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3430 static void net_socket_send_dgram(void *opaque
)
3432 NetSocketState
*s
= opaque
;
3435 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3439 /* end of connection */
3440 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3443 qemu_send_packet(s
->vc
, s
->buf
, size
);
3446 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3451 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3452 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3453 inet_ntoa(mcastaddr
->sin_addr
),
3454 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3458 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3460 perror("socket(PF_INET, SOCK_DGRAM)");
3465 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3466 (const char *)&val
, sizeof(val
));
3468 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3472 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3478 /* Add host to multicast group */
3479 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3480 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3482 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3483 (const char *)&imr
, sizeof(struct ip_mreq
));
3485 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3489 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3491 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3492 (const char *)&val
, sizeof(val
));
3494 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3498 socket_set_nonblock(fd
);
3506 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3509 struct sockaddr_in saddr
;
3511 socklen_t saddr_len
;
3514 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3515 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3516 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3520 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3522 if (saddr
.sin_addr
.s_addr
==0) {
3523 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3527 /* clone dgram socket */
3528 newfd
= net_socket_mcast_create(&saddr
);
3530 /* error already reported by net_socket_mcast_create() */
3534 /* clone newfd to fd, close newfd */
3539 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3540 fd
, strerror(errno
));
3545 s
= qemu_mallocz(sizeof(NetSocketState
));
3550 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3551 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3553 /* mcast: save bound address as dst */
3554 if (is_connected
) s
->dgram_dst
=saddr
;
3556 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3557 "socket: fd=%d (%s mcast=%s:%d)",
3558 fd
, is_connected
? "cloned" : "",
3559 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3563 static void net_socket_connect(void *opaque
)
3565 NetSocketState
*s
= opaque
;
3566 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3569 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3573 s
= qemu_mallocz(sizeof(NetSocketState
));
3577 s
->vc
= qemu_new_vlan_client(vlan
,
3578 net_socket_receive
, NULL
, s
);
3579 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3580 "socket: fd=%d", fd
);
3582 net_socket_connect(s
);
3584 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3589 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3592 int so_type
=-1, optlen
=sizeof(so_type
);
3594 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3595 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3600 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3602 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3604 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3605 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3606 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3611 static void net_socket_accept(void *opaque
)
3613 NetSocketListenState
*s
= opaque
;
3615 struct sockaddr_in saddr
;
3620 len
= sizeof(saddr
);
3621 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3622 if (fd
< 0 && errno
!= EINTR
) {
3624 } else if (fd
>= 0) {
3628 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3632 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3633 "socket: connection from %s:%d",
3634 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3638 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3640 NetSocketListenState
*s
;
3642 struct sockaddr_in saddr
;
3644 if (parse_host_port(&saddr
, host_str
) < 0)
3647 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3651 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3656 socket_set_nonblock(fd
);
3658 /* allow fast reuse */
3660 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3662 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3667 ret
= listen(fd
, 0);
3674 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3678 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3681 int fd
, connected
, ret
, err
;
3682 struct sockaddr_in saddr
;
3684 if (parse_host_port(&saddr
, host_str
) < 0)
3687 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3692 socket_set_nonblock(fd
);
3696 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3698 err
= socket_error();
3699 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3700 } else if (err
== EINPROGRESS
) {
3712 s
= net_socket_fd_init(vlan
, fd
, connected
);
3715 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3716 "socket: connect to %s:%d",
3717 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3721 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
3725 struct sockaddr_in saddr
;
3727 if (parse_host_port(&saddr
, host_str
) < 0)
3731 fd
= net_socket_mcast_create(&saddr
);
3735 s
= net_socket_fd_init(vlan
, fd
, 0);
3739 s
->dgram_dst
= saddr
;
3741 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3742 "socket: mcast=%s:%d",
3743 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3748 static int get_param_value(char *buf
, int buf_size
,
3749 const char *tag
, const char *str
)
3758 while (*p
!= '\0' && *p
!= '=') {
3759 if ((q
- option
) < sizeof(option
) - 1)
3767 if (!strcmp(tag
, option
)) {
3769 while (*p
!= '\0' && *p
!= ',') {
3770 if ((q
- buf
) < buf_size
- 1)
3777 while (*p
!= '\0' && *p
!= ',') {
3788 static int net_client_init(const char *str
)
3799 while (*p
!= '\0' && *p
!= ',') {
3800 if ((q
- device
) < sizeof(device
) - 1)
3808 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
3809 vlan_id
= strtol(buf
, NULL
, 0);
3811 vlan
= qemu_find_vlan(vlan_id
);
3813 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
3816 if (!strcmp(device
, "nic")) {
3820 if (nb_nics
>= MAX_NICS
) {
3821 fprintf(stderr
, "Too Many NICs\n");
3824 nd
= &nd_table
[nb_nics
];
3825 macaddr
= nd
->macaddr
;
3831 macaddr
[5] = 0x56 + nb_nics
;
3833 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
3834 if (parse_macaddr(macaddr
, buf
) < 0) {
3835 fprintf(stderr
, "invalid syntax for ethernet address\n");
3839 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
3840 nd
->model
= strdup(buf
);
3846 if (!strcmp(device
, "none")) {
3847 /* does nothing. It is needed to signal that no network cards
3852 if (!strcmp(device
, "user")) {
3853 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
3854 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
3856 ret
= net_slirp_init(vlan
);
3860 if (!strcmp(device
, "tap")) {
3862 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3863 fprintf(stderr
, "tap: no interface name\n");
3866 ret
= tap_win32_init(vlan
, ifname
);
3869 if (!strcmp(device
, "tap")) {
3871 char setup_script
[1024];
3873 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3874 fd
= strtol(buf
, NULL
, 0);
3876 if (net_tap_fd_init(vlan
, fd
))
3879 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3882 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
3883 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
3885 ret
= net_tap_init(vlan
, ifname
, setup_script
);
3889 if (!strcmp(device
, "socket")) {
3890 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3892 fd
= strtol(buf
, NULL
, 0);
3894 if (net_socket_fd_init(vlan
, fd
, 1))
3896 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
3897 ret
= net_socket_listen_init(vlan
, buf
);
3898 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
3899 ret
= net_socket_connect_init(vlan
, buf
);
3900 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
3901 ret
= net_socket_mcast_init(vlan
, buf
);
3903 fprintf(stderr
, "Unknown socket options: %s\n", p
);
3908 fprintf(stderr
, "Unknown network device: %s\n", device
);
3912 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
3918 void do_info_network(void)
3921 VLANClientState
*vc
;
3923 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3924 term_printf("VLAN %d devices:\n", vlan
->id
);
3925 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
3926 term_printf(" %s\n", vc
->info_str
);
3930 /***********************************************************/
3933 static USBPort
*used_usb_ports
;
3934 static USBPort
*free_usb_ports
;
3936 /* ??? Maybe change this to register a hub to keep track of the topology. */
3937 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
3938 usb_attachfn attach
)
3940 port
->opaque
= opaque
;
3941 port
->index
= index
;
3942 port
->attach
= attach
;
3943 port
->next
= free_usb_ports
;
3944 free_usb_ports
= port
;
3947 static int usb_device_add(const char *devname
)
3953 if (!free_usb_ports
)
3956 if (strstart(devname
, "host:", &p
)) {
3957 dev
= usb_host_device_open(p
);
3958 } else if (!strcmp(devname
, "mouse")) {
3959 dev
= usb_mouse_init();
3960 } else if (!strcmp(devname
, "tablet")) {
3961 dev
= usb_tablet_init();
3962 } else if (strstart(devname
, "disk:", &p
)) {
3963 dev
= usb_msd_init(p
);
3970 /* Find a USB port to add the device to. */
3971 port
= free_usb_ports
;
3975 /* Create a new hub and chain it on. */
3976 free_usb_ports
= NULL
;
3977 port
->next
= used_usb_ports
;
3978 used_usb_ports
= port
;
3980 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
3981 usb_attach(port
, hub
);
3982 port
= free_usb_ports
;
3985 free_usb_ports
= port
->next
;
3986 port
->next
= used_usb_ports
;
3987 used_usb_ports
= port
;
3988 usb_attach(port
, dev
);
3992 static int usb_device_del(const char *devname
)
4000 if (!used_usb_ports
)
4003 p
= strchr(devname
, '.');
4006 bus_num
= strtoul(devname
, NULL
, 0);
4007 addr
= strtoul(p
+ 1, NULL
, 0);
4011 lastp
= &used_usb_ports
;
4012 port
= used_usb_ports
;
4013 while (port
&& port
->dev
->addr
!= addr
) {
4014 lastp
= &port
->next
;
4022 *lastp
= port
->next
;
4023 usb_attach(port
, NULL
);
4024 dev
->handle_destroy(dev
);
4025 port
->next
= free_usb_ports
;
4026 free_usb_ports
= port
;
4030 void do_usb_add(const char *devname
)
4033 ret
= usb_device_add(devname
);
4035 term_printf("Could not add USB device '%s'\n", devname
);
4038 void do_usb_del(const char *devname
)
4041 ret
= usb_device_del(devname
);
4043 term_printf("Could not remove USB device '%s'\n", devname
);
4050 const char *speed_str
;
4053 term_printf("USB support not enabled\n");
4057 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4061 switch(dev
->speed
) {
4065 case USB_SPEED_FULL
:
4068 case USB_SPEED_HIGH
:
4075 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4076 0, dev
->addr
, speed_str
, dev
->devname
);
4080 /***********************************************************/
4083 static char *pid_filename
;
4085 /* Remove PID file. Called on normal exit */
4087 static void remove_pidfile(void)
4089 unlink (pid_filename
);
4092 static void create_pidfile(const char *filename
)
4094 struct stat pidstat
;
4097 /* Try to write our PID to the named file */
4098 if (stat(filename
, &pidstat
) < 0) {
4099 if (errno
== ENOENT
) {
4100 if ((f
= fopen (filename
, "w")) == NULL
) {
4101 perror("Opening pidfile");
4104 fprintf(f
, "%d\n", getpid());
4106 pid_filename
= qemu_strdup(filename
);
4107 if (!pid_filename
) {
4108 fprintf(stderr
, "Could not save PID filename");
4111 atexit(remove_pidfile
);
4114 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4120 /***********************************************************/
4123 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4127 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4131 static void dumb_refresh(DisplayState
*ds
)
4136 void dumb_display_init(DisplayState
*ds
)
4141 ds
->dpy_update
= dumb_update
;
4142 ds
->dpy_resize
= dumb_resize
;
4143 ds
->dpy_refresh
= dumb_refresh
;
4146 /***********************************************************/
4149 #define MAX_IO_HANDLERS 64
4151 typedef struct IOHandlerRecord
{
4153 IOCanRWHandler
*fd_read_poll
;
4155 IOHandler
*fd_write
;
4158 /* temporary data */
4160 struct IOHandlerRecord
*next
;
4163 static IOHandlerRecord
*first_io_handler
;
4165 /* XXX: fd_read_poll should be suppressed, but an API change is
4166 necessary in the character devices to suppress fd_can_read(). */
4167 int qemu_set_fd_handler2(int fd
,
4168 IOCanRWHandler
*fd_read_poll
,
4170 IOHandler
*fd_write
,
4173 IOHandlerRecord
**pioh
, *ioh
;
4175 if (!fd_read
&& !fd_write
) {
4176 pioh
= &first_io_handler
;
4181 if (ioh
->fd
== fd
) {
4188 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4192 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4195 ioh
->next
= first_io_handler
;
4196 first_io_handler
= ioh
;
4199 ioh
->fd_read_poll
= fd_read_poll
;
4200 ioh
->fd_read
= fd_read
;
4201 ioh
->fd_write
= fd_write
;
4202 ioh
->opaque
= opaque
;
4208 int qemu_set_fd_handler(int fd
,
4210 IOHandler
*fd_write
,
4213 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4216 /***********************************************************/
4217 /* Polling handling */
4219 typedef struct PollingEntry
{
4222 struct PollingEntry
*next
;
4225 static PollingEntry
*first_polling_entry
;
4227 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4229 PollingEntry
**ppe
, *pe
;
4230 pe
= qemu_mallocz(sizeof(PollingEntry
));
4234 pe
->opaque
= opaque
;
4235 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4240 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4242 PollingEntry
**ppe
, *pe
;
4243 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4245 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4254 /***********************************************************/
4255 /* Wait objects support */
4256 typedef struct WaitObjects
{
4258 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4259 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4260 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4263 static WaitObjects wait_objects
= {0};
4265 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4267 WaitObjects
*w
= &wait_objects
;
4269 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4271 w
->events
[w
->num
] = handle
;
4272 w
->func
[w
->num
] = func
;
4273 w
->opaque
[w
->num
] = opaque
;
4278 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4281 WaitObjects
*w
= &wait_objects
;
4284 for (i
= 0; i
< w
->num
; i
++) {
4285 if (w
->events
[i
] == handle
)
4288 w
->events
[i
] = w
->events
[i
+ 1];
4289 w
->func
[i
] = w
->func
[i
+ 1];
4290 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4298 #define SELF_ANNOUNCE_ROUNDS 5
4299 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4300 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4301 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4303 static int announce_self_create(uint8_t *buf
,
4306 uint32_t magic
= EXPERIMENTAL_MAGIC
;
4307 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
4309 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4311 memset(buf
, 0xff, 6); /* h_dst */
4312 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
4313 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
4314 memcpy(buf
+ 14, &magic
, 4); /* magic */
4316 return 18; /* len */
4319 static void qemu_announce_self(void)
4323 VLANClientState
*vc
;
4326 for (i
= 0; i
< nb_nics
; i
++) {
4327 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
4328 vlan
= nd_table
[i
].vlan
;
4329 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4330 if (vc
->fd_read
== tap_receive
) /* send only if tap */
4331 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
4332 vc
->fd_read(vc
->opaque
, buf
, len
);
4337 /***********************************************************/
4338 /* savevm/loadvm support */
4340 #define IO_BUF_SIZE 32768
4343 QEMUFilePutBufferFunc
*put_buffer
;
4344 QEMUFileGetBufferFunc
*get_buffer
;
4345 QEMUFileCloseFunc
*close
;
4348 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4351 int buf_size
; /* 0 when writing */
4352 uint8_t buf
[IO_BUF_SIZE
];
4355 typedef struct QEMUFileFD
4360 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4362 QEMUFileFD
*s
= opaque
;
4367 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
4369 if (errno
== EINTR
|| errno
== EAGAIN
)
4376 QEMUFile
*qemu_fopen_fd(int fd
)
4378 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
4380 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
4383 typedef struct QEMUFileUnix
4388 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4390 QEMUFileUnix
*s
= opaque
;
4391 fseek(s
->outfile
, pos
, SEEK_SET
);
4392 fwrite(buf
, 1, size
, s
->outfile
);
4395 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4397 QEMUFileUnix
*s
= opaque
;
4398 fseek(s
->outfile
, pos
, SEEK_SET
);
4399 return fread(buf
, 1, size
, s
->outfile
);
4402 static void file_close(void *opaque
)
4404 QEMUFileUnix
*s
= opaque
;
4409 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
4413 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
4417 s
->outfile
= fopen(filename
, mode
);
4421 if (!strcmp(mode
, "wb"))
4422 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
4423 else if (!strcmp(mode
, "rb"))
4424 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
4433 typedef struct QEMUFileBdrv
4435 BlockDriverState
*bs
;
4436 int64_t base_offset
;
4439 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4441 QEMUFileBdrv
*s
= opaque
;
4442 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4445 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4447 QEMUFileBdrv
*s
= opaque
;
4448 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4451 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4455 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
4460 s
->base_offset
= offset
;
4463 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
4465 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
4468 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
4469 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
4473 f
= qemu_mallocz(sizeof(QEMUFile
));
4478 f
->put_buffer
= put_buffer
;
4479 f
->get_buffer
= get_buffer
;
4485 void qemu_fflush(QEMUFile
*f
)
4490 if (f
->buf_index
> 0) {
4491 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
4492 f
->buf_offset
+= f
->buf_index
;
4497 static void qemu_fill_buffer(QEMUFile
*f
)
4504 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
4510 f
->buf_offset
+= len
;
4513 void qemu_fclose(QEMUFile
*f
)
4517 f
->close(f
->opaque
);
4521 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4525 l
= IO_BUF_SIZE
- f
->buf_index
;
4528 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4532 if (f
->buf_index
>= IO_BUF_SIZE
)
4537 void qemu_put_byte(QEMUFile
*f
, int v
)
4539 f
->buf
[f
->buf_index
++] = v
;
4540 if (f
->buf_index
>= IO_BUF_SIZE
)
4544 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4550 l
= f
->buf_size
- f
->buf_index
;
4552 qemu_fill_buffer(f
);
4553 l
= f
->buf_size
- f
->buf_index
;
4559 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4564 return size1
- size
;
4567 int qemu_get_byte(QEMUFile
*f
)
4569 if (f
->buf_index
>= f
->buf_size
) {
4570 qemu_fill_buffer(f
);
4571 if (f
->buf_index
>= f
->buf_size
)
4574 return f
->buf
[f
->buf_index
++];
4577 int64_t qemu_ftell(QEMUFile
*f
)
4579 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4582 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4584 if (whence
== SEEK_SET
) {
4586 } else if (whence
== SEEK_CUR
) {
4587 pos
+= qemu_ftell(f
);
4589 /* SEEK_END not supported */
4592 if (f
->put_buffer
) {
4594 f
->buf_offset
= pos
;
4596 f
->buf_offset
= pos
;
4603 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4605 qemu_put_byte(f
, v
>> 8);
4606 qemu_put_byte(f
, v
);
4609 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4611 qemu_put_byte(f
, v
>> 24);
4612 qemu_put_byte(f
, v
>> 16);
4613 qemu_put_byte(f
, v
>> 8);
4614 qemu_put_byte(f
, v
);
4617 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4619 qemu_put_be32(f
, v
>> 32);
4620 qemu_put_be32(f
, v
);
4623 unsigned int qemu_get_be16(QEMUFile
*f
)
4626 v
= qemu_get_byte(f
) << 8;
4627 v
|= qemu_get_byte(f
);
4631 unsigned int qemu_get_be32(QEMUFile
*f
)
4634 v
= qemu_get_byte(f
) << 24;
4635 v
|= qemu_get_byte(f
) << 16;
4636 v
|= qemu_get_byte(f
) << 8;
4637 v
|= qemu_get_byte(f
);
4641 uint64_t qemu_get_be64(QEMUFile
*f
)
4644 v
= (uint64_t)qemu_get_be32(f
) << 32;
4645 v
|= qemu_get_be32(f
);
4649 typedef struct SaveStateEntry
{
4653 SaveStateHandler
*save_state
;
4654 LoadStateHandler
*load_state
;
4656 struct SaveStateEntry
*next
;
4659 static SaveStateEntry
*first_se
;
4661 int register_savevm(const char *idstr
,
4664 SaveStateHandler
*save_state
,
4665 LoadStateHandler
*load_state
,
4668 SaveStateEntry
*se
, **pse
;
4670 se
= qemu_malloc(sizeof(SaveStateEntry
));
4673 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4674 se
->instance_id
= instance_id
;
4675 se
->version_id
= version_id
;
4676 se
->save_state
= save_state
;
4677 se
->load_state
= load_state
;
4678 se
->opaque
= opaque
;
4681 /* add at the end of list */
4683 while (*pse
!= NULL
)
4684 pse
= &(*pse
)->next
;
4689 #define QEMU_VM_FILE_MAGIC 0x5145564d
4690 #define QEMU_VM_FILE_VERSION 0x00000002
4692 int qemu_savevm_state(QEMUFile
*f
)
4696 int64_t cur_pos
, len_pos
, total_len_pos
;
4698 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4699 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4700 total_len_pos
= qemu_ftell(f
);
4701 qemu_put_be64(f
, 0); /* total size */
4703 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4705 len
= strlen(se
->idstr
);
4706 qemu_put_byte(f
, len
);
4707 qemu_put_buffer(f
, se
->idstr
, len
);
4709 qemu_put_be32(f
, se
->instance_id
);
4710 qemu_put_be32(f
, se
->version_id
);
4712 /* record size: filled later */
4713 len_pos
= qemu_ftell(f
);
4714 qemu_put_be32(f
, 0);
4716 se
->save_state(f
, se
->opaque
);
4718 /* fill record size */
4719 cur_pos
= qemu_ftell(f
);
4720 len
= cur_pos
- len_pos
- 4;
4721 qemu_fseek(f
, len_pos
, SEEK_SET
);
4722 qemu_put_be32(f
, len
);
4723 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4725 cur_pos
= qemu_ftell(f
);
4726 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4727 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4728 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4734 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4738 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4739 if (!strcmp(se
->idstr
, idstr
) &&
4740 instance_id
== se
->instance_id
)
4746 int qemu_loadvm_state(QEMUFile
*f
)
4749 int len
, ret
, instance_id
, record_len
, version_id
;
4750 int64_t total_len
, end_pos
, cur_pos
;
4754 v
= qemu_get_be32(f
);
4755 if (v
!= QEMU_VM_FILE_MAGIC
)
4757 v
= qemu_get_be32(f
);
4758 if (v
!= QEMU_VM_FILE_VERSION
) {
4763 total_len
= qemu_get_be64(f
);
4764 end_pos
= total_len
+ qemu_ftell(f
);
4766 if (qemu_ftell(f
) >= end_pos
)
4768 len
= qemu_get_byte(f
);
4769 qemu_get_buffer(f
, idstr
, len
);
4771 instance_id
= qemu_get_be32(f
);
4772 version_id
= qemu_get_be32(f
);
4773 record_len
= qemu_get_be32(f
);
4775 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4776 idstr
, instance_id
, version_id
, record_len
);
4778 cur_pos
= qemu_ftell(f
);
4779 se
= find_se(idstr
, instance_id
);
4781 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4782 instance_id
, idstr
);
4784 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4786 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4787 instance_id
, idstr
);
4791 /* always seek to exact end of record */
4792 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4799 int qemu_live_savevm_state(QEMUFile
*f
)
4804 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4805 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4807 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4808 len
= strlen(se
->idstr
);
4810 qemu_put_byte(f
, len
);
4811 qemu_put_buffer(f
, se
->idstr
, len
);
4812 qemu_put_be32(f
, se
->instance_id
);
4813 qemu_put_be32(f
, se
->version_id
);
4815 se
->save_state(f
, se
->opaque
);
4818 qemu_put_byte(f
, 0);
4824 int qemu_live_loadvm_state(QEMUFile
*f
)
4827 int len
, ret
, instance_id
, version_id
;
4831 v
= qemu_get_be32(f
);
4832 if (v
!= QEMU_VM_FILE_MAGIC
)
4834 v
= qemu_get_be32(f
);
4835 if (v
!= QEMU_VM_FILE_VERSION
) {
4842 len
= qemu_get_byte(f
);
4845 qemu_get_buffer(f
, idstr
, len
);
4847 instance_id
= qemu_get_be32(f
);
4848 version_id
= qemu_get_be32(f
);
4849 se
= find_se(idstr
, instance_id
);
4851 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4852 instance_id
, idstr
);
4854 if (version_id
> se
->version_id
) { /* src version > dst version */
4855 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
4856 idstr
, version_id
, se
->version_id
);
4860 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4862 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4863 instance_id
, idstr
);
4870 qemu_announce_self();
4876 /* device can contain snapshots */
4877 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4880 !bdrv_is_removable(bs
) &&
4881 !bdrv_is_read_only(bs
));
4884 /* device must be snapshots in order to have a reliable snapshot */
4885 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4888 !bdrv_is_removable(bs
) &&
4889 !bdrv_is_read_only(bs
));
4892 static BlockDriverState
*get_bs_snapshots(void)
4894 BlockDriverState
*bs
;
4898 return bs_snapshots
;
4899 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4901 if (bdrv_can_snapshot(bs
))
4910 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
4913 QEMUSnapshotInfo
*sn_tab
, *sn
;
4917 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
4920 for(i
= 0; i
< nb_sns
; i
++) {
4922 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
4932 void do_savevm(const char *name
)
4934 BlockDriverState
*bs
, *bs1
;
4935 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
4936 int must_delete
, ret
, i
;
4937 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
4939 int saved_vm_running
;
4946 bs
= get_bs_snapshots();
4948 term_printf("No block device can accept snapshots\n");
4952 /* ??? Should this occur after vm_stop? */
4955 saved_vm_running
= vm_running
;
4960 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
4965 memset(sn
, 0, sizeof(*sn
));
4967 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
4968 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
4971 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
4974 /* fill auxiliary fields */
4977 sn
->date_sec
= tb
.time
;
4978 sn
->date_nsec
= tb
.millitm
* 1000000;
4980 gettimeofday(&tv
, NULL
);
4981 sn
->date_sec
= tv
.tv_sec
;
4982 sn
->date_nsec
= tv
.tv_usec
* 1000;
4984 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
4986 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
4987 term_printf("Device %s does not support VM state snapshots\n",
4988 bdrv_get_device_name(bs
));
4992 /* save the VM state */
4993 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
4995 term_printf("Could not open VM state file\n");
4998 ret
= qemu_savevm_state(f
);
4999 sn
->vm_state_size
= qemu_ftell(f
);
5002 term_printf("Error %d while writing VM\n", ret
);
5006 /* create the snapshots */
5008 for(i
= 0; i
< MAX_DISKS
; i
++) {
5010 if (bdrv_has_snapshot(bs1
)) {
5012 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5014 term_printf("Error while deleting snapshot on '%s'\n",
5015 bdrv_get_device_name(bs1
));
5018 ret
= bdrv_snapshot_create(bs1
, sn
);
5020 term_printf("Error while creating snapshot on '%s'\n",
5021 bdrv_get_device_name(bs1
));
5027 if (saved_vm_running
)
5031 void do_loadvm(const char *name
)
5033 BlockDriverState
*bs
, *bs1
;
5034 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5037 int saved_vm_running
;
5039 bs
= get_bs_snapshots();
5041 term_printf("No block device supports snapshots\n");
5045 /* Flush all IO requests so they don't interfere with the new state. */
5048 saved_vm_running
= vm_running
;
5051 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5053 if (bdrv_has_snapshot(bs1
)) {
5054 ret
= bdrv_snapshot_goto(bs1
, name
);
5057 term_printf("Warning: ");
5060 term_printf("Snapshots not supported on device '%s'\n",
5061 bdrv_get_device_name(bs1
));
5064 term_printf("Could not find snapshot '%s' on device '%s'\n",
5065 name
, bdrv_get_device_name(bs1
));
5068 term_printf("Error %d while activating snapshot on '%s'\n",
5069 ret
, bdrv_get_device_name(bs1
));
5072 /* fatal on snapshot block device */
5079 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5080 term_printf("Device %s does not support VM state snapshots\n",
5081 bdrv_get_device_name(bs
));
5085 /* restore the VM state */
5086 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5088 term_printf("Could not open VM state file\n");
5091 ret
= qemu_loadvm_state(f
);
5094 term_printf("Error %d while loading VM state\n", ret
);
5097 if (saved_vm_running
)
5101 void do_delvm(const char *name
)
5103 BlockDriverState
*bs
, *bs1
;
5106 bs
= get_bs_snapshots();
5108 term_printf("No block device supports snapshots\n");
5112 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5114 if (bdrv_has_snapshot(bs1
)) {
5115 ret
= bdrv_snapshot_delete(bs1
, name
);
5117 if (ret
== -ENOTSUP
)
5118 term_printf("Snapshots not supported on device '%s'\n",
5119 bdrv_get_device_name(bs1
));
5121 term_printf("Error %d while deleting snapshot on '%s'\n",
5122 ret
, bdrv_get_device_name(bs1
));
5128 void do_info_snapshots(void)
5130 BlockDriverState
*bs
, *bs1
;
5131 QEMUSnapshotInfo
*sn_tab
, *sn
;
5135 bs
= get_bs_snapshots();
5137 term_printf("No available block device supports snapshots\n");
5140 term_printf("Snapshot devices:");
5141 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5143 if (bdrv_has_snapshot(bs1
)) {
5145 term_printf(" %s", bdrv_get_device_name(bs1
));
5150 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5152 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5155 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5156 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5157 for(i
= 0; i
< nb_sns
; i
++) {
5159 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5164 /***********************************************************/
5165 /* cpu save/restore */
5167 #if defined(TARGET_I386)
5169 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5171 qemu_put_be32(f
, dt
->selector
);
5172 qemu_put_betl(f
, dt
->base
);
5173 qemu_put_be32(f
, dt
->limit
);
5174 qemu_put_be32(f
, dt
->flags
);
5177 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5179 dt
->selector
= qemu_get_be32(f
);
5180 dt
->base
= qemu_get_betl(f
);
5181 dt
->limit
= qemu_get_be32(f
);
5182 dt
->flags
= qemu_get_be32(f
);
5185 void cpu_save(QEMUFile
*f
, void *opaque
)
5187 CPUState
*env
= opaque
;
5188 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5194 kvm_save_registers(env
);
5197 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5198 qemu_put_betls(f
, &env
->regs
[i
]);
5199 qemu_put_betls(f
, &env
->eip
);
5200 qemu_put_betls(f
, &env
->eflags
);
5201 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5202 qemu_put_be32s(f
, &hflags
);
5206 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5208 for(i
= 0; i
< 8; i
++) {
5209 fptag
|= ((!env
->fptags
[i
]) << i
);
5212 qemu_put_be16s(f
, &fpuc
);
5213 qemu_put_be16s(f
, &fpus
);
5214 qemu_put_be16s(f
, &fptag
);
5216 #ifdef USE_X86LDOUBLE
5221 qemu_put_be16s(f
, &fpregs_format
);
5223 for(i
= 0; i
< 8; i
++) {
5224 #ifdef USE_X86LDOUBLE
5228 /* we save the real CPU data (in case of MMX usage only 'mant'
5229 contains the MMX register */
5230 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5231 qemu_put_be64(f
, mant
);
5232 qemu_put_be16(f
, exp
);
5235 /* if we use doubles for float emulation, we save the doubles to
5236 avoid losing information in case of MMX usage. It can give
5237 problems if the image is restored on a CPU where long
5238 doubles are used instead. */
5239 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5243 for(i
= 0; i
< 6; i
++)
5244 cpu_put_seg(f
, &env
->segs
[i
]);
5245 cpu_put_seg(f
, &env
->ldt
);
5246 cpu_put_seg(f
, &env
->tr
);
5247 cpu_put_seg(f
, &env
->gdt
);
5248 cpu_put_seg(f
, &env
->idt
);
5250 qemu_put_be32s(f
, &env
->sysenter_cs
);
5251 qemu_put_be32s(f
, &env
->sysenter_esp
);
5252 qemu_put_be32s(f
, &env
->sysenter_eip
);
5254 qemu_put_betls(f
, &env
->cr
[0]);
5255 qemu_put_betls(f
, &env
->cr
[2]);
5256 qemu_put_betls(f
, &env
->cr
[3]);
5257 qemu_put_betls(f
, &env
->cr
[4]);
5259 for(i
= 0; i
< 8; i
++)
5260 qemu_put_betls(f
, &env
->dr
[i
]);
5263 qemu_put_be32s(f
, &env
->a20_mask
);
5266 qemu_put_be32s(f
, &env
->mxcsr
);
5267 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5268 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5269 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5272 #ifdef TARGET_X86_64
5273 qemu_put_be64s(f
, &env
->efer
);
5274 qemu_put_be64s(f
, &env
->star
);
5275 qemu_put_be64s(f
, &env
->lstar
);
5276 qemu_put_be64s(f
, &env
->cstar
);
5277 qemu_put_be64s(f
, &env
->fmask
);
5278 qemu_put_be64s(f
, &env
->kernelgsbase
);
5280 qemu_put_be32s(f
, &env
->smbase
);
5284 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5285 qemu_put_be32s(f
, &env
->kvm_interrupt_bitmap
[i
]);
5287 qemu_put_be64s(f
, &env
->tsc
);
5293 #ifdef USE_X86LDOUBLE
5294 /* XXX: add that in a FPU generic layer */
5295 union x86_longdouble
{
5300 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5301 #define EXPBIAS1 1023
5302 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5303 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5305 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5309 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5310 /* exponent + sign */
5311 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5312 e
|= SIGND1(temp
) >> 16;
5317 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5319 CPUState
*env
= opaque
;
5322 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5324 if (version_id
!= 3 && version_id
!= 4)
5326 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5327 qemu_get_betls(f
, &env
->regs
[i
]);
5328 qemu_get_betls(f
, &env
->eip
);
5329 qemu_get_betls(f
, &env
->eflags
);
5330 qemu_get_be32s(f
, &hflags
);
5332 qemu_get_be16s(f
, &fpuc
);
5333 qemu_get_be16s(f
, &fpus
);
5334 qemu_get_be16s(f
, &fptag
);
5335 qemu_get_be16s(f
, &fpregs_format
);
5337 /* NOTE: we cannot always restore the FPU state if the image come
5338 from a host with a different 'USE_X86LDOUBLE' define. We guess
5339 if we are in an MMX state to restore correctly in that case. */
5340 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5341 for(i
= 0; i
< 8; i
++) {
5345 switch(fpregs_format
) {
5347 mant
= qemu_get_be64(f
);
5348 exp
= qemu_get_be16(f
);
5349 #ifdef USE_X86LDOUBLE
5350 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5352 /* difficult case */
5354 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5356 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5360 mant
= qemu_get_be64(f
);
5361 #ifdef USE_X86LDOUBLE
5363 union x86_longdouble
*p
;
5364 /* difficult case */
5365 p
= (void *)&env
->fpregs
[i
];
5370 fp64_to_fp80(p
, mant
);
5374 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5383 /* XXX: restore FPU round state */
5384 env
->fpstt
= (fpus
>> 11) & 7;
5385 env
->fpus
= fpus
& ~0x3800;
5387 for(i
= 0; i
< 8; i
++) {
5388 env
->fptags
[i
] = (fptag
>> i
) & 1;
5391 for(i
= 0; i
< 6; i
++)
5392 cpu_get_seg(f
, &env
->segs
[i
]);
5393 cpu_get_seg(f
, &env
->ldt
);
5394 cpu_get_seg(f
, &env
->tr
);
5395 cpu_get_seg(f
, &env
->gdt
);
5396 cpu_get_seg(f
, &env
->idt
);
5398 qemu_get_be32s(f
, &env
->sysenter_cs
);
5399 qemu_get_be32s(f
, &env
->sysenter_esp
);
5400 qemu_get_be32s(f
, &env
->sysenter_eip
);
5402 qemu_get_betls(f
, &env
->cr
[0]);
5403 qemu_get_betls(f
, &env
->cr
[2]);
5404 qemu_get_betls(f
, &env
->cr
[3]);
5405 qemu_get_betls(f
, &env
->cr
[4]);
5407 for(i
= 0; i
< 8; i
++)
5408 qemu_get_betls(f
, &env
->dr
[i
]);
5411 qemu_get_be32s(f
, &env
->a20_mask
);
5413 qemu_get_be32s(f
, &env
->mxcsr
);
5414 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5415 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5416 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5419 #ifdef TARGET_X86_64
5420 qemu_get_be64s(f
, &env
->efer
);
5421 qemu_get_be64s(f
, &env
->star
);
5422 qemu_get_be64s(f
, &env
->lstar
);
5423 qemu_get_be64s(f
, &env
->cstar
);
5424 qemu_get_be64s(f
, &env
->fmask
);
5425 qemu_get_be64s(f
, &env
->kernelgsbase
);
5427 if (version_id
>= 4)
5428 qemu_get_be32s(f
, &env
->smbase
);
5430 /* XXX: compute hflags from scratch, except for CPL and IIF */
5431 env
->hflags
= hflags
;
5435 /* when in-kernel irqchip is used, HF_HALTED_MASK causes deadlock
5436 because no userspace IRQs will ever clear this flag */
5437 env
->hflags
&= ~HF_HALTED_MASK
;
5438 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5439 qemu_get_be32s(f
, &env
->kvm_interrupt_bitmap
[i
]);
5441 qemu_get_be64s(f
, &env
->tsc
);
5442 kvm_load_registers(env
);
5448 #elif defined(TARGET_PPC)
5449 void cpu_save(QEMUFile
*f
, void *opaque
)
5453 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5458 #elif defined(TARGET_MIPS)
5459 void cpu_save(QEMUFile
*f
, void *opaque
)
5463 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5468 #elif defined(TARGET_SPARC)
5469 void cpu_save(QEMUFile
*f
, void *opaque
)
5471 CPUState
*env
= opaque
;
5475 for(i
= 0; i
< 8; i
++)
5476 qemu_put_betls(f
, &env
->gregs
[i
]);
5477 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5478 qemu_put_betls(f
, &env
->regbase
[i
]);
5481 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5487 qemu_put_be32(f
, u
.i
);
5490 qemu_put_betls(f
, &env
->pc
);
5491 qemu_put_betls(f
, &env
->npc
);
5492 qemu_put_betls(f
, &env
->y
);
5494 qemu_put_be32(f
, tmp
);
5495 qemu_put_betls(f
, &env
->fsr
);
5496 qemu_put_betls(f
, &env
->tbr
);
5497 #ifndef TARGET_SPARC64
5498 qemu_put_be32s(f
, &env
->wim
);
5500 for(i
= 0; i
< 16; i
++)
5501 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5505 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5507 CPUState
*env
= opaque
;
5511 for(i
= 0; i
< 8; i
++)
5512 qemu_get_betls(f
, &env
->gregs
[i
]);
5513 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5514 qemu_get_betls(f
, &env
->regbase
[i
]);
5517 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5522 u
.i
= qemu_get_be32(f
);
5526 qemu_get_betls(f
, &env
->pc
);
5527 qemu_get_betls(f
, &env
->npc
);
5528 qemu_get_betls(f
, &env
->y
);
5529 tmp
= qemu_get_be32(f
);
5530 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5531 correctly updated */
5533 qemu_get_betls(f
, &env
->fsr
);
5534 qemu_get_betls(f
, &env
->tbr
);
5535 #ifndef TARGET_SPARC64
5536 qemu_get_be32s(f
, &env
->wim
);
5538 for(i
= 0; i
< 16; i
++)
5539 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5545 #elif defined(TARGET_ARM)
5547 /* ??? Need to implement these. */
5548 void cpu_save(QEMUFile
*f
, void *opaque
)
5552 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5559 #warning No CPU save/restore functions
5563 /***********************************************************/
5564 /* ram save/restore */
5566 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5570 v
= qemu_get_byte(f
);
5573 if (qemu_get_buffer(f
, buf
, len
) != len
)
5577 v
= qemu_get_byte(f
);
5578 memset(buf
, v
, len
);
5586 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5590 if (qemu_get_be32(f
) != phys_ram_size
)
5592 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5594 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5597 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5604 #define BDRV_HASH_BLOCK_SIZE 1024
5605 #define IOBUF_SIZE 4096
5606 #define RAM_CBLOCK_MAGIC 0xfabe
5608 typedef struct RamCompressState
{
5611 uint8_t buf
[IOBUF_SIZE
];
5614 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5617 memset(s
, 0, sizeof(*s
));
5619 ret
= deflateInit2(&s
->zstream
, 1,
5621 9, Z_DEFAULT_STRATEGY
);
5624 s
->zstream
.avail_out
= IOBUF_SIZE
;
5625 s
->zstream
.next_out
= s
->buf
;
5629 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5631 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5632 qemu_put_be16(s
->f
, len
);
5633 qemu_put_buffer(s
->f
, buf
, len
);
5636 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5640 s
->zstream
.avail_in
= len
;
5641 s
->zstream
.next_in
= (uint8_t *)buf
;
5642 while (s
->zstream
.avail_in
> 0) {
5643 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5646 if (s
->zstream
.avail_out
== 0) {
5647 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5648 s
->zstream
.avail_out
= IOBUF_SIZE
;
5649 s
->zstream
.next_out
= s
->buf
;
5655 static void ram_compress_close(RamCompressState
*s
)
5659 /* compress last bytes */
5661 ret
= deflate(&s
->zstream
, Z_FINISH
);
5662 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5663 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5665 ram_put_cblock(s
, s
->buf
, len
);
5667 s
->zstream
.avail_out
= IOBUF_SIZE
;
5668 s
->zstream
.next_out
= s
->buf
;
5669 if (ret
== Z_STREAM_END
)
5676 deflateEnd(&s
->zstream
);
5679 typedef struct RamDecompressState
{
5682 uint8_t buf
[IOBUF_SIZE
];
5683 } RamDecompressState
;
5685 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5688 memset(s
, 0, sizeof(*s
));
5690 ret
= inflateInit(&s
->zstream
);
5696 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5700 s
->zstream
.avail_out
= len
;
5701 s
->zstream
.next_out
= buf
;
5702 while (s
->zstream
.avail_out
> 0) {
5703 if (s
->zstream
.avail_in
== 0) {
5704 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5706 clen
= qemu_get_be16(s
->f
);
5707 if (clen
> IOBUF_SIZE
)
5709 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5710 s
->zstream
.avail_in
= clen
;
5711 s
->zstream
.next_in
= s
->buf
;
5713 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5714 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5721 static void ram_decompress_close(RamDecompressState
*s
)
5723 inflateEnd(&s
->zstream
);
5726 static void ram_save_live(QEMUFile
*f
, void *opaque
)
5730 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
5732 if (kvm_allowed
&& (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
5735 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
5736 qemu_put_be32(f
, addr
);
5737 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5740 qemu_put_be32(f
, 1);
5743 static void ram_save_static(QEMUFile
*f
, void *opaque
)
5746 RamCompressState s1
, *s
= &s1
;
5749 qemu_put_be32(f
, phys_ram_size
);
5750 if (ram_compress_open(s
, f
) < 0)
5752 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5754 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5758 if (tight_savevm_enabled
) {
5762 /* find if the memory block is available on a virtual
5765 for(j
= 0; j
< MAX_DISKS
; j
++) {
5767 sector_num
= bdrv_hash_find(bs_table
[j
],
5768 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5769 if (sector_num
>= 0)
5774 goto normal_compress
;
5777 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5778 ram_compress_buf(s
, buf
, 10);
5784 ram_compress_buf(s
, buf
, 1);
5785 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5788 ram_compress_close(s
);
5791 static void ram_save(QEMUFile
*f
, void *opaque
)
5793 int in_migration
= cpu_physical_memory_get_dirty_tracking();
5795 qemu_put_byte(f
, in_migration
);
5798 ram_save_live(f
, opaque
);
5800 ram_save_static(f
, opaque
);
5803 static int ram_load_live(QEMUFile
*f
, void *opaque
)
5808 addr
= qemu_get_be32(f
);
5812 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5818 static int ram_load_static(QEMUFile
*f
, void *opaque
)
5820 RamDecompressState s1
, *s
= &s1
;
5824 if (qemu_get_be32(f
) != phys_ram_size
)
5826 if (ram_decompress_open(s
, f
) < 0)
5828 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5830 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5833 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5834 fprintf(stderr
, "Error while reading ram block header\n");
5838 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5839 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5848 ram_decompress_buf(s
, buf
+ 1, 9);
5850 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5851 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5852 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5855 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5856 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5857 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5858 bs_index
, sector_num
);
5865 printf("Error block header\n");
5869 ram_decompress_close(s
);
5873 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5877 switch (version_id
) {
5879 ret
= ram_load_v1(f
, opaque
);
5882 if (qemu_get_byte(f
)) {
5883 ret
= ram_load_live(f
, opaque
);
5887 ret
= ram_load_static(f
, opaque
);
5897 /***********************************************************/
5898 /* bottom halves (can be seen as timers which expire ASAP) */
5907 static QEMUBH
*first_bh
= NULL
;
5909 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5912 bh
= qemu_mallocz(sizeof(QEMUBH
));
5916 bh
->opaque
= opaque
;
5920 int qemu_bh_poll(void)
5939 void qemu_bh_schedule(QEMUBH
*bh
)
5941 CPUState
*env
= cpu_single_env
;
5945 bh
->next
= first_bh
;
5948 /* stop the currently executing CPU to execute the BH ASAP */
5950 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5954 void qemu_bh_cancel(QEMUBH
*bh
)
5957 if (bh
->scheduled
) {
5960 pbh
= &(*pbh
)->next
;
5966 void qemu_bh_delete(QEMUBH
*bh
)
5972 /***********************************************************/
5973 /* machine registration */
5975 QEMUMachine
*first_machine
= NULL
;
5977 int qemu_register_machine(QEMUMachine
*m
)
5980 pm
= &first_machine
;
5988 QEMUMachine
*find_machine(const char *name
)
5992 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5993 if (!strcmp(m
->name
, name
))
5999 /***********************************************************/
6000 /* main execution loop */
6002 void gui_update(void *opaque
)
6004 display_state
.dpy_refresh(&display_state
);
6005 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6008 struct vm_change_state_entry
{
6009 VMChangeStateHandler
*cb
;
6011 LIST_ENTRY (vm_change_state_entry
) entries
;
6014 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6016 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6019 VMChangeStateEntry
*e
;
6021 e
= qemu_mallocz(sizeof (*e
));
6027 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6031 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6033 LIST_REMOVE (e
, entries
);
6037 static void vm_state_notify(int running
)
6039 VMChangeStateEntry
*e
;
6041 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6042 e
->cb(e
->opaque
, running
);
6046 /* XXX: support several handlers */
6047 static VMStopHandler
*vm_stop_cb
;
6048 static void *vm_stop_opaque
;
6050 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6053 vm_stop_opaque
= opaque
;
6057 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6071 void vm_stop(int reason
)
6074 cpu_disable_ticks();
6078 vm_stop_cb(vm_stop_opaque
, reason
);
6085 /* reset/shutdown handler */
6087 typedef struct QEMUResetEntry
{
6088 QEMUResetHandler
*func
;
6090 struct QEMUResetEntry
*next
;
6093 static QEMUResetEntry
*first_reset_entry
;
6094 static int reset_requested
;
6095 static int shutdown_requested
;
6096 static int powerdown_requested
;
6098 int qemu_shutdown_requested(void)
6100 int r
= shutdown_requested
;
6101 shutdown_requested
= 0;
6105 int qemu_reset_requested(void)
6107 int r
= reset_requested
;
6108 reset_requested
= 0;
6112 int qemu_powerdown_requested(void)
6114 int r
= powerdown_requested
;
6115 powerdown_requested
= 0;
6119 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6121 QEMUResetEntry
**pre
, *re
;
6123 pre
= &first_reset_entry
;
6124 while (*pre
!= NULL
)
6125 pre
= &(*pre
)->next
;
6126 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6128 re
->opaque
= opaque
;
6133 void qemu_system_reset(void)
6137 /* reset all devices */
6138 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6139 re
->func(re
->opaque
);
6143 void qemu_system_reset_request(void)
6146 shutdown_requested
= 1;
6148 reset_requested
= 1;
6151 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6154 void qemu_system_shutdown_request(void)
6156 shutdown_requested
= 1;
6158 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6161 void qemu_system_powerdown_request(void)
6163 powerdown_requested
= 1;
6165 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6168 void main_loop_wait(int timeout
)
6170 IOHandlerRecord
*ioh
;
6171 fd_set rfds
, wfds
, xfds
;
6177 /* XXX: need to suppress polling by better using win32 events */
6179 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6180 ret
|= pe
->func(pe
->opaque
);
6183 if (ret
== 0 && timeout
> 0) {
6185 WaitObjects
*w
= &wait_objects
;
6187 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6188 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6189 if (w
->func
[ret
- WAIT_OBJECT_0
])
6190 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6191 } else if (ret
== WAIT_TIMEOUT
) {
6193 err
= GetLastError();
6194 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6198 /* poll any events */
6199 /* XXX: separate device handlers from system ones */
6204 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6208 (!ioh
->fd_read_poll
||
6209 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6210 FD_SET(ioh
->fd
, &rfds
);
6214 if (ioh
->fd_write
) {
6215 FD_SET(ioh
->fd
, &wfds
);
6225 tv
.tv_usec
= timeout
* 1000;
6227 #if defined(CONFIG_SLIRP)
6229 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6232 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6234 IOHandlerRecord
**pioh
;
6236 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6239 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6240 ioh
->fd_read(ioh
->opaque
);
6242 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6243 ioh
->fd_write(ioh
->opaque
);
6247 /* remove deleted IO handlers */
6248 pioh
= &first_io_handler
;
6258 #if defined(CONFIG_SLIRP)
6265 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6272 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6273 qemu_get_clock(vm_clock
));
6274 /* run dma transfers, if any */
6278 /* real time timers */
6279 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6280 qemu_get_clock(rt_clock
));
6283 static CPUState
*cur_cpu
;
6288 #ifdef CONFIG_PROFILER
6297 cpu_disable_ticks();
6301 cur_cpu
= first_cpu
;
6308 env
= env
->next_cpu
;
6311 #ifdef CONFIG_PROFILER
6312 ti
= profile_getclock();
6314 ret
= cpu_exec(env
);
6315 #ifdef CONFIG_PROFILER
6316 qemu_time
+= profile_getclock() - ti
;
6318 if (ret
!= EXCP_HALTED
)
6320 /* all CPUs are halted ? */
6321 if (env
== cur_cpu
) {
6328 if (shutdown_requested
) {
6329 ret
= EXCP_INTERRUPT
;
6332 if (reset_requested
) {
6333 reset_requested
= 0;
6334 qemu_system_reset();
6337 kvm_load_registers(env
);
6339 ret
= EXCP_INTERRUPT
;
6341 if (powerdown_requested
) {
6342 powerdown_requested
= 0;
6343 qemu_system_powerdown();
6344 ret
= EXCP_INTERRUPT
;
6346 if (ret
== EXCP_DEBUG
) {
6347 vm_stop(EXCP_DEBUG
);
6349 /* if hlt instruction, we wait until the next IRQ */
6350 /* XXX: use timeout computed from timers */
6351 if (ret
== EXCP_HLT
)
6358 #ifdef CONFIG_PROFILER
6359 ti
= profile_getclock();
6361 main_loop_wait(timeout
);
6362 #ifdef CONFIG_PROFILER
6363 dev_time
+= profile_getclock() - ti
;
6366 cpu_disable_ticks();
6372 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6373 "usage: %s [options] [disk_image]\n"
6375 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6377 "Standard options:\n"
6378 "-M machine select emulated machine (-M ? for list)\n"
6379 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6380 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6381 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6382 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6383 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6384 "-snapshot write to temporary files instead of disk image files\n"
6386 "-no-quit disable SDL window close capability\n"
6389 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6391 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6392 "-smp n set the number of CPUs to 'n' [default=1]\n"
6393 "-nographic disable graphical output and redirect serial I/Os to console\n"
6395 "-k language use keyboard layout (for example \"fr\" for French)\n"
6398 "-audio-help print list of audio drivers and their options\n"
6399 "-soundhw c1,... enable audio support\n"
6400 " and only specified sound cards (comma separated list)\n"
6401 " use -soundhw ? to get the list of supported cards\n"
6402 " use -soundhw all to enable all of them\n"
6404 "-localtime set the real time clock to local time [default=utc]\n"
6405 "-full-screen start in full screen\n"
6407 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6409 "-usb enable the USB driver (will be the default soon)\n"
6410 "-usbdevice name add the host or guest USB device 'name'\n"
6411 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6412 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6415 "Network options:\n"
6416 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6417 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6419 "-net user[,vlan=n][,hostname=host]\n"
6420 " connect the user mode network stack to VLAN 'n' and send\n"
6421 " hostname 'host' to DHCP clients\n"
6424 "-net tap[,vlan=n],ifname=name\n"
6425 " connect the host TAP network interface to VLAN 'n'\n"
6427 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6428 " connect the host TAP network interface to VLAN 'n' and use\n"
6429 " the network script 'file' (default=%s);\n"
6430 " use 'script=no' to disable script execution;\n"
6431 " use 'fd=h' to connect to an already opened TAP interface\n"
6433 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6434 " connect the vlan 'n' to another VLAN using a socket connection\n"
6435 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6436 " connect the vlan 'n' to multicast maddr and port\n"
6437 "-net none use it alone to have zero network devices; if no -net option\n"
6438 " is provided, the default is '-net nic -net user'\n"
6441 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6443 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6445 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6446 " redirect TCP or UDP connections from host to guest [-net user]\n"
6449 "Linux boot specific:\n"
6450 "-kernel bzImage use 'bzImage' as kernel image\n"
6451 "-append cmdline use 'cmdline' as kernel command line\n"
6452 "-initrd file use 'file' as initial ram disk\n"
6454 "Debug/Expert options:\n"
6455 "-monitor dev redirect the monitor to char device 'dev'\n"
6456 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6457 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
6458 "-serial dev redirect the serial port to char device 'dev'\n"
6459 "-parallel dev redirect the parallel port to char device 'dev'\n"
6460 "-pidfile file Write PID to 'file'\n"
6461 "-S freeze CPU at startup (use 'c' to start execution)\n"
6462 "-s wait gdb connection to port %d\n"
6463 "-p port change gdb connection port\n"
6464 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6465 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6466 " translation (t=none or lba) (usually qemu can guess them)\n"
6467 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6469 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6470 "-no-kqemu disable KQEMU kernel module usage\n"
6473 "-no-kvm disable KVM hardware virtualization\n"
6475 #ifdef USE_CODE_COPY
6476 "-no-code-copy disable code copy acceleration\n"
6479 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6480 " (default is CL-GD5446 PCI VGA)\n"
6481 "-no-acpi disable ACPI\n"
6483 "-no-reboot exit instead of rebooting\n"
6484 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6485 "-vnc display start a VNC server on display\n"
6487 "-daemonize daemonize QEMU after initializing\n"
6489 "-tdf inject timer interrupts that got lost\n"
6490 #if defined(__linux__)
6491 "-no-rtc don't use /dev/rtc for timer alarm (do use gettimeofday)\n"
6493 "-option-rom rom load a file, rom, into the option ROM space\n"
6495 "During emulation, the following keys are useful:\n"
6496 "ctrl-alt-f toggle full screen\n"
6497 "ctrl-alt-n switch to virtual console 'n'\n"
6498 "ctrl-alt toggle mouse and keyboard grab\n"
6500 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6505 DEFAULT_NETWORK_SCRIPT
,
6507 DEFAULT_GDBSTUB_PORT
,
6512 #define HAS_ARG 0x0001
6526 QEMU_OPTION_snapshot
,
6528 QEMU_OPTION_no_fd_bootchk
,
6531 QEMU_OPTION_nographic
,
6533 QEMU_OPTION_audio_help
,
6534 QEMU_OPTION_soundhw
,
6552 QEMU_OPTION_no_code_copy
,
6554 QEMU_OPTION_localtime
,
6555 QEMU_OPTION_cirrusvga
,
6557 QEMU_OPTION_std_vga
,
6558 QEMU_OPTION_monitor
,
6559 QEMU_OPTION_balloon
,
6560 QEMU_OPTION_vmchannel
,
6562 QEMU_OPTION_parallel
,
6564 QEMU_OPTION_full_screen
,
6565 QEMU_OPTION_no_quit
,
6566 QEMU_OPTION_pidfile
,
6567 QEMU_OPTION_no_kqemu
,
6568 QEMU_OPTION_kernel_kqemu
,
6569 QEMU_OPTION_win2k_hack
,
6571 QEMU_OPTION_usbdevice
,
6574 QEMU_OPTION_no_acpi
,
6576 QEMU_OPTION_no_kvm_irqchip
,
6577 QEMU_OPTION_no_reboot
,
6578 QEMU_OPTION_daemonize
,
6579 QEMU_OPTION_option_rom
,
6580 QEMU_OPTION_semihosting
,
6581 QEMU_OPTION_incoming
,
6583 #if defined(__linux__)
6586 QEMU_OPTION_cpu_vendor
,
6589 typedef struct QEMUOption
{
6595 const QEMUOption qemu_options
[] = {
6596 { "h", 0, QEMU_OPTION_h
},
6597 { "help", 0, QEMU_OPTION_h
},
6599 { "M", HAS_ARG
, QEMU_OPTION_M
},
6600 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6601 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6602 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6603 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6604 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6605 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6606 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6607 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6608 { "snapshot", 0, QEMU_OPTION_snapshot
},
6610 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6612 { "m", HAS_ARG
, QEMU_OPTION_m
},
6613 { "nographic", 0, QEMU_OPTION_nographic
},
6614 { "k", HAS_ARG
, QEMU_OPTION_k
},
6616 { "audio-help", 0, QEMU_OPTION_audio_help
},
6617 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6620 { "net", HAS_ARG
, QEMU_OPTION_net
},
6622 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6624 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6626 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6629 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6630 { "append", HAS_ARG
, QEMU_OPTION_append
},
6631 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6633 { "S", 0, QEMU_OPTION_S
},
6634 { "s", 0, QEMU_OPTION_s
},
6635 { "p", HAS_ARG
, QEMU_OPTION_p
},
6636 { "d", HAS_ARG
, QEMU_OPTION_d
},
6637 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6638 { "L", HAS_ARG
, QEMU_OPTION_L
},
6639 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6641 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6642 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6645 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
6646 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
6648 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6649 { "g", 1, QEMU_OPTION_g
},
6651 { "localtime", 0, QEMU_OPTION_localtime
},
6652 { "std-vga", 0, QEMU_OPTION_std_vga
},
6653 { "monitor", 1, QEMU_OPTION_monitor
},
6654 { "balloon", 1, QEMU_OPTION_balloon
},
6655 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
6656 { "serial", 1, QEMU_OPTION_serial
},
6657 { "parallel", 1, QEMU_OPTION_parallel
},
6658 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6659 { "incoming", 1, QEMU_OPTION_incoming
},
6660 { "full-screen", 0, QEMU_OPTION_full_screen
},
6662 { "no-quit", 0, QEMU_OPTION_no_quit
},
6664 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6665 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6666 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6667 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6668 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6670 /* temporary options */
6671 { "usb", 0, QEMU_OPTION_usb
},
6672 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6673 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6674 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6675 { "daemonize", 0, QEMU_OPTION_daemonize
},
6676 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6677 #if defined(TARGET_ARM)
6678 { "semihosting", 0, QEMU_OPTION_semihosting
},
6680 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
6681 #if defined(__linux__)
6682 { "no-rtc", 0, QEMU_OPTION_no_rtc
},
6684 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
6688 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6690 /* this stack is only used during signal handling */
6691 #define SIGNAL_STACK_SIZE 32768
6693 static uint8_t *signal_stack
;
6697 /* password input */
6699 static BlockDriverState
*get_bdrv(int index
)
6701 BlockDriverState
*bs
;
6704 bs
= bs_table
[index
];
6705 } else if (index
< 6) {
6706 bs
= fd_table
[index
- 4];
6713 static void read_passwords(void)
6715 BlockDriverState
*bs
;
6719 for(i
= 0; i
< 6; i
++) {
6721 if (bs
&& bdrv_is_encrypted(bs
)) {
6722 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6723 for(j
= 0; j
< 3; j
++) {
6724 monitor_readline("Password: ",
6725 1, password
, sizeof(password
));
6726 if (bdrv_set_key(bs
, password
) == 0)
6728 term_printf("invalid password\n");
6734 /* XXX: currently we cannot use simultaneously different CPUs */
6735 void register_machines(void)
6737 #if defined(TARGET_I386)
6738 qemu_register_machine(&pc_machine
);
6739 qemu_register_machine(&isapc_machine
);
6740 #elif defined(TARGET_PPC)
6741 qemu_register_machine(&heathrow_machine
);
6742 qemu_register_machine(&core99_machine
);
6743 qemu_register_machine(&prep_machine
);
6744 #elif defined(TARGET_MIPS)
6745 qemu_register_machine(&mips_machine
);
6746 qemu_register_machine(&mips_malta_machine
);
6747 #elif defined(TARGET_SPARC)
6748 #ifdef TARGET_SPARC64
6749 qemu_register_machine(&sun4u_machine
);
6751 qemu_register_machine(&sun4m_machine
);
6753 #elif defined(TARGET_ARM)
6754 qemu_register_machine(&integratorcp926_machine
);
6755 qemu_register_machine(&integratorcp1026_machine
);
6756 qemu_register_machine(&versatilepb_machine
);
6757 qemu_register_machine(&versatileab_machine
);
6758 qemu_register_machine(&realview_machine
);
6759 #elif defined(TARGET_SH4)
6760 qemu_register_machine(&shix_machine
);
6762 #error unsupported CPU
6767 struct soundhw soundhw
[] = {
6774 { .init_isa
= pcspk_audio_init
}
6779 "Creative Sound Blaster 16",
6782 { .init_isa
= SB16_init
}
6789 "Yamaha YMF262 (OPL3)",
6791 "Yamaha YM3812 (OPL2)",
6795 { .init_isa
= Adlib_init
}
6802 "Gravis Ultrasound GF1",
6805 { .init_isa
= GUS_init
}
6811 "ENSONIQ AudioPCI ES1370",
6814 { .init_pci
= es1370_init
}
6817 { NULL
, NULL
, 0, 0, { NULL
} }
6820 static void select_soundhw (const char *optarg
)
6824 if (*optarg
== '?') {
6827 printf ("Valid sound card names (comma separated):\n");
6828 for (c
= soundhw
; c
->name
; ++c
) {
6829 printf ("%-11s %s\n", c
->name
, c
->descr
);
6831 printf ("\n-soundhw all will enable all of the above\n");
6832 exit (*optarg
!= '?');
6840 if (!strcmp (optarg
, "all")) {
6841 for (c
= soundhw
; c
->name
; ++c
) {
6849 e
= strchr (p
, ',');
6850 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6852 for (c
= soundhw
; c
->name
; ++c
) {
6853 if (!strncmp (c
->name
, p
, l
)) {
6862 "Unknown sound card name (too big to show)\n");
6865 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6870 p
+= l
+ (e
!= NULL
);
6874 goto show_valid_cards
;
6880 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6882 exit(STATUS_CONTROL_C_EXIT
);
6887 #define MAX_NET_CLIENTS 32
6889 static int saved_argc
;
6890 static char **saved_argv
;
6892 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
6896 *opt_daemonize
= daemonize
;
6897 *opt_incoming
= incoming
;
6900 int main(int argc
, char **argv
)
6902 #ifdef CONFIG_GDBSTUB
6903 int use_gdbstub
, gdbstub_port
;
6906 int snapshot
, linux_boot
;
6907 const char *initrd_filename
;
6908 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6909 const char *kernel_filename
, *kernel_cmdline
;
6910 DisplayState
*ds
= &display_state
;
6911 int cyls
, heads
, secs
, translation
;
6912 char net_clients
[MAX_NET_CLIENTS
][256];
6915 const char *r
, *optarg
;
6916 CharDriverState
*monitor_hd
;
6917 char monitor_device
[128];
6918 char vmchannel_devices
[MAX_VMCHANNEL_DEVICES
][128];
6919 int vmchannel_device_index
;
6920 char serial_devices
[MAX_SERIAL_PORTS
][128];
6921 int serial_device_index
;
6922 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6923 int parallel_device_index
;
6924 const char *loadvm
= NULL
;
6925 QEMUMachine
*machine
;
6926 char usb_devices
[MAX_USB_CMDLINE
][128];
6927 int usb_devices_index
;
6933 LIST_INIT (&vm_change_state_head
);
6936 struct sigaction act
;
6937 sigfillset(&act
.sa_mask
);
6939 act
.sa_handler
= SIG_IGN
;
6940 sigaction(SIGPIPE
, &act
, NULL
);
6943 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6944 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6945 QEMU to run on a single CPU */
6950 h
= GetCurrentProcess();
6951 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6952 for(i
= 0; i
< 32; i
++) {
6953 if (mask
& (1 << i
))
6958 SetProcessAffinityMask(h
, mask
);
6964 register_machines();
6965 machine
= first_machine
;
6966 initrd_filename
= NULL
;
6967 for(i
= 0; i
< MAX_FD
; i
++)
6968 fd_filename
[i
] = NULL
;
6969 for(i
= 0; i
< MAX_DISKS
; i
++)
6970 hd_filename
[i
] = NULL
;
6971 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6972 vga_ram_size
= VGA_RAM_SIZE
;
6973 bios_size
= BIOS_SIZE
;
6974 #ifdef CONFIG_GDBSTUB
6976 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6980 kernel_filename
= NULL
;
6981 kernel_cmdline
= "";
6987 cyls
= heads
= secs
= 0;
6988 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6989 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6991 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++)
6992 vmchannel_devices
[i
][0] = '\0';
6993 vmchannel_device_index
= 0;
6995 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6996 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6997 serial_devices
[i
][0] = '\0';
6998 serial_device_index
= 0;
7000 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
7001 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
7002 parallel_devices
[i
][0] = '\0';
7003 parallel_device_index
= 0;
7005 usb_devices_index
= 0;
7010 /* default mac address of the first network interface */
7018 hd_filename
[0] = argv
[optind
++];
7020 const QEMUOption
*popt
;
7023 /* Treat --foo the same as -foo. */
7026 popt
= qemu_options
;
7029 fprintf(stderr
, "%s: invalid option -- '%s'\n",
7033 if (!strcmp(popt
->name
, r
+ 1))
7037 if (popt
->flags
& HAS_ARG
) {
7038 if (optind
>= argc
) {
7039 fprintf(stderr
, "%s: option '%s' requires an argument\n",
7043 optarg
= argv
[optind
++];
7048 switch(popt
->index
) {
7050 machine
= find_machine(optarg
);
7053 printf("Supported machines are:\n");
7054 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7055 printf("%-10s %s%s\n",
7057 m
== first_machine
? " (default)" : "");
7062 case QEMU_OPTION_initrd
:
7063 initrd_filename
= optarg
;
7065 case QEMU_OPTION_hda
:
7066 case QEMU_OPTION_hdb
:
7067 case QEMU_OPTION_hdc
:
7068 case QEMU_OPTION_hdd
:
7071 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7072 hd_filename
[hd_index
] = optarg
;
7073 if (hd_index
== cdrom_index
)
7077 case QEMU_OPTION_snapshot
:
7080 case QEMU_OPTION_hdachs
:
7084 cyls
= strtol(p
, (char **)&p
, 0);
7085 if (cyls
< 1 || cyls
> 16383)
7090 heads
= strtol(p
, (char **)&p
, 0);
7091 if (heads
< 1 || heads
> 16)
7096 secs
= strtol(p
, (char **)&p
, 0);
7097 if (secs
< 1 || secs
> 63)
7101 if (!strcmp(p
, "none"))
7102 translation
= BIOS_ATA_TRANSLATION_NONE
;
7103 else if (!strcmp(p
, "lba"))
7104 translation
= BIOS_ATA_TRANSLATION_LBA
;
7105 else if (!strcmp(p
, "auto"))
7106 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7109 } else if (*p
!= '\0') {
7111 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7116 case QEMU_OPTION_nographic
:
7117 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7118 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7121 case QEMU_OPTION_kernel
:
7122 kernel_filename
= optarg
;
7124 case QEMU_OPTION_append
:
7125 kernel_cmdline
= optarg
;
7127 case QEMU_OPTION_cdrom
:
7128 if (cdrom_index
>= 0) {
7129 hd_filename
[cdrom_index
] = optarg
;
7132 case QEMU_OPTION_boot
:
7133 boot_device
= optarg
[0];
7134 if (boot_device
!= 'a' &&
7135 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7137 boot_device
!= 'n' &&
7139 boot_device
!= 'c' && boot_device
!= 'd') {
7140 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7144 case QEMU_OPTION_fda
:
7145 fd_filename
[0] = optarg
;
7147 case QEMU_OPTION_fdb
:
7148 fd_filename
[1] = optarg
;
7151 case QEMU_OPTION_no_fd_bootchk
:
7155 case QEMU_OPTION_no_code_copy
:
7156 code_copy_enabled
= 0;
7158 case QEMU_OPTION_net
:
7159 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7160 fprintf(stderr
, "qemu: too many network clients\n");
7163 pstrcpy(net_clients
[nb_net_clients
],
7164 sizeof(net_clients
[0]),
7169 case QEMU_OPTION_tftp
:
7170 tftp_prefix
= optarg
;
7173 case QEMU_OPTION_smb
:
7174 net_slirp_smb(optarg
);
7177 case QEMU_OPTION_redir
:
7178 net_slirp_redir(optarg
);
7182 case QEMU_OPTION_audio_help
:
7186 case QEMU_OPTION_soundhw
:
7187 select_soundhw (optarg
);
7194 ram_size
= (int64_t)atoi(optarg
) * 1024 * 1024;
7197 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7198 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7199 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7208 mask
= cpu_str_to_log_mask(optarg
);
7210 printf("Log items (comma separated):\n");
7211 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7212 printf("%-10s %s\n", item
->name
, item
->help
);
7219 #ifdef CONFIG_GDBSTUB
7224 gdbstub_port
= atoi(optarg
);
7234 keyboard_layout
= optarg
;
7236 case QEMU_OPTION_localtime
:
7239 case QEMU_OPTION_cirrusvga
:
7240 cirrus_vga_enabled
= 1;
7242 case QEMU_OPTION_std_vga
:
7243 cirrus_vga_enabled
= 0;
7250 w
= strtol(p
, (char **)&p
, 10);
7253 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7259 h
= strtol(p
, (char **)&p
, 10);
7264 depth
= strtol(p
, (char **)&p
, 10);
7265 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7266 depth
!= 24 && depth
!= 32)
7268 } else if (*p
== '\0') {
7269 depth
= graphic_depth
;
7276 graphic_depth
= depth
;
7279 case QEMU_OPTION_monitor
:
7280 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7282 case QEMU_OPTION_balloon
:
7283 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
7284 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
7288 fprintf(stderr
, "qemu: only one balloon device can be used\n");
7291 sprintf(vmchannel_devices
[vmchannel_device_index
],"di:cdcd,%s", optarg
);
7292 vmchannel_device_index
++;
7295 case QEMU_OPTION_vmchannel
:
7296 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
7297 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
7300 pstrcpy(vmchannel_devices
[vmchannel_device_index
],
7301 sizeof(vmchannel_devices
[0]), optarg
);
7302 vmchannel_device_index
++;
7304 case QEMU_OPTION_serial
:
7305 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7306 fprintf(stderr
, "qemu: too many serial ports\n");
7309 pstrcpy(serial_devices
[serial_device_index
],
7310 sizeof(serial_devices
[0]), optarg
);
7311 serial_device_index
++;
7313 case QEMU_OPTION_parallel
:
7314 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7315 fprintf(stderr
, "qemu: too many parallel ports\n");
7318 pstrcpy(parallel_devices
[parallel_device_index
],
7319 sizeof(parallel_devices
[0]), optarg
);
7320 parallel_device_index
++;
7322 case QEMU_OPTION_loadvm
:
7325 case QEMU_OPTION_incoming
:
7328 case QEMU_OPTION_full_screen
:
7332 case QEMU_OPTION_no_quit
:
7336 case QEMU_OPTION_pidfile
:
7337 create_pidfile(optarg
);
7340 case QEMU_OPTION_win2k_hack
:
7341 win2k_install_hack
= 1;
7345 case QEMU_OPTION_no_kqemu
:
7348 case QEMU_OPTION_kernel_kqemu
:
7353 case QEMU_OPTION_no_kvm
:
7356 case QEMU_OPTION_no_kvm_irqchip
:
7360 case QEMU_OPTION_usb
:
7363 case QEMU_OPTION_usbdevice
:
7365 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7366 fprintf(stderr
, "Too many USB devices\n");
7369 pstrcpy(usb_devices
[usb_devices_index
],
7370 sizeof(usb_devices
[usb_devices_index
]),
7372 usb_devices_index
++;
7374 case QEMU_OPTION_smp
:
7375 smp_cpus
= atoi(optarg
);
7376 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7377 fprintf(stderr
, "Invalid number of CPUs\n");
7381 case QEMU_OPTION_vnc
:
7382 vnc_display
= optarg
;
7384 case QEMU_OPTION_no_acpi
:
7387 case QEMU_OPTION_no_reboot
:
7390 case QEMU_OPTION_daemonize
:
7393 case QEMU_OPTION_option_rom
:
7394 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7395 fprintf(stderr
, "Too many option ROMs\n");
7398 option_rom
[nb_option_roms
] = optarg
;
7401 case QEMU_OPTION_semihosting
:
7402 semihosting_enabled
= 1;
7404 case QEMU_OPTION_tdf
:
7406 #if defined(__linux__)
7407 case QEMU_OPTION_no_rtc
:
7411 case QEMU_OPTION_cpu_vendor
:
7412 cpu_vendor_string
= optarg
;
7422 if (pipe(fds
) == -1)
7433 len
= read(fds
[0], &status
, 1);
7434 if (len
== -1 && (errno
== EINTR
))
7437 if (len
!= 1 || status
!= 0)
7454 signal(SIGTSTP
, SIG_IGN
);
7455 signal(SIGTTOU
, SIG_IGN
);
7456 signal(SIGTTIN
, SIG_IGN
);
7462 if (kvm_qemu_init() < 0) {
7463 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
7473 linux_boot
= (kernel_filename
!= NULL
);
7476 hd_filename
[0] == '\0' &&
7477 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7478 fd_filename
[0] == '\0')
7481 /* boot to floppy or the default cd if no hard disk defined yet */
7482 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7483 if (fd_filename
[0] != '\0')
7489 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7499 /* init network clients */
7500 if (nb_net_clients
== 0) {
7501 /* if no clients, we use a default config */
7502 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7504 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7509 for(i
= 0;i
< nb_net_clients
; i
++) {
7510 if (net_client_init(net_clients
[i
]) < 0)
7515 if (boot_device
== 'n') {
7516 for (i
= 0; i
< nb_nics
; i
++) {
7517 const char *model
= nd_table
[i
].model
;
7521 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7522 if (get_image_size(buf
) > 0) {
7523 option_rom
[nb_option_roms
] = strdup(buf
);
7529 fprintf(stderr
, "No valid PXE rom found for network device\n");
7535 /* init the memory */
7536 phys_ram_size
= ram_size
+ vga_ram_size
+ bios_size
;
7539 for (i
= 0; i
< nb_option_roms
; i
++) {
7540 int ret
= get_image_size(option_rom
[i
]);
7542 fprintf(stderr
, "Could not load option rom '%s'\n", option_rom
[i
]);
7545 phys_ram_size
+= ret
;
7549 /* Initialize kvm */
7551 phys_ram_size
+= KVM_EXTRA_PAGES
* 4096;
7552 if (kvm_qemu_create_context() < 0) {
7553 fprintf(stderr
, "Could not create KVM context\n");
7557 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7558 if (!phys_ram_base
) {
7559 fprintf(stderr
, "Could not allocate physical memory\n");
7564 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7565 if (!phys_ram_base
) {
7566 fprintf(stderr
, "Could not allocate physical memory\n");
7571 /* we always create the cdrom drive, even if no disk is there */
7573 if (cdrom_index
>= 0) {
7574 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7575 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7578 /* open the virtual block devices */
7579 for(i
= 0; i
< MAX_DISKS
; i
++) {
7580 if (hd_filename
[i
]) {
7583 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7584 bs_table
[i
] = bdrv_new(buf
);
7586 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7587 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7591 if (i
== 0 && cyls
!= 0) {
7592 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7593 bdrv_set_translation_hint(bs_table
[i
], translation
);
7598 /* we always create at least one floppy disk */
7599 fd_table
[0] = bdrv_new("fda");
7600 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7602 for(i
= 0; i
< MAX_FD
; i
++) {
7603 if (fd_filename
[i
]) {
7606 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7607 fd_table
[i
] = bdrv_new(buf
);
7608 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7610 if (fd_filename
[i
] != '\0') {
7611 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7612 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7613 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7621 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7622 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
7628 dumb_display_init(ds
);
7629 } else if (vnc_display
!= NULL
) {
7630 vnc_display_init(ds
, vnc_display
);
7632 #if defined(CONFIG_SDL)
7633 sdl_display_init(ds
, full_screen
);
7634 #elif defined(CONFIG_COCOA)
7635 cocoa_display_init(ds
, full_screen
);
7637 dumb_display_init(ds
);
7641 monitor_hd
= qemu_chr_open(monitor_device
);
7643 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7646 monitor_init(monitor_hd
, !nographic
);
7648 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++) {
7649 const char *devname
= vmchannel_devices
[i
];
7650 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7654 if (strstart(devname
, "di:", &devname
)) {
7655 devid
= strtol(devname
, &termn
, 16);
7656 devname
= termn
+ 1;
7659 fprintf(stderr
, "qemu: could not find vmchannel device id '%s'\n",
7663 vmchannel_hds
[i
] = qemu_chr_open(devname
);
7664 if (!vmchannel_hds
[i
]) {
7665 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n",
7669 vmchannel_init(vmchannel_hds
[i
], devid
, i
);
7673 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7674 const char *devname
= serial_devices
[i
];
7675 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7676 serial_hds
[i
] = qemu_chr_open(devname
);
7677 if (!serial_hds
[i
]) {
7678 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7682 if (!strcmp(devname
, "vc"))
7683 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7687 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7688 const char *devname
= parallel_devices
[i
];
7689 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7690 parallel_hds
[i
] = qemu_chr_open(devname
);
7691 if (!parallel_hds
[i
]) {
7692 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7696 if (!strcmp(devname
, "vc"))
7697 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7701 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7702 ds
, fd_filename
, snapshot
,
7703 kernel_filename
, kernel_cmdline
, initrd_filename
);
7705 /* init USB devices */
7707 for(i
= 0; i
< usb_devices_index
; i
++) {
7708 if (usb_device_add(usb_devices
[i
]) < 0) {
7709 fprintf(stderr
, "Warning: could not add USB device %s\n",
7715 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7716 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7723 #ifdef CONFIG_GDBSTUB
7725 /* XXX: use standard host:port notation and modify options
7727 if (gdbserver_start_port(gdbstub_port
) < 0) {
7728 fprintf(stderr
, "qemu: could not open gdbstub device on port '%d'\n",
7741 rc
= migrate_incoming(incoming
);
7743 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
7749 /* XXX: simplify init */
7762 len
= write(fds
[1], &status
, 1);
7763 if (len
== -1 && (errno
== EINTR
))
7770 fd
= open("/dev/null", O_RDWR
);