4 * Copyright (c) 2003-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
64 #if !defined(__APPLE__) && !defined(__OpenBSD__)
70 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71 #include <freebsd/stdlib.h>
75 #include <linux/if_tun.h>
78 #include <linux/rtc.h>
80 /* For the benefit of older linux systems which don't supply it,
81 we use a local copy of hpet.h. */
82 /* #include <linux/hpet.h> */
85 #include <linux/ppdev.h>
86 #include <linux/parport.h>
89 #include <sys/ethernet.h>
90 #include <sys/sockio.h>
91 #include <netinet/arp.h>
92 #include <netinet/in.h>
93 #include <netinet/in_systm.h>
94 #include <netinet/ip.h>
95 #include <netinet/ip_icmp.h> // must come after ip.h
96 #include <netinet/udp.h>
97 #include <netinet/tcp.h>
105 #include "qemu_socket.h"
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
111 #if defined(__OpenBSD__)
115 #if defined(CONFIG_VDE)
116 #include <libvdeplug.h>
121 #include <sys/timeb.h>
122 #include <mmsystem.h>
123 #define getopt_long_only getopt_long
124 #define memalign(align, size) malloc(size)
131 #endif /* CONFIG_SDL */
135 #define main qemu_main
136 #endif /* CONFIG_COCOA */
140 #include "exec-all.h"
142 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
143 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
145 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
147 #define SMBD_COMMAND "/usr/sbin/smbd"
150 //#define DEBUG_UNUSED_IOPORT
151 //#define DEBUG_IOPORT
154 #define DEFAULT_RAM_SIZE 144
156 #define DEFAULT_RAM_SIZE 128
159 /* Max number of USB devices that can be specified on the commandline. */
160 #define MAX_USB_CMDLINE 8
162 /* XXX: use a two level table to limit memory usage */
163 #define MAX_IOPORTS 65536
165 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
166 const char *bios_name
= NULL
;
167 void *ioport_opaque
[MAX_IOPORTS
];
168 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
169 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
170 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
171 to store the VM snapshots */
172 DriveInfo drives_table
[MAX_DRIVES
+1];
174 /* point to the block driver where the snapshots are managed */
175 BlockDriverState
*bs_snapshots
;
177 static DisplayState display_state
;
180 const char* keyboard_layout
= NULL
;
181 int64_t ticks_per_sec
;
183 int pit_min_timer_count
= 0;
185 NICInfo nd_table
[MAX_NICS
];
187 static int rtc_utc
= 1;
188 static int rtc_date_offset
= -1; /* -1 means no change */
189 int cirrus_vga_enabled
= 1;
190 int vmsvga_enabled
= 0;
192 int graphic_width
= 1024;
193 int graphic_height
= 768;
194 int graphic_depth
= 8;
196 int graphic_width
= 800;
197 int graphic_height
= 600;
198 int graphic_depth
= 15;
203 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
204 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
206 int win2k_install_hack
= 0;
209 static VLANState
*first_vlan
;
211 const char *vnc_display
;
212 #if defined(TARGET_SPARC)
214 #elif defined(TARGET_I386)
219 int acpi_enabled
= 1;
224 int graphic_rotate
= 0;
226 const char *option_rom
[MAX_OPTION_ROMS
];
228 int semihosting_enabled
= 0;
233 const char *qemu_name
;
236 unsigned int nb_prom_envs
= 0;
237 const char *prom_envs
[MAX_PROM_ENVS
];
243 } drives_opt
[MAX_DRIVES
];
245 static CPUState
*cur_cpu
;
246 static CPUState
*next_cpu
;
247 static int event_pending
= 1;
248 /* Conversion factor from emulated instructions to virtual clock ticks. */
249 static int icount_time_shift
;
250 /* Arbitrarily pick 1MIPS as the minimum allowable speed. */
251 #define MAX_ICOUNT_SHIFT 10
252 /* Compensate for varying guest execution speed. */
253 static int64_t qemu_icount_bias
;
254 QEMUTimer
*icount_rt_timer
;
255 QEMUTimer
*icount_vm_timer
;
257 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
259 /***********************************************************/
260 /* x86 ISA bus support */
262 target_phys_addr_t isa_mem_base
= 0;
265 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
266 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
268 static uint32_t ioport_read(int index
, uint32_t address
)
270 static IOPortReadFunc
*default_func
[3] = {
271 default_ioport_readb
,
272 default_ioport_readw
,
275 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
277 func
= default_func
[index
];
278 return func(ioport_opaque
[address
], address
);
281 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
283 static IOPortWriteFunc
*default_func
[3] = {
284 default_ioport_writeb
,
285 default_ioport_writew
,
286 default_ioport_writel
288 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
290 func
= default_func
[index
];
291 func(ioport_opaque
[address
], address
, data
);
294 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
296 #ifdef DEBUG_UNUSED_IOPORT
297 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
302 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
304 #ifdef DEBUG_UNUSED_IOPORT
305 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
309 /* default is to make two byte accesses */
310 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
313 data
= ioport_read(0, address
);
314 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
315 data
|= ioport_read(0, address
) << 8;
319 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
321 ioport_write(0, address
, data
& 0xff);
322 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
323 ioport_write(0, address
, (data
>> 8) & 0xff);
326 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
328 #ifdef DEBUG_UNUSED_IOPORT
329 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
334 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
336 #ifdef DEBUG_UNUSED_IOPORT
337 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
341 /* size is the word size in byte */
342 int register_ioport_read(int start
, int length
, int size
,
343 IOPortReadFunc
*func
, void *opaque
)
349 } else if (size
== 2) {
351 } else if (size
== 4) {
354 hw_error("register_ioport_read: invalid size");
357 for(i
= start
; i
< start
+ length
; i
+= size
) {
358 ioport_read_table
[bsize
][i
] = func
;
359 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
360 hw_error("register_ioport_read: invalid opaque");
361 ioport_opaque
[i
] = opaque
;
366 /* size is the word size in byte */
367 int register_ioport_write(int start
, int length
, int size
,
368 IOPortWriteFunc
*func
, void *opaque
)
374 } else if (size
== 2) {
376 } else if (size
== 4) {
379 hw_error("register_ioport_write: invalid size");
382 for(i
= start
; i
< start
+ length
; i
+= size
) {
383 ioport_write_table
[bsize
][i
] = func
;
384 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
385 hw_error("register_ioport_write: invalid opaque");
386 ioport_opaque
[i
] = opaque
;
391 void isa_unassign_ioport(int start
, int length
)
395 for(i
= start
; i
< start
+ length
; i
++) {
396 ioport_read_table
[0][i
] = default_ioport_readb
;
397 ioport_read_table
[1][i
] = default_ioport_readw
;
398 ioport_read_table
[2][i
] = default_ioport_readl
;
400 ioport_write_table
[0][i
] = default_ioport_writeb
;
401 ioport_write_table
[1][i
] = default_ioport_writew
;
402 ioport_write_table
[2][i
] = default_ioport_writel
;
406 /***********************************************************/
408 void cpu_outb(CPUState
*env
, int addr
, int val
)
411 if (loglevel
& CPU_LOG_IOPORT
)
412 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
414 ioport_write(0, addr
, val
);
417 env
->last_io_time
= cpu_get_time_fast();
421 void cpu_outw(CPUState
*env
, int addr
, int val
)
424 if (loglevel
& CPU_LOG_IOPORT
)
425 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
427 ioport_write(1, addr
, val
);
430 env
->last_io_time
= cpu_get_time_fast();
434 void cpu_outl(CPUState
*env
, int addr
, int val
)
437 if (loglevel
& CPU_LOG_IOPORT
)
438 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
440 ioport_write(2, addr
, val
);
443 env
->last_io_time
= cpu_get_time_fast();
447 int cpu_inb(CPUState
*env
, int addr
)
450 val
= ioport_read(0, addr
);
452 if (loglevel
& CPU_LOG_IOPORT
)
453 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
457 env
->last_io_time
= cpu_get_time_fast();
462 int cpu_inw(CPUState
*env
, int addr
)
465 val
= ioport_read(1, addr
);
467 if (loglevel
& CPU_LOG_IOPORT
)
468 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
472 env
->last_io_time
= cpu_get_time_fast();
477 int cpu_inl(CPUState
*env
, int addr
)
480 val
= ioport_read(2, addr
);
482 if (loglevel
& CPU_LOG_IOPORT
)
483 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
487 env
->last_io_time
= cpu_get_time_fast();
492 /***********************************************************/
493 void hw_error(const char *fmt
, ...)
499 fprintf(stderr
, "qemu: hardware error: ");
500 vfprintf(stderr
, fmt
, ap
);
501 fprintf(stderr
, "\n");
502 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
503 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
505 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
507 cpu_dump_state(env
, stderr
, fprintf
, 0);
514 /***********************************************************/
517 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
518 static void *qemu_put_kbd_event_opaque
;
519 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
520 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
522 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
524 qemu_put_kbd_event_opaque
= opaque
;
525 qemu_put_kbd_event
= func
;
528 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
529 void *opaque
, int absolute
,
532 QEMUPutMouseEntry
*s
, *cursor
;
534 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
538 s
->qemu_put_mouse_event
= func
;
539 s
->qemu_put_mouse_event_opaque
= opaque
;
540 s
->qemu_put_mouse_event_absolute
= absolute
;
541 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
544 if (!qemu_put_mouse_event_head
) {
545 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
549 cursor
= qemu_put_mouse_event_head
;
550 while (cursor
->next
!= NULL
)
551 cursor
= cursor
->next
;
554 qemu_put_mouse_event_current
= s
;
559 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
561 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
563 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
566 cursor
= qemu_put_mouse_event_head
;
567 while (cursor
!= NULL
&& cursor
!= entry
) {
569 cursor
= cursor
->next
;
572 if (cursor
== NULL
) // does not exist or list empty
574 else if (prev
== NULL
) { // entry is head
575 qemu_put_mouse_event_head
= cursor
->next
;
576 if (qemu_put_mouse_event_current
== entry
)
577 qemu_put_mouse_event_current
= cursor
->next
;
578 qemu_free(entry
->qemu_put_mouse_event_name
);
583 prev
->next
= entry
->next
;
585 if (qemu_put_mouse_event_current
== entry
)
586 qemu_put_mouse_event_current
= prev
;
588 qemu_free(entry
->qemu_put_mouse_event_name
);
592 void kbd_put_keycode(int keycode
)
594 if (qemu_put_kbd_event
) {
595 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
599 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
601 QEMUPutMouseEvent
*mouse_event
;
602 void *mouse_event_opaque
;
605 if (!qemu_put_mouse_event_current
) {
610 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
612 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
615 if (graphic_rotate
) {
616 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
619 width
= graphic_width
- 1;
620 mouse_event(mouse_event_opaque
,
621 width
- dy
, dx
, dz
, buttons_state
);
623 mouse_event(mouse_event_opaque
,
624 dx
, dy
, dz
, buttons_state
);
628 int kbd_mouse_is_absolute(void)
630 if (!qemu_put_mouse_event_current
)
633 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
636 void do_info_mice(void)
638 QEMUPutMouseEntry
*cursor
;
641 if (!qemu_put_mouse_event_head
) {
642 term_printf("No mouse devices connected\n");
646 term_printf("Mouse devices available:\n");
647 cursor
= qemu_put_mouse_event_head
;
648 while (cursor
!= NULL
) {
649 term_printf("%c Mouse #%d: %s\n",
650 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
651 index
, cursor
->qemu_put_mouse_event_name
);
653 cursor
= cursor
->next
;
657 void do_mouse_set(int index
)
659 QEMUPutMouseEntry
*cursor
;
662 if (!qemu_put_mouse_event_head
) {
663 term_printf("No mouse devices connected\n");
667 cursor
= qemu_put_mouse_event_head
;
668 while (cursor
!= NULL
&& index
!= i
) {
670 cursor
= cursor
->next
;
674 qemu_put_mouse_event_current
= cursor
;
676 term_printf("Mouse at given index not found\n");
679 /* compute with 96 bit intermediate result: (a*b)/c */
680 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
685 #ifdef WORDS_BIGENDIAN
695 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
696 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
699 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
703 /***********************************************************/
704 /* real time host monotonic timer */
706 #define QEMU_TIMER_BASE 1000000000LL
710 static int64_t clock_freq
;
712 static void init_get_clock(void)
716 ret
= QueryPerformanceFrequency(&freq
);
718 fprintf(stderr
, "Could not calibrate ticks\n");
721 clock_freq
= freq
.QuadPart
;
724 static int64_t get_clock(void)
727 QueryPerformanceCounter(&ti
);
728 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
733 static int use_rt_clock
;
735 static void init_get_clock(void)
738 #if defined(__linux__)
741 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
748 static int64_t get_clock(void)
750 #if defined(__linux__)
753 clock_gettime(CLOCK_MONOTONIC
, &ts
);
754 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
758 /* XXX: using gettimeofday leads to problems if the date
759 changes, so it should be avoided. */
761 gettimeofday(&tv
, NULL
);
762 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
767 /* Return the virtual CPU time, based on the instruction counter. */
768 static int64_t cpu_get_icount(void)
771 CPUState
*env
= cpu_single_env
;;
772 icount
= qemu_icount
;
775 fprintf(stderr
, "Bad clock read\n");
776 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
778 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
781 /***********************************************************/
782 /* guest cycle counter */
784 static int64_t cpu_ticks_prev
;
785 static int64_t cpu_ticks_offset
;
786 static int64_t cpu_clock_offset
;
787 static int cpu_ticks_enabled
;
789 /* return the host CPU cycle counter and handle stop/restart */
790 int64_t cpu_get_ticks(void)
793 return cpu_get_icount();
795 if (!cpu_ticks_enabled
) {
796 return cpu_ticks_offset
;
799 ticks
= cpu_get_real_ticks();
800 if (cpu_ticks_prev
> ticks
) {
801 /* Note: non increasing ticks may happen if the host uses
803 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
805 cpu_ticks_prev
= ticks
;
806 return ticks
+ cpu_ticks_offset
;
810 /* return the host CPU monotonic timer and handle stop/restart */
811 static int64_t cpu_get_clock(void)
814 if (!cpu_ticks_enabled
) {
815 return cpu_clock_offset
;
818 return ti
+ cpu_clock_offset
;
822 /* enable cpu_get_ticks() */
823 void cpu_enable_ticks(void)
825 if (!cpu_ticks_enabled
) {
826 cpu_ticks_offset
-= cpu_get_real_ticks();
827 cpu_clock_offset
-= get_clock();
828 cpu_ticks_enabled
= 1;
832 /* disable cpu_get_ticks() : the clock is stopped. You must not call
833 cpu_get_ticks() after that. */
834 void cpu_disable_ticks(void)
836 if (cpu_ticks_enabled
) {
837 cpu_ticks_offset
= cpu_get_ticks();
838 cpu_clock_offset
= cpu_get_clock();
839 cpu_ticks_enabled
= 0;
843 /***********************************************************/
846 #define QEMU_TIMER_REALTIME 0
847 #define QEMU_TIMER_VIRTUAL 1
851 /* XXX: add frequency */
859 struct QEMUTimer
*next
;
862 struct qemu_alarm_timer
{
866 int (*start
)(struct qemu_alarm_timer
*t
);
867 void (*stop
)(struct qemu_alarm_timer
*t
);
868 void (*rearm
)(struct qemu_alarm_timer
*t
);
872 #define ALARM_FLAG_DYNTICKS 0x1
873 #define ALARM_FLAG_EXPIRED 0x2
875 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
877 return t
->flags
& ALARM_FLAG_DYNTICKS
;
880 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
882 if (!alarm_has_dynticks(t
))
888 /* TODO: MIN_TIMER_REARM_US should be optimized */
889 #define MIN_TIMER_REARM_US 250
891 static struct qemu_alarm_timer
*alarm_timer
;
895 struct qemu_alarm_win32
{
899 } alarm_win32_data
= {0, NULL
, -1};
901 static int win32_start_timer(struct qemu_alarm_timer
*t
);
902 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
903 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
907 static int unix_start_timer(struct qemu_alarm_timer
*t
);
908 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
912 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
913 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
914 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
916 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
917 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
919 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
920 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
922 #endif /* __linux__ */
926 /* Correlation between real and virtual time is always going to be
927 fairly approximate, so ignore small variation.
928 When the guest is idle real and virtual time will be aligned in
930 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
932 static void icount_adjust(void)
937 static int64_t last_delta
;
938 /* If the VM is not running, then do nothing. */
942 cur_time
= cpu_get_clock();
943 cur_icount
= qemu_get_clock(vm_clock
);
944 delta
= cur_icount
- cur_time
;
945 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
947 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
948 && icount_time_shift
> 0) {
949 /* The guest is getting too far ahead. Slow time down. */
953 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
954 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
955 /* The guest is getting too far behind. Speed time up. */
959 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
962 static void icount_adjust_rt(void * opaque
)
964 qemu_mod_timer(icount_rt_timer
,
965 qemu_get_clock(rt_clock
) + 1000);
969 static void icount_adjust_vm(void * opaque
)
971 qemu_mod_timer(icount_vm_timer
,
972 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
976 static void init_icount_adjust(void)
978 /* Have both realtime and virtual time triggers for speed adjustment.
979 The realtime trigger catches emulated time passing too slowly,
980 the virtual time trigger catches emulated time passing too fast.
981 Realtime triggers occur even when idle, so use them less frequently
983 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
984 qemu_mod_timer(icount_rt_timer
,
985 qemu_get_clock(rt_clock
) + 1000);
986 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
987 qemu_mod_timer(icount_vm_timer
,
988 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
991 static struct qemu_alarm_timer alarm_timers
[] = {
994 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
995 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
996 /* HPET - if available - is preferred */
997 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
998 /* ...otherwise try RTC */
999 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1001 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1003 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1004 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1005 {"win32", 0, win32_start_timer
,
1006 win32_stop_timer
, NULL
, &alarm_win32_data
},
1011 static void show_available_alarms(void)
1015 printf("Available alarm timers, in order of precedence:\n");
1016 for (i
= 0; alarm_timers
[i
].name
; i
++)
1017 printf("%s\n", alarm_timers
[i
].name
);
1020 static void configure_alarms(char const *opt
)
1024 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1027 struct qemu_alarm_timer tmp
;
1029 if (!strcmp(opt
, "?")) {
1030 show_available_alarms();
1036 /* Reorder the array */
1037 name
= strtok(arg
, ",");
1039 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1040 if (!strcmp(alarm_timers
[i
].name
, name
))
1045 fprintf(stderr
, "Unknown clock %s\n", name
);
1054 tmp
= alarm_timers
[i
];
1055 alarm_timers
[i
] = alarm_timers
[cur
];
1056 alarm_timers
[cur
] = tmp
;
1060 name
= strtok(NULL
, ",");
1066 /* Disable remaining timers */
1067 for (i
= cur
; i
< count
; i
++)
1068 alarm_timers
[i
].name
= NULL
;
1070 show_available_alarms();
1075 QEMUClock
*rt_clock
;
1076 QEMUClock
*vm_clock
;
1078 static QEMUTimer
*active_timers
[2];
1080 static QEMUClock
*qemu_new_clock(int type
)
1083 clock
= qemu_mallocz(sizeof(QEMUClock
));
1090 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1094 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1097 ts
->opaque
= opaque
;
1101 void qemu_free_timer(QEMUTimer
*ts
)
1106 /* stop a timer, but do not dealloc it */
1107 void qemu_del_timer(QEMUTimer
*ts
)
1111 /* NOTE: this code must be signal safe because
1112 qemu_timer_expired() can be called from a signal. */
1113 pt
= &active_timers
[ts
->clock
->type
];
1126 /* modify the current timer so that it will be fired when current_time
1127 >= expire_time. The corresponding callback will be called. */
1128 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1134 /* add the timer in the sorted list */
1135 /* NOTE: this code must be signal safe because
1136 qemu_timer_expired() can be called from a signal. */
1137 pt
= &active_timers
[ts
->clock
->type
];
1142 if (t
->expire_time
> expire_time
)
1146 ts
->expire_time
= expire_time
;
1150 /* Rearm if necessary */
1151 if (pt
== &active_timers
[ts
->clock
->type
]) {
1152 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1153 qemu_rearm_alarm_timer(alarm_timer
);
1155 /* Interrupt execution to force deadline recalculation. */
1156 if (use_icount
&& cpu_single_env
) {
1157 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1162 int qemu_timer_pending(QEMUTimer
*ts
)
1165 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1172 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1176 return (timer_head
->expire_time
<= current_time
);
1179 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1185 if (!ts
|| ts
->expire_time
> current_time
)
1187 /* remove timer from the list before calling the callback */
1188 *ptimer_head
= ts
->next
;
1191 /* run the callback (the timer list can be modified) */
1196 int64_t qemu_get_clock(QEMUClock
*clock
)
1198 switch(clock
->type
) {
1199 case QEMU_TIMER_REALTIME
:
1200 return get_clock() / 1000000;
1202 case QEMU_TIMER_VIRTUAL
:
1204 return cpu_get_icount();
1206 return cpu_get_clock();
1211 static void init_timers(void)
1214 ticks_per_sec
= QEMU_TIMER_BASE
;
1215 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1216 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1220 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1222 uint64_t expire_time
;
1224 if (qemu_timer_pending(ts
)) {
1225 expire_time
= ts
->expire_time
;
1229 qemu_put_be64(f
, expire_time
);
1232 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1234 uint64_t expire_time
;
1236 expire_time
= qemu_get_be64(f
);
1237 if (expire_time
!= -1) {
1238 qemu_mod_timer(ts
, expire_time
);
1244 static void timer_save(QEMUFile
*f
, void *opaque
)
1246 if (cpu_ticks_enabled
) {
1247 hw_error("cannot save state if virtual timers are running");
1249 qemu_put_be64(f
, cpu_ticks_offset
);
1250 qemu_put_be64(f
, ticks_per_sec
);
1251 qemu_put_be64(f
, cpu_clock_offset
);
1254 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1256 if (version_id
!= 1 && version_id
!= 2)
1258 if (cpu_ticks_enabled
) {
1261 cpu_ticks_offset
=qemu_get_be64(f
);
1262 ticks_per_sec
=qemu_get_be64(f
);
1263 if (version_id
== 2) {
1264 cpu_clock_offset
=qemu_get_be64(f
);
1270 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1271 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1273 static void host_alarm_handler(int host_signum
)
1277 #define DISP_FREQ 1000
1279 static int64_t delta_min
= INT64_MAX
;
1280 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1282 ti
= qemu_get_clock(vm_clock
);
1283 if (last_clock
!= 0) {
1284 delta
= ti
- last_clock
;
1285 if (delta
< delta_min
)
1287 if (delta
> delta_max
)
1290 if (++count
== DISP_FREQ
) {
1291 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1292 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1293 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1294 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1295 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1297 delta_min
= INT64_MAX
;
1305 if (alarm_has_dynticks(alarm_timer
) ||
1307 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1308 qemu_get_clock(vm_clock
))) ||
1309 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1310 qemu_get_clock(rt_clock
))) {
1312 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1313 SetEvent(data
->host_alarm
);
1315 CPUState
*env
= next_cpu
;
1317 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1320 /* stop the currently executing cpu because a timer occured */
1321 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1323 if (env
->kqemu_enabled
) {
1324 kqemu_cpu_interrupt(env
);
1332 static int64_t qemu_next_deadline(void)
1336 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1337 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1338 qemu_get_clock(vm_clock
);
1340 /* To avoid problems with overflow limit this to 2^32. */
1350 #if defined(__linux__) || defined(_WIN32)
1351 static uint64_t qemu_next_deadline_dyntick(void)
1359 delta
= (qemu_next_deadline() + 999) / 1000;
1361 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1362 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1363 qemu_get_clock(rt_clock
))*1000;
1364 if (rtdelta
< delta
)
1368 if (delta
< MIN_TIMER_REARM_US
)
1369 delta
= MIN_TIMER_REARM_US
;
1377 #if defined(__linux__)
1379 #define RTC_FREQ 1024
1381 static void enable_sigio_timer(int fd
)
1383 struct sigaction act
;
1386 sigfillset(&act
.sa_mask
);
1388 act
.sa_handler
= host_alarm_handler
;
1390 sigaction(SIGIO
, &act
, NULL
);
1391 fcntl(fd
, F_SETFL
, O_ASYNC
);
1392 fcntl(fd
, F_SETOWN
, getpid());
1395 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1397 struct hpet_info info
;
1400 fd
= open("/dev/hpet", O_RDONLY
);
1405 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1407 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1408 "error, but for better emulation accuracy type:\n"
1409 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1413 /* Check capabilities */
1414 r
= ioctl(fd
, HPET_INFO
, &info
);
1418 /* Enable periodic mode */
1419 r
= ioctl(fd
, HPET_EPI
, 0);
1420 if (info
.hi_flags
&& (r
< 0))
1423 /* Enable interrupt */
1424 r
= ioctl(fd
, HPET_IE_ON
, 0);
1428 enable_sigio_timer(fd
);
1429 t
->priv
= (void *)(long)fd
;
1437 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1439 int fd
= (long)t
->priv
;
1444 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1447 unsigned long current_rtc_freq
= 0;
1449 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1452 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1453 if (current_rtc_freq
!= RTC_FREQ
&&
1454 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1455 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1456 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1457 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1460 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1466 enable_sigio_timer(rtc_fd
);
1468 t
->priv
= (void *)(long)rtc_fd
;
1473 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1475 int rtc_fd
= (long)t
->priv
;
1480 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1484 struct sigaction act
;
1486 sigfillset(&act
.sa_mask
);
1488 act
.sa_handler
= host_alarm_handler
;
1490 sigaction(SIGALRM
, &act
, NULL
);
1492 ev
.sigev_value
.sival_int
= 0;
1493 ev
.sigev_notify
= SIGEV_SIGNAL
;
1494 ev
.sigev_signo
= SIGALRM
;
1496 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1497 perror("timer_create");
1499 /* disable dynticks */
1500 fprintf(stderr
, "Dynamic Ticks disabled\n");
1505 t
->priv
= (void *)host_timer
;
1510 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1512 timer_t host_timer
= (timer_t
)t
->priv
;
1514 timer_delete(host_timer
);
1517 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1519 timer_t host_timer
= (timer_t
)t
->priv
;
1520 struct itimerspec timeout
;
1521 int64_t nearest_delta_us
= INT64_MAX
;
1524 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1525 !active_timers
[QEMU_TIMER_VIRTUAL
])
1528 nearest_delta_us
= qemu_next_deadline_dyntick();
1530 /* check whether a timer is already running */
1531 if (timer_gettime(host_timer
, &timeout
)) {
1533 fprintf(stderr
, "Internal timer error: aborting\n");
1536 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1537 if (current_us
&& current_us
<= nearest_delta_us
)
1540 timeout
.it_interval
.tv_sec
= 0;
1541 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1542 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1543 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1544 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1546 fprintf(stderr
, "Internal timer error: aborting\n");
1551 #endif /* defined(__linux__) */
1553 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1555 struct sigaction act
;
1556 struct itimerval itv
;
1560 sigfillset(&act
.sa_mask
);
1562 act
.sa_handler
= host_alarm_handler
;
1564 sigaction(SIGALRM
, &act
, NULL
);
1566 itv
.it_interval
.tv_sec
= 0;
1567 /* for i386 kernel 2.6 to get 1 ms */
1568 itv
.it_interval
.tv_usec
= 999;
1569 itv
.it_value
.tv_sec
= 0;
1570 itv
.it_value
.tv_usec
= 10 * 1000;
1572 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1579 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1581 struct itimerval itv
;
1583 memset(&itv
, 0, sizeof(itv
));
1584 setitimer(ITIMER_REAL
, &itv
, NULL
);
1587 #endif /* !defined(_WIN32) */
1591 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1594 struct qemu_alarm_win32
*data
= t
->priv
;
1597 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1598 if (!data
->host_alarm
) {
1599 perror("Failed CreateEvent");
1603 memset(&tc
, 0, sizeof(tc
));
1604 timeGetDevCaps(&tc
, sizeof(tc
));
1606 if (data
->period
< tc
.wPeriodMin
)
1607 data
->period
= tc
.wPeriodMin
;
1609 timeBeginPeriod(data
->period
);
1611 flags
= TIME_CALLBACK_FUNCTION
;
1612 if (alarm_has_dynticks(t
))
1613 flags
|= TIME_ONESHOT
;
1615 flags
|= TIME_PERIODIC
;
1617 data
->timerId
= timeSetEvent(1, // interval (ms)
1618 data
->period
, // resolution
1619 host_alarm_handler
, // function
1620 (DWORD
)t
, // parameter
1623 if (!data
->timerId
) {
1624 perror("Failed to initialize win32 alarm timer");
1626 timeEndPeriod(data
->period
);
1627 CloseHandle(data
->host_alarm
);
1631 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1636 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1638 struct qemu_alarm_win32
*data
= t
->priv
;
1640 timeKillEvent(data
->timerId
);
1641 timeEndPeriod(data
->period
);
1643 CloseHandle(data
->host_alarm
);
1646 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1648 struct qemu_alarm_win32
*data
= t
->priv
;
1649 uint64_t nearest_delta_us
;
1651 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1652 !active_timers
[QEMU_TIMER_VIRTUAL
])
1655 nearest_delta_us
= qemu_next_deadline_dyntick();
1656 nearest_delta_us
/= 1000;
1658 timeKillEvent(data
->timerId
);
1660 data
->timerId
= timeSetEvent(1,
1664 TIME_ONESHOT
| TIME_PERIODIC
);
1666 if (!data
->timerId
) {
1667 perror("Failed to re-arm win32 alarm timer");
1669 timeEndPeriod(data
->period
);
1670 CloseHandle(data
->host_alarm
);
1677 static void init_timer_alarm(void)
1679 struct qemu_alarm_timer
*t
;
1682 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1683 t
= &alarm_timers
[i
];
1691 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1692 fprintf(stderr
, "Terminating\n");
1699 static void quit_timers(void)
1701 alarm_timer
->stop(alarm_timer
);
1705 /***********************************************************/
1706 /* host time/date access */
1707 void qemu_get_timedate(struct tm
*tm
, int offset
)
1714 if (rtc_date_offset
== -1) {
1718 ret
= localtime(&ti
);
1720 ti
-= rtc_date_offset
;
1724 memcpy(tm
, ret
, sizeof(struct tm
));
1727 int qemu_timedate_diff(struct tm
*tm
)
1731 if (rtc_date_offset
== -1)
1733 seconds
= mktimegm(tm
);
1735 seconds
= mktime(tm
);
1737 seconds
= mktimegm(tm
) + rtc_date_offset
;
1739 return seconds
- time(NULL
);
1742 /***********************************************************/
1743 /* character device */
1745 static void qemu_chr_event(CharDriverState
*s
, int event
)
1749 s
->chr_event(s
->handler_opaque
, event
);
1752 static void qemu_chr_reset_bh(void *opaque
)
1754 CharDriverState
*s
= opaque
;
1755 qemu_chr_event(s
, CHR_EVENT_RESET
);
1756 qemu_bh_delete(s
->bh
);
1760 void qemu_chr_reset(CharDriverState
*s
)
1762 if (s
->bh
== NULL
) {
1763 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1764 qemu_bh_schedule(s
->bh
);
1768 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1770 return s
->chr_write(s
, buf
, len
);
1773 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1777 return s
->chr_ioctl(s
, cmd
, arg
);
1780 int qemu_chr_can_read(CharDriverState
*s
)
1782 if (!s
->chr_can_read
)
1784 return s
->chr_can_read(s
->handler_opaque
);
1787 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1789 s
->chr_read(s
->handler_opaque
, buf
, len
);
1792 void qemu_chr_accept_input(CharDriverState
*s
)
1794 if (s
->chr_accept_input
)
1795 s
->chr_accept_input(s
);
1798 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1803 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1804 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1808 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1810 if (s
->chr_send_event
)
1811 s
->chr_send_event(s
, event
);
1814 void qemu_chr_add_handlers(CharDriverState
*s
,
1815 IOCanRWHandler
*fd_can_read
,
1816 IOReadHandler
*fd_read
,
1817 IOEventHandler
*fd_event
,
1820 s
->chr_can_read
= fd_can_read
;
1821 s
->chr_read
= fd_read
;
1822 s
->chr_event
= fd_event
;
1823 s
->handler_opaque
= opaque
;
1824 if (s
->chr_update_read_handler
)
1825 s
->chr_update_read_handler(s
);
1828 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1833 static CharDriverState
*qemu_chr_open_null(void)
1835 CharDriverState
*chr
;
1837 chr
= qemu_mallocz(sizeof(CharDriverState
));
1840 chr
->chr_write
= null_chr_write
;
1844 /* MUX driver for serial I/O splitting */
1845 static int term_timestamps
;
1846 static int64_t term_timestamps_start
;
1848 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1849 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1851 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1852 IOReadHandler
*chr_read
[MAX_MUX
];
1853 IOEventHandler
*chr_event
[MAX_MUX
];
1854 void *ext_opaque
[MAX_MUX
];
1855 CharDriverState
*drv
;
1856 unsigned char buffer
[MUX_BUFFER_SIZE
];
1860 int term_got_escape
;
1865 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1867 MuxDriver
*d
= chr
->opaque
;
1869 if (!term_timestamps
) {
1870 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1875 for(i
= 0; i
< len
; i
++) {
1876 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1877 if (buf
[i
] == '\n') {
1883 if (term_timestamps_start
== -1)
1884 term_timestamps_start
= ti
;
1885 ti
-= term_timestamps_start
;
1886 secs
= ti
/ 1000000000;
1887 snprintf(buf1
, sizeof(buf1
),
1888 "[%02d:%02d:%02d.%03d] ",
1892 (int)((ti
/ 1000000) % 1000));
1893 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1900 static const char * const mux_help
[] = {
1901 "% h print this help\n\r",
1902 "% x exit emulator\n\r",
1903 "% s save disk data back to file (if -snapshot)\n\r",
1904 "% t toggle console timestamps\n\r"
1905 "% b send break (magic sysrq)\n\r",
1906 "% c switch between console and monitor\n\r",
1911 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1912 static void mux_print_help(CharDriverState
*chr
)
1915 char ebuf
[15] = "Escape-Char";
1916 char cbuf
[50] = "\n\r";
1918 if (term_escape_char
> 0 && term_escape_char
< 26) {
1919 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1920 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1922 snprintf(cbuf
, sizeof(cbuf
),
1923 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1926 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1927 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1928 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1929 if (mux_help
[i
][j
] == '%')
1930 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1932 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1937 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1939 if (d
->term_got_escape
) {
1940 d
->term_got_escape
= 0;
1941 if (ch
== term_escape_char
)
1946 mux_print_help(chr
);
1950 const char *term
= "QEMU: Terminated\n\r";
1951 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1958 for (i
= 0; i
< nb_drives
; i
++) {
1959 bdrv_commit(drives_table
[i
].bdrv
);
1964 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1967 /* Switch to the next registered device */
1969 if (chr
->focus
>= d
->mux_cnt
)
1973 term_timestamps
= !term_timestamps
;
1974 term_timestamps_start
= -1;
1977 } else if (ch
== term_escape_char
) {
1978 d
->term_got_escape
= 1;
1986 static void mux_chr_accept_input(CharDriverState
*chr
)
1989 MuxDriver
*d
= chr
->opaque
;
1991 while (d
->prod
!= d
->cons
&&
1992 d
->chr_can_read
[m
] &&
1993 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1994 d
->chr_read
[m
](d
->ext_opaque
[m
],
1995 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1999 static int mux_chr_can_read(void *opaque
)
2001 CharDriverState
*chr
= opaque
;
2002 MuxDriver
*d
= chr
->opaque
;
2004 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2006 if (d
->chr_can_read
[chr
->focus
])
2007 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2011 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2013 CharDriverState
*chr
= opaque
;
2014 MuxDriver
*d
= chr
->opaque
;
2018 mux_chr_accept_input (opaque
);
2020 for(i
= 0; i
< size
; i
++)
2021 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2022 if (d
->prod
== d
->cons
&&
2023 d
->chr_can_read
[m
] &&
2024 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2025 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2027 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2031 static void mux_chr_event(void *opaque
, int event
)
2033 CharDriverState
*chr
= opaque
;
2034 MuxDriver
*d
= chr
->opaque
;
2037 /* Send the event to all registered listeners */
2038 for (i
= 0; i
< d
->mux_cnt
; i
++)
2039 if (d
->chr_event
[i
])
2040 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2043 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2045 MuxDriver
*d
= chr
->opaque
;
2047 if (d
->mux_cnt
>= MAX_MUX
) {
2048 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2051 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2052 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2053 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2054 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2055 /* Fix up the real driver with mux routines */
2056 if (d
->mux_cnt
== 0) {
2057 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2058 mux_chr_event
, chr
);
2060 chr
->focus
= d
->mux_cnt
;
2064 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2066 CharDriverState
*chr
;
2069 chr
= qemu_mallocz(sizeof(CharDriverState
));
2072 d
= qemu_mallocz(sizeof(MuxDriver
));
2081 chr
->chr_write
= mux_chr_write
;
2082 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2083 chr
->chr_accept_input
= mux_chr_accept_input
;
2090 static void socket_cleanup(void)
2095 static int socket_init(void)
2100 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2102 err
= WSAGetLastError();
2103 fprintf(stderr
, "WSAStartup: %d\n", err
);
2106 atexit(socket_cleanup
);
2110 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2116 ret
= send(fd
, buf
, len
, 0);
2119 errno
= WSAGetLastError();
2120 if (errno
!= WSAEWOULDBLOCK
) {
2123 } else if (ret
== 0) {
2135 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2141 ret
= write(fd
, buf
, len
);
2143 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2145 } else if (ret
== 0) {
2155 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2157 return unix_write(fd
, buf
, len1
);
2159 #endif /* !_WIN32 */
2168 #define STDIO_MAX_CLIENTS 1
2169 static int stdio_nb_clients
= 0;
2171 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2173 FDCharDriver
*s
= chr
->opaque
;
2174 return unix_write(s
->fd_out
, buf
, len
);
2177 static int fd_chr_read_poll(void *opaque
)
2179 CharDriverState
*chr
= opaque
;
2180 FDCharDriver
*s
= chr
->opaque
;
2182 s
->max_size
= qemu_chr_can_read(chr
);
2186 static void fd_chr_read(void *opaque
)
2188 CharDriverState
*chr
= opaque
;
2189 FDCharDriver
*s
= chr
->opaque
;
2194 if (len
> s
->max_size
)
2198 size
= read(s
->fd_in
, buf
, len
);
2200 /* FD has been closed. Remove it from the active list. */
2201 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2205 qemu_chr_read(chr
, buf
, size
);
2209 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2211 FDCharDriver
*s
= chr
->opaque
;
2213 if (s
->fd_in
>= 0) {
2214 if (nographic
&& s
->fd_in
== 0) {
2216 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2217 fd_chr_read
, NULL
, chr
);
2222 static void fd_chr_close(struct CharDriverState
*chr
)
2224 FDCharDriver
*s
= chr
->opaque
;
2226 if (s
->fd_in
>= 0) {
2227 if (nographic
&& s
->fd_in
== 0) {
2229 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2236 /* open a character device to a unix fd */
2237 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2239 CharDriverState
*chr
;
2242 chr
= qemu_mallocz(sizeof(CharDriverState
));
2245 s
= qemu_mallocz(sizeof(FDCharDriver
));
2253 chr
->chr_write
= fd_chr_write
;
2254 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2255 chr
->chr_close
= fd_chr_close
;
2257 qemu_chr_reset(chr
);
2262 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2266 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2269 return qemu_chr_open_fd(-1, fd_out
);
2272 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2275 char filename_in
[256], filename_out
[256];
2277 snprintf(filename_in
, 256, "%s.in", filename
);
2278 snprintf(filename_out
, 256, "%s.out", filename
);
2279 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2280 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2281 if (fd_in
< 0 || fd_out
< 0) {
2286 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2290 return qemu_chr_open_fd(fd_in
, fd_out
);
2294 /* for STDIO, we handle the case where several clients use it
2297 #define TERM_FIFO_MAX_SIZE 1
2299 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2300 static int term_fifo_size
;
2302 static int stdio_read_poll(void *opaque
)
2304 CharDriverState
*chr
= opaque
;
2306 /* try to flush the queue if needed */
2307 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2308 qemu_chr_read(chr
, term_fifo
, 1);
2311 /* see if we can absorb more chars */
2312 if (term_fifo_size
== 0)
2318 static void stdio_read(void *opaque
)
2322 CharDriverState
*chr
= opaque
;
2324 size
= read(0, buf
, 1);
2326 /* stdin has been closed. Remove it from the active list. */
2327 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2331 if (qemu_chr_can_read(chr
) > 0) {
2332 qemu_chr_read(chr
, buf
, 1);
2333 } else if (term_fifo_size
== 0) {
2334 term_fifo
[term_fifo_size
++] = buf
[0];
2339 /* init terminal so that we can grab keys */
2340 static struct termios oldtty
;
2341 static int old_fd0_flags
;
2342 static int term_atexit_done
;
2344 static void term_exit(void)
2346 tcsetattr (0, TCSANOW
, &oldtty
);
2347 fcntl(0, F_SETFL
, old_fd0_flags
);
2350 static void term_init(void)
2354 tcgetattr (0, &tty
);
2356 old_fd0_flags
= fcntl(0, F_GETFL
);
2358 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2359 |INLCR
|IGNCR
|ICRNL
|IXON
);
2360 tty
.c_oflag
|= OPOST
;
2361 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2362 /* if graphical mode, we allow Ctrl-C handling */
2364 tty
.c_lflag
&= ~ISIG
;
2365 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2368 tty
.c_cc
[VTIME
] = 0;
2370 tcsetattr (0, TCSANOW
, &tty
);
2372 if (!term_atexit_done
++)
2375 fcntl(0, F_SETFL
, O_NONBLOCK
);
2378 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2382 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2386 static CharDriverState
*qemu_chr_open_stdio(void)
2388 CharDriverState
*chr
;
2390 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2392 chr
= qemu_chr_open_fd(0, 1);
2393 chr
->chr_close
= qemu_chr_close_stdio
;
2394 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2402 /* Once Solaris has openpty(), this is going to be removed. */
2403 int openpty(int *amaster
, int *aslave
, char *name
,
2404 struct termios
*termp
, struct winsize
*winp
)
2407 int mfd
= -1, sfd
= -1;
2409 *amaster
= *aslave
= -1;
2411 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2415 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2418 if ((slave
= ptsname(mfd
)) == NULL
)
2421 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2424 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2425 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2433 ioctl(sfd
, TIOCSWINSZ
, winp
);
2444 void cfmakeraw (struct termios
*termios_p
)
2446 termios_p
->c_iflag
&=
2447 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2448 termios_p
->c_oflag
&= ~OPOST
;
2449 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2450 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2451 termios_p
->c_cflag
|= CS8
;
2453 termios_p
->c_cc
[VMIN
] = 0;
2454 termios_p
->c_cc
[VTIME
] = 0;
2458 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2459 || defined(__NetBSD__) || defined(__OpenBSD__)
2469 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2470 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2472 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2474 PtyCharDriver
*s
= chr
->opaque
;
2476 if (!s
->connected
) {
2477 /* guest sends data, check for (re-)connect */
2478 pty_chr_update_read_handler(chr
);
2481 return unix_write(s
->fd
, buf
, len
);
2484 static int pty_chr_read_poll(void *opaque
)
2486 CharDriverState
*chr
= opaque
;
2487 PtyCharDriver
*s
= chr
->opaque
;
2489 s
->read_bytes
= qemu_chr_can_read(chr
);
2490 return s
->read_bytes
;
2493 static void pty_chr_read(void *opaque
)
2495 CharDriverState
*chr
= opaque
;
2496 PtyCharDriver
*s
= chr
->opaque
;
2501 if (len
> s
->read_bytes
)
2502 len
= s
->read_bytes
;
2505 size
= read(s
->fd
, buf
, len
);
2506 if ((size
== -1 && errno
== EIO
) ||
2508 pty_chr_state(chr
, 0);
2512 pty_chr_state(chr
, 1);
2513 qemu_chr_read(chr
, buf
, size
);
2517 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2519 PtyCharDriver
*s
= chr
->opaque
;
2521 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2522 pty_chr_read
, NULL
, chr
);
2525 * Short timeout here: just need wait long enougth that qemu makes
2526 * it through the poll loop once. When reconnected we want a
2527 * short timeout so we notice it almost instantly. Otherwise
2528 * read() gives us -EIO instantly, making pty_chr_state() reset the
2529 * timeout to the normal (much longer) poll interval before the
2532 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2535 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2537 PtyCharDriver
*s
= chr
->opaque
;
2540 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2543 /* (re-)connect poll interval for idle guests: once per second.
2544 * We check more frequently in case the guests sends data to
2545 * the virtual device linked to our pty. */
2546 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2549 qemu_chr_reset(chr
);
2554 static void pty_chr_timer(void *opaque
)
2556 struct CharDriverState
*chr
= opaque
;
2557 PtyCharDriver
*s
= chr
->opaque
;
2562 /* If we arrive here without polling being cleared due
2563 * read returning -EIO, then we are (re-)connected */
2564 pty_chr_state(chr
, 1);
2569 pty_chr_update_read_handler(chr
);
2572 static void pty_chr_close(struct CharDriverState
*chr
)
2574 PtyCharDriver
*s
= chr
->opaque
;
2576 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2581 static CharDriverState
*qemu_chr_open_pty(void)
2583 CharDriverState
*chr
;
2587 #if defined(__OpenBSD__)
2588 char pty_name
[PATH_MAX
];
2589 #define q_ptsname(x) pty_name
2591 char *pty_name
= NULL
;
2592 #define q_ptsname(x) ptsname(x)
2595 chr
= qemu_mallocz(sizeof(CharDriverState
));
2598 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2604 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2608 /* Set raw attributes on the pty. */
2610 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2613 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2616 chr
->chr_write
= pty_chr_write
;
2617 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2618 chr
->chr_close
= pty_chr_close
;
2620 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2625 static void tty_serial_init(int fd
, int speed
,
2626 int parity
, int data_bits
, int stop_bits
)
2632 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2633 speed
, parity
, data_bits
, stop_bits
);
2635 tcgetattr (fd
, &tty
);
2638 if (speed
<= 50 * MARGIN
)
2640 else if (speed
<= 75 * MARGIN
)
2642 else if (speed
<= 300 * MARGIN
)
2644 else if (speed
<= 600 * MARGIN
)
2646 else if (speed
<= 1200 * MARGIN
)
2648 else if (speed
<= 2400 * MARGIN
)
2650 else if (speed
<= 4800 * MARGIN
)
2652 else if (speed
<= 9600 * MARGIN
)
2654 else if (speed
<= 19200 * MARGIN
)
2656 else if (speed
<= 38400 * MARGIN
)
2658 else if (speed
<= 57600 * MARGIN
)
2660 else if (speed
<= 115200 * MARGIN
)
2665 cfsetispeed(&tty
, spd
);
2666 cfsetospeed(&tty
, spd
);
2668 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2669 |INLCR
|IGNCR
|ICRNL
|IXON
);
2670 tty
.c_oflag
|= OPOST
;
2671 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2672 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2693 tty
.c_cflag
|= PARENB
;
2696 tty
.c_cflag
|= PARENB
| PARODD
;
2700 tty
.c_cflag
|= CSTOPB
;
2702 tcsetattr (fd
, TCSANOW
, &tty
);
2705 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2707 FDCharDriver
*s
= chr
->opaque
;
2710 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2712 QEMUSerialSetParams
*ssp
= arg
;
2713 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2714 ssp
->data_bits
, ssp
->stop_bits
);
2717 case CHR_IOCTL_SERIAL_SET_BREAK
:
2719 int enable
= *(int *)arg
;
2721 tcsendbreak(s
->fd_in
, 1);
2724 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2727 int *targ
= (int *)arg
;
2728 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2730 if (sarg
| TIOCM_CTS
)
2731 *targ
|= CHR_TIOCM_CTS
;
2732 if (sarg
| TIOCM_CAR
)
2733 *targ
|= CHR_TIOCM_CAR
;
2734 if (sarg
| TIOCM_DSR
)
2735 *targ
|= CHR_TIOCM_DSR
;
2736 if (sarg
| TIOCM_RI
)
2737 *targ
|= CHR_TIOCM_RI
;
2738 if (sarg
| TIOCM_DTR
)
2739 *targ
|= CHR_TIOCM_DTR
;
2740 if (sarg
| TIOCM_RTS
)
2741 *targ
|= CHR_TIOCM_RTS
;
2744 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2746 int sarg
= *(int *)arg
;
2748 if (sarg
| CHR_TIOCM_DTR
)
2750 if (sarg
| CHR_TIOCM_RTS
)
2752 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2761 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2763 CharDriverState
*chr
;
2766 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2767 tty_serial_init(fd
, 115200, 'N', 8, 1);
2768 chr
= qemu_chr_open_fd(fd
, fd
);
2773 chr
->chr_ioctl
= tty_serial_ioctl
;
2774 qemu_chr_reset(chr
);
2777 #else /* ! __linux__ && ! __sun__ */
2778 static CharDriverState
*qemu_chr_open_pty(void)
2782 #endif /* __linux__ || __sun__ */
2784 #if defined(__linux__)
2788 } ParallelCharDriver
;
2790 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2792 if (s
->mode
!= mode
) {
2794 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2801 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2803 ParallelCharDriver
*drv
= chr
->opaque
;
2808 case CHR_IOCTL_PP_READ_DATA
:
2809 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2811 *(uint8_t *)arg
= b
;
2813 case CHR_IOCTL_PP_WRITE_DATA
:
2814 b
= *(uint8_t *)arg
;
2815 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2818 case CHR_IOCTL_PP_READ_CONTROL
:
2819 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2821 /* Linux gives only the lowest bits, and no way to know data
2822 direction! For better compatibility set the fixed upper
2824 *(uint8_t *)arg
= b
| 0xc0;
2826 case CHR_IOCTL_PP_WRITE_CONTROL
:
2827 b
= *(uint8_t *)arg
;
2828 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2831 case CHR_IOCTL_PP_READ_STATUS
:
2832 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2834 *(uint8_t *)arg
= b
;
2836 case CHR_IOCTL_PP_DATA_DIR
:
2837 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2840 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2841 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2842 struct ParallelIOArg
*parg
= arg
;
2843 int n
= read(fd
, parg
->buffer
, parg
->count
);
2844 if (n
!= parg
->count
) {
2849 case CHR_IOCTL_PP_EPP_READ
:
2850 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2851 struct ParallelIOArg
*parg
= arg
;
2852 int n
= read(fd
, parg
->buffer
, parg
->count
);
2853 if (n
!= parg
->count
) {
2858 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2859 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2860 struct ParallelIOArg
*parg
= arg
;
2861 int n
= write(fd
, parg
->buffer
, parg
->count
);
2862 if (n
!= parg
->count
) {
2867 case CHR_IOCTL_PP_EPP_WRITE
:
2868 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2869 struct ParallelIOArg
*parg
= arg
;
2870 int n
= write(fd
, parg
->buffer
, parg
->count
);
2871 if (n
!= parg
->count
) {
2882 static void pp_close(CharDriverState
*chr
)
2884 ParallelCharDriver
*drv
= chr
->opaque
;
2887 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2888 ioctl(fd
, PPRELEASE
);
2893 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2895 CharDriverState
*chr
;
2896 ParallelCharDriver
*drv
;
2899 TFR(fd
= open(filename
, O_RDWR
));
2903 if (ioctl(fd
, PPCLAIM
) < 0) {
2908 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2914 drv
->mode
= IEEE1284_MODE_COMPAT
;
2916 chr
= qemu_mallocz(sizeof(CharDriverState
));
2922 chr
->chr_write
= null_chr_write
;
2923 chr
->chr_ioctl
= pp_ioctl
;
2924 chr
->chr_close
= pp_close
;
2927 qemu_chr_reset(chr
);
2931 #endif /* __linux__ */
2937 HANDLE hcom
, hrecv
, hsend
;
2938 OVERLAPPED orecv
, osend
;
2943 #define NSENDBUF 2048
2944 #define NRECVBUF 2048
2945 #define MAXCONNECT 1
2946 #define NTIMEOUT 5000
2948 static int win_chr_poll(void *opaque
);
2949 static int win_chr_pipe_poll(void *opaque
);
2951 static void win_chr_close(CharDriverState
*chr
)
2953 WinCharState
*s
= chr
->opaque
;
2956 CloseHandle(s
->hsend
);
2960 CloseHandle(s
->hrecv
);
2964 CloseHandle(s
->hcom
);
2968 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2970 qemu_del_polling_cb(win_chr_poll
, chr
);
2973 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2975 WinCharState
*s
= chr
->opaque
;
2977 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2982 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2984 fprintf(stderr
, "Failed CreateEvent\n");
2987 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2989 fprintf(stderr
, "Failed CreateEvent\n");
2993 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2994 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2995 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2996 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3001 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3002 fprintf(stderr
, "Failed SetupComm\n");
3006 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3007 size
= sizeof(COMMCONFIG
);
3008 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3009 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3010 CommConfigDialog(filename
, NULL
, &comcfg
);
3012 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3013 fprintf(stderr
, "Failed SetCommState\n");
3017 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3018 fprintf(stderr
, "Failed SetCommMask\n");
3022 cto
.ReadIntervalTimeout
= MAXDWORD
;
3023 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3024 fprintf(stderr
, "Failed SetCommTimeouts\n");
3028 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3029 fprintf(stderr
, "Failed ClearCommError\n");
3032 qemu_add_polling_cb(win_chr_poll
, chr
);
3040 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3042 WinCharState
*s
= chr
->opaque
;
3043 DWORD len
, ret
, size
, err
;
3046 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3047 s
->osend
.hEvent
= s
->hsend
;
3050 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3052 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3054 err
= GetLastError();
3055 if (err
== ERROR_IO_PENDING
) {
3056 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3074 static int win_chr_read_poll(CharDriverState
*chr
)
3076 WinCharState
*s
= chr
->opaque
;
3078 s
->max_size
= qemu_chr_can_read(chr
);
3082 static void win_chr_readfile(CharDriverState
*chr
)
3084 WinCharState
*s
= chr
->opaque
;
3089 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3090 s
->orecv
.hEvent
= s
->hrecv
;
3091 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3093 err
= GetLastError();
3094 if (err
== ERROR_IO_PENDING
) {
3095 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3100 qemu_chr_read(chr
, buf
, size
);
3104 static void win_chr_read(CharDriverState
*chr
)
3106 WinCharState
*s
= chr
->opaque
;
3108 if (s
->len
> s
->max_size
)
3109 s
->len
= s
->max_size
;
3113 win_chr_readfile(chr
);
3116 static int win_chr_poll(void *opaque
)
3118 CharDriverState
*chr
= opaque
;
3119 WinCharState
*s
= chr
->opaque
;
3123 ClearCommError(s
->hcom
, &comerr
, &status
);
3124 if (status
.cbInQue
> 0) {
3125 s
->len
= status
.cbInQue
;
3126 win_chr_read_poll(chr
);
3133 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3135 CharDriverState
*chr
;
3138 chr
= qemu_mallocz(sizeof(CharDriverState
));
3141 s
= qemu_mallocz(sizeof(WinCharState
));
3147 chr
->chr_write
= win_chr_write
;
3148 chr
->chr_close
= win_chr_close
;
3150 if (win_chr_init(chr
, filename
) < 0) {
3155 qemu_chr_reset(chr
);
3159 static int win_chr_pipe_poll(void *opaque
)
3161 CharDriverState
*chr
= opaque
;
3162 WinCharState
*s
= chr
->opaque
;
3165 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3168 win_chr_read_poll(chr
);
3175 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3177 WinCharState
*s
= chr
->opaque
;
3185 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3187 fprintf(stderr
, "Failed CreateEvent\n");
3190 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3192 fprintf(stderr
, "Failed CreateEvent\n");
3196 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3197 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3198 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3200 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3201 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3202 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3207 ZeroMemory(&ov
, sizeof(ov
));
3208 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3209 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3211 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3215 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3217 fprintf(stderr
, "Failed GetOverlappedResult\n");
3219 CloseHandle(ov
.hEvent
);
3226 CloseHandle(ov
.hEvent
);
3229 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3238 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3240 CharDriverState
*chr
;
3243 chr
= qemu_mallocz(sizeof(CharDriverState
));
3246 s
= qemu_mallocz(sizeof(WinCharState
));
3252 chr
->chr_write
= win_chr_write
;
3253 chr
->chr_close
= win_chr_close
;
3255 if (win_chr_pipe_init(chr
, filename
) < 0) {
3260 qemu_chr_reset(chr
);
3264 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3266 CharDriverState
*chr
;
3269 chr
= qemu_mallocz(sizeof(CharDriverState
));
3272 s
= qemu_mallocz(sizeof(WinCharState
));
3279 chr
->chr_write
= win_chr_write
;
3280 qemu_chr_reset(chr
);
3284 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3286 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3289 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3293 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3294 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3295 if (fd_out
== INVALID_HANDLE_VALUE
)
3298 return qemu_chr_open_win_file(fd_out
);
3300 #endif /* !_WIN32 */
3302 /***********************************************************/
3303 /* UDP Net console */
3307 struct sockaddr_in daddr
;
3314 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3316 NetCharDriver
*s
= chr
->opaque
;
3318 return sendto(s
->fd
, buf
, len
, 0,
3319 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3322 static int udp_chr_read_poll(void *opaque
)
3324 CharDriverState
*chr
= opaque
;
3325 NetCharDriver
*s
= chr
->opaque
;
3327 s
->max_size
= qemu_chr_can_read(chr
);
3329 /* If there were any stray characters in the queue process them
3332 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3333 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3335 s
->max_size
= qemu_chr_can_read(chr
);
3340 static void udp_chr_read(void *opaque
)
3342 CharDriverState
*chr
= opaque
;
3343 NetCharDriver
*s
= chr
->opaque
;
3345 if (s
->max_size
== 0)
3347 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3348 s
->bufptr
= s
->bufcnt
;
3353 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3354 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3356 s
->max_size
= qemu_chr_can_read(chr
);
3360 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3362 NetCharDriver
*s
= chr
->opaque
;
3365 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3366 udp_chr_read
, NULL
, chr
);
3370 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3372 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3374 int parse_host_src_port(struct sockaddr_in
*haddr
,
3375 struct sockaddr_in
*saddr
,
3378 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3380 CharDriverState
*chr
= NULL
;
3381 NetCharDriver
*s
= NULL
;
3383 struct sockaddr_in saddr
;
3385 chr
= qemu_mallocz(sizeof(CharDriverState
));
3388 s
= qemu_mallocz(sizeof(NetCharDriver
));
3392 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3394 perror("socket(PF_INET, SOCK_DGRAM)");
3398 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3399 printf("Could not parse: %s\n", def
);
3403 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3413 chr
->chr_write
= udp_chr_write
;
3414 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3427 /***********************************************************/
3428 /* TCP Net console */
3439 static void tcp_chr_accept(void *opaque
);
3441 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3443 TCPCharDriver
*s
= chr
->opaque
;
3445 return send_all(s
->fd
, buf
, len
);
3447 /* XXX: indicate an error ? */
3452 static int tcp_chr_read_poll(void *opaque
)
3454 CharDriverState
*chr
= opaque
;
3455 TCPCharDriver
*s
= chr
->opaque
;
3458 s
->max_size
= qemu_chr_can_read(chr
);
3463 #define IAC_BREAK 243
3464 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3466 uint8_t *buf
, int *size
)
3468 /* Handle any telnet client's basic IAC options to satisfy char by
3469 * char mode with no echo. All IAC options will be removed from
3470 * the buf and the do_telnetopt variable will be used to track the
3471 * state of the width of the IAC information.
3473 * IAC commands come in sets of 3 bytes with the exception of the
3474 * "IAC BREAK" command and the double IAC.
3480 for (i
= 0; i
< *size
; i
++) {
3481 if (s
->do_telnetopt
> 1) {
3482 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3483 /* Double IAC means send an IAC */
3487 s
->do_telnetopt
= 1;
3489 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3490 /* Handle IAC break commands by sending a serial break */
3491 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3496 if (s
->do_telnetopt
>= 4) {
3497 s
->do_telnetopt
= 1;
3500 if ((unsigned char)buf
[i
] == IAC
) {
3501 s
->do_telnetopt
= 2;
3512 static void tcp_chr_read(void *opaque
)
3514 CharDriverState
*chr
= opaque
;
3515 TCPCharDriver
*s
= chr
->opaque
;
3519 if (!s
->connected
|| s
->max_size
<= 0)
3522 if (len
> s
->max_size
)
3524 size
= recv(s
->fd
, buf
, len
, 0);
3526 /* connection closed */
3528 if (s
->listen_fd
>= 0) {
3529 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3531 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3534 } else if (size
> 0) {
3535 if (s
->do_telnetopt
)
3536 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3538 qemu_chr_read(chr
, buf
, size
);
3542 static void tcp_chr_connect(void *opaque
)
3544 CharDriverState
*chr
= opaque
;
3545 TCPCharDriver
*s
= chr
->opaque
;
3548 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3549 tcp_chr_read
, NULL
, chr
);
3550 qemu_chr_reset(chr
);
3553 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3554 static void tcp_chr_telnet_init(int fd
)
3557 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3558 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3559 send(fd
, (char *)buf
, 3, 0);
3560 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3561 send(fd
, (char *)buf
, 3, 0);
3562 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3563 send(fd
, (char *)buf
, 3, 0);
3564 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3565 send(fd
, (char *)buf
, 3, 0);
3568 static void socket_set_nodelay(int fd
)
3571 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3574 static void tcp_chr_accept(void *opaque
)
3576 CharDriverState
*chr
= opaque
;
3577 TCPCharDriver
*s
= chr
->opaque
;
3578 struct sockaddr_in saddr
;
3580 struct sockaddr_un uaddr
;
3582 struct sockaddr
*addr
;
3589 len
= sizeof(uaddr
);
3590 addr
= (struct sockaddr
*)&uaddr
;
3594 len
= sizeof(saddr
);
3595 addr
= (struct sockaddr
*)&saddr
;
3597 fd
= accept(s
->listen_fd
, addr
, &len
);
3598 if (fd
< 0 && errno
!= EINTR
) {
3600 } else if (fd
>= 0) {
3601 if (s
->do_telnetopt
)
3602 tcp_chr_telnet_init(fd
);
3606 socket_set_nonblock(fd
);
3608 socket_set_nodelay(fd
);
3610 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3611 tcp_chr_connect(chr
);
3614 static void tcp_chr_close(CharDriverState
*chr
)
3616 TCPCharDriver
*s
= chr
->opaque
;
3619 if (s
->listen_fd
>= 0)
3620 closesocket(s
->listen_fd
);
3624 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3628 CharDriverState
*chr
= NULL
;
3629 TCPCharDriver
*s
= NULL
;
3630 int fd
= -1, ret
, err
, val
;
3632 int is_waitconnect
= 1;
3635 struct sockaddr_in saddr
;
3637 struct sockaddr_un uaddr
;
3639 struct sockaddr
*addr
;
3644 addr
= (struct sockaddr
*)&uaddr
;
3645 addrlen
= sizeof(uaddr
);
3646 if (parse_unix_path(&uaddr
, host_str
) < 0)
3651 addr
= (struct sockaddr
*)&saddr
;
3652 addrlen
= sizeof(saddr
);
3653 if (parse_host_port(&saddr
, host_str
) < 0)
3658 while((ptr
= strchr(ptr
,','))) {
3660 if (!strncmp(ptr
,"server",6)) {
3662 } else if (!strncmp(ptr
,"nowait",6)) {
3664 } else if (!strncmp(ptr
,"nodelay",6)) {
3667 printf("Unknown option: %s\n", ptr
);
3674 chr
= qemu_mallocz(sizeof(CharDriverState
));
3677 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3683 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3686 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3691 if (!is_waitconnect
)
3692 socket_set_nonblock(fd
);
3697 s
->is_unix
= is_unix
;
3698 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3701 chr
->chr_write
= tcp_chr_write
;
3702 chr
->chr_close
= tcp_chr_close
;
3705 /* allow fast reuse */
3709 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3715 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3718 ret
= bind(fd
, addr
, addrlen
);
3722 ret
= listen(fd
, 0);
3727 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3729 s
->do_telnetopt
= 1;
3732 ret
= connect(fd
, addr
, addrlen
);
3734 err
= socket_error();
3735 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3736 } else if (err
== EINPROGRESS
) {
3739 } else if (err
== WSAEALREADY
) {
3751 socket_set_nodelay(fd
);
3753 tcp_chr_connect(chr
);
3755 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3758 if (is_listen
&& is_waitconnect
) {
3759 printf("QEMU waiting for connection on: %s\n", host_str
);
3760 tcp_chr_accept(chr
);
3761 socket_set_nonblock(s
->listen_fd
);
3773 CharDriverState
*qemu_chr_open(const char *filename
)
3777 if (!strcmp(filename
, "vc")) {
3778 return text_console_init(&display_state
, 0);
3779 } else if (strstart(filename
, "vc:", &p
)) {
3780 return text_console_init(&display_state
, p
);
3781 } else if (!strcmp(filename
, "null")) {
3782 return qemu_chr_open_null();
3784 if (strstart(filename
, "tcp:", &p
)) {
3785 return qemu_chr_open_tcp(p
, 0, 0);
3787 if (strstart(filename
, "telnet:", &p
)) {
3788 return qemu_chr_open_tcp(p
, 1, 0);
3790 if (strstart(filename
, "udp:", &p
)) {
3791 return qemu_chr_open_udp(p
);
3793 if (strstart(filename
, "mon:", &p
)) {
3794 CharDriverState
*drv
= qemu_chr_open(p
);
3796 drv
= qemu_chr_open_mux(drv
);
3797 monitor_init(drv
, !nographic
);
3800 printf("Unable to open driver: %s\n", p
);
3804 if (strstart(filename
, "unix:", &p
)) {
3805 return qemu_chr_open_tcp(p
, 0, 1);
3806 } else if (strstart(filename
, "file:", &p
)) {
3807 return qemu_chr_open_file_out(p
);
3808 } else if (strstart(filename
, "pipe:", &p
)) {
3809 return qemu_chr_open_pipe(p
);
3810 } else if (!strcmp(filename
, "pty")) {
3811 return qemu_chr_open_pty();
3812 } else if (!strcmp(filename
, "stdio")) {
3813 return qemu_chr_open_stdio();
3815 #if defined(__linux__)
3816 if (strstart(filename
, "/dev/parport", NULL
)) {
3817 return qemu_chr_open_pp(filename
);
3820 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3821 || defined(__NetBSD__) || defined(__OpenBSD__)
3822 if (strstart(filename
, "/dev/", NULL
)) {
3823 return qemu_chr_open_tty(filename
);
3827 if (strstart(filename
, "COM", NULL
)) {
3828 return qemu_chr_open_win(filename
);
3830 if (strstart(filename
, "pipe:", &p
)) {
3831 return qemu_chr_open_win_pipe(p
);
3833 if (strstart(filename
, "con:", NULL
)) {
3834 return qemu_chr_open_win_con(filename
);
3836 if (strstart(filename
, "file:", &p
)) {
3837 return qemu_chr_open_win_file_out(p
);
3840 #ifdef CONFIG_BRLAPI
3841 if (!strcmp(filename
, "braille")) {
3842 return chr_baum_init();
3850 void qemu_chr_close(CharDriverState
*chr
)
3853 chr
->chr_close(chr
);
3857 /***********************************************************/
3858 /* network device redirectors */
3860 __attribute__ (( unused
))
3861 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3865 for(i
=0;i
<size
;i
+=16) {
3869 fprintf(f
, "%08x ", i
);
3872 fprintf(f
, " %02x", buf
[i
+j
]);
3877 for(j
=0;j
<len
;j
++) {
3879 if (c
< ' ' || c
> '~')
3881 fprintf(f
, "%c", c
);
3887 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3894 offset
= strtol(p
, &last_char
, 0);
3895 if (0 == errno
&& '\0' == *last_char
&&
3896 offset
>= 0 && offset
<= 0xFFFFFF) {
3897 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3898 macaddr
[4] = (offset
& 0xFF00) >> 8;
3899 macaddr
[5] = offset
& 0xFF;
3902 for(i
= 0; i
< 6; i
++) {
3903 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3908 if (*p
!= ':' && *p
!= '-')
3919 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3924 p1
= strchr(p
, sep
);
3930 if (len
> buf_size
- 1)
3932 memcpy(buf
, p
, len
);
3939 int parse_host_src_port(struct sockaddr_in
*haddr
,
3940 struct sockaddr_in
*saddr
,
3941 const char *input_str
)
3943 char *str
= strdup(input_str
);
3944 char *host_str
= str
;
3946 const char *src_str2
;
3950 * Chop off any extra arguments at the end of the string which
3951 * would start with a comma, then fill in the src port information
3952 * if it was provided else use the "any address" and "any port".
3954 if ((ptr
= strchr(str
,',')))
3957 if ((src_str
= strchr(input_str
,'@'))) {
3962 if (parse_host_port(haddr
, host_str
) < 0)
3966 if (!src_str
|| *src_str
== '\0')
3969 if (parse_host_port(saddr
, src_str2
) < 0)
3980 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3988 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3990 saddr
->sin_family
= AF_INET
;
3991 if (buf
[0] == '\0') {
3992 saddr
->sin_addr
.s_addr
= 0;
3994 if (isdigit(buf
[0])) {
3995 if (!inet_aton(buf
, &saddr
->sin_addr
))
3998 if ((he
= gethostbyname(buf
)) == NULL
)
4000 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4003 port
= strtol(p
, (char **)&r
, 0);
4006 saddr
->sin_port
= htons(port
);
4011 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4016 len
= MIN(108, strlen(str
));
4017 p
= strchr(str
, ',');
4019 len
= MIN(len
, p
- str
);
4021 memset(uaddr
, 0, sizeof(*uaddr
));
4023 uaddr
->sun_family
= AF_UNIX
;
4024 memcpy(uaddr
->sun_path
, str
, len
);
4030 /* find or alloc a new VLAN */
4031 VLANState
*qemu_find_vlan(int id
)
4033 VLANState
**pvlan
, *vlan
;
4034 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4038 vlan
= qemu_mallocz(sizeof(VLANState
));
4043 pvlan
= &first_vlan
;
4044 while (*pvlan
!= NULL
)
4045 pvlan
= &(*pvlan
)->next
;
4050 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4051 IOReadHandler
*fd_read
,
4052 IOCanRWHandler
*fd_can_read
,
4055 VLANClientState
*vc
, **pvc
;
4056 vc
= qemu_mallocz(sizeof(VLANClientState
));
4059 vc
->fd_read
= fd_read
;
4060 vc
->fd_can_read
= fd_can_read
;
4061 vc
->opaque
= opaque
;
4065 pvc
= &vlan
->first_client
;
4066 while (*pvc
!= NULL
)
4067 pvc
= &(*pvc
)->next
;
4072 void qemu_del_vlan_client(VLANClientState
*vc
)
4074 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4076 while (*pvc
!= NULL
)
4082 pvc
= &(*pvc
)->next
;
4085 int qemu_can_send_packet(VLANClientState
*vc1
)
4087 VLANState
*vlan
= vc1
->vlan
;
4088 VLANClientState
*vc
;
4090 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4092 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4099 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4101 VLANState
*vlan
= vc1
->vlan
;
4102 VLANClientState
*vc
;
4105 printf("vlan %d send:\n", vlan
->id
);
4106 hex_dump(stdout
, buf
, size
);
4108 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4110 vc
->fd_read(vc
->opaque
, buf
, size
);
4115 #if defined(CONFIG_SLIRP)
4117 /* slirp network adapter */
4119 static int slirp_inited
;
4120 static VLANClientState
*slirp_vc
;
4122 int slirp_can_output(void)
4124 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4127 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4130 printf("slirp output:\n");
4131 hex_dump(stdout
, pkt
, pkt_len
);
4135 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4138 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4141 printf("slirp input:\n");
4142 hex_dump(stdout
, buf
, size
);
4144 slirp_input(buf
, size
);
4147 static int net_slirp_init(VLANState
*vlan
)
4149 if (!slirp_inited
) {
4153 slirp_vc
= qemu_new_vlan_client(vlan
,
4154 slirp_receive
, NULL
, NULL
);
4155 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4159 static void net_slirp_redir(const char *redir_str
)
4164 struct in_addr guest_addr
;
4165 int host_port
, guest_port
;
4167 if (!slirp_inited
) {
4173 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4175 if (!strcmp(buf
, "tcp")) {
4177 } else if (!strcmp(buf
, "udp")) {
4183 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4185 host_port
= strtol(buf
, &r
, 0);
4189 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4191 if (buf
[0] == '\0') {
4192 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4194 if (!inet_aton(buf
, &guest_addr
))
4197 guest_port
= strtol(p
, &r
, 0);
4201 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4202 fprintf(stderr
, "qemu: could not set up redirection\n");
4207 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4215 static void erase_dir(char *dir_name
)
4219 char filename
[1024];
4221 /* erase all the files in the directory */
4222 if ((d
= opendir(dir_name
)) != 0) {
4227 if (strcmp(de
->d_name
, ".") != 0 &&
4228 strcmp(de
->d_name
, "..") != 0) {
4229 snprintf(filename
, sizeof(filename
), "%s/%s",
4230 smb_dir
, de
->d_name
);
4231 if (unlink(filename
) != 0) /* is it a directory? */
4232 erase_dir(filename
);
4240 /* automatic user mode samba server configuration */
4241 static void smb_exit(void)
4246 /* automatic user mode samba server configuration */
4247 static void net_slirp_smb(const char *exported_dir
)
4249 char smb_conf
[1024];
4250 char smb_cmdline
[1024];
4253 if (!slirp_inited
) {
4258 /* XXX: better tmp dir construction */
4259 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4260 if (mkdir(smb_dir
, 0700) < 0) {
4261 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4264 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4266 f
= fopen(smb_conf
, "w");
4268 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4275 "socket address=127.0.0.1\n"
4276 "pid directory=%s\n"
4277 "lock directory=%s\n"
4278 "log file=%s/log.smbd\n"
4279 "smb passwd file=%s/smbpasswd\n"
4280 "security = share\n"
4295 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4296 SMBD_COMMAND
, smb_conf
);
4298 slirp_add_exec(0, smb_cmdline
, 4, 139);
4301 #endif /* !defined(_WIN32) */
4302 void do_info_slirp(void)
4307 #endif /* CONFIG_SLIRP */
4309 #if !defined(_WIN32)
4311 typedef struct TAPState
{
4312 VLANClientState
*vc
;
4314 char down_script
[1024];
4317 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4319 TAPState
*s
= opaque
;
4322 ret
= write(s
->fd
, buf
, size
);
4323 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4330 static void tap_send(void *opaque
)
4332 TAPState
*s
= opaque
;
4339 sbuf
.maxlen
= sizeof(buf
);
4341 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4343 size
= read(s
->fd
, buf
, sizeof(buf
));
4346 qemu_send_packet(s
->vc
, buf
, size
);
4352 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4356 s
= qemu_mallocz(sizeof(TAPState
));
4360 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4361 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4362 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4366 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4367 static int tap_open(char *ifname
, int ifname_size
)
4373 TFR(fd
= open("/dev/tap", O_RDWR
));
4375 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4380 dev
= devname(s
.st_rdev
, S_IFCHR
);
4381 pstrcpy(ifname
, ifname_size
, dev
);
4383 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4386 #elif defined(__sun__)
4387 #define TUNNEWPPA (('T'<<16) | 0x0001)
4389 * Allocate TAP device, returns opened fd.
4390 * Stores dev name in the first arg(must be large enough).
4392 int tap_alloc(char *dev
, size_t dev_size
)
4394 int tap_fd
, if_fd
, ppa
= -1;
4395 static int ip_fd
= 0;
4398 static int arp_fd
= 0;
4399 int ip_muxid
, arp_muxid
;
4400 struct strioctl strioc_if
, strioc_ppa
;
4401 int link_type
= I_PLINK
;;
4403 char actual_name
[32] = "";
4405 memset(&ifr
, 0x0, sizeof(ifr
));
4409 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4413 /* Check if IP device was opened */
4417 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4419 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4423 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4425 syslog(LOG_ERR
, "Can't open /dev/tap");
4429 /* Assign a new PPA and get its unit number. */
4430 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4431 strioc_ppa
.ic_timout
= 0;
4432 strioc_ppa
.ic_len
= sizeof(ppa
);
4433 strioc_ppa
.ic_dp
= (char *)&ppa
;
4434 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4435 syslog (LOG_ERR
, "Can't assign new interface");
4437 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4439 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4442 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4443 syslog(LOG_ERR
, "Can't push IP module");
4447 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4448 syslog(LOG_ERR
, "Can't get flags\n");
4450 snprintf (actual_name
, 32, "tap%d", ppa
);
4451 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4454 /* Assign ppa according to the unit number returned by tun device */
4456 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4457 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4458 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4459 syslog (LOG_ERR
, "Can't get flags\n");
4460 /* Push arp module to if_fd */
4461 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4462 syslog (LOG_ERR
, "Can't push ARP module (2)");
4464 /* Push arp module to ip_fd */
4465 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4466 syslog (LOG_ERR
, "I_POP failed\n");
4467 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4468 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4470 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4472 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4474 /* Set ifname to arp */
4475 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4476 strioc_if
.ic_timout
= 0;
4477 strioc_if
.ic_len
= sizeof(ifr
);
4478 strioc_if
.ic_dp
= (char *)&ifr
;
4479 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4480 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4483 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4484 syslog(LOG_ERR
, "Can't link TAP device to IP");
4488 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4489 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4493 memset(&ifr
, 0x0, sizeof(ifr
));
4494 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4495 ifr
.lifr_ip_muxid
= ip_muxid
;
4496 ifr
.lifr_arp_muxid
= arp_muxid
;
4498 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4500 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4501 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4502 syslog (LOG_ERR
, "Can't set multiplexor id");
4505 snprintf(dev
, dev_size
, "tap%d", ppa
);
4509 static int tap_open(char *ifname
, int ifname_size
)
4513 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4514 fprintf(stderr
, "Cannot allocate TAP device\n");
4517 pstrcpy(ifname
, ifname_size
, dev
);
4518 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4522 static int tap_open(char *ifname
, int ifname_size
)
4527 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4529 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4532 memset(&ifr
, 0, sizeof(ifr
));
4533 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4534 if (ifname
[0] != '\0')
4535 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4537 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4538 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4540 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4544 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4545 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4550 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4556 /* try to launch network script */
4560 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4561 for (i
= 0; i
< open_max
; i
++)
4562 if (i
!= STDIN_FILENO
&&
4563 i
!= STDOUT_FILENO
&&
4564 i
!= STDERR_FILENO
&&
4569 *parg
++ = (char *)setup_script
;
4570 *parg
++ = (char *)ifname
;
4572 execv(setup_script
, args
);
4575 while (waitpid(pid
, &status
, 0) != pid
);
4576 if (!WIFEXITED(status
) ||
4577 WEXITSTATUS(status
) != 0) {
4578 fprintf(stderr
, "%s: could not launch network script\n",
4586 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4587 const char *setup_script
, const char *down_script
)
4593 if (ifname1
!= NULL
)
4594 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4597 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4601 if (!setup_script
|| !strcmp(setup_script
, "no"))
4603 if (setup_script
[0] != '\0') {
4604 if (launch_script(setup_script
, ifname
, fd
))
4607 s
= net_tap_fd_init(vlan
, fd
);
4610 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4611 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4612 if (down_script
&& strcmp(down_script
, "no"))
4613 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4617 #endif /* !_WIN32 */
4619 #if defined(CONFIG_VDE)
4620 typedef struct VDEState
{
4621 VLANClientState
*vc
;
4625 static void vde_to_qemu(void *opaque
)
4627 VDEState
*s
= opaque
;
4631 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4633 qemu_send_packet(s
->vc
, buf
, size
);
4637 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4639 VDEState
*s
= opaque
;
4642 ret
= vde_send(s
->vde
, buf
, size
, 0);
4643 if (ret
< 0 && errno
== EINTR
) {
4650 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4651 const char *group
, int mode
)
4654 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4655 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4657 struct vde_open_args args
= {
4659 .group
= init_group
,
4663 s
= qemu_mallocz(sizeof(VDEState
));
4666 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4671 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4672 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4673 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4674 sock
, vde_datafd(s
->vde
));
4679 /* network connection */
4680 typedef struct NetSocketState
{
4681 VLANClientState
*vc
;
4683 int state
; /* 0 = getting length, 1 = getting data */
4687 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4690 typedef struct NetSocketListenState
{
4693 } NetSocketListenState
;
4695 /* XXX: we consider we can send the whole packet without blocking */
4696 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4698 NetSocketState
*s
= opaque
;
4702 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4703 send_all(s
->fd
, buf
, size
);
4706 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4708 NetSocketState
*s
= opaque
;
4709 sendto(s
->fd
, buf
, size
, 0,
4710 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4713 static void net_socket_send(void *opaque
)
4715 NetSocketState
*s
= opaque
;
4720 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4722 err
= socket_error();
4723 if (err
!= EWOULDBLOCK
)
4725 } else if (size
== 0) {
4726 /* end of connection */
4728 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4734 /* reassemble a packet from the network */
4740 memcpy(s
->buf
+ s
->index
, buf
, l
);
4744 if (s
->index
== 4) {
4746 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4752 l
= s
->packet_len
- s
->index
;
4755 memcpy(s
->buf
+ s
->index
, buf
, l
);
4759 if (s
->index
>= s
->packet_len
) {
4760 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4769 static void net_socket_send_dgram(void *opaque
)
4771 NetSocketState
*s
= opaque
;
4774 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4778 /* end of connection */
4779 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4782 qemu_send_packet(s
->vc
, s
->buf
, size
);
4785 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4790 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4791 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4792 inet_ntoa(mcastaddr
->sin_addr
),
4793 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4797 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4799 perror("socket(PF_INET, SOCK_DGRAM)");
4804 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4805 (const char *)&val
, sizeof(val
));
4807 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4811 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4817 /* Add host to multicast group */
4818 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4819 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4821 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4822 (const char *)&imr
, sizeof(struct ip_mreq
));
4824 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4828 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4830 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4831 (const char *)&val
, sizeof(val
));
4833 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4837 socket_set_nonblock(fd
);
4845 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4848 struct sockaddr_in saddr
;
4850 socklen_t saddr_len
;
4853 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4854 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4855 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4859 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4861 if (saddr
.sin_addr
.s_addr
==0) {
4862 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4866 /* clone dgram socket */
4867 newfd
= net_socket_mcast_create(&saddr
);
4869 /* error already reported by net_socket_mcast_create() */
4873 /* clone newfd to fd, close newfd */
4878 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4879 fd
, strerror(errno
));
4884 s
= qemu_mallocz(sizeof(NetSocketState
));
4889 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4890 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4892 /* mcast: save bound address as dst */
4893 if (is_connected
) s
->dgram_dst
=saddr
;
4895 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4896 "socket: fd=%d (%s mcast=%s:%d)",
4897 fd
, is_connected
? "cloned" : "",
4898 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4902 static void net_socket_connect(void *opaque
)
4904 NetSocketState
*s
= opaque
;
4905 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4908 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4912 s
= qemu_mallocz(sizeof(NetSocketState
));
4916 s
->vc
= qemu_new_vlan_client(vlan
,
4917 net_socket_receive
, NULL
, s
);
4918 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4919 "socket: fd=%d", fd
);
4921 net_socket_connect(s
);
4923 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4928 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4931 int so_type
=-1, optlen
=sizeof(so_type
);
4933 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4934 (socklen_t
*)&optlen
)< 0) {
4935 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4940 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4942 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4944 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4945 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4946 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4951 static void net_socket_accept(void *opaque
)
4953 NetSocketListenState
*s
= opaque
;
4955 struct sockaddr_in saddr
;
4960 len
= sizeof(saddr
);
4961 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4962 if (fd
< 0 && errno
!= EINTR
) {
4964 } else if (fd
>= 0) {
4968 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4972 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4973 "socket: connection from %s:%d",
4974 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4978 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4980 NetSocketListenState
*s
;
4982 struct sockaddr_in saddr
;
4984 if (parse_host_port(&saddr
, host_str
) < 0)
4987 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4991 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4996 socket_set_nonblock(fd
);
4998 /* allow fast reuse */
5000 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5002 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5007 ret
= listen(fd
, 0);
5014 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5018 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5021 int fd
, connected
, ret
, err
;
5022 struct sockaddr_in saddr
;
5024 if (parse_host_port(&saddr
, host_str
) < 0)
5027 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5032 socket_set_nonblock(fd
);
5036 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5038 err
= socket_error();
5039 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5040 } else if (err
== EINPROGRESS
) {
5043 } else if (err
== WSAEALREADY
) {
5056 s
= net_socket_fd_init(vlan
, fd
, connected
);
5059 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5060 "socket: connect to %s:%d",
5061 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5065 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5069 struct sockaddr_in saddr
;
5071 if (parse_host_port(&saddr
, host_str
) < 0)
5075 fd
= net_socket_mcast_create(&saddr
);
5079 s
= net_socket_fd_init(vlan
, fd
, 0);
5083 s
->dgram_dst
= saddr
;
5085 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5086 "socket: mcast=%s:%d",
5087 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5092 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5097 while (*p
!= '\0' && *p
!= '=') {
5098 if (q
&& (q
- buf
) < buf_size
- 1)
5108 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5113 while (*p
!= '\0') {
5115 if (*(p
+ 1) != ',')
5119 if (q
&& (q
- buf
) < buf_size
- 1)
5129 static int get_param_value(char *buf
, int buf_size
,
5130 const char *tag
, const char *str
)
5137 p
= get_opt_name(option
, sizeof(option
), p
);
5141 if (!strcmp(tag
, option
)) {
5142 (void)get_opt_value(buf
, buf_size
, p
);
5145 p
= get_opt_value(NULL
, 0, p
);
5154 static int check_params(char *buf
, int buf_size
,
5155 const char * const *params
, const char *str
)
5162 p
= get_opt_name(buf
, buf_size
, p
);
5166 for(i
= 0; params
[i
] != NULL
; i
++)
5167 if (!strcmp(params
[i
], buf
))
5169 if (params
[i
] == NULL
)
5171 p
= get_opt_value(NULL
, 0, p
);
5179 static int net_client_init(const char *device
, const char *p
)
5186 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5187 vlan_id
= strtol(buf
, NULL
, 0);
5189 vlan
= qemu_find_vlan(vlan_id
);
5191 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5194 if (!strcmp(device
, "nic")) {
5198 if (nb_nics
>= MAX_NICS
) {
5199 fprintf(stderr
, "Too Many NICs\n");
5202 nd
= &nd_table
[nb_nics
];
5203 macaddr
= nd
->macaddr
;
5209 macaddr
[5] = 0x56 + nb_nics
;
5211 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5212 if (parse_macaddr(macaddr
, buf
) < 0) {
5213 fprintf(stderr
, "invalid syntax for ethernet address\n");
5217 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5218 nd
->model
= strdup(buf
);
5222 vlan
->nb_guest_devs
++;
5225 if (!strcmp(device
, "none")) {
5226 /* does nothing. It is needed to signal that no network cards
5231 if (!strcmp(device
, "user")) {
5232 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5233 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5235 vlan
->nb_host_devs
++;
5236 ret
= net_slirp_init(vlan
);
5240 if (!strcmp(device
, "tap")) {
5242 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5243 fprintf(stderr
, "tap: no interface name\n");
5246 vlan
->nb_host_devs
++;
5247 ret
= tap_win32_init(vlan
, ifname
);
5250 if (!strcmp(device
, "tap")) {
5252 char setup_script
[1024], down_script
[1024];
5254 vlan
->nb_host_devs
++;
5255 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5256 fd
= strtol(buf
, NULL
, 0);
5257 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5259 if (net_tap_fd_init(vlan
, fd
))
5262 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5265 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5266 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5268 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5269 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5271 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5275 if (!strcmp(device
, "socket")) {
5276 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5278 fd
= strtol(buf
, NULL
, 0);
5280 if (net_socket_fd_init(vlan
, fd
, 1))
5282 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5283 ret
= net_socket_listen_init(vlan
, buf
);
5284 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5285 ret
= net_socket_connect_init(vlan
, buf
);
5286 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5287 ret
= net_socket_mcast_init(vlan
, buf
);
5289 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5292 vlan
->nb_host_devs
++;
5295 if (!strcmp(device
, "vde")) {
5296 char vde_sock
[1024], vde_group
[512];
5297 int vde_port
, vde_mode
;
5298 vlan
->nb_host_devs
++;
5299 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5302 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5303 vde_port
= strtol(buf
, NULL
, 10);
5307 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5308 vde_group
[0] = '\0';
5310 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5311 vde_mode
= strtol(buf
, NULL
, 8);
5315 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5319 fprintf(stderr
, "Unknown network device: %s\n", device
);
5323 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5329 static int net_client_parse(const char *str
)
5337 while (*p
!= '\0' && *p
!= ',') {
5338 if ((q
- device
) < sizeof(device
) - 1)
5346 return net_client_init(device
, p
);
5349 void do_info_network(void)
5352 VLANClientState
*vc
;
5354 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5355 term_printf("VLAN %d devices:\n", vlan
->id
);
5356 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5357 term_printf(" %s\n", vc
->info_str
);
5361 #define HD_ALIAS "index=%d,media=disk"
5363 #define CDROM_ALIAS "index=1,media=cdrom"
5365 #define CDROM_ALIAS "index=2,media=cdrom"
5367 #define FD_ALIAS "index=%d,if=floppy"
5368 #define PFLASH_ALIAS "if=pflash"
5369 #define MTD_ALIAS "if=mtd"
5370 #define SD_ALIAS "index=0,if=sd"
5372 static int drive_add(const char *file
, const char *fmt
, ...)
5376 if (nb_drives_opt
>= MAX_DRIVES
) {
5377 fprintf(stderr
, "qemu: too many drives\n");
5381 drives_opt
[nb_drives_opt
].file
= file
;
5383 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5384 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5387 return nb_drives_opt
++;
5390 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5394 /* seek interface, bus and unit */
5396 for (index
= 0; index
< nb_drives
; index
++)
5397 if (drives_table
[index
].type
== type
&&
5398 drives_table
[index
].bus
== bus
&&
5399 drives_table
[index
].unit
== unit
)
5405 int drive_get_max_bus(BlockInterfaceType type
)
5411 for (index
= 0; index
< nb_drives
; index
++) {
5412 if(drives_table
[index
].type
== type
&&
5413 drives_table
[index
].bus
> max_bus
)
5414 max_bus
= drives_table
[index
].bus
;
5419 static void bdrv_format_print(void *opaque
, const char *name
)
5421 fprintf(stderr
, " %s", name
);
5424 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5425 QEMUMachine
*machine
)
5430 const char *mediastr
= "";
5431 BlockInterfaceType type
;
5432 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5433 int bus_id
, unit_id
;
5434 int cyls
, heads
, secs
, translation
;
5435 BlockDriverState
*bdrv
;
5436 BlockDriver
*drv
= NULL
;
5441 char *str
= arg
->opt
;
5442 static const char * const params
[] = { "bus", "unit", "if", "index",
5443 "cyls", "heads", "secs", "trans",
5444 "media", "snapshot", "file",
5445 "cache", "format", NULL
};
5447 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5448 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5454 cyls
= heads
= secs
= 0;
5457 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5461 if (!strcmp(machine
->name
, "realview") ||
5462 !strcmp(machine
->name
, "SS-5") ||
5463 !strcmp(machine
->name
, "SS-10") ||
5464 !strcmp(machine
->name
, "SS-600MP") ||
5465 !strcmp(machine
->name
, "versatilepb") ||
5466 !strcmp(machine
->name
, "versatileab")) {
5468 max_devs
= MAX_SCSI_DEVS
;
5469 pstrcpy(devname
, sizeof(devname
), "scsi");
5472 max_devs
= MAX_IDE_DEVS
;
5473 pstrcpy(devname
, sizeof(devname
), "ide");
5477 /* extract parameters */
5479 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5480 bus_id
= strtol(buf
, NULL
, 0);
5482 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5487 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5488 unit_id
= strtol(buf
, NULL
, 0);
5490 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5495 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5496 pstrcpy(devname
, sizeof(devname
), buf
);
5497 if (!strcmp(buf
, "ide")) {
5499 max_devs
= MAX_IDE_DEVS
;
5500 } else if (!strcmp(buf
, "scsi")) {
5502 max_devs
= MAX_SCSI_DEVS
;
5503 } else if (!strcmp(buf
, "floppy")) {
5506 } else if (!strcmp(buf
, "pflash")) {
5509 } else if (!strcmp(buf
, "mtd")) {
5512 } else if (!strcmp(buf
, "sd")) {
5516 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5521 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5522 index
= strtol(buf
, NULL
, 0);
5524 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5529 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5530 cyls
= strtol(buf
, NULL
, 0);
5533 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5534 heads
= strtol(buf
, NULL
, 0);
5537 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5538 secs
= strtol(buf
, NULL
, 0);
5541 if (cyls
|| heads
|| secs
) {
5542 if (cyls
< 1 || cyls
> 16383) {
5543 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5546 if (heads
< 1 || heads
> 16) {
5547 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5550 if (secs
< 1 || secs
> 63) {
5551 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5556 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5559 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5563 if (!strcmp(buf
, "none"))
5564 translation
= BIOS_ATA_TRANSLATION_NONE
;
5565 else if (!strcmp(buf
, "lba"))
5566 translation
= BIOS_ATA_TRANSLATION_LBA
;
5567 else if (!strcmp(buf
, "auto"))
5568 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5570 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5575 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5576 if (!strcmp(buf
, "disk")) {
5578 } else if (!strcmp(buf
, "cdrom")) {
5579 if (cyls
|| secs
|| heads
) {
5581 "qemu: '%s' invalid physical CHS format\n", str
);
5584 media
= MEDIA_CDROM
;
5586 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5591 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5592 if (!strcmp(buf
, "on"))
5594 else if (!strcmp(buf
, "off"))
5597 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5602 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5603 if (!strcmp(buf
, "off"))
5605 else if (!strcmp(buf
, "on"))
5608 fprintf(stderr
, "qemu: invalid cache option\n");
5613 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5614 if (strcmp(buf
, "?") == 0) {
5615 fprintf(stderr
, "qemu: Supported formats:");
5616 bdrv_iterate_format(bdrv_format_print
, NULL
);
5617 fprintf(stderr
, "\n");
5620 drv
= bdrv_find_format(buf
);
5622 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5627 if (arg
->file
== NULL
)
5628 get_param_value(file
, sizeof(file
), "file", str
);
5630 pstrcpy(file
, sizeof(file
), arg
->file
);
5632 /* compute bus and unit according index */
5635 if (bus_id
!= 0 || unit_id
!= -1) {
5637 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5645 unit_id
= index
% max_devs
;
5646 bus_id
= index
/ max_devs
;
5650 /* if user doesn't specify a unit_id,
5651 * try to find the first free
5654 if (unit_id
== -1) {
5656 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5658 if (max_devs
&& unit_id
>= max_devs
) {
5659 unit_id
-= max_devs
;
5667 if (max_devs
&& unit_id
>= max_devs
) {
5668 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5669 str
, unit_id
, max_devs
- 1);
5674 * ignore multiple definitions
5677 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5682 if (type
== IF_IDE
|| type
== IF_SCSI
)
5683 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5685 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5686 devname
, bus_id
, mediastr
, unit_id
);
5688 snprintf(buf
, sizeof(buf
), "%s%s%i",
5689 devname
, mediastr
, unit_id
);
5690 bdrv
= bdrv_new(buf
);
5691 drives_table
[nb_drives
].bdrv
= bdrv
;
5692 drives_table
[nb_drives
].type
= type
;
5693 drives_table
[nb_drives
].bus
= bus_id
;
5694 drives_table
[nb_drives
].unit
= unit_id
;
5703 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5704 bdrv_set_translation_hint(bdrv
, translation
);
5708 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5713 /* FIXME: This isn't really a floppy, but it's a reasonable
5716 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5726 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5728 bdrv_flags
|= BDRV_O_DIRECT
;
5729 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5730 fprintf(stderr
, "qemu: could not open disk image %s\n",
5737 /***********************************************************/
5740 static USBPort
*used_usb_ports
;
5741 static USBPort
*free_usb_ports
;
5743 /* ??? Maybe change this to register a hub to keep track of the topology. */
5744 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5745 usb_attachfn attach
)
5747 port
->opaque
= opaque
;
5748 port
->index
= index
;
5749 port
->attach
= attach
;
5750 port
->next
= free_usb_ports
;
5751 free_usb_ports
= port
;
5754 int usb_device_add_dev(USBDevice
*dev
)
5758 /* Find a USB port to add the device to. */
5759 port
= free_usb_ports
;
5763 /* Create a new hub and chain it on. */
5764 free_usb_ports
= NULL
;
5765 port
->next
= used_usb_ports
;
5766 used_usb_ports
= port
;
5768 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5769 usb_attach(port
, hub
);
5770 port
= free_usb_ports
;
5773 free_usb_ports
= port
->next
;
5774 port
->next
= used_usb_ports
;
5775 used_usb_ports
= port
;
5776 usb_attach(port
, dev
);
5780 static int usb_device_add(const char *devname
)
5785 if (!free_usb_ports
)
5788 if (strstart(devname
, "host:", &p
)) {
5789 dev
= usb_host_device_open(p
);
5790 } else if (!strcmp(devname
, "mouse")) {
5791 dev
= usb_mouse_init();
5792 } else if (!strcmp(devname
, "tablet")) {
5793 dev
= usb_tablet_init();
5794 } else if (!strcmp(devname
, "keyboard")) {
5795 dev
= usb_keyboard_init();
5796 } else if (strstart(devname
, "disk:", &p
)) {
5797 dev
= usb_msd_init(p
);
5798 } else if (!strcmp(devname
, "wacom-tablet")) {
5799 dev
= usb_wacom_init();
5800 } else if (strstart(devname
, "serial:", &p
)) {
5801 dev
= usb_serial_init(p
);
5802 #ifdef CONFIG_BRLAPI
5803 } else if (!strcmp(devname
, "braille")) {
5804 dev
= usb_baum_init();
5806 } else if (strstart(devname
, "net:", &p
)) {
5809 if (net_client_init("nic", p
) < 0)
5811 nd_table
[nic
].model
= "usb";
5812 dev
= usb_net_init(&nd_table
[nic
]);
5819 return usb_device_add_dev(dev
);
5822 int usb_device_del_addr(int bus_num
, int addr
)
5828 if (!used_usb_ports
)
5834 lastp
= &used_usb_ports
;
5835 port
= used_usb_ports
;
5836 while (port
&& port
->dev
->addr
!= addr
) {
5837 lastp
= &port
->next
;
5845 *lastp
= port
->next
;
5846 usb_attach(port
, NULL
);
5847 dev
->handle_destroy(dev
);
5848 port
->next
= free_usb_ports
;
5849 free_usb_ports
= port
;
5853 static int usb_device_del(const char *devname
)
5858 if (strstart(devname
, "host:", &p
))
5859 return usb_host_device_close(p
);
5861 if (!used_usb_ports
)
5864 p
= strchr(devname
, '.');
5867 bus_num
= strtoul(devname
, NULL
, 0);
5868 addr
= strtoul(p
+ 1, NULL
, 0);
5870 return usb_device_del_addr(bus_num
, addr
);
5873 void do_usb_add(const char *devname
)
5875 usb_device_add(devname
);
5878 void do_usb_del(const char *devname
)
5880 usb_device_del(devname
);
5887 const char *speed_str
;
5890 term_printf("USB support not enabled\n");
5894 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5898 switch(dev
->speed
) {
5902 case USB_SPEED_FULL
:
5905 case USB_SPEED_HIGH
:
5912 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5913 0, dev
->addr
, speed_str
, dev
->devname
);
5917 /***********************************************************/
5918 /* PCMCIA/Cardbus */
5920 static struct pcmcia_socket_entry_s
{
5921 struct pcmcia_socket_s
*socket
;
5922 struct pcmcia_socket_entry_s
*next
;
5923 } *pcmcia_sockets
= 0;
5925 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5927 struct pcmcia_socket_entry_s
*entry
;
5929 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5930 entry
->socket
= socket
;
5931 entry
->next
= pcmcia_sockets
;
5932 pcmcia_sockets
= entry
;
5935 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5937 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5939 ptr
= &pcmcia_sockets
;
5940 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5941 if (entry
->socket
== socket
) {
5947 void pcmcia_info(void)
5949 struct pcmcia_socket_entry_s
*iter
;
5950 if (!pcmcia_sockets
)
5951 term_printf("No PCMCIA sockets\n");
5953 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5954 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5955 iter
->socket
->attached
? iter
->socket
->card_string
:
5959 /***********************************************************/
5962 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5966 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5970 static void dumb_refresh(DisplayState
*ds
)
5972 #if defined(CONFIG_SDL)
5977 static void dumb_display_init(DisplayState
*ds
)
5982 ds
->dpy_update
= dumb_update
;
5983 ds
->dpy_resize
= dumb_resize
;
5984 ds
->dpy_refresh
= dumb_refresh
;
5985 ds
->gui_timer_interval
= 500;
5989 /***********************************************************/
5992 #define MAX_IO_HANDLERS 64
5994 typedef struct IOHandlerRecord
{
5996 IOCanRWHandler
*fd_read_poll
;
5998 IOHandler
*fd_write
;
6001 /* temporary data */
6003 struct IOHandlerRecord
*next
;
6006 static IOHandlerRecord
*first_io_handler
;
6008 /* XXX: fd_read_poll should be suppressed, but an API change is
6009 necessary in the character devices to suppress fd_can_read(). */
6010 int qemu_set_fd_handler2(int fd
,
6011 IOCanRWHandler
*fd_read_poll
,
6013 IOHandler
*fd_write
,
6016 IOHandlerRecord
**pioh
, *ioh
;
6018 if (!fd_read
&& !fd_write
) {
6019 pioh
= &first_io_handler
;
6024 if (ioh
->fd
== fd
) {
6031 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6035 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6038 ioh
->next
= first_io_handler
;
6039 first_io_handler
= ioh
;
6042 ioh
->fd_read_poll
= fd_read_poll
;
6043 ioh
->fd_read
= fd_read
;
6044 ioh
->fd_write
= fd_write
;
6045 ioh
->opaque
= opaque
;
6051 int qemu_set_fd_handler(int fd
,
6053 IOHandler
*fd_write
,
6056 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6059 /***********************************************************/
6060 /* Polling handling */
6062 typedef struct PollingEntry
{
6065 struct PollingEntry
*next
;
6068 static PollingEntry
*first_polling_entry
;
6070 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6072 PollingEntry
**ppe
, *pe
;
6073 pe
= qemu_mallocz(sizeof(PollingEntry
));
6077 pe
->opaque
= opaque
;
6078 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6083 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6085 PollingEntry
**ppe
, *pe
;
6086 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6088 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6097 /***********************************************************/
6098 /* Wait objects support */
6099 typedef struct WaitObjects
{
6101 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6102 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6103 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6106 static WaitObjects wait_objects
= {0};
6108 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6110 WaitObjects
*w
= &wait_objects
;
6112 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6114 w
->events
[w
->num
] = handle
;
6115 w
->func
[w
->num
] = func
;
6116 w
->opaque
[w
->num
] = opaque
;
6121 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6124 WaitObjects
*w
= &wait_objects
;
6127 for (i
= 0; i
< w
->num
; i
++) {
6128 if (w
->events
[i
] == handle
)
6131 w
->events
[i
] = w
->events
[i
+ 1];
6132 w
->func
[i
] = w
->func
[i
+ 1];
6133 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6141 /***********************************************************/
6142 /* savevm/loadvm support */
6144 #define IO_BUF_SIZE 32768
6148 BlockDriverState
*bs
;
6151 int64_t base_offset
;
6152 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6155 int buf_size
; /* 0 when writing */
6156 uint8_t buf
[IO_BUF_SIZE
];
6159 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6163 f
= qemu_mallocz(sizeof(QEMUFile
));
6166 if (!strcmp(mode
, "wb")) {
6168 } else if (!strcmp(mode
, "rb")) {
6173 f
->outfile
= fopen(filename
, mode
);
6185 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6189 f
= qemu_mallocz(sizeof(QEMUFile
));
6194 f
->is_writable
= is_writable
;
6195 f
->base_offset
= offset
;
6199 void qemu_fflush(QEMUFile
*f
)
6201 if (!f
->is_writable
)
6203 if (f
->buf_index
> 0) {
6205 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6206 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6208 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6209 f
->buf
, f
->buf_index
);
6211 f
->buf_offset
+= f
->buf_index
;
6216 static void qemu_fill_buffer(QEMUFile
*f
)
6223 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6224 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6228 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6229 f
->buf
, IO_BUF_SIZE
);
6235 f
->buf_offset
+= len
;
6238 void qemu_fclose(QEMUFile
*f
)
6248 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6252 l
= IO_BUF_SIZE
- f
->buf_index
;
6255 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6259 if (f
->buf_index
>= IO_BUF_SIZE
)
6264 void qemu_put_byte(QEMUFile
*f
, int v
)
6266 f
->buf
[f
->buf_index
++] = v
;
6267 if (f
->buf_index
>= IO_BUF_SIZE
)
6271 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6277 l
= f
->buf_size
- f
->buf_index
;
6279 qemu_fill_buffer(f
);
6280 l
= f
->buf_size
- f
->buf_index
;
6286 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6291 return size1
- size
;
6294 int qemu_get_byte(QEMUFile
*f
)
6296 if (f
->buf_index
>= f
->buf_size
) {
6297 qemu_fill_buffer(f
);
6298 if (f
->buf_index
>= f
->buf_size
)
6301 return f
->buf
[f
->buf_index
++];
6304 int64_t qemu_ftell(QEMUFile
*f
)
6306 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6309 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6311 if (whence
== SEEK_SET
) {
6313 } else if (whence
== SEEK_CUR
) {
6314 pos
+= qemu_ftell(f
);
6316 /* SEEK_END not supported */
6319 if (f
->is_writable
) {
6321 f
->buf_offset
= pos
;
6323 f
->buf_offset
= pos
;
6330 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6332 qemu_put_byte(f
, v
>> 8);
6333 qemu_put_byte(f
, v
);
6336 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6338 qemu_put_byte(f
, v
>> 24);
6339 qemu_put_byte(f
, v
>> 16);
6340 qemu_put_byte(f
, v
>> 8);
6341 qemu_put_byte(f
, v
);
6344 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6346 qemu_put_be32(f
, v
>> 32);
6347 qemu_put_be32(f
, v
);
6350 unsigned int qemu_get_be16(QEMUFile
*f
)
6353 v
= qemu_get_byte(f
) << 8;
6354 v
|= qemu_get_byte(f
);
6358 unsigned int qemu_get_be32(QEMUFile
*f
)
6361 v
= qemu_get_byte(f
) << 24;
6362 v
|= qemu_get_byte(f
) << 16;
6363 v
|= qemu_get_byte(f
) << 8;
6364 v
|= qemu_get_byte(f
);
6368 uint64_t qemu_get_be64(QEMUFile
*f
)
6371 v
= (uint64_t)qemu_get_be32(f
) << 32;
6372 v
|= qemu_get_be32(f
);
6376 typedef struct SaveStateEntry
{
6380 SaveStateHandler
*save_state
;
6381 LoadStateHandler
*load_state
;
6383 struct SaveStateEntry
*next
;
6386 static SaveStateEntry
*first_se
;
6388 /* TODO: Individual devices generally have very little idea about the rest
6389 of the system, so instance_id should be removed/replaced.
6390 Meanwhile pass -1 as instance_id if you do not already have a clearly
6391 distinguishing id for all instances of your device class. */
6392 int register_savevm(const char *idstr
,
6395 SaveStateHandler
*save_state
,
6396 LoadStateHandler
*load_state
,
6399 SaveStateEntry
*se
, **pse
;
6401 se
= qemu_malloc(sizeof(SaveStateEntry
));
6404 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6405 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6406 se
->version_id
= version_id
;
6407 se
->save_state
= save_state
;
6408 se
->load_state
= load_state
;
6409 se
->opaque
= opaque
;
6412 /* add at the end of list */
6414 while (*pse
!= NULL
) {
6415 if (instance_id
== -1
6416 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6417 && se
->instance_id
<= (*pse
)->instance_id
)
6418 se
->instance_id
= (*pse
)->instance_id
+ 1;
6419 pse
= &(*pse
)->next
;
6425 #define QEMU_VM_FILE_MAGIC 0x5145564d
6426 #define QEMU_VM_FILE_VERSION 0x00000002
6428 static int qemu_savevm_state(QEMUFile
*f
)
6432 int64_t cur_pos
, len_pos
, total_len_pos
;
6434 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6435 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6436 total_len_pos
= qemu_ftell(f
);
6437 qemu_put_be64(f
, 0); /* total size */
6439 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6440 if (se
->save_state
== NULL
)
6441 /* this one has a loader only, for backwards compatibility */
6445 len
= strlen(se
->idstr
);
6446 qemu_put_byte(f
, len
);
6447 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6449 qemu_put_be32(f
, se
->instance_id
);
6450 qemu_put_be32(f
, se
->version_id
);
6452 /* record size: filled later */
6453 len_pos
= qemu_ftell(f
);
6454 qemu_put_be32(f
, 0);
6455 se
->save_state(f
, se
->opaque
);
6457 /* fill record size */
6458 cur_pos
= qemu_ftell(f
);
6459 len
= cur_pos
- len_pos
- 4;
6460 qemu_fseek(f
, len_pos
, SEEK_SET
);
6461 qemu_put_be32(f
, len
);
6462 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6464 cur_pos
= qemu_ftell(f
);
6465 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6466 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6467 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6473 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6477 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6478 if (!strcmp(se
->idstr
, idstr
) &&
6479 instance_id
== se
->instance_id
)
6485 static int qemu_loadvm_state(QEMUFile
*f
)
6488 int len
, ret
, instance_id
, record_len
, version_id
;
6489 int64_t total_len
, end_pos
, cur_pos
;
6493 v
= qemu_get_be32(f
);
6494 if (v
!= QEMU_VM_FILE_MAGIC
)
6496 v
= qemu_get_be32(f
);
6497 if (v
!= QEMU_VM_FILE_VERSION
) {
6502 total_len
= qemu_get_be64(f
);
6503 end_pos
= total_len
+ qemu_ftell(f
);
6505 if (qemu_ftell(f
) >= end_pos
)
6507 len
= qemu_get_byte(f
);
6508 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6510 instance_id
= qemu_get_be32(f
);
6511 version_id
= qemu_get_be32(f
);
6512 record_len
= qemu_get_be32(f
);
6514 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6515 idstr
, instance_id
, version_id
, record_len
);
6517 cur_pos
= qemu_ftell(f
);
6518 se
= find_se(idstr
, instance_id
);
6520 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6521 instance_id
, idstr
);
6523 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6525 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6526 instance_id
, idstr
);
6529 /* always seek to exact end of record */
6530 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6537 /* device can contain snapshots */
6538 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6541 !bdrv_is_removable(bs
) &&
6542 !bdrv_is_read_only(bs
));
6545 /* device must be snapshots in order to have a reliable snapshot */
6546 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6549 !bdrv_is_removable(bs
) &&
6550 !bdrv_is_read_only(bs
));
6553 static BlockDriverState
*get_bs_snapshots(void)
6555 BlockDriverState
*bs
;
6559 return bs_snapshots
;
6560 for(i
= 0; i
<= nb_drives
; i
++) {
6561 bs
= drives_table
[i
].bdrv
;
6562 if (bdrv_can_snapshot(bs
))
6571 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6574 QEMUSnapshotInfo
*sn_tab
, *sn
;
6578 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6581 for(i
= 0; i
< nb_sns
; i
++) {
6583 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6593 void do_savevm(const char *name
)
6595 BlockDriverState
*bs
, *bs1
;
6596 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6597 int must_delete
, ret
, i
;
6598 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6600 int saved_vm_running
;
6607 bs
= get_bs_snapshots();
6609 term_printf("No block device can accept snapshots\n");
6613 /* ??? Should this occur after vm_stop? */
6616 saved_vm_running
= vm_running
;
6621 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6626 memset(sn
, 0, sizeof(*sn
));
6628 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6629 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6632 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6635 /* fill auxiliary fields */
6638 sn
->date_sec
= tb
.time
;
6639 sn
->date_nsec
= tb
.millitm
* 1000000;
6641 gettimeofday(&tv
, NULL
);
6642 sn
->date_sec
= tv
.tv_sec
;
6643 sn
->date_nsec
= tv
.tv_usec
* 1000;
6645 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6647 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6648 term_printf("Device %s does not support VM state snapshots\n",
6649 bdrv_get_device_name(bs
));
6653 /* save the VM state */
6654 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6656 term_printf("Could not open VM state file\n");
6659 ret
= qemu_savevm_state(f
);
6660 sn
->vm_state_size
= qemu_ftell(f
);
6663 term_printf("Error %d while writing VM\n", ret
);
6667 /* create the snapshots */
6669 for(i
= 0; i
< nb_drives
; i
++) {
6670 bs1
= drives_table
[i
].bdrv
;
6671 if (bdrv_has_snapshot(bs1
)) {
6673 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6675 term_printf("Error while deleting snapshot on '%s'\n",
6676 bdrv_get_device_name(bs1
));
6679 ret
= bdrv_snapshot_create(bs1
, sn
);
6681 term_printf("Error while creating snapshot on '%s'\n",
6682 bdrv_get_device_name(bs1
));
6688 if (saved_vm_running
)
6692 void do_loadvm(const char *name
)
6694 BlockDriverState
*bs
, *bs1
;
6695 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6698 int saved_vm_running
;
6700 bs
= get_bs_snapshots();
6702 term_printf("No block device supports snapshots\n");
6706 /* Flush all IO requests so they don't interfere with the new state. */
6709 saved_vm_running
= vm_running
;
6712 for(i
= 0; i
<= nb_drives
; i
++) {
6713 bs1
= drives_table
[i
].bdrv
;
6714 if (bdrv_has_snapshot(bs1
)) {
6715 ret
= bdrv_snapshot_goto(bs1
, name
);
6718 term_printf("Warning: ");
6721 term_printf("Snapshots not supported on device '%s'\n",
6722 bdrv_get_device_name(bs1
));
6725 term_printf("Could not find snapshot '%s' on device '%s'\n",
6726 name
, bdrv_get_device_name(bs1
));
6729 term_printf("Error %d while activating snapshot on '%s'\n",
6730 ret
, bdrv_get_device_name(bs1
));
6733 /* fatal on snapshot block device */
6740 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6741 term_printf("Device %s does not support VM state snapshots\n",
6742 bdrv_get_device_name(bs
));
6746 /* restore the VM state */
6747 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6749 term_printf("Could not open VM state file\n");
6752 ret
= qemu_loadvm_state(f
);
6755 term_printf("Error %d while loading VM state\n", ret
);
6758 if (saved_vm_running
)
6762 void do_delvm(const char *name
)
6764 BlockDriverState
*bs
, *bs1
;
6767 bs
= get_bs_snapshots();
6769 term_printf("No block device supports snapshots\n");
6773 for(i
= 0; i
<= nb_drives
; i
++) {
6774 bs1
= drives_table
[i
].bdrv
;
6775 if (bdrv_has_snapshot(bs1
)) {
6776 ret
= bdrv_snapshot_delete(bs1
, name
);
6778 if (ret
== -ENOTSUP
)
6779 term_printf("Snapshots not supported on device '%s'\n",
6780 bdrv_get_device_name(bs1
));
6782 term_printf("Error %d while deleting snapshot on '%s'\n",
6783 ret
, bdrv_get_device_name(bs1
));
6789 void do_info_snapshots(void)
6791 BlockDriverState
*bs
, *bs1
;
6792 QEMUSnapshotInfo
*sn_tab
, *sn
;
6796 bs
= get_bs_snapshots();
6798 term_printf("No available block device supports snapshots\n");
6801 term_printf("Snapshot devices:");
6802 for(i
= 0; i
<= nb_drives
; i
++) {
6803 bs1
= drives_table
[i
].bdrv
;
6804 if (bdrv_has_snapshot(bs1
)) {
6806 term_printf(" %s", bdrv_get_device_name(bs1
));
6811 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6813 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6816 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6817 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6818 for(i
= 0; i
< nb_sns
; i
++) {
6820 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6825 /***********************************************************/
6826 /* ram save/restore */
6828 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6832 v
= qemu_get_byte(f
);
6835 if (qemu_get_buffer(f
, buf
, len
) != len
)
6839 v
= qemu_get_byte(f
);
6840 memset(buf
, v
, len
);
6848 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6853 if (qemu_get_be32(f
) != phys_ram_size
)
6855 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6856 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6863 #define BDRV_HASH_BLOCK_SIZE 1024
6864 #define IOBUF_SIZE 4096
6865 #define RAM_CBLOCK_MAGIC 0xfabe
6867 typedef struct RamCompressState
{
6870 uint8_t buf
[IOBUF_SIZE
];
6873 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6876 memset(s
, 0, sizeof(*s
));
6878 ret
= deflateInit2(&s
->zstream
, 1,
6880 9, Z_DEFAULT_STRATEGY
);
6883 s
->zstream
.avail_out
= IOBUF_SIZE
;
6884 s
->zstream
.next_out
= s
->buf
;
6888 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6890 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6891 qemu_put_be16(s
->f
, len
);
6892 qemu_put_buffer(s
->f
, buf
, len
);
6895 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6899 s
->zstream
.avail_in
= len
;
6900 s
->zstream
.next_in
= (uint8_t *)buf
;
6901 while (s
->zstream
.avail_in
> 0) {
6902 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6905 if (s
->zstream
.avail_out
== 0) {
6906 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6907 s
->zstream
.avail_out
= IOBUF_SIZE
;
6908 s
->zstream
.next_out
= s
->buf
;
6914 static void ram_compress_close(RamCompressState
*s
)
6918 /* compress last bytes */
6920 ret
= deflate(&s
->zstream
, Z_FINISH
);
6921 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6922 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6924 ram_put_cblock(s
, s
->buf
, len
);
6926 s
->zstream
.avail_out
= IOBUF_SIZE
;
6927 s
->zstream
.next_out
= s
->buf
;
6928 if (ret
== Z_STREAM_END
)
6935 deflateEnd(&s
->zstream
);
6938 typedef struct RamDecompressState
{
6941 uint8_t buf
[IOBUF_SIZE
];
6942 } RamDecompressState
;
6944 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6947 memset(s
, 0, sizeof(*s
));
6949 ret
= inflateInit(&s
->zstream
);
6955 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6959 s
->zstream
.avail_out
= len
;
6960 s
->zstream
.next_out
= buf
;
6961 while (s
->zstream
.avail_out
> 0) {
6962 if (s
->zstream
.avail_in
== 0) {
6963 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6965 clen
= qemu_get_be16(s
->f
);
6966 if (clen
> IOBUF_SIZE
)
6968 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6969 s
->zstream
.avail_in
= clen
;
6970 s
->zstream
.next_in
= s
->buf
;
6972 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6973 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6980 static void ram_decompress_close(RamDecompressState
*s
)
6982 inflateEnd(&s
->zstream
);
6985 static void ram_save(QEMUFile
*f
, void *opaque
)
6988 RamCompressState s1
, *s
= &s1
;
6991 qemu_put_be32(f
, phys_ram_size
);
6992 if (ram_compress_open(s
, f
) < 0)
6994 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6996 if (tight_savevm_enabled
) {
7000 /* find if the memory block is available on a virtual
7003 for(j
= 0; j
< nb_drives
; j
++) {
7004 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7006 BDRV_HASH_BLOCK_SIZE
);
7007 if (sector_num
>= 0)
7011 goto normal_compress
;
7014 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7015 ram_compress_buf(s
, buf
, 10);
7021 ram_compress_buf(s
, buf
, 1);
7022 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7025 ram_compress_close(s
);
7028 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7030 RamDecompressState s1
, *s
= &s1
;
7034 if (version_id
== 1)
7035 return ram_load_v1(f
, opaque
);
7036 if (version_id
!= 2)
7038 if (qemu_get_be32(f
) != phys_ram_size
)
7040 if (ram_decompress_open(s
, f
) < 0)
7042 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7043 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7044 fprintf(stderr
, "Error while reading ram block header\n");
7048 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7049 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7058 ram_decompress_buf(s
, buf
+ 1, 9);
7060 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7061 if (bs_index
>= nb_drives
) {
7062 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7065 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7067 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7068 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7069 bs_index
, sector_num
);
7076 printf("Error block header\n");
7080 ram_decompress_close(s
);
7084 /***********************************************************/
7085 /* bottom halves (can be seen as timers which expire ASAP) */
7094 static QEMUBH
*first_bh
= NULL
;
7096 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7099 bh
= qemu_mallocz(sizeof(QEMUBH
));
7103 bh
->opaque
= opaque
;
7107 int qemu_bh_poll(void)
7126 void qemu_bh_schedule(QEMUBH
*bh
)
7128 CPUState
*env
= cpu_single_env
;
7132 bh
->next
= first_bh
;
7135 /* stop the currently executing CPU to execute the BH ASAP */
7137 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7141 void qemu_bh_cancel(QEMUBH
*bh
)
7144 if (bh
->scheduled
) {
7147 pbh
= &(*pbh
)->next
;
7153 void qemu_bh_delete(QEMUBH
*bh
)
7159 /***********************************************************/
7160 /* machine registration */
7162 QEMUMachine
*first_machine
= NULL
;
7164 int qemu_register_machine(QEMUMachine
*m
)
7167 pm
= &first_machine
;
7175 static QEMUMachine
*find_machine(const char *name
)
7179 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7180 if (!strcmp(m
->name
, name
))
7186 /***********************************************************/
7187 /* main execution loop */
7189 static void gui_update(void *opaque
)
7191 DisplayState
*ds
= opaque
;
7192 ds
->dpy_refresh(ds
);
7193 qemu_mod_timer(ds
->gui_timer
,
7194 (ds
->gui_timer_interval
?
7195 ds
->gui_timer_interval
:
7196 GUI_REFRESH_INTERVAL
)
7197 + qemu_get_clock(rt_clock
));
7200 struct vm_change_state_entry
{
7201 VMChangeStateHandler
*cb
;
7203 LIST_ENTRY (vm_change_state_entry
) entries
;
7206 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7208 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7211 VMChangeStateEntry
*e
;
7213 e
= qemu_mallocz(sizeof (*e
));
7219 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7223 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7225 LIST_REMOVE (e
, entries
);
7229 static void vm_state_notify(int running
)
7231 VMChangeStateEntry
*e
;
7233 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7234 e
->cb(e
->opaque
, running
);
7238 /* XXX: support several handlers */
7239 static VMStopHandler
*vm_stop_cb
;
7240 static void *vm_stop_opaque
;
7242 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7245 vm_stop_opaque
= opaque
;
7249 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7260 qemu_rearm_alarm_timer(alarm_timer
);
7264 void vm_stop(int reason
)
7267 cpu_disable_ticks();
7271 vm_stop_cb(vm_stop_opaque
, reason
);
7278 /* reset/shutdown handler */
7280 typedef struct QEMUResetEntry
{
7281 QEMUResetHandler
*func
;
7283 struct QEMUResetEntry
*next
;
7286 static QEMUResetEntry
*first_reset_entry
;
7287 static int reset_requested
;
7288 static int shutdown_requested
;
7289 static int powerdown_requested
;
7291 int qemu_shutdown_requested(void)
7293 int r
= shutdown_requested
;
7294 shutdown_requested
= 0;
7298 int qemu_reset_requested(void)
7300 int r
= reset_requested
;
7301 reset_requested
= 0;
7305 int qemu_powerdown_requested(void)
7307 int r
= powerdown_requested
;
7308 powerdown_requested
= 0;
7312 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7314 QEMUResetEntry
**pre
, *re
;
7316 pre
= &first_reset_entry
;
7317 while (*pre
!= NULL
)
7318 pre
= &(*pre
)->next
;
7319 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7321 re
->opaque
= opaque
;
7326 void qemu_system_reset(void)
7330 /* reset all devices */
7331 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7332 re
->func(re
->opaque
);
7336 void qemu_system_reset_request(void)
7339 shutdown_requested
= 1;
7341 reset_requested
= 1;
7344 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7347 void qemu_system_shutdown_request(void)
7349 shutdown_requested
= 1;
7351 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7354 void qemu_system_powerdown_request(void)
7356 powerdown_requested
= 1;
7358 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7361 void main_loop_wait(int timeout
)
7363 IOHandlerRecord
*ioh
;
7364 fd_set rfds
, wfds
, xfds
;
7373 /* XXX: need to suppress polling by better using win32 events */
7375 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7376 ret
|= pe
->func(pe
->opaque
);
7381 WaitObjects
*w
= &wait_objects
;
7383 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7384 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7385 if (w
->func
[ret
- WAIT_OBJECT_0
])
7386 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7388 /* Check for additional signaled events */
7389 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7391 /* Check if event is signaled */
7392 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7393 if(ret2
== WAIT_OBJECT_0
) {
7395 w
->func
[i
](w
->opaque
[i
]);
7396 } else if (ret2
== WAIT_TIMEOUT
) {
7398 err
= GetLastError();
7399 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7402 } else if (ret
== WAIT_TIMEOUT
) {
7404 err
= GetLastError();
7405 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7409 /* poll any events */
7410 /* XXX: separate device handlers from system ones */
7415 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7419 (!ioh
->fd_read_poll
||
7420 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7421 FD_SET(ioh
->fd
, &rfds
);
7425 if (ioh
->fd_write
) {
7426 FD_SET(ioh
->fd
, &wfds
);
7436 tv
.tv_usec
= timeout
* 1000;
7438 #if defined(CONFIG_SLIRP)
7440 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7443 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7445 IOHandlerRecord
**pioh
;
7447 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7448 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7449 ioh
->fd_read(ioh
->opaque
);
7451 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7452 ioh
->fd_write(ioh
->opaque
);
7456 /* remove deleted IO handlers */
7457 pioh
= &first_io_handler
;
7467 #if defined(CONFIG_SLIRP)
7474 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7479 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7480 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7481 qemu_get_clock(vm_clock
));
7482 /* run dma transfers, if any */
7486 /* real time timers */
7487 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7488 qemu_get_clock(rt_clock
));
7490 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7491 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7492 qemu_rearm_alarm_timer(alarm_timer
);
7495 /* Check bottom-halves last in case any of the earlier events triggered
7501 static int main_loop(void)
7504 #ifdef CONFIG_PROFILER
7509 cur_cpu
= first_cpu
;
7510 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7517 #ifdef CONFIG_PROFILER
7518 ti
= profile_getclock();
7523 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7524 env
->icount_decr
.u16
.low
= 0;
7525 env
->icount_extra
= 0;
7526 count
= qemu_next_deadline();
7527 count
= (count
+ (1 << icount_time_shift
) - 1)
7528 >> icount_time_shift
;
7529 qemu_icount
+= count
;
7530 decr
= (count
> 0xffff) ? 0xffff : count
;
7532 env
->icount_decr
.u16
.low
= decr
;
7533 env
->icount_extra
= count
;
7535 ret
= cpu_exec(env
);
7536 #ifdef CONFIG_PROFILER
7537 qemu_time
+= profile_getclock() - ti
;
7540 /* Fold pending instructions back into the
7541 instruction counter, and clear the interrupt flag. */
7542 qemu_icount
-= (env
->icount_decr
.u16
.low
7543 + env
->icount_extra
);
7544 env
->icount_decr
.u32
= 0;
7545 env
->icount_extra
= 0;
7547 next_cpu
= env
->next_cpu
?: first_cpu
;
7548 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7549 ret
= EXCP_INTERRUPT
;
7553 if (ret
== EXCP_HLT
) {
7554 /* Give the next CPU a chance to run. */
7558 if (ret
!= EXCP_HALTED
)
7560 /* all CPUs are halted ? */
7566 if (shutdown_requested
) {
7567 ret
= EXCP_INTERRUPT
;
7575 if (reset_requested
) {
7576 reset_requested
= 0;
7577 qemu_system_reset();
7578 ret
= EXCP_INTERRUPT
;
7580 if (powerdown_requested
) {
7581 powerdown_requested
= 0;
7582 qemu_system_powerdown();
7583 ret
= EXCP_INTERRUPT
;
7585 if (unlikely(ret
== EXCP_DEBUG
)) {
7586 vm_stop(EXCP_DEBUG
);
7588 /* If all cpus are halted then wait until the next IRQ */
7589 /* XXX: use timeout computed from timers */
7590 if (ret
== EXCP_HALTED
) {
7594 /* Advance virtual time to the next event. */
7595 if (use_icount
== 1) {
7596 /* When not using an adaptive execution frequency
7597 we tend to get badly out of sync with real time,
7598 so just delay for a reasonable amount of time. */
7601 delta
= cpu_get_icount() - cpu_get_clock();
7604 /* If virtual time is ahead of real time then just
7606 timeout
= (delta
/ 1000000) + 1;
7608 /* Wait for either IO to occur or the next
7610 add
= qemu_next_deadline();
7611 /* We advance the timer before checking for IO.
7612 Limit the amount we advance so that early IO
7613 activity won't get the guest too far ahead. */
7617 add
= (add
+ (1 << icount_time_shift
) - 1)
7618 >> icount_time_shift
;
7620 timeout
= delta
/ 1000000;
7631 if (shutdown_requested
)
7635 #ifdef CONFIG_PROFILER
7636 ti
= profile_getclock();
7638 main_loop_wait(timeout
);
7639 #ifdef CONFIG_PROFILER
7640 dev_time
+= profile_getclock() - ti
;
7643 cpu_disable_ticks();
7647 static void help(int exitcode
)
7649 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7650 "usage: %s [options] [disk_image]\n"
7652 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7654 "Standard options:\n"
7655 "-M machine select emulated machine (-M ? for list)\n"
7656 "-cpu cpu select CPU (-cpu ? for list)\n"
7657 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7658 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7659 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7660 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7661 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7662 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7663 " [,cache=on|off][,format=f]\n"
7664 " use 'file' as a drive image\n"
7665 "-mtdblock file use 'file' as on-board Flash memory image\n"
7666 "-sd file use 'file' as SecureDigital card image\n"
7667 "-pflash file use 'file' as a parallel flash image\n"
7668 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7669 "-snapshot write to temporary files instead of disk image files\n"
7671 "-no-frame open SDL window without a frame and window decorations\n"
7672 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7673 "-no-quit disable SDL window close capability\n"
7676 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7678 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7679 "-smp n set the number of CPUs to 'n' [default=1]\n"
7680 "-nographic disable graphical output and redirect serial I/Os to console\n"
7681 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7683 "-k language use keyboard layout (for example \"fr\" for French)\n"
7686 "-audio-help print list of audio drivers and their options\n"
7687 "-soundhw c1,... enable audio support\n"
7688 " and only specified sound cards (comma separated list)\n"
7689 " use -soundhw ? to get the list of supported cards\n"
7690 " use -soundhw all to enable all of them\n"
7692 "-localtime set the real time clock to local time [default=utc]\n"
7693 "-full-screen start in full screen\n"
7695 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7697 "-usb enable the USB driver (will be the default soon)\n"
7698 "-usbdevice name add the host or guest USB device 'name'\n"
7699 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7700 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7702 "-name string set the name of the guest\n"
7704 "Network options:\n"
7705 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7706 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7708 "-net user[,vlan=n][,hostname=host]\n"
7709 " connect the user mode network stack to VLAN 'n' and send\n"
7710 " hostname 'host' to DHCP clients\n"
7713 "-net tap[,vlan=n],ifname=name\n"
7714 " connect the host TAP network interface to VLAN 'n'\n"
7716 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7717 " connect the host TAP network interface to VLAN 'n' and use the\n"
7718 " network scripts 'file' (default=%s)\n"
7719 " and 'dfile' (default=%s);\n"
7720 " use '[down]script=no' to disable script execution;\n"
7721 " use 'fd=h' to connect to an already opened TAP interface\n"
7723 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7724 " connect the vlan 'n' to another VLAN using a socket connection\n"
7725 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7726 " connect the vlan 'n' to multicast maddr and port\n"
7728 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7729 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7730 " on host and listening for incoming connections on 'socketpath'.\n"
7731 " Use group 'groupname' and mode 'octalmode' to change default\n"
7732 " ownership and permissions for communication port.\n"
7734 "-net none use it alone to have zero network devices; if no -net option\n"
7735 " is provided, the default is '-net nic -net user'\n"
7738 "-tftp dir allow tftp access to files in dir [-net user]\n"
7739 "-bootp file advertise file in BOOTP replies\n"
7741 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7743 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7744 " redirect TCP or UDP connections from host to guest [-net user]\n"
7747 "Linux boot specific:\n"
7748 "-kernel bzImage use 'bzImage' as kernel image\n"
7749 "-append cmdline use 'cmdline' as kernel command line\n"
7750 "-initrd file use 'file' as initial ram disk\n"
7752 "Debug/Expert options:\n"
7753 "-monitor dev redirect the monitor to char device 'dev'\n"
7754 "-serial dev redirect the serial port to char device 'dev'\n"
7755 "-parallel dev redirect the parallel port to char device 'dev'\n"
7756 "-pidfile file Write PID to 'file'\n"
7757 "-S freeze CPU at startup (use 'c' to start execution)\n"
7758 "-s wait gdb connection to port\n"
7759 "-p port set gdb connection port [default=%s]\n"
7760 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7761 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7762 " translation (t=none or lba) (usually qemu can guess them)\n"
7763 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7765 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7766 "-no-kqemu disable KQEMU kernel module usage\n"
7769 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7770 " (default is CL-GD5446 PCI VGA)\n"
7771 "-no-acpi disable ACPI\n"
7773 #ifdef CONFIG_CURSES
7774 "-curses use a curses/ncurses interface instead of SDL\n"
7776 "-no-reboot exit instead of rebooting\n"
7777 "-no-shutdown stop before shutdown\n"
7778 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7779 "-vnc display start a VNC server on display\n"
7781 "-daemonize daemonize QEMU after initializing\n"
7783 "-option-rom rom load a file, rom, into the option ROM space\n"
7785 "-prom-env variable=value set OpenBIOS nvram variables\n"
7787 "-clock force the use of the given methods for timer alarm.\n"
7788 " To see what timers are available use -clock ?\n"
7789 "-startdate select initial date of the clock\n"
7790 "-icount [N|auto]\n"
7791 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7793 "During emulation, the following keys are useful:\n"
7794 "ctrl-alt-f toggle full screen\n"
7795 "ctrl-alt-n switch to virtual console 'n'\n"
7796 "ctrl-alt toggle mouse and keyboard grab\n"
7798 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7803 DEFAULT_NETWORK_SCRIPT
,
7804 DEFAULT_NETWORK_DOWN_SCRIPT
,
7806 DEFAULT_GDBSTUB_PORT
,
7811 #define HAS_ARG 0x0001
7826 QEMU_OPTION_mtdblock
,
7830 QEMU_OPTION_snapshot
,
7832 QEMU_OPTION_no_fd_bootchk
,
7835 QEMU_OPTION_nographic
,
7836 QEMU_OPTION_portrait
,
7838 QEMU_OPTION_audio_help
,
7839 QEMU_OPTION_soundhw
,
7860 QEMU_OPTION_localtime
,
7861 QEMU_OPTION_cirrusvga
,
7864 QEMU_OPTION_std_vga
,
7866 QEMU_OPTION_monitor
,
7868 QEMU_OPTION_parallel
,
7870 QEMU_OPTION_full_screen
,
7871 QEMU_OPTION_no_frame
,
7872 QEMU_OPTION_alt_grab
,
7873 QEMU_OPTION_no_quit
,
7874 QEMU_OPTION_pidfile
,
7875 QEMU_OPTION_no_kqemu
,
7876 QEMU_OPTION_kernel_kqemu
,
7877 QEMU_OPTION_win2k_hack
,
7879 QEMU_OPTION_usbdevice
,
7882 QEMU_OPTION_no_acpi
,
7884 QEMU_OPTION_no_reboot
,
7885 QEMU_OPTION_no_shutdown
,
7886 QEMU_OPTION_show_cursor
,
7887 QEMU_OPTION_daemonize
,
7888 QEMU_OPTION_option_rom
,
7889 QEMU_OPTION_semihosting
,
7891 QEMU_OPTION_prom_env
,
7892 QEMU_OPTION_old_param
,
7894 QEMU_OPTION_startdate
,
7895 QEMU_OPTION_tb_size
,
7899 typedef struct QEMUOption
{
7905 const QEMUOption qemu_options
[] = {
7906 { "h", 0, QEMU_OPTION_h
},
7907 { "help", 0, QEMU_OPTION_h
},
7909 { "M", HAS_ARG
, QEMU_OPTION_M
},
7910 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7911 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7912 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7913 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7914 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7915 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7916 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7917 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7918 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7919 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7920 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7921 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7922 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7923 { "snapshot", 0, QEMU_OPTION_snapshot
},
7925 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7927 { "m", HAS_ARG
, QEMU_OPTION_m
},
7928 { "nographic", 0, QEMU_OPTION_nographic
},
7929 { "portrait", 0, QEMU_OPTION_portrait
},
7930 { "k", HAS_ARG
, QEMU_OPTION_k
},
7932 { "audio-help", 0, QEMU_OPTION_audio_help
},
7933 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7936 { "net", HAS_ARG
, QEMU_OPTION_net
},
7938 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7939 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7941 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7943 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7946 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7947 { "append", HAS_ARG
, QEMU_OPTION_append
},
7948 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7950 { "S", 0, QEMU_OPTION_S
},
7951 { "s", 0, QEMU_OPTION_s
},
7952 { "p", HAS_ARG
, QEMU_OPTION_p
},
7953 { "d", HAS_ARG
, QEMU_OPTION_d
},
7954 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7955 { "L", HAS_ARG
, QEMU_OPTION_L
},
7956 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7958 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7959 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7961 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7962 { "g", 1, QEMU_OPTION_g
},
7964 { "localtime", 0, QEMU_OPTION_localtime
},
7965 { "std-vga", 0, QEMU_OPTION_std_vga
},
7966 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7967 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7968 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7969 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7970 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7971 { "full-screen", 0, QEMU_OPTION_full_screen
},
7973 { "no-frame", 0, QEMU_OPTION_no_frame
},
7974 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7975 { "no-quit", 0, QEMU_OPTION_no_quit
},
7977 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7978 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7979 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7980 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7981 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7982 #ifdef CONFIG_CURSES
7983 { "curses", 0, QEMU_OPTION_curses
},
7986 /* temporary options */
7987 { "usb", 0, QEMU_OPTION_usb
},
7988 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7989 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7990 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7991 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7992 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7993 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7994 { "daemonize", 0, QEMU_OPTION_daemonize
},
7995 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7996 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7997 { "semihosting", 0, QEMU_OPTION_semihosting
},
7999 { "name", HAS_ARG
, QEMU_OPTION_name
},
8000 #if defined(TARGET_SPARC)
8001 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8003 #if defined(TARGET_ARM)
8004 { "old-param", 0, QEMU_OPTION_old_param
},
8006 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8007 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8008 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8009 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8013 /* password input */
8015 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8020 if (!bdrv_is_encrypted(bs
))
8023 term_printf("%s is encrypted.\n", name
);
8024 for(i
= 0; i
< 3; i
++) {
8025 monitor_readline("Password: ", 1, password
, sizeof(password
));
8026 if (bdrv_set_key(bs
, password
) == 0)
8028 term_printf("invalid password\n");
8033 static BlockDriverState
*get_bdrv(int index
)
8035 if (index
> nb_drives
)
8037 return drives_table
[index
].bdrv
;
8040 static void read_passwords(void)
8042 BlockDriverState
*bs
;
8045 for(i
= 0; i
< 6; i
++) {
8048 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8053 struct soundhw soundhw
[] = {
8054 #ifdef HAS_AUDIO_CHOICE
8055 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8061 { .init_isa
= pcspk_audio_init
}
8066 "Creative Sound Blaster 16",
8069 { .init_isa
= SB16_init
}
8072 #ifdef CONFIG_CS4231A
8078 { .init_isa
= cs4231a_init
}
8086 "Yamaha YMF262 (OPL3)",
8088 "Yamaha YM3812 (OPL2)",
8092 { .init_isa
= Adlib_init
}
8099 "Gravis Ultrasound GF1",
8102 { .init_isa
= GUS_init
}
8109 "Intel 82801AA AC97 Audio",
8112 { .init_pci
= ac97_init
}
8118 "ENSONIQ AudioPCI ES1370",
8121 { .init_pci
= es1370_init
}
8125 { NULL
, NULL
, 0, 0, { NULL
} }
8128 static void select_soundhw (const char *optarg
)
8132 if (*optarg
== '?') {
8135 printf ("Valid sound card names (comma separated):\n");
8136 for (c
= soundhw
; c
->name
; ++c
) {
8137 printf ("%-11s %s\n", c
->name
, c
->descr
);
8139 printf ("\n-soundhw all will enable all of the above\n");
8140 exit (*optarg
!= '?');
8148 if (!strcmp (optarg
, "all")) {
8149 for (c
= soundhw
; c
->name
; ++c
) {
8157 e
= strchr (p
, ',');
8158 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8160 for (c
= soundhw
; c
->name
; ++c
) {
8161 if (!strncmp (c
->name
, p
, l
)) {
8170 "Unknown sound card name (too big to show)\n");
8173 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8178 p
+= l
+ (e
!= NULL
);
8182 goto show_valid_cards
;
8188 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8190 exit(STATUS_CONTROL_C_EXIT
);
8195 #define MAX_NET_CLIENTS 32
8199 static void termsig_handler(int signal
)
8201 qemu_system_shutdown_request();
8204 static void termsig_setup(void)
8206 struct sigaction act
;
8208 memset(&act
, 0, sizeof(act
));
8209 act
.sa_handler
= termsig_handler
;
8210 sigaction(SIGINT
, &act
, NULL
);
8211 sigaction(SIGHUP
, &act
, NULL
);
8212 sigaction(SIGTERM
, &act
, NULL
);
8217 int main(int argc
, char **argv
)
8219 #ifdef CONFIG_GDBSTUB
8221 const char *gdbstub_port
;
8223 uint32_t boot_devices_bitmap
= 0;
8225 int snapshot
, linux_boot
, net_boot
;
8226 const char *initrd_filename
;
8227 const char *kernel_filename
, *kernel_cmdline
;
8228 const char *boot_devices
= "";
8229 DisplayState
*ds
= &display_state
;
8230 int cyls
, heads
, secs
, translation
;
8231 const char *net_clients
[MAX_NET_CLIENTS
];
8235 const char *r
, *optarg
;
8236 CharDriverState
*monitor_hd
;
8237 const char *monitor_device
;
8238 const char *serial_devices
[MAX_SERIAL_PORTS
];
8239 int serial_device_index
;
8240 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8241 int parallel_device_index
;
8242 const char *loadvm
= NULL
;
8243 QEMUMachine
*machine
;
8244 const char *cpu_model
;
8245 const char *usb_devices
[MAX_USB_CMDLINE
];
8246 int usb_devices_index
;
8249 const char *pid_file
= NULL
;
8252 LIST_INIT (&vm_change_state_head
);
8255 struct sigaction act
;
8256 sigfillset(&act
.sa_mask
);
8258 act
.sa_handler
= SIG_IGN
;
8259 sigaction(SIGPIPE
, &act
, NULL
);
8262 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8263 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8264 QEMU to run on a single CPU */
8269 h
= GetCurrentProcess();
8270 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8271 for(i
= 0; i
< 32; i
++) {
8272 if (mask
& (1 << i
))
8277 SetProcessAffinityMask(h
, mask
);
8283 register_machines();
8284 machine
= first_machine
;
8286 initrd_filename
= NULL
;
8288 vga_ram_size
= VGA_RAM_SIZE
;
8289 #ifdef CONFIG_GDBSTUB
8291 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8296 kernel_filename
= NULL
;
8297 kernel_cmdline
= "";
8298 cyls
= heads
= secs
= 0;
8299 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8300 monitor_device
= "vc";
8302 serial_devices
[0] = "vc:80Cx24C";
8303 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8304 serial_devices
[i
] = NULL
;
8305 serial_device_index
= 0;
8307 parallel_devices
[0] = "vc:640x480";
8308 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8309 parallel_devices
[i
] = NULL
;
8310 parallel_device_index
= 0;
8312 usb_devices_index
= 0;
8329 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8331 const QEMUOption
*popt
;
8334 /* Treat --foo the same as -foo. */
8337 popt
= qemu_options
;
8340 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8344 if (!strcmp(popt
->name
, r
+ 1))
8348 if (popt
->flags
& HAS_ARG
) {
8349 if (optind
>= argc
) {
8350 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8354 optarg
= argv
[optind
++];
8359 switch(popt
->index
) {
8361 machine
= find_machine(optarg
);
8364 printf("Supported machines are:\n");
8365 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8366 printf("%-10s %s%s\n",
8368 m
== first_machine
? " (default)" : "");
8370 exit(*optarg
!= '?');
8373 case QEMU_OPTION_cpu
:
8374 /* hw initialization will check this */
8375 if (*optarg
== '?') {
8376 /* XXX: implement xxx_cpu_list for targets that still miss it */
8377 #if defined(cpu_list)
8378 cpu_list(stdout
, &fprintf
);
8385 case QEMU_OPTION_initrd
:
8386 initrd_filename
= optarg
;
8388 case QEMU_OPTION_hda
:
8390 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8392 hda_index
= drive_add(optarg
, HD_ALIAS
8393 ",cyls=%d,heads=%d,secs=%d%s",
8394 0, cyls
, heads
, secs
,
8395 translation
== BIOS_ATA_TRANSLATION_LBA
?
8397 translation
== BIOS_ATA_TRANSLATION_NONE
?
8398 ",trans=none" : "");
8400 case QEMU_OPTION_hdb
:
8401 case QEMU_OPTION_hdc
:
8402 case QEMU_OPTION_hdd
:
8403 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8405 case QEMU_OPTION_drive
:
8406 drive_add(NULL
, "%s", optarg
);
8408 case QEMU_OPTION_mtdblock
:
8409 drive_add(optarg
, MTD_ALIAS
);
8411 case QEMU_OPTION_sd
:
8412 drive_add(optarg
, SD_ALIAS
);
8414 case QEMU_OPTION_pflash
:
8415 drive_add(optarg
, PFLASH_ALIAS
);
8417 case QEMU_OPTION_snapshot
:
8420 case QEMU_OPTION_hdachs
:
8424 cyls
= strtol(p
, (char **)&p
, 0);
8425 if (cyls
< 1 || cyls
> 16383)
8430 heads
= strtol(p
, (char **)&p
, 0);
8431 if (heads
< 1 || heads
> 16)
8436 secs
= strtol(p
, (char **)&p
, 0);
8437 if (secs
< 1 || secs
> 63)
8441 if (!strcmp(p
, "none"))
8442 translation
= BIOS_ATA_TRANSLATION_NONE
;
8443 else if (!strcmp(p
, "lba"))
8444 translation
= BIOS_ATA_TRANSLATION_LBA
;
8445 else if (!strcmp(p
, "auto"))
8446 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8449 } else if (*p
!= '\0') {
8451 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8454 if (hda_index
!= -1)
8455 snprintf(drives_opt
[hda_index
].opt
,
8456 sizeof(drives_opt
[hda_index
].opt
),
8457 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8458 0, cyls
, heads
, secs
,
8459 translation
== BIOS_ATA_TRANSLATION_LBA
?
8461 translation
== BIOS_ATA_TRANSLATION_NONE
?
8462 ",trans=none" : "");
8465 case QEMU_OPTION_nographic
:
8468 #ifdef CONFIG_CURSES
8469 case QEMU_OPTION_curses
:
8473 case QEMU_OPTION_portrait
:
8476 case QEMU_OPTION_kernel
:
8477 kernel_filename
= optarg
;
8479 case QEMU_OPTION_append
:
8480 kernel_cmdline
= optarg
;
8482 case QEMU_OPTION_cdrom
:
8483 drive_add(optarg
, CDROM_ALIAS
);
8485 case QEMU_OPTION_boot
:
8486 boot_devices
= optarg
;
8487 /* We just do some generic consistency checks */
8489 /* Could easily be extended to 64 devices if needed */
8492 boot_devices_bitmap
= 0;
8493 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8494 /* Allowed boot devices are:
8495 * a b : floppy disk drives
8496 * c ... f : IDE disk drives
8497 * g ... m : machine implementation dependant drives
8498 * n ... p : network devices
8499 * It's up to each machine implementation to check
8500 * if the given boot devices match the actual hardware
8501 * implementation and firmware features.
8503 if (*p
< 'a' || *p
> 'q') {
8504 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8507 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8509 "Boot device '%c' was given twice\n",*p
);
8512 boot_devices_bitmap
|= 1 << (*p
- 'a');
8516 case QEMU_OPTION_fda
:
8517 case QEMU_OPTION_fdb
:
8518 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8521 case QEMU_OPTION_no_fd_bootchk
:
8525 case QEMU_OPTION_net
:
8526 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8527 fprintf(stderr
, "qemu: too many network clients\n");
8530 net_clients
[nb_net_clients
] = optarg
;
8534 case QEMU_OPTION_tftp
:
8535 tftp_prefix
= optarg
;
8537 case QEMU_OPTION_bootp
:
8538 bootp_filename
= optarg
;
8541 case QEMU_OPTION_smb
:
8542 net_slirp_smb(optarg
);
8545 case QEMU_OPTION_redir
:
8546 net_slirp_redir(optarg
);
8550 case QEMU_OPTION_audio_help
:
8554 case QEMU_OPTION_soundhw
:
8555 select_soundhw (optarg
);
8561 case QEMU_OPTION_m
: {
8565 value
= strtoul(optarg
, &ptr
, 10);
8567 case 0: case 'M': case 'm':
8574 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8578 /* On 32-bit hosts, QEMU is limited by virtual address space */
8579 if (value
> (2047 << 20)
8581 && HOST_LONG_BITS
== 32
8584 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8587 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8588 fprintf(stderr
, "qemu: ram size too large\n");
8599 mask
= cpu_str_to_log_mask(optarg
);
8601 printf("Log items (comma separated):\n");
8602 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8603 printf("%-10s %s\n", item
->name
, item
->help
);
8610 #ifdef CONFIG_GDBSTUB
8615 gdbstub_port
= optarg
;
8621 case QEMU_OPTION_bios
:
8628 keyboard_layout
= optarg
;
8630 case QEMU_OPTION_localtime
:
8633 case QEMU_OPTION_cirrusvga
:
8634 cirrus_vga_enabled
= 1;
8637 case QEMU_OPTION_vmsvga
:
8638 cirrus_vga_enabled
= 0;
8641 case QEMU_OPTION_std_vga
:
8642 cirrus_vga_enabled
= 0;
8650 w
= strtol(p
, (char **)&p
, 10);
8653 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8659 h
= strtol(p
, (char **)&p
, 10);
8664 depth
= strtol(p
, (char **)&p
, 10);
8665 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8666 depth
!= 24 && depth
!= 32)
8668 } else if (*p
== '\0') {
8669 depth
= graphic_depth
;
8676 graphic_depth
= depth
;
8679 case QEMU_OPTION_echr
:
8682 term_escape_char
= strtol(optarg
, &r
, 0);
8684 printf("Bad argument to echr\n");
8687 case QEMU_OPTION_monitor
:
8688 monitor_device
= optarg
;
8690 case QEMU_OPTION_serial
:
8691 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8692 fprintf(stderr
, "qemu: too many serial ports\n");
8695 serial_devices
[serial_device_index
] = optarg
;
8696 serial_device_index
++;
8698 case QEMU_OPTION_parallel
:
8699 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8700 fprintf(stderr
, "qemu: too many parallel ports\n");
8703 parallel_devices
[parallel_device_index
] = optarg
;
8704 parallel_device_index
++;
8706 case QEMU_OPTION_loadvm
:
8709 case QEMU_OPTION_full_screen
:
8713 case QEMU_OPTION_no_frame
:
8716 case QEMU_OPTION_alt_grab
:
8719 case QEMU_OPTION_no_quit
:
8723 case QEMU_OPTION_pidfile
:
8727 case QEMU_OPTION_win2k_hack
:
8728 win2k_install_hack
= 1;
8732 case QEMU_OPTION_no_kqemu
:
8735 case QEMU_OPTION_kernel_kqemu
:
8739 case QEMU_OPTION_usb
:
8742 case QEMU_OPTION_usbdevice
:
8744 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8745 fprintf(stderr
, "Too many USB devices\n");
8748 usb_devices
[usb_devices_index
] = optarg
;
8749 usb_devices_index
++;
8751 case QEMU_OPTION_smp
:
8752 smp_cpus
= atoi(optarg
);
8753 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8754 fprintf(stderr
, "Invalid number of CPUs\n");
8758 case QEMU_OPTION_vnc
:
8759 vnc_display
= optarg
;
8761 case QEMU_OPTION_no_acpi
:
8764 case QEMU_OPTION_no_reboot
:
8767 case QEMU_OPTION_no_shutdown
:
8770 case QEMU_OPTION_show_cursor
:
8773 case QEMU_OPTION_daemonize
:
8776 case QEMU_OPTION_option_rom
:
8777 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8778 fprintf(stderr
, "Too many option ROMs\n");
8781 option_rom
[nb_option_roms
] = optarg
;
8784 case QEMU_OPTION_semihosting
:
8785 semihosting_enabled
= 1;
8787 case QEMU_OPTION_name
:
8791 case QEMU_OPTION_prom_env
:
8792 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8793 fprintf(stderr
, "Too many prom variables\n");
8796 prom_envs
[nb_prom_envs
] = optarg
;
8801 case QEMU_OPTION_old_param
:
8805 case QEMU_OPTION_clock
:
8806 configure_alarms(optarg
);
8808 case QEMU_OPTION_startdate
:
8811 time_t rtc_start_date
;
8812 if (!strcmp(optarg
, "now")) {
8813 rtc_date_offset
= -1;
8815 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8823 } else if (sscanf(optarg
, "%d-%d-%d",
8826 &tm
.tm_mday
) == 3) {
8835 rtc_start_date
= mktimegm(&tm
);
8836 if (rtc_start_date
== -1) {
8838 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8839 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8842 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8846 case QEMU_OPTION_tb_size
:
8847 tb_size
= strtol(optarg
, NULL
, 0);
8851 case QEMU_OPTION_icount
:
8853 if (strcmp(optarg
, "auto") == 0) {
8854 icount_time_shift
= -1;
8856 icount_time_shift
= strtol(optarg
, NULL
, 0);
8864 if (serial_device_index
== 0)
8865 serial_devices
[0] = "stdio";
8866 if (parallel_device_index
== 0)
8867 parallel_devices
[0] = "null";
8868 if (strncmp(monitor_device
, "vc", 2) == 0)
8869 monitor_device
= "stdio";
8876 if (pipe(fds
) == -1)
8887 len
= read(fds
[0], &status
, 1);
8888 if (len
== -1 && (errno
== EINTR
))
8893 else if (status
== 1) {
8894 fprintf(stderr
, "Could not acquire pidfile\n");
8911 signal(SIGTSTP
, SIG_IGN
);
8912 signal(SIGTTOU
, SIG_IGN
);
8913 signal(SIGTTIN
, SIG_IGN
);
8917 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8920 write(fds
[1], &status
, 1);
8922 fprintf(stderr
, "Could not acquire pid file\n");
8930 linux_boot
= (kernel_filename
!= NULL
);
8931 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8933 if (!linux_boot
&& net_boot
== 0 &&
8934 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8937 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8938 fprintf(stderr
, "-append only allowed with -kernel option\n");
8942 if (!linux_boot
&& initrd_filename
!= NULL
) {
8943 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8947 /* boot to floppy or the default cd if no hard disk defined yet */
8948 if (!boot_devices
[0]) {
8949 boot_devices
= "cad";
8951 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8956 if (use_icount
&& icount_time_shift
< 0) {
8958 /* 125MIPS seems a reasonable initial guess at the guest speed.
8959 It will be corrected fairly quickly anyway. */
8960 icount_time_shift
= 3;
8961 init_icount_adjust();
8968 /* init network clients */
8969 if (nb_net_clients
== 0) {
8970 /* if no clients, we use a default config */
8971 net_clients
[nb_net_clients
++] = "nic";
8973 net_clients
[nb_net_clients
++] = "user";
8977 for(i
= 0;i
< nb_net_clients
; i
++) {
8978 if (net_client_parse(net_clients
[i
]) < 0)
8981 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8982 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8984 if (vlan
->nb_guest_devs
== 0)
8985 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
8986 if (vlan
->nb_host_devs
== 0)
8988 "Warning: vlan %d is not connected to host network\n",
8993 /* XXX: this should be moved in the PC machine instantiation code */
8994 if (net_boot
!= 0) {
8996 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8997 const char *model
= nd_table
[i
].model
;
8999 if (net_boot
& (1 << i
)) {
9002 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9003 if (get_image_size(buf
) > 0) {
9004 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9005 fprintf(stderr
, "Too many option ROMs\n");
9008 option_rom
[nb_option_roms
] = strdup(buf
);
9015 fprintf(stderr
, "No valid PXE rom found for network device\n");
9021 /* init the memory */
9022 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9024 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9026 if (ram_size
< phys_ram_size
) {
9027 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9028 machine
->name
, (unsigned long long) phys_ram_size
);
9032 phys_ram_size
= ram_size
;
9034 ram_size
= phys_ram_size
;
9037 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9039 phys_ram_size
+= ram_size
;
9042 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9043 if (!phys_ram_base
) {
9044 fprintf(stderr
, "Could not allocate physical memory\n");
9048 /* init the dynamic translator */
9049 cpu_exec_init_all(tb_size
* 1024 * 1024);
9053 /* we always create the cdrom drive, even if no disk is there */
9055 if (nb_drives_opt
< MAX_DRIVES
)
9056 drive_add(NULL
, CDROM_ALIAS
);
9058 /* we always create at least one floppy */
9060 if (nb_drives_opt
< MAX_DRIVES
)
9061 drive_add(NULL
, FD_ALIAS
, 0);
9063 /* we always create one sd slot, even if no card is in it */
9065 if (nb_drives_opt
< MAX_DRIVES
)
9066 drive_add(NULL
, SD_ALIAS
);
9068 /* open the virtual block devices */
9070 for(i
= 0; i
< nb_drives_opt
; i
++)
9071 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9074 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9075 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9078 memset(&display_state
, 0, sizeof(display_state
));
9081 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9084 /* nearly nothing to do */
9085 dumb_display_init(ds
);
9086 } else if (vnc_display
!= NULL
) {
9087 vnc_display_init(ds
);
9088 if (vnc_display_open(ds
, vnc_display
) < 0)
9091 #if defined(CONFIG_CURSES)
9093 curses_display_init(ds
, full_screen
);
9097 #if defined(CONFIG_SDL)
9098 sdl_display_init(ds
, full_screen
, no_frame
);
9099 #elif defined(CONFIG_COCOA)
9100 cocoa_display_init(ds
, full_screen
);
9102 dumb_display_init(ds
);
9107 /* must be after terminal init, SDL library changes signal handlers */
9111 /* Maintain compatibility with multiple stdio monitors */
9112 if (!strcmp(monitor_device
,"stdio")) {
9113 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9114 const char *devname
= serial_devices
[i
];
9115 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9116 monitor_device
= NULL
;
9118 } else if (devname
&& !strcmp(devname
,"stdio")) {
9119 monitor_device
= NULL
;
9120 serial_devices
[i
] = "mon:stdio";
9125 if (monitor_device
) {
9126 monitor_hd
= qemu_chr_open(monitor_device
);
9128 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9131 monitor_init(monitor_hd
, !nographic
);
9134 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9135 const char *devname
= serial_devices
[i
];
9136 if (devname
&& strcmp(devname
, "none")) {
9137 serial_hds
[i
] = qemu_chr_open(devname
);
9138 if (!serial_hds
[i
]) {
9139 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9143 if (strstart(devname
, "vc", 0))
9144 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9148 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9149 const char *devname
= parallel_devices
[i
];
9150 if (devname
&& strcmp(devname
, "none")) {
9151 parallel_hds
[i
] = qemu_chr_open(devname
);
9152 if (!parallel_hds
[i
]) {
9153 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9157 if (strstart(devname
, "vc", 0))
9158 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9162 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9163 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9165 /* init USB devices */
9167 for(i
= 0; i
< usb_devices_index
; i
++) {
9168 if (usb_device_add(usb_devices
[i
]) < 0) {
9169 fprintf(stderr
, "Warning: could not add USB device %s\n",
9175 if (display_state
.dpy_refresh
) {
9176 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9177 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9180 #ifdef CONFIG_GDBSTUB
9182 /* XXX: use standard host:port notation and modify options
9184 if (gdbserver_start(gdbstub_port
) < 0) {
9185 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9196 /* XXX: simplify init */
9209 len
= write(fds
[1], &status
, 1);
9210 if (len
== -1 && (errno
== EINTR
))
9217 TFR(fd
= open("/dev/null", O_RDWR
));
9231 #if !defined(_WIN32)
9232 /* close network clients */
9233 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9234 VLANClientState
*vc
;
9236 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9237 if (vc
->fd_read
== tap_receive
) {
9239 TAPState
*s
= vc
->opaque
;
9241 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9243 launch_script(s
->down_script
, ifname
, s
->fd
);
9245 #if defined(CONFIG_VDE)
9246 if (vc
->fd_read
== vde_from_qemu
) {
9247 VDEState
*s
= vc
->opaque
;