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 uint8_t qemu_uuid
[16];
259 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
261 /***********************************************************/
262 /* x86 ISA bus support */
264 target_phys_addr_t isa_mem_base
= 0;
267 static IOPortReadFunc default_ioport_readb
, default_ioport_readw
, default_ioport_readl
;
268 static IOPortWriteFunc default_ioport_writeb
, default_ioport_writew
, default_ioport_writel
;
270 static uint32_t ioport_read(int index
, uint32_t address
)
272 static IOPortReadFunc
*default_func
[3] = {
273 default_ioport_readb
,
274 default_ioport_readw
,
277 IOPortReadFunc
*func
= ioport_read_table
[index
][address
];
279 func
= default_func
[index
];
280 return func(ioport_opaque
[address
], address
);
283 static void ioport_write(int index
, uint32_t address
, uint32_t data
)
285 static IOPortWriteFunc
*default_func
[3] = {
286 default_ioport_writeb
,
287 default_ioport_writew
,
288 default_ioport_writel
290 IOPortWriteFunc
*func
= ioport_write_table
[index
][address
];
292 func
= default_func
[index
];
293 func(ioport_opaque
[address
], address
, data
);
296 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
298 #ifdef DEBUG_UNUSED_IOPORT
299 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
304 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
306 #ifdef DEBUG_UNUSED_IOPORT
307 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
311 /* default is to make two byte accesses */
312 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
315 data
= ioport_read(0, address
);
316 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
317 data
|= ioport_read(0, address
) << 8;
321 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
323 ioport_write(0, address
, data
& 0xff);
324 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
325 ioport_write(0, address
, (data
>> 8) & 0xff);
328 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
330 #ifdef DEBUG_UNUSED_IOPORT
331 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
336 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
338 #ifdef DEBUG_UNUSED_IOPORT
339 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
343 /* size is the word size in byte */
344 int register_ioport_read(int start
, int length
, int size
,
345 IOPortReadFunc
*func
, void *opaque
)
351 } else if (size
== 2) {
353 } else if (size
== 4) {
356 hw_error("register_ioport_read: invalid size");
359 for(i
= start
; i
< start
+ length
; i
+= size
) {
360 ioport_read_table
[bsize
][i
] = func
;
361 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
362 hw_error("register_ioport_read: invalid opaque");
363 ioport_opaque
[i
] = opaque
;
368 /* size is the word size in byte */
369 int register_ioport_write(int start
, int length
, int size
,
370 IOPortWriteFunc
*func
, void *opaque
)
376 } else if (size
== 2) {
378 } else if (size
== 4) {
381 hw_error("register_ioport_write: invalid size");
384 for(i
= start
; i
< start
+ length
; i
+= size
) {
385 ioport_write_table
[bsize
][i
] = func
;
386 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
387 hw_error("register_ioport_write: invalid opaque");
388 ioport_opaque
[i
] = opaque
;
393 void isa_unassign_ioport(int start
, int length
)
397 for(i
= start
; i
< start
+ length
; i
++) {
398 ioport_read_table
[0][i
] = default_ioport_readb
;
399 ioport_read_table
[1][i
] = default_ioport_readw
;
400 ioport_read_table
[2][i
] = default_ioport_readl
;
402 ioport_write_table
[0][i
] = default_ioport_writeb
;
403 ioport_write_table
[1][i
] = default_ioport_writew
;
404 ioport_write_table
[2][i
] = default_ioport_writel
;
408 /***********************************************************/
410 void cpu_outb(CPUState
*env
, int addr
, int val
)
413 if (loglevel
& CPU_LOG_IOPORT
)
414 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
416 ioport_write(0, addr
, val
);
419 env
->last_io_time
= cpu_get_time_fast();
423 void cpu_outw(CPUState
*env
, int addr
, int val
)
426 if (loglevel
& CPU_LOG_IOPORT
)
427 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
429 ioport_write(1, addr
, val
);
432 env
->last_io_time
= cpu_get_time_fast();
436 void cpu_outl(CPUState
*env
, int addr
, int val
)
439 if (loglevel
& CPU_LOG_IOPORT
)
440 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
442 ioport_write(2, addr
, val
);
445 env
->last_io_time
= cpu_get_time_fast();
449 int cpu_inb(CPUState
*env
, int addr
)
452 val
= ioport_read(0, addr
);
454 if (loglevel
& CPU_LOG_IOPORT
)
455 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
459 env
->last_io_time
= cpu_get_time_fast();
464 int cpu_inw(CPUState
*env
, int addr
)
467 val
= ioport_read(1, addr
);
469 if (loglevel
& CPU_LOG_IOPORT
)
470 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
474 env
->last_io_time
= cpu_get_time_fast();
479 int cpu_inl(CPUState
*env
, int addr
)
482 val
= ioport_read(2, addr
);
484 if (loglevel
& CPU_LOG_IOPORT
)
485 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
489 env
->last_io_time
= cpu_get_time_fast();
494 /***********************************************************/
495 void hw_error(const char *fmt
, ...)
501 fprintf(stderr
, "qemu: hardware error: ");
502 vfprintf(stderr
, fmt
, ap
);
503 fprintf(stderr
, "\n");
504 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
505 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
507 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
509 cpu_dump_state(env
, stderr
, fprintf
, 0);
516 /***********************************************************/
519 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
520 static void *qemu_put_kbd_event_opaque
;
521 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
522 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
524 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
526 qemu_put_kbd_event_opaque
= opaque
;
527 qemu_put_kbd_event
= func
;
530 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
531 void *opaque
, int absolute
,
534 QEMUPutMouseEntry
*s
, *cursor
;
536 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
540 s
->qemu_put_mouse_event
= func
;
541 s
->qemu_put_mouse_event_opaque
= opaque
;
542 s
->qemu_put_mouse_event_absolute
= absolute
;
543 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
546 if (!qemu_put_mouse_event_head
) {
547 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
551 cursor
= qemu_put_mouse_event_head
;
552 while (cursor
->next
!= NULL
)
553 cursor
= cursor
->next
;
556 qemu_put_mouse_event_current
= s
;
561 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
563 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
565 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
568 cursor
= qemu_put_mouse_event_head
;
569 while (cursor
!= NULL
&& cursor
!= entry
) {
571 cursor
= cursor
->next
;
574 if (cursor
== NULL
) // does not exist or list empty
576 else if (prev
== NULL
) { // entry is head
577 qemu_put_mouse_event_head
= cursor
->next
;
578 if (qemu_put_mouse_event_current
== entry
)
579 qemu_put_mouse_event_current
= cursor
->next
;
580 qemu_free(entry
->qemu_put_mouse_event_name
);
585 prev
->next
= entry
->next
;
587 if (qemu_put_mouse_event_current
== entry
)
588 qemu_put_mouse_event_current
= prev
;
590 qemu_free(entry
->qemu_put_mouse_event_name
);
594 void kbd_put_keycode(int keycode
)
596 if (qemu_put_kbd_event
) {
597 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
601 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
603 QEMUPutMouseEvent
*mouse_event
;
604 void *mouse_event_opaque
;
607 if (!qemu_put_mouse_event_current
) {
612 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
614 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
617 if (graphic_rotate
) {
618 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
621 width
= graphic_width
- 1;
622 mouse_event(mouse_event_opaque
,
623 width
- dy
, dx
, dz
, buttons_state
);
625 mouse_event(mouse_event_opaque
,
626 dx
, dy
, dz
, buttons_state
);
630 int kbd_mouse_is_absolute(void)
632 if (!qemu_put_mouse_event_current
)
635 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
638 void do_info_mice(void)
640 QEMUPutMouseEntry
*cursor
;
643 if (!qemu_put_mouse_event_head
) {
644 term_printf("No mouse devices connected\n");
648 term_printf("Mouse devices available:\n");
649 cursor
= qemu_put_mouse_event_head
;
650 while (cursor
!= NULL
) {
651 term_printf("%c Mouse #%d: %s\n",
652 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
653 index
, cursor
->qemu_put_mouse_event_name
);
655 cursor
= cursor
->next
;
659 void do_mouse_set(int index
)
661 QEMUPutMouseEntry
*cursor
;
664 if (!qemu_put_mouse_event_head
) {
665 term_printf("No mouse devices connected\n");
669 cursor
= qemu_put_mouse_event_head
;
670 while (cursor
!= NULL
&& index
!= i
) {
672 cursor
= cursor
->next
;
676 qemu_put_mouse_event_current
= cursor
;
678 term_printf("Mouse at given index not found\n");
681 /* compute with 96 bit intermediate result: (a*b)/c */
682 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
687 #ifdef WORDS_BIGENDIAN
697 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
698 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
701 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
705 /***********************************************************/
706 /* real time host monotonic timer */
708 #define QEMU_TIMER_BASE 1000000000LL
712 static int64_t clock_freq
;
714 static void init_get_clock(void)
718 ret
= QueryPerformanceFrequency(&freq
);
720 fprintf(stderr
, "Could not calibrate ticks\n");
723 clock_freq
= freq
.QuadPart
;
726 static int64_t get_clock(void)
729 QueryPerformanceCounter(&ti
);
730 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
735 static int use_rt_clock
;
737 static void init_get_clock(void)
740 #if defined(__linux__)
743 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
750 static int64_t get_clock(void)
752 #if defined(__linux__)
755 clock_gettime(CLOCK_MONOTONIC
, &ts
);
756 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
760 /* XXX: using gettimeofday leads to problems if the date
761 changes, so it should be avoided. */
763 gettimeofday(&tv
, NULL
);
764 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
769 /* Return the virtual CPU time, based on the instruction counter. */
770 static int64_t cpu_get_icount(void)
773 CPUState
*env
= cpu_single_env
;;
774 icount
= qemu_icount
;
777 fprintf(stderr
, "Bad clock read\n");
778 icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
780 return qemu_icount_bias
+ (icount
<< icount_time_shift
);
783 /***********************************************************/
784 /* guest cycle counter */
786 static int64_t cpu_ticks_prev
;
787 static int64_t cpu_ticks_offset
;
788 static int64_t cpu_clock_offset
;
789 static int cpu_ticks_enabled
;
791 /* return the host CPU cycle counter and handle stop/restart */
792 int64_t cpu_get_ticks(void)
795 return cpu_get_icount();
797 if (!cpu_ticks_enabled
) {
798 return cpu_ticks_offset
;
801 ticks
= cpu_get_real_ticks();
802 if (cpu_ticks_prev
> ticks
) {
803 /* Note: non increasing ticks may happen if the host uses
805 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
807 cpu_ticks_prev
= ticks
;
808 return ticks
+ cpu_ticks_offset
;
812 /* return the host CPU monotonic timer and handle stop/restart */
813 static int64_t cpu_get_clock(void)
816 if (!cpu_ticks_enabled
) {
817 return cpu_clock_offset
;
820 return ti
+ cpu_clock_offset
;
824 /* enable cpu_get_ticks() */
825 void cpu_enable_ticks(void)
827 if (!cpu_ticks_enabled
) {
828 cpu_ticks_offset
-= cpu_get_real_ticks();
829 cpu_clock_offset
-= get_clock();
830 cpu_ticks_enabled
= 1;
834 /* disable cpu_get_ticks() : the clock is stopped. You must not call
835 cpu_get_ticks() after that. */
836 void cpu_disable_ticks(void)
838 if (cpu_ticks_enabled
) {
839 cpu_ticks_offset
= cpu_get_ticks();
840 cpu_clock_offset
= cpu_get_clock();
841 cpu_ticks_enabled
= 0;
845 /***********************************************************/
848 #define QEMU_TIMER_REALTIME 0
849 #define QEMU_TIMER_VIRTUAL 1
853 /* XXX: add frequency */
861 struct QEMUTimer
*next
;
864 struct qemu_alarm_timer
{
868 int (*start
)(struct qemu_alarm_timer
*t
);
869 void (*stop
)(struct qemu_alarm_timer
*t
);
870 void (*rearm
)(struct qemu_alarm_timer
*t
);
874 #define ALARM_FLAG_DYNTICKS 0x1
875 #define ALARM_FLAG_EXPIRED 0x2
877 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
879 return t
->flags
& ALARM_FLAG_DYNTICKS
;
882 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
884 if (!alarm_has_dynticks(t
))
890 /* TODO: MIN_TIMER_REARM_US should be optimized */
891 #define MIN_TIMER_REARM_US 250
893 static struct qemu_alarm_timer
*alarm_timer
;
897 struct qemu_alarm_win32
{
901 } alarm_win32_data
= {0, NULL
, -1};
903 static int win32_start_timer(struct qemu_alarm_timer
*t
);
904 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
905 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
909 static int unix_start_timer(struct qemu_alarm_timer
*t
);
910 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
914 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
915 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
916 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
918 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
919 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
921 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
922 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
924 #endif /* __linux__ */
928 /* Correlation between real and virtual time is always going to be
929 fairly approximate, so ignore small variation.
930 When the guest is idle real and virtual time will be aligned in
932 #define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
934 static void icount_adjust(void)
939 static int64_t last_delta
;
940 /* If the VM is not running, then do nothing. */
944 cur_time
= cpu_get_clock();
945 cur_icount
= qemu_get_clock(vm_clock
);
946 delta
= cur_icount
- cur_time
;
947 /* FIXME: This is a very crude algorithm, somewhat prone to oscillation. */
949 && last_delta
+ ICOUNT_WOBBLE
< delta
* 2
950 && icount_time_shift
> 0) {
951 /* The guest is getting too far ahead. Slow time down. */
955 && last_delta
- ICOUNT_WOBBLE
> delta
* 2
956 && icount_time_shift
< MAX_ICOUNT_SHIFT
) {
957 /* The guest is getting too far behind. Speed time up. */
961 qemu_icount_bias
= cur_icount
- (qemu_icount
<< icount_time_shift
);
964 static void icount_adjust_rt(void * opaque
)
966 qemu_mod_timer(icount_rt_timer
,
967 qemu_get_clock(rt_clock
) + 1000);
971 static void icount_adjust_vm(void * opaque
)
973 qemu_mod_timer(icount_vm_timer
,
974 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
978 static void init_icount_adjust(void)
980 /* Have both realtime and virtual time triggers for speed adjustment.
981 The realtime trigger catches emulated time passing too slowly,
982 the virtual time trigger catches emulated time passing too fast.
983 Realtime triggers occur even when idle, so use them less frequently
985 icount_rt_timer
= qemu_new_timer(rt_clock
, icount_adjust_rt
, NULL
);
986 qemu_mod_timer(icount_rt_timer
,
987 qemu_get_clock(rt_clock
) + 1000);
988 icount_vm_timer
= qemu_new_timer(vm_clock
, icount_adjust_vm
, NULL
);
989 qemu_mod_timer(icount_vm_timer
,
990 qemu_get_clock(vm_clock
) + QEMU_TIMER_BASE
/ 10);
993 static struct qemu_alarm_timer alarm_timers
[] = {
996 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
997 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
998 /* HPET - if available - is preferred */
999 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
1000 /* ...otherwise try RTC */
1001 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
1003 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
1005 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
1006 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
1007 {"win32", 0, win32_start_timer
,
1008 win32_stop_timer
, NULL
, &alarm_win32_data
},
1013 static void show_available_alarms(void)
1017 printf("Available alarm timers, in order of precedence:\n");
1018 for (i
= 0; alarm_timers
[i
].name
; i
++)
1019 printf("%s\n", alarm_timers
[i
].name
);
1022 static void configure_alarms(char const *opt
)
1026 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
1029 struct qemu_alarm_timer tmp
;
1031 if (!strcmp(opt
, "?")) {
1032 show_available_alarms();
1038 /* Reorder the array */
1039 name
= strtok(arg
, ",");
1041 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
1042 if (!strcmp(alarm_timers
[i
].name
, name
))
1047 fprintf(stderr
, "Unknown clock %s\n", name
);
1056 tmp
= alarm_timers
[i
];
1057 alarm_timers
[i
] = alarm_timers
[cur
];
1058 alarm_timers
[cur
] = tmp
;
1062 name
= strtok(NULL
, ",");
1068 /* Disable remaining timers */
1069 for (i
= cur
; i
< count
; i
++)
1070 alarm_timers
[i
].name
= NULL
;
1072 show_available_alarms();
1077 QEMUClock
*rt_clock
;
1078 QEMUClock
*vm_clock
;
1080 static QEMUTimer
*active_timers
[2];
1082 static QEMUClock
*qemu_new_clock(int type
)
1085 clock
= qemu_mallocz(sizeof(QEMUClock
));
1092 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1096 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1099 ts
->opaque
= opaque
;
1103 void qemu_free_timer(QEMUTimer
*ts
)
1108 /* stop a timer, but do not dealloc it */
1109 void qemu_del_timer(QEMUTimer
*ts
)
1113 /* NOTE: this code must be signal safe because
1114 qemu_timer_expired() can be called from a signal. */
1115 pt
= &active_timers
[ts
->clock
->type
];
1128 /* modify the current timer so that it will be fired when current_time
1129 >= expire_time. The corresponding callback will be called. */
1130 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1136 /* add the timer in the sorted list */
1137 /* NOTE: this code must be signal safe because
1138 qemu_timer_expired() can be called from a signal. */
1139 pt
= &active_timers
[ts
->clock
->type
];
1144 if (t
->expire_time
> expire_time
)
1148 ts
->expire_time
= expire_time
;
1152 /* Rearm if necessary */
1153 if (pt
== &active_timers
[ts
->clock
->type
]) {
1154 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0) {
1155 qemu_rearm_alarm_timer(alarm_timer
);
1157 /* Interrupt execution to force deadline recalculation. */
1158 if (use_icount
&& cpu_single_env
) {
1159 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
1164 int qemu_timer_pending(QEMUTimer
*ts
)
1167 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1174 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1178 return (timer_head
->expire_time
<= current_time
);
1181 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1187 if (!ts
|| ts
->expire_time
> current_time
)
1189 /* remove timer from the list before calling the callback */
1190 *ptimer_head
= ts
->next
;
1193 /* run the callback (the timer list can be modified) */
1198 int64_t qemu_get_clock(QEMUClock
*clock
)
1200 switch(clock
->type
) {
1201 case QEMU_TIMER_REALTIME
:
1202 return get_clock() / 1000000;
1204 case QEMU_TIMER_VIRTUAL
:
1206 return cpu_get_icount();
1208 return cpu_get_clock();
1213 static void init_timers(void)
1216 ticks_per_sec
= QEMU_TIMER_BASE
;
1217 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1218 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1222 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1224 uint64_t expire_time
;
1226 if (qemu_timer_pending(ts
)) {
1227 expire_time
= ts
->expire_time
;
1231 qemu_put_be64(f
, expire_time
);
1234 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1236 uint64_t expire_time
;
1238 expire_time
= qemu_get_be64(f
);
1239 if (expire_time
!= -1) {
1240 qemu_mod_timer(ts
, expire_time
);
1246 static void timer_save(QEMUFile
*f
, void *opaque
)
1248 if (cpu_ticks_enabled
) {
1249 hw_error("cannot save state if virtual timers are running");
1251 qemu_put_be64(f
, cpu_ticks_offset
);
1252 qemu_put_be64(f
, ticks_per_sec
);
1253 qemu_put_be64(f
, cpu_clock_offset
);
1256 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1258 if (version_id
!= 1 && version_id
!= 2)
1260 if (cpu_ticks_enabled
) {
1263 cpu_ticks_offset
=qemu_get_be64(f
);
1264 ticks_per_sec
=qemu_get_be64(f
);
1265 if (version_id
== 2) {
1266 cpu_clock_offset
=qemu_get_be64(f
);
1272 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1273 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1275 static void host_alarm_handler(int host_signum
)
1279 #define DISP_FREQ 1000
1281 static int64_t delta_min
= INT64_MAX
;
1282 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1284 ti
= qemu_get_clock(vm_clock
);
1285 if (last_clock
!= 0) {
1286 delta
= ti
- last_clock
;
1287 if (delta
< delta_min
)
1289 if (delta
> delta_max
)
1292 if (++count
== DISP_FREQ
) {
1293 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1294 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1295 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1296 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1297 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1299 delta_min
= INT64_MAX
;
1307 if (alarm_has_dynticks(alarm_timer
) ||
1309 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1310 qemu_get_clock(vm_clock
))) ||
1311 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1312 qemu_get_clock(rt_clock
))) {
1314 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1315 SetEvent(data
->host_alarm
);
1317 CPUState
*env
= next_cpu
;
1319 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1322 /* stop the currently executing cpu because a timer occured */
1323 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1325 if (env
->kqemu_enabled
) {
1326 kqemu_cpu_interrupt(env
);
1334 static int64_t qemu_next_deadline(void)
1338 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1339 delta
= active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1340 qemu_get_clock(vm_clock
);
1342 /* To avoid problems with overflow limit this to 2^32. */
1352 #if defined(__linux__) || defined(_WIN32)
1353 static uint64_t qemu_next_deadline_dyntick(void)
1361 delta
= (qemu_next_deadline() + 999) / 1000;
1363 if (active_timers
[QEMU_TIMER_REALTIME
]) {
1364 rtdelta
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1365 qemu_get_clock(rt_clock
))*1000;
1366 if (rtdelta
< delta
)
1370 if (delta
< MIN_TIMER_REARM_US
)
1371 delta
= MIN_TIMER_REARM_US
;
1379 #if defined(__linux__)
1381 #define RTC_FREQ 1024
1383 static void enable_sigio_timer(int fd
)
1385 struct sigaction act
;
1388 sigfillset(&act
.sa_mask
);
1390 act
.sa_handler
= host_alarm_handler
;
1392 sigaction(SIGIO
, &act
, NULL
);
1393 fcntl(fd
, F_SETFL
, O_ASYNC
);
1394 fcntl(fd
, F_SETOWN
, getpid());
1397 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1399 struct hpet_info info
;
1402 fd
= open("/dev/hpet", O_RDONLY
);
1407 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1409 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1410 "error, but for better emulation accuracy type:\n"
1411 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1415 /* Check capabilities */
1416 r
= ioctl(fd
, HPET_INFO
, &info
);
1420 /* Enable periodic mode */
1421 r
= ioctl(fd
, HPET_EPI
, 0);
1422 if (info
.hi_flags
&& (r
< 0))
1425 /* Enable interrupt */
1426 r
= ioctl(fd
, HPET_IE_ON
, 0);
1430 enable_sigio_timer(fd
);
1431 t
->priv
= (void *)(long)fd
;
1439 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1441 int fd
= (long)t
->priv
;
1446 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1449 unsigned long current_rtc_freq
= 0;
1451 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1454 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1455 if (current_rtc_freq
!= RTC_FREQ
&&
1456 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1457 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1458 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1459 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1462 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1468 enable_sigio_timer(rtc_fd
);
1470 t
->priv
= (void *)(long)rtc_fd
;
1475 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1477 int rtc_fd
= (long)t
->priv
;
1482 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1486 struct sigaction act
;
1488 sigfillset(&act
.sa_mask
);
1490 act
.sa_handler
= host_alarm_handler
;
1492 sigaction(SIGALRM
, &act
, NULL
);
1494 ev
.sigev_value
.sival_int
= 0;
1495 ev
.sigev_notify
= SIGEV_SIGNAL
;
1496 ev
.sigev_signo
= SIGALRM
;
1498 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1499 perror("timer_create");
1501 /* disable dynticks */
1502 fprintf(stderr
, "Dynamic Ticks disabled\n");
1507 t
->priv
= (void *)host_timer
;
1512 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1514 timer_t host_timer
= (timer_t
)t
->priv
;
1516 timer_delete(host_timer
);
1519 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1521 timer_t host_timer
= (timer_t
)t
->priv
;
1522 struct itimerspec timeout
;
1523 int64_t nearest_delta_us
= INT64_MAX
;
1526 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1527 !active_timers
[QEMU_TIMER_VIRTUAL
])
1530 nearest_delta_us
= qemu_next_deadline_dyntick();
1532 /* check whether a timer is already running */
1533 if (timer_gettime(host_timer
, &timeout
)) {
1535 fprintf(stderr
, "Internal timer error: aborting\n");
1538 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1539 if (current_us
&& current_us
<= nearest_delta_us
)
1542 timeout
.it_interval
.tv_sec
= 0;
1543 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1544 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1545 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1546 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1548 fprintf(stderr
, "Internal timer error: aborting\n");
1553 #endif /* defined(__linux__) */
1555 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1557 struct sigaction act
;
1558 struct itimerval itv
;
1562 sigfillset(&act
.sa_mask
);
1564 act
.sa_handler
= host_alarm_handler
;
1566 sigaction(SIGALRM
, &act
, NULL
);
1568 itv
.it_interval
.tv_sec
= 0;
1569 /* for i386 kernel 2.6 to get 1 ms */
1570 itv
.it_interval
.tv_usec
= 999;
1571 itv
.it_value
.tv_sec
= 0;
1572 itv
.it_value
.tv_usec
= 10 * 1000;
1574 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1581 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1583 struct itimerval itv
;
1585 memset(&itv
, 0, sizeof(itv
));
1586 setitimer(ITIMER_REAL
, &itv
, NULL
);
1589 #endif /* !defined(_WIN32) */
1593 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1596 struct qemu_alarm_win32
*data
= t
->priv
;
1599 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1600 if (!data
->host_alarm
) {
1601 perror("Failed CreateEvent");
1605 memset(&tc
, 0, sizeof(tc
));
1606 timeGetDevCaps(&tc
, sizeof(tc
));
1608 if (data
->period
< tc
.wPeriodMin
)
1609 data
->period
= tc
.wPeriodMin
;
1611 timeBeginPeriod(data
->period
);
1613 flags
= TIME_CALLBACK_FUNCTION
;
1614 if (alarm_has_dynticks(t
))
1615 flags
|= TIME_ONESHOT
;
1617 flags
|= TIME_PERIODIC
;
1619 data
->timerId
= timeSetEvent(1, // interval (ms)
1620 data
->period
, // resolution
1621 host_alarm_handler
, // function
1622 (DWORD
)t
, // parameter
1625 if (!data
->timerId
) {
1626 perror("Failed to initialize win32 alarm timer");
1628 timeEndPeriod(data
->period
);
1629 CloseHandle(data
->host_alarm
);
1633 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1638 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1640 struct qemu_alarm_win32
*data
= t
->priv
;
1642 timeKillEvent(data
->timerId
);
1643 timeEndPeriod(data
->period
);
1645 CloseHandle(data
->host_alarm
);
1648 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1650 struct qemu_alarm_win32
*data
= t
->priv
;
1651 uint64_t nearest_delta_us
;
1653 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1654 !active_timers
[QEMU_TIMER_VIRTUAL
])
1657 nearest_delta_us
= qemu_next_deadline_dyntick();
1658 nearest_delta_us
/= 1000;
1660 timeKillEvent(data
->timerId
);
1662 data
->timerId
= timeSetEvent(1,
1666 TIME_ONESHOT
| TIME_PERIODIC
);
1668 if (!data
->timerId
) {
1669 perror("Failed to re-arm win32 alarm timer");
1671 timeEndPeriod(data
->period
);
1672 CloseHandle(data
->host_alarm
);
1679 static void init_timer_alarm(void)
1681 struct qemu_alarm_timer
*t
;
1684 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1685 t
= &alarm_timers
[i
];
1693 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1694 fprintf(stderr
, "Terminating\n");
1701 static void quit_timers(void)
1703 alarm_timer
->stop(alarm_timer
);
1707 /***********************************************************/
1708 /* host time/date access */
1709 void qemu_get_timedate(struct tm
*tm
, int offset
)
1716 if (rtc_date_offset
== -1) {
1720 ret
= localtime(&ti
);
1722 ti
-= rtc_date_offset
;
1726 memcpy(tm
, ret
, sizeof(struct tm
));
1729 int qemu_timedate_diff(struct tm
*tm
)
1733 if (rtc_date_offset
== -1)
1735 seconds
= mktimegm(tm
);
1737 seconds
= mktime(tm
);
1739 seconds
= mktimegm(tm
) + rtc_date_offset
;
1741 return seconds
- time(NULL
);
1744 /***********************************************************/
1745 /* character device */
1747 static void qemu_chr_event(CharDriverState
*s
, int event
)
1751 s
->chr_event(s
->handler_opaque
, event
);
1754 static void qemu_chr_reset_bh(void *opaque
)
1756 CharDriverState
*s
= opaque
;
1757 qemu_chr_event(s
, CHR_EVENT_RESET
);
1758 qemu_bh_delete(s
->bh
);
1762 void qemu_chr_reset(CharDriverState
*s
)
1764 if (s
->bh
== NULL
) {
1765 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1766 qemu_bh_schedule(s
->bh
);
1770 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1772 return s
->chr_write(s
, buf
, len
);
1775 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1779 return s
->chr_ioctl(s
, cmd
, arg
);
1782 int qemu_chr_can_read(CharDriverState
*s
)
1784 if (!s
->chr_can_read
)
1786 return s
->chr_can_read(s
->handler_opaque
);
1789 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1791 s
->chr_read(s
->handler_opaque
, buf
, len
);
1794 void qemu_chr_accept_input(CharDriverState
*s
)
1796 if (s
->chr_accept_input
)
1797 s
->chr_accept_input(s
);
1800 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1805 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1806 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1810 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1812 if (s
->chr_send_event
)
1813 s
->chr_send_event(s
, event
);
1816 void qemu_chr_add_handlers(CharDriverState
*s
,
1817 IOCanRWHandler
*fd_can_read
,
1818 IOReadHandler
*fd_read
,
1819 IOEventHandler
*fd_event
,
1822 s
->chr_can_read
= fd_can_read
;
1823 s
->chr_read
= fd_read
;
1824 s
->chr_event
= fd_event
;
1825 s
->handler_opaque
= opaque
;
1826 if (s
->chr_update_read_handler
)
1827 s
->chr_update_read_handler(s
);
1830 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1835 static CharDriverState
*qemu_chr_open_null(void)
1837 CharDriverState
*chr
;
1839 chr
= qemu_mallocz(sizeof(CharDriverState
));
1842 chr
->chr_write
= null_chr_write
;
1846 /* MUX driver for serial I/O splitting */
1847 static int term_timestamps
;
1848 static int64_t term_timestamps_start
;
1850 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1851 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1853 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1854 IOReadHandler
*chr_read
[MAX_MUX
];
1855 IOEventHandler
*chr_event
[MAX_MUX
];
1856 void *ext_opaque
[MAX_MUX
];
1857 CharDriverState
*drv
;
1858 unsigned char buffer
[MUX_BUFFER_SIZE
];
1862 int term_got_escape
;
1867 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1869 MuxDriver
*d
= chr
->opaque
;
1871 if (!term_timestamps
) {
1872 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1877 for(i
= 0; i
< len
; i
++) {
1878 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1879 if (buf
[i
] == '\n') {
1885 if (term_timestamps_start
== -1)
1886 term_timestamps_start
= ti
;
1887 ti
-= term_timestamps_start
;
1888 secs
= ti
/ 1000000000;
1889 snprintf(buf1
, sizeof(buf1
),
1890 "[%02d:%02d:%02d.%03d] ",
1894 (int)((ti
/ 1000000) % 1000));
1895 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1902 static const char * const mux_help
[] = {
1903 "% h print this help\n\r",
1904 "% x exit emulator\n\r",
1905 "% s save disk data back to file (if -snapshot)\n\r",
1906 "% t toggle console timestamps\n\r"
1907 "% b send break (magic sysrq)\n\r",
1908 "% c switch between console and monitor\n\r",
1913 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1914 static void mux_print_help(CharDriverState
*chr
)
1917 char ebuf
[15] = "Escape-Char";
1918 char cbuf
[50] = "\n\r";
1920 if (term_escape_char
> 0 && term_escape_char
< 26) {
1921 snprintf(cbuf
, sizeof(cbuf
), "\n\r");
1922 snprintf(ebuf
, sizeof(ebuf
), "C-%c", term_escape_char
- 1 + 'a');
1924 snprintf(cbuf
, sizeof(cbuf
),
1925 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1928 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1929 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1930 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1931 if (mux_help
[i
][j
] == '%')
1932 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1934 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1939 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1941 if (d
->term_got_escape
) {
1942 d
->term_got_escape
= 0;
1943 if (ch
== term_escape_char
)
1948 mux_print_help(chr
);
1952 const char *term
= "QEMU: Terminated\n\r";
1953 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1960 for (i
= 0; i
< nb_drives
; i
++) {
1961 bdrv_commit(drives_table
[i
].bdrv
);
1966 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1969 /* Switch to the next registered device */
1971 if (chr
->focus
>= d
->mux_cnt
)
1975 term_timestamps
= !term_timestamps
;
1976 term_timestamps_start
= -1;
1979 } else if (ch
== term_escape_char
) {
1980 d
->term_got_escape
= 1;
1988 static void mux_chr_accept_input(CharDriverState
*chr
)
1991 MuxDriver
*d
= chr
->opaque
;
1993 while (d
->prod
!= d
->cons
&&
1994 d
->chr_can_read
[m
] &&
1995 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1996 d
->chr_read
[m
](d
->ext_opaque
[m
],
1997 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
2001 static int mux_chr_can_read(void *opaque
)
2003 CharDriverState
*chr
= opaque
;
2004 MuxDriver
*d
= chr
->opaque
;
2006 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
2008 if (d
->chr_can_read
[chr
->focus
])
2009 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
2013 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
2015 CharDriverState
*chr
= opaque
;
2016 MuxDriver
*d
= chr
->opaque
;
2020 mux_chr_accept_input (opaque
);
2022 for(i
= 0; i
< size
; i
++)
2023 if (mux_proc_byte(chr
, d
, buf
[i
])) {
2024 if (d
->prod
== d
->cons
&&
2025 d
->chr_can_read
[m
] &&
2026 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
2027 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
2029 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
2033 static void mux_chr_event(void *opaque
, int event
)
2035 CharDriverState
*chr
= opaque
;
2036 MuxDriver
*d
= chr
->opaque
;
2039 /* Send the event to all registered listeners */
2040 for (i
= 0; i
< d
->mux_cnt
; i
++)
2041 if (d
->chr_event
[i
])
2042 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
2045 static void mux_chr_update_read_handler(CharDriverState
*chr
)
2047 MuxDriver
*d
= chr
->opaque
;
2049 if (d
->mux_cnt
>= MAX_MUX
) {
2050 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
2053 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
2054 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
2055 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
2056 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
2057 /* Fix up the real driver with mux routines */
2058 if (d
->mux_cnt
== 0) {
2059 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
2060 mux_chr_event
, chr
);
2062 chr
->focus
= d
->mux_cnt
;
2066 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
2068 CharDriverState
*chr
;
2071 chr
= qemu_mallocz(sizeof(CharDriverState
));
2074 d
= qemu_mallocz(sizeof(MuxDriver
));
2083 chr
->chr_write
= mux_chr_write
;
2084 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
2085 chr
->chr_accept_input
= mux_chr_accept_input
;
2092 static void socket_cleanup(void)
2097 static int socket_init(void)
2102 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
2104 err
= WSAGetLastError();
2105 fprintf(stderr
, "WSAStartup: %d\n", err
);
2108 atexit(socket_cleanup
);
2112 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2118 ret
= send(fd
, buf
, len
, 0);
2121 errno
= WSAGetLastError();
2122 if (errno
!= WSAEWOULDBLOCK
) {
2125 } else if (ret
== 0) {
2137 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2143 ret
= write(fd
, buf
, len
);
2145 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2147 } else if (ret
== 0) {
2157 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2159 return unix_write(fd
, buf
, len1
);
2161 #endif /* !_WIN32 */
2170 #define STDIO_MAX_CLIENTS 1
2171 static int stdio_nb_clients
= 0;
2173 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2175 FDCharDriver
*s
= chr
->opaque
;
2176 return unix_write(s
->fd_out
, buf
, len
);
2179 static int fd_chr_read_poll(void *opaque
)
2181 CharDriverState
*chr
= opaque
;
2182 FDCharDriver
*s
= chr
->opaque
;
2184 s
->max_size
= qemu_chr_can_read(chr
);
2188 static void fd_chr_read(void *opaque
)
2190 CharDriverState
*chr
= opaque
;
2191 FDCharDriver
*s
= chr
->opaque
;
2196 if (len
> s
->max_size
)
2200 size
= read(s
->fd_in
, buf
, len
);
2202 /* FD has been closed. Remove it from the active list. */
2203 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2207 qemu_chr_read(chr
, buf
, size
);
2211 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2213 FDCharDriver
*s
= chr
->opaque
;
2215 if (s
->fd_in
>= 0) {
2216 if (nographic
&& s
->fd_in
== 0) {
2218 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2219 fd_chr_read
, NULL
, chr
);
2224 static void fd_chr_close(struct CharDriverState
*chr
)
2226 FDCharDriver
*s
= chr
->opaque
;
2228 if (s
->fd_in
>= 0) {
2229 if (nographic
&& s
->fd_in
== 0) {
2231 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2238 /* open a character device to a unix fd */
2239 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2241 CharDriverState
*chr
;
2244 chr
= qemu_mallocz(sizeof(CharDriverState
));
2247 s
= qemu_mallocz(sizeof(FDCharDriver
));
2255 chr
->chr_write
= fd_chr_write
;
2256 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2257 chr
->chr_close
= fd_chr_close
;
2259 qemu_chr_reset(chr
);
2264 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2268 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2271 return qemu_chr_open_fd(-1, fd_out
);
2274 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2277 char filename_in
[256], filename_out
[256];
2279 snprintf(filename_in
, 256, "%s.in", filename
);
2280 snprintf(filename_out
, 256, "%s.out", filename
);
2281 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2282 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2283 if (fd_in
< 0 || fd_out
< 0) {
2288 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2292 return qemu_chr_open_fd(fd_in
, fd_out
);
2296 /* for STDIO, we handle the case where several clients use it
2299 #define TERM_FIFO_MAX_SIZE 1
2301 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2302 static int term_fifo_size
;
2304 static int stdio_read_poll(void *opaque
)
2306 CharDriverState
*chr
= opaque
;
2308 /* try to flush the queue if needed */
2309 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2310 qemu_chr_read(chr
, term_fifo
, 1);
2313 /* see if we can absorb more chars */
2314 if (term_fifo_size
== 0)
2320 static void stdio_read(void *opaque
)
2324 CharDriverState
*chr
= opaque
;
2326 size
= read(0, buf
, 1);
2328 /* stdin has been closed. Remove it from the active list. */
2329 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2333 if (qemu_chr_can_read(chr
) > 0) {
2334 qemu_chr_read(chr
, buf
, 1);
2335 } else if (term_fifo_size
== 0) {
2336 term_fifo
[term_fifo_size
++] = buf
[0];
2341 /* init terminal so that we can grab keys */
2342 static struct termios oldtty
;
2343 static int old_fd0_flags
;
2344 static int term_atexit_done
;
2346 static void term_exit(void)
2348 tcsetattr (0, TCSANOW
, &oldtty
);
2349 fcntl(0, F_SETFL
, old_fd0_flags
);
2352 static void term_init(void)
2356 tcgetattr (0, &tty
);
2358 old_fd0_flags
= fcntl(0, F_GETFL
);
2360 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2361 |INLCR
|IGNCR
|ICRNL
|IXON
);
2362 tty
.c_oflag
|= OPOST
;
2363 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2364 /* if graphical mode, we allow Ctrl-C handling */
2366 tty
.c_lflag
&= ~ISIG
;
2367 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2370 tty
.c_cc
[VTIME
] = 0;
2372 tcsetattr (0, TCSANOW
, &tty
);
2374 if (!term_atexit_done
++)
2377 fcntl(0, F_SETFL
, O_NONBLOCK
);
2380 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2384 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2388 static CharDriverState
*qemu_chr_open_stdio(void)
2390 CharDriverState
*chr
;
2392 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2394 chr
= qemu_chr_open_fd(0, 1);
2395 chr
->chr_close
= qemu_chr_close_stdio
;
2396 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2404 /* Once Solaris has openpty(), this is going to be removed. */
2405 int openpty(int *amaster
, int *aslave
, char *name
,
2406 struct termios
*termp
, struct winsize
*winp
)
2409 int mfd
= -1, sfd
= -1;
2411 *amaster
= *aslave
= -1;
2413 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2417 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2420 if ((slave
= ptsname(mfd
)) == NULL
)
2423 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2426 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2427 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2435 ioctl(sfd
, TIOCSWINSZ
, winp
);
2446 void cfmakeraw (struct termios
*termios_p
)
2448 termios_p
->c_iflag
&=
2449 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2450 termios_p
->c_oflag
&= ~OPOST
;
2451 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2452 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2453 termios_p
->c_cflag
|= CS8
;
2455 termios_p
->c_cc
[VMIN
] = 0;
2456 termios_p
->c_cc
[VTIME
] = 0;
2460 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2461 || defined(__NetBSD__) || defined(__OpenBSD__)
2471 static void pty_chr_update_read_handler(CharDriverState
*chr
);
2472 static void pty_chr_state(CharDriverState
*chr
, int connected
);
2474 static int pty_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2476 PtyCharDriver
*s
= chr
->opaque
;
2478 if (!s
->connected
) {
2479 /* guest sends data, check for (re-)connect */
2480 pty_chr_update_read_handler(chr
);
2483 return unix_write(s
->fd
, buf
, len
);
2486 static int pty_chr_read_poll(void *opaque
)
2488 CharDriverState
*chr
= opaque
;
2489 PtyCharDriver
*s
= chr
->opaque
;
2491 s
->read_bytes
= qemu_chr_can_read(chr
);
2492 return s
->read_bytes
;
2495 static void pty_chr_read(void *opaque
)
2497 CharDriverState
*chr
= opaque
;
2498 PtyCharDriver
*s
= chr
->opaque
;
2503 if (len
> s
->read_bytes
)
2504 len
= s
->read_bytes
;
2507 size
= read(s
->fd
, buf
, len
);
2508 if ((size
== -1 && errno
== EIO
) ||
2510 pty_chr_state(chr
, 0);
2514 pty_chr_state(chr
, 1);
2515 qemu_chr_read(chr
, buf
, size
);
2519 static void pty_chr_update_read_handler(CharDriverState
*chr
)
2521 PtyCharDriver
*s
= chr
->opaque
;
2523 qemu_set_fd_handler2(s
->fd
, pty_chr_read_poll
,
2524 pty_chr_read
, NULL
, chr
);
2527 * Short timeout here: just need wait long enougth that qemu makes
2528 * it through the poll loop once. When reconnected we want a
2529 * short timeout so we notice it almost instantly. Otherwise
2530 * read() gives us -EIO instantly, making pty_chr_state() reset the
2531 * timeout to the normal (much longer) poll interval before the
2534 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 10);
2537 static void pty_chr_state(CharDriverState
*chr
, int connected
)
2539 PtyCharDriver
*s
= chr
->opaque
;
2542 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2545 /* (re-)connect poll interval for idle guests: once per second.
2546 * We check more frequently in case the guests sends data to
2547 * the virtual device linked to our pty. */
2548 qemu_mod_timer(s
->timer
, qemu_get_clock(rt_clock
) + 1000);
2551 qemu_chr_reset(chr
);
2556 static void pty_chr_timer(void *opaque
)
2558 struct CharDriverState
*chr
= opaque
;
2559 PtyCharDriver
*s
= chr
->opaque
;
2564 /* If we arrive here without polling being cleared due
2565 * read returning -EIO, then we are (re-)connected */
2566 pty_chr_state(chr
, 1);
2571 pty_chr_update_read_handler(chr
);
2574 static void pty_chr_close(struct CharDriverState
*chr
)
2576 PtyCharDriver
*s
= chr
->opaque
;
2578 qemu_set_fd_handler2(s
->fd
, NULL
, NULL
, NULL
, NULL
);
2583 static CharDriverState
*qemu_chr_open_pty(void)
2585 CharDriverState
*chr
;
2589 #if defined(__OpenBSD__)
2590 char pty_name
[PATH_MAX
];
2591 #define q_ptsname(x) pty_name
2593 char *pty_name
= NULL
;
2594 #define q_ptsname(x) ptsname(x)
2597 chr
= qemu_mallocz(sizeof(CharDriverState
));
2600 s
= qemu_mallocz(sizeof(PtyCharDriver
));
2606 if (openpty(&s
->fd
, &slave_fd
, pty_name
, NULL
, NULL
) < 0) {
2610 /* Set raw attributes on the pty. */
2612 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2615 fprintf(stderr
, "char device redirected to %s\n", q_ptsname(s
->fd
));
2618 chr
->chr_write
= pty_chr_write
;
2619 chr
->chr_update_read_handler
= pty_chr_update_read_handler
;
2620 chr
->chr_close
= pty_chr_close
;
2622 s
->timer
= qemu_new_timer(rt_clock
, pty_chr_timer
, chr
);
2627 static void tty_serial_init(int fd
, int speed
,
2628 int parity
, int data_bits
, int stop_bits
)
2634 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2635 speed
, parity
, data_bits
, stop_bits
);
2637 tcgetattr (fd
, &tty
);
2640 if (speed
<= 50 * MARGIN
)
2642 else if (speed
<= 75 * MARGIN
)
2644 else if (speed
<= 300 * MARGIN
)
2646 else if (speed
<= 600 * MARGIN
)
2648 else if (speed
<= 1200 * MARGIN
)
2650 else if (speed
<= 2400 * MARGIN
)
2652 else if (speed
<= 4800 * MARGIN
)
2654 else if (speed
<= 9600 * MARGIN
)
2656 else if (speed
<= 19200 * MARGIN
)
2658 else if (speed
<= 38400 * MARGIN
)
2660 else if (speed
<= 57600 * MARGIN
)
2662 else if (speed
<= 115200 * MARGIN
)
2667 cfsetispeed(&tty
, spd
);
2668 cfsetospeed(&tty
, spd
);
2670 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2671 |INLCR
|IGNCR
|ICRNL
|IXON
);
2672 tty
.c_oflag
|= OPOST
;
2673 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2674 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2695 tty
.c_cflag
|= PARENB
;
2698 tty
.c_cflag
|= PARENB
| PARODD
;
2702 tty
.c_cflag
|= CSTOPB
;
2704 tcsetattr (fd
, TCSANOW
, &tty
);
2707 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2709 FDCharDriver
*s
= chr
->opaque
;
2712 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2714 QEMUSerialSetParams
*ssp
= arg
;
2715 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2716 ssp
->data_bits
, ssp
->stop_bits
);
2719 case CHR_IOCTL_SERIAL_SET_BREAK
:
2721 int enable
= *(int *)arg
;
2723 tcsendbreak(s
->fd_in
, 1);
2726 case CHR_IOCTL_SERIAL_GET_TIOCM
:
2729 int *targ
= (int *)arg
;
2730 ioctl(s
->fd_in
, TIOCMGET
, &sarg
);
2732 if (sarg
| TIOCM_CTS
)
2733 *targ
|= CHR_TIOCM_CTS
;
2734 if (sarg
| TIOCM_CAR
)
2735 *targ
|= CHR_TIOCM_CAR
;
2736 if (sarg
| TIOCM_DSR
)
2737 *targ
|= CHR_TIOCM_DSR
;
2738 if (sarg
| TIOCM_RI
)
2739 *targ
|= CHR_TIOCM_RI
;
2740 if (sarg
| TIOCM_DTR
)
2741 *targ
|= CHR_TIOCM_DTR
;
2742 if (sarg
| TIOCM_RTS
)
2743 *targ
|= CHR_TIOCM_RTS
;
2746 case CHR_IOCTL_SERIAL_SET_TIOCM
:
2748 int sarg
= *(int *)arg
;
2750 if (sarg
| CHR_TIOCM_DTR
)
2752 if (sarg
| CHR_TIOCM_RTS
)
2754 ioctl(s
->fd_in
, TIOCMSET
, &targ
);
2763 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2765 CharDriverState
*chr
;
2768 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2769 tty_serial_init(fd
, 115200, 'N', 8, 1);
2770 chr
= qemu_chr_open_fd(fd
, fd
);
2775 chr
->chr_ioctl
= tty_serial_ioctl
;
2776 qemu_chr_reset(chr
);
2779 #else /* ! __linux__ && ! __sun__ */
2780 static CharDriverState
*qemu_chr_open_pty(void)
2784 #endif /* __linux__ || __sun__ */
2786 #if defined(__linux__)
2790 } ParallelCharDriver
;
2792 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2794 if (s
->mode
!= mode
) {
2796 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2803 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2805 ParallelCharDriver
*drv
= chr
->opaque
;
2810 case CHR_IOCTL_PP_READ_DATA
:
2811 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2813 *(uint8_t *)arg
= b
;
2815 case CHR_IOCTL_PP_WRITE_DATA
:
2816 b
= *(uint8_t *)arg
;
2817 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2820 case CHR_IOCTL_PP_READ_CONTROL
:
2821 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2823 /* Linux gives only the lowest bits, and no way to know data
2824 direction! For better compatibility set the fixed upper
2826 *(uint8_t *)arg
= b
| 0xc0;
2828 case CHR_IOCTL_PP_WRITE_CONTROL
:
2829 b
= *(uint8_t *)arg
;
2830 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2833 case CHR_IOCTL_PP_READ_STATUS
:
2834 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2836 *(uint8_t *)arg
= b
;
2838 case CHR_IOCTL_PP_DATA_DIR
:
2839 if (ioctl(fd
, PPDATADIR
, (int *)arg
) < 0)
2842 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2843 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2844 struct ParallelIOArg
*parg
= arg
;
2845 int n
= read(fd
, parg
->buffer
, parg
->count
);
2846 if (n
!= parg
->count
) {
2851 case CHR_IOCTL_PP_EPP_READ
:
2852 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2853 struct ParallelIOArg
*parg
= arg
;
2854 int n
= read(fd
, parg
->buffer
, parg
->count
);
2855 if (n
!= parg
->count
) {
2860 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2861 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2862 struct ParallelIOArg
*parg
= arg
;
2863 int n
= write(fd
, parg
->buffer
, parg
->count
);
2864 if (n
!= parg
->count
) {
2869 case CHR_IOCTL_PP_EPP_WRITE
:
2870 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2871 struct ParallelIOArg
*parg
= arg
;
2872 int n
= write(fd
, parg
->buffer
, parg
->count
);
2873 if (n
!= parg
->count
) {
2884 static void pp_close(CharDriverState
*chr
)
2886 ParallelCharDriver
*drv
= chr
->opaque
;
2889 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2890 ioctl(fd
, PPRELEASE
);
2895 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2897 CharDriverState
*chr
;
2898 ParallelCharDriver
*drv
;
2901 TFR(fd
= open(filename
, O_RDWR
));
2905 if (ioctl(fd
, PPCLAIM
) < 0) {
2910 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2916 drv
->mode
= IEEE1284_MODE_COMPAT
;
2918 chr
= qemu_mallocz(sizeof(CharDriverState
));
2924 chr
->chr_write
= null_chr_write
;
2925 chr
->chr_ioctl
= pp_ioctl
;
2926 chr
->chr_close
= pp_close
;
2929 qemu_chr_reset(chr
);
2933 #endif /* __linux__ */
2939 HANDLE hcom
, hrecv
, hsend
;
2940 OVERLAPPED orecv
, osend
;
2945 #define NSENDBUF 2048
2946 #define NRECVBUF 2048
2947 #define MAXCONNECT 1
2948 #define NTIMEOUT 5000
2950 static int win_chr_poll(void *opaque
);
2951 static int win_chr_pipe_poll(void *opaque
);
2953 static void win_chr_close(CharDriverState
*chr
)
2955 WinCharState
*s
= chr
->opaque
;
2958 CloseHandle(s
->hsend
);
2962 CloseHandle(s
->hrecv
);
2966 CloseHandle(s
->hcom
);
2970 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2972 qemu_del_polling_cb(win_chr_poll
, chr
);
2975 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2977 WinCharState
*s
= chr
->opaque
;
2979 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2984 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2986 fprintf(stderr
, "Failed CreateEvent\n");
2989 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2991 fprintf(stderr
, "Failed CreateEvent\n");
2995 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2996 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2997 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2998 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
3003 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
3004 fprintf(stderr
, "Failed SetupComm\n");
3008 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
3009 size
= sizeof(COMMCONFIG
);
3010 GetDefaultCommConfig(filename
, &comcfg
, &size
);
3011 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
3012 CommConfigDialog(filename
, NULL
, &comcfg
);
3014 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
3015 fprintf(stderr
, "Failed SetCommState\n");
3019 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
3020 fprintf(stderr
, "Failed SetCommMask\n");
3024 cto
.ReadIntervalTimeout
= MAXDWORD
;
3025 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
3026 fprintf(stderr
, "Failed SetCommTimeouts\n");
3030 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
3031 fprintf(stderr
, "Failed ClearCommError\n");
3034 qemu_add_polling_cb(win_chr_poll
, chr
);
3042 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
3044 WinCharState
*s
= chr
->opaque
;
3045 DWORD len
, ret
, size
, err
;
3048 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
3049 s
->osend
.hEvent
= s
->hsend
;
3052 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
3054 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
3056 err
= GetLastError();
3057 if (err
== ERROR_IO_PENDING
) {
3058 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
3076 static int win_chr_read_poll(CharDriverState
*chr
)
3078 WinCharState
*s
= chr
->opaque
;
3080 s
->max_size
= qemu_chr_can_read(chr
);
3084 static void win_chr_readfile(CharDriverState
*chr
)
3086 WinCharState
*s
= chr
->opaque
;
3091 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
3092 s
->orecv
.hEvent
= s
->hrecv
;
3093 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
3095 err
= GetLastError();
3096 if (err
== ERROR_IO_PENDING
) {
3097 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
3102 qemu_chr_read(chr
, buf
, size
);
3106 static void win_chr_read(CharDriverState
*chr
)
3108 WinCharState
*s
= chr
->opaque
;
3110 if (s
->len
> s
->max_size
)
3111 s
->len
= s
->max_size
;
3115 win_chr_readfile(chr
);
3118 static int win_chr_poll(void *opaque
)
3120 CharDriverState
*chr
= opaque
;
3121 WinCharState
*s
= chr
->opaque
;
3125 ClearCommError(s
->hcom
, &comerr
, &status
);
3126 if (status
.cbInQue
> 0) {
3127 s
->len
= status
.cbInQue
;
3128 win_chr_read_poll(chr
);
3135 static CharDriverState
*qemu_chr_open_win(const char *filename
)
3137 CharDriverState
*chr
;
3140 chr
= qemu_mallocz(sizeof(CharDriverState
));
3143 s
= qemu_mallocz(sizeof(WinCharState
));
3149 chr
->chr_write
= win_chr_write
;
3150 chr
->chr_close
= win_chr_close
;
3152 if (win_chr_init(chr
, filename
) < 0) {
3157 qemu_chr_reset(chr
);
3161 static int win_chr_pipe_poll(void *opaque
)
3163 CharDriverState
*chr
= opaque
;
3164 WinCharState
*s
= chr
->opaque
;
3167 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
3170 win_chr_read_poll(chr
);
3177 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
3179 WinCharState
*s
= chr
->opaque
;
3187 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3189 fprintf(stderr
, "Failed CreateEvent\n");
3192 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3194 fprintf(stderr
, "Failed CreateEvent\n");
3198 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
3199 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
3200 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
3202 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
3203 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
3204 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3209 ZeroMemory(&ov
, sizeof(ov
));
3210 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
3211 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
3213 fprintf(stderr
, "Failed ConnectNamedPipe\n");
3217 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
3219 fprintf(stderr
, "Failed GetOverlappedResult\n");
3221 CloseHandle(ov
.hEvent
);
3228 CloseHandle(ov
.hEvent
);
3231 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
3240 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
3242 CharDriverState
*chr
;
3245 chr
= qemu_mallocz(sizeof(CharDriverState
));
3248 s
= qemu_mallocz(sizeof(WinCharState
));
3254 chr
->chr_write
= win_chr_write
;
3255 chr
->chr_close
= win_chr_close
;
3257 if (win_chr_pipe_init(chr
, filename
) < 0) {
3262 qemu_chr_reset(chr
);
3266 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
3268 CharDriverState
*chr
;
3271 chr
= qemu_mallocz(sizeof(CharDriverState
));
3274 s
= qemu_mallocz(sizeof(WinCharState
));
3281 chr
->chr_write
= win_chr_write
;
3282 qemu_chr_reset(chr
);
3286 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3288 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3291 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3295 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3296 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3297 if (fd_out
== INVALID_HANDLE_VALUE
)
3300 return qemu_chr_open_win_file(fd_out
);
3302 #endif /* !_WIN32 */
3304 /***********************************************************/
3305 /* UDP Net console */
3309 struct sockaddr_in daddr
;
3316 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3318 NetCharDriver
*s
= chr
->opaque
;
3320 return sendto(s
->fd
, buf
, len
, 0,
3321 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3324 static int udp_chr_read_poll(void *opaque
)
3326 CharDriverState
*chr
= opaque
;
3327 NetCharDriver
*s
= chr
->opaque
;
3329 s
->max_size
= qemu_chr_can_read(chr
);
3331 /* If there were any stray characters in the queue process them
3334 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3335 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3337 s
->max_size
= qemu_chr_can_read(chr
);
3342 static void udp_chr_read(void *opaque
)
3344 CharDriverState
*chr
= opaque
;
3345 NetCharDriver
*s
= chr
->opaque
;
3347 if (s
->max_size
== 0)
3349 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3350 s
->bufptr
= s
->bufcnt
;
3355 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3356 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3358 s
->max_size
= qemu_chr_can_read(chr
);
3362 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3364 NetCharDriver
*s
= chr
->opaque
;
3367 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3368 udp_chr_read
, NULL
, chr
);
3372 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
3374 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3376 int parse_host_src_port(struct sockaddr_in
*haddr
,
3377 struct sockaddr_in
*saddr
,
3380 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3382 CharDriverState
*chr
= NULL
;
3383 NetCharDriver
*s
= NULL
;
3385 struct sockaddr_in saddr
;
3387 chr
= qemu_mallocz(sizeof(CharDriverState
));
3390 s
= qemu_mallocz(sizeof(NetCharDriver
));
3394 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3396 perror("socket(PF_INET, SOCK_DGRAM)");
3400 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3401 printf("Could not parse: %s\n", def
);
3405 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3415 chr
->chr_write
= udp_chr_write
;
3416 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3429 /***********************************************************/
3430 /* TCP Net console */
3441 static void tcp_chr_accept(void *opaque
);
3443 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3445 TCPCharDriver
*s
= chr
->opaque
;
3447 return send_all(s
->fd
, buf
, len
);
3449 /* XXX: indicate an error ? */
3454 static int tcp_chr_read_poll(void *opaque
)
3456 CharDriverState
*chr
= opaque
;
3457 TCPCharDriver
*s
= chr
->opaque
;
3460 s
->max_size
= qemu_chr_can_read(chr
);
3465 #define IAC_BREAK 243
3466 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3468 uint8_t *buf
, int *size
)
3470 /* Handle any telnet client's basic IAC options to satisfy char by
3471 * char mode with no echo. All IAC options will be removed from
3472 * the buf and the do_telnetopt variable will be used to track the
3473 * state of the width of the IAC information.
3475 * IAC commands come in sets of 3 bytes with the exception of the
3476 * "IAC BREAK" command and the double IAC.
3482 for (i
= 0; i
< *size
; i
++) {
3483 if (s
->do_telnetopt
> 1) {
3484 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3485 /* Double IAC means send an IAC */
3489 s
->do_telnetopt
= 1;
3491 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3492 /* Handle IAC break commands by sending a serial break */
3493 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3498 if (s
->do_telnetopt
>= 4) {
3499 s
->do_telnetopt
= 1;
3502 if ((unsigned char)buf
[i
] == IAC
) {
3503 s
->do_telnetopt
= 2;
3514 static void tcp_chr_read(void *opaque
)
3516 CharDriverState
*chr
= opaque
;
3517 TCPCharDriver
*s
= chr
->opaque
;
3521 if (!s
->connected
|| s
->max_size
<= 0)
3524 if (len
> s
->max_size
)
3526 size
= recv(s
->fd
, buf
, len
, 0);
3528 /* connection closed */
3530 if (s
->listen_fd
>= 0) {
3531 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3533 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3536 } else if (size
> 0) {
3537 if (s
->do_telnetopt
)
3538 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3540 qemu_chr_read(chr
, buf
, size
);
3544 static void tcp_chr_connect(void *opaque
)
3546 CharDriverState
*chr
= opaque
;
3547 TCPCharDriver
*s
= chr
->opaque
;
3550 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3551 tcp_chr_read
, NULL
, chr
);
3552 qemu_chr_reset(chr
);
3555 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3556 static void tcp_chr_telnet_init(int fd
)
3559 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3560 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3561 send(fd
, (char *)buf
, 3, 0);
3562 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3563 send(fd
, (char *)buf
, 3, 0);
3564 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3565 send(fd
, (char *)buf
, 3, 0);
3566 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3567 send(fd
, (char *)buf
, 3, 0);
3570 static void socket_set_nodelay(int fd
)
3573 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3576 static void tcp_chr_accept(void *opaque
)
3578 CharDriverState
*chr
= opaque
;
3579 TCPCharDriver
*s
= chr
->opaque
;
3580 struct sockaddr_in saddr
;
3582 struct sockaddr_un uaddr
;
3584 struct sockaddr
*addr
;
3591 len
= sizeof(uaddr
);
3592 addr
= (struct sockaddr
*)&uaddr
;
3596 len
= sizeof(saddr
);
3597 addr
= (struct sockaddr
*)&saddr
;
3599 fd
= accept(s
->listen_fd
, addr
, &len
);
3600 if (fd
< 0 && errno
!= EINTR
) {
3602 } else if (fd
>= 0) {
3603 if (s
->do_telnetopt
)
3604 tcp_chr_telnet_init(fd
);
3608 socket_set_nonblock(fd
);
3610 socket_set_nodelay(fd
);
3612 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3613 tcp_chr_connect(chr
);
3616 static void tcp_chr_close(CharDriverState
*chr
)
3618 TCPCharDriver
*s
= chr
->opaque
;
3621 if (s
->listen_fd
>= 0)
3622 closesocket(s
->listen_fd
);
3626 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3630 CharDriverState
*chr
= NULL
;
3631 TCPCharDriver
*s
= NULL
;
3632 int fd
= -1, ret
, err
, val
;
3634 int is_waitconnect
= 1;
3637 struct sockaddr_in saddr
;
3639 struct sockaddr_un uaddr
;
3641 struct sockaddr
*addr
;
3646 addr
= (struct sockaddr
*)&uaddr
;
3647 addrlen
= sizeof(uaddr
);
3648 if (parse_unix_path(&uaddr
, host_str
) < 0)
3653 addr
= (struct sockaddr
*)&saddr
;
3654 addrlen
= sizeof(saddr
);
3655 if (parse_host_port(&saddr
, host_str
) < 0)
3660 while((ptr
= strchr(ptr
,','))) {
3662 if (!strncmp(ptr
,"server",6)) {
3664 } else if (!strncmp(ptr
,"nowait",6)) {
3666 } else if (!strncmp(ptr
,"nodelay",6)) {
3669 printf("Unknown option: %s\n", ptr
);
3676 chr
= qemu_mallocz(sizeof(CharDriverState
));
3679 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3685 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3688 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3693 if (!is_waitconnect
)
3694 socket_set_nonblock(fd
);
3699 s
->is_unix
= is_unix
;
3700 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3703 chr
->chr_write
= tcp_chr_write
;
3704 chr
->chr_close
= tcp_chr_close
;
3707 /* allow fast reuse */
3711 pstrcpy(path
, sizeof(path
), uaddr
.sun_path
);
3717 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3720 ret
= bind(fd
, addr
, addrlen
);
3724 ret
= listen(fd
, 0);
3729 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3731 s
->do_telnetopt
= 1;
3734 ret
= connect(fd
, addr
, addrlen
);
3736 err
= socket_error();
3737 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3738 } else if (err
== EINPROGRESS
) {
3741 } else if (err
== WSAEALREADY
) {
3753 socket_set_nodelay(fd
);
3755 tcp_chr_connect(chr
);
3757 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3760 if (is_listen
&& is_waitconnect
) {
3761 printf("QEMU waiting for connection on: %s\n", host_str
);
3762 tcp_chr_accept(chr
);
3763 socket_set_nonblock(s
->listen_fd
);
3775 CharDriverState
*qemu_chr_open(const char *filename
)
3779 if (!strcmp(filename
, "vc")) {
3780 return text_console_init(&display_state
, 0);
3781 } else if (strstart(filename
, "vc:", &p
)) {
3782 return text_console_init(&display_state
, p
);
3783 } else if (!strcmp(filename
, "null")) {
3784 return qemu_chr_open_null();
3786 if (strstart(filename
, "tcp:", &p
)) {
3787 return qemu_chr_open_tcp(p
, 0, 0);
3789 if (strstart(filename
, "telnet:", &p
)) {
3790 return qemu_chr_open_tcp(p
, 1, 0);
3792 if (strstart(filename
, "udp:", &p
)) {
3793 return qemu_chr_open_udp(p
);
3795 if (strstart(filename
, "mon:", &p
)) {
3796 CharDriverState
*drv
= qemu_chr_open(p
);
3798 drv
= qemu_chr_open_mux(drv
);
3799 monitor_init(drv
, !nographic
);
3802 printf("Unable to open driver: %s\n", p
);
3806 if (strstart(filename
, "unix:", &p
)) {
3807 return qemu_chr_open_tcp(p
, 0, 1);
3808 } else if (strstart(filename
, "file:", &p
)) {
3809 return qemu_chr_open_file_out(p
);
3810 } else if (strstart(filename
, "pipe:", &p
)) {
3811 return qemu_chr_open_pipe(p
);
3812 } else if (!strcmp(filename
, "pty")) {
3813 return qemu_chr_open_pty();
3814 } else if (!strcmp(filename
, "stdio")) {
3815 return qemu_chr_open_stdio();
3817 #if defined(__linux__)
3818 if (strstart(filename
, "/dev/parport", NULL
)) {
3819 return qemu_chr_open_pp(filename
);
3822 #if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3823 || defined(__NetBSD__) || defined(__OpenBSD__)
3824 if (strstart(filename
, "/dev/", NULL
)) {
3825 return qemu_chr_open_tty(filename
);
3829 if (strstart(filename
, "COM", NULL
)) {
3830 return qemu_chr_open_win(filename
);
3832 if (strstart(filename
, "pipe:", &p
)) {
3833 return qemu_chr_open_win_pipe(p
);
3835 if (strstart(filename
, "con:", NULL
)) {
3836 return qemu_chr_open_win_con(filename
);
3838 if (strstart(filename
, "file:", &p
)) {
3839 return qemu_chr_open_win_file_out(p
);
3842 #ifdef CONFIG_BRLAPI
3843 if (!strcmp(filename
, "braille")) {
3844 return chr_baum_init();
3852 void qemu_chr_close(CharDriverState
*chr
)
3855 chr
->chr_close(chr
);
3859 /***********************************************************/
3860 /* network device redirectors */
3862 __attribute__ (( unused
))
3863 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3867 for(i
=0;i
<size
;i
+=16) {
3871 fprintf(f
, "%08x ", i
);
3874 fprintf(f
, " %02x", buf
[i
+j
]);
3879 for(j
=0;j
<len
;j
++) {
3881 if (c
< ' ' || c
> '~')
3883 fprintf(f
, "%c", c
);
3889 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3896 offset
= strtol(p
, &last_char
, 0);
3897 if (0 == errno
&& '\0' == *last_char
&&
3898 offset
>= 0 && offset
<= 0xFFFFFF) {
3899 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3900 macaddr
[4] = (offset
& 0xFF00) >> 8;
3901 macaddr
[5] = offset
& 0xFF;
3904 for(i
= 0; i
< 6; i
++) {
3905 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3910 if (*p
!= ':' && *p
!= '-')
3921 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3926 p1
= strchr(p
, sep
);
3932 if (len
> buf_size
- 1)
3934 memcpy(buf
, p
, len
);
3941 int parse_host_src_port(struct sockaddr_in
*haddr
,
3942 struct sockaddr_in
*saddr
,
3943 const char *input_str
)
3945 char *str
= strdup(input_str
);
3946 char *host_str
= str
;
3948 const char *src_str2
;
3952 * Chop off any extra arguments at the end of the string which
3953 * would start with a comma, then fill in the src port information
3954 * if it was provided else use the "any address" and "any port".
3956 if ((ptr
= strchr(str
,',')))
3959 if ((src_str
= strchr(input_str
,'@'))) {
3964 if (parse_host_port(haddr
, host_str
) < 0)
3968 if (!src_str
|| *src_str
== '\0')
3971 if (parse_host_port(saddr
, src_str2
) < 0)
3982 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3990 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3992 saddr
->sin_family
= AF_INET
;
3993 if (buf
[0] == '\0') {
3994 saddr
->sin_addr
.s_addr
= 0;
3996 if (isdigit(buf
[0])) {
3997 if (!inet_aton(buf
, &saddr
->sin_addr
))
4000 if ((he
= gethostbyname(buf
)) == NULL
)
4002 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
4005 port
= strtol(p
, (char **)&r
, 0);
4008 saddr
->sin_port
= htons(port
);
4013 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
4018 len
= MIN(108, strlen(str
));
4019 p
= strchr(str
, ',');
4021 len
= MIN(len
, p
- str
);
4023 memset(uaddr
, 0, sizeof(*uaddr
));
4025 uaddr
->sun_family
= AF_UNIX
;
4026 memcpy(uaddr
->sun_path
, str
, len
);
4032 /* find or alloc a new VLAN */
4033 VLANState
*qemu_find_vlan(int id
)
4035 VLANState
**pvlan
, *vlan
;
4036 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4040 vlan
= qemu_mallocz(sizeof(VLANState
));
4045 pvlan
= &first_vlan
;
4046 while (*pvlan
!= NULL
)
4047 pvlan
= &(*pvlan
)->next
;
4052 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
4053 IOReadHandler
*fd_read
,
4054 IOCanRWHandler
*fd_can_read
,
4057 VLANClientState
*vc
, **pvc
;
4058 vc
= qemu_mallocz(sizeof(VLANClientState
));
4061 vc
->fd_read
= fd_read
;
4062 vc
->fd_can_read
= fd_can_read
;
4063 vc
->opaque
= opaque
;
4067 pvc
= &vlan
->first_client
;
4068 while (*pvc
!= NULL
)
4069 pvc
= &(*pvc
)->next
;
4074 void qemu_del_vlan_client(VLANClientState
*vc
)
4076 VLANClientState
**pvc
= &vc
->vlan
->first_client
;
4078 while (*pvc
!= NULL
)
4084 pvc
= &(*pvc
)->next
;
4087 int qemu_can_send_packet(VLANClientState
*vc1
)
4089 VLANState
*vlan
= vc1
->vlan
;
4090 VLANClientState
*vc
;
4092 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4094 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
4101 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
4103 VLANState
*vlan
= vc1
->vlan
;
4104 VLANClientState
*vc
;
4107 printf("vlan %d send:\n", vlan
->id
);
4108 hex_dump(stdout
, buf
, size
);
4110 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4112 vc
->fd_read(vc
->opaque
, buf
, size
);
4117 #if defined(CONFIG_SLIRP)
4119 /* slirp network adapter */
4121 static int slirp_inited
;
4122 static VLANClientState
*slirp_vc
;
4124 int slirp_can_output(void)
4126 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
4129 void slirp_output(const uint8_t *pkt
, int pkt_len
)
4132 printf("slirp output:\n");
4133 hex_dump(stdout
, pkt
, pkt_len
);
4137 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
4140 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
4143 printf("slirp input:\n");
4144 hex_dump(stdout
, buf
, size
);
4146 slirp_input(buf
, size
);
4149 static int net_slirp_init(VLANState
*vlan
)
4151 if (!slirp_inited
) {
4155 slirp_vc
= qemu_new_vlan_client(vlan
,
4156 slirp_receive
, NULL
, NULL
);
4157 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
4161 static void net_slirp_redir(const char *redir_str
)
4166 struct in_addr guest_addr
;
4167 int host_port
, guest_port
;
4169 if (!slirp_inited
) {
4175 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4177 if (!strcmp(buf
, "tcp")) {
4179 } else if (!strcmp(buf
, "udp")) {
4185 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4187 host_port
= strtol(buf
, &r
, 0);
4191 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
4193 if (buf
[0] == '\0') {
4194 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
4196 if (!inet_aton(buf
, &guest_addr
))
4199 guest_port
= strtol(p
, &r
, 0);
4203 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
4204 fprintf(stderr
, "qemu: could not set up redirection\n");
4209 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4217 static void erase_dir(char *dir_name
)
4221 char filename
[1024];
4223 /* erase all the files in the directory */
4224 if ((d
= opendir(dir_name
)) != 0) {
4229 if (strcmp(de
->d_name
, ".") != 0 &&
4230 strcmp(de
->d_name
, "..") != 0) {
4231 snprintf(filename
, sizeof(filename
), "%s/%s",
4232 smb_dir
, de
->d_name
);
4233 if (unlink(filename
) != 0) /* is it a directory? */
4234 erase_dir(filename
);
4242 /* automatic user mode samba server configuration */
4243 static void smb_exit(void)
4248 /* automatic user mode samba server configuration */
4249 static void net_slirp_smb(const char *exported_dir
)
4251 char smb_conf
[1024];
4252 char smb_cmdline
[1024];
4255 if (!slirp_inited
) {
4260 /* XXX: better tmp dir construction */
4261 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4262 if (mkdir(smb_dir
, 0700) < 0) {
4263 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4266 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4268 f
= fopen(smb_conf
, "w");
4270 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4277 "socket address=127.0.0.1\n"
4278 "pid directory=%s\n"
4279 "lock directory=%s\n"
4280 "log file=%s/log.smbd\n"
4281 "smb passwd file=%s/smbpasswd\n"
4282 "security = share\n"
4297 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4298 SMBD_COMMAND
, smb_conf
);
4300 slirp_add_exec(0, smb_cmdline
, 4, 139);
4303 #endif /* !defined(_WIN32) */
4304 void do_info_slirp(void)
4309 #endif /* CONFIG_SLIRP */
4311 #if !defined(_WIN32)
4313 typedef struct TAPState
{
4314 VLANClientState
*vc
;
4316 char down_script
[1024];
4319 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4321 TAPState
*s
= opaque
;
4324 ret
= write(s
->fd
, buf
, size
);
4325 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4332 static void tap_send(void *opaque
)
4334 TAPState
*s
= opaque
;
4341 sbuf
.maxlen
= sizeof(buf
);
4343 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4345 size
= read(s
->fd
, buf
, sizeof(buf
));
4348 qemu_send_packet(s
->vc
, buf
, size
);
4354 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4358 s
= qemu_mallocz(sizeof(TAPState
));
4362 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4363 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
4364 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4368 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4369 static int tap_open(char *ifname
, int ifname_size
)
4375 TFR(fd
= open("/dev/tap", O_RDWR
));
4377 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4382 dev
= devname(s
.st_rdev
, S_IFCHR
);
4383 pstrcpy(ifname
, ifname_size
, dev
);
4385 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4388 #elif defined(__sun__)
4389 #define TUNNEWPPA (('T'<<16) | 0x0001)
4391 * Allocate TAP device, returns opened fd.
4392 * Stores dev name in the first arg(must be large enough).
4394 int tap_alloc(char *dev
, size_t dev_size
)
4396 int tap_fd
, if_fd
, ppa
= -1;
4397 static int ip_fd
= 0;
4400 static int arp_fd
= 0;
4401 int ip_muxid
, arp_muxid
;
4402 struct strioctl strioc_if
, strioc_ppa
;
4403 int link_type
= I_PLINK
;;
4405 char actual_name
[32] = "";
4407 memset(&ifr
, 0x0, sizeof(ifr
));
4411 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4415 /* Check if IP device was opened */
4419 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4421 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4425 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4427 syslog(LOG_ERR
, "Can't open /dev/tap");
4431 /* Assign a new PPA and get its unit number. */
4432 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4433 strioc_ppa
.ic_timout
= 0;
4434 strioc_ppa
.ic_len
= sizeof(ppa
);
4435 strioc_ppa
.ic_dp
= (char *)&ppa
;
4436 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4437 syslog (LOG_ERR
, "Can't assign new interface");
4439 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4441 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4444 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4445 syslog(LOG_ERR
, "Can't push IP module");
4449 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4450 syslog(LOG_ERR
, "Can't get flags\n");
4452 snprintf (actual_name
, 32, "tap%d", ppa
);
4453 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4456 /* Assign ppa according to the unit number returned by tun device */
4458 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4459 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4460 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4461 syslog (LOG_ERR
, "Can't get flags\n");
4462 /* Push arp module to if_fd */
4463 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4464 syslog (LOG_ERR
, "Can't push ARP module (2)");
4466 /* Push arp module to ip_fd */
4467 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4468 syslog (LOG_ERR
, "I_POP failed\n");
4469 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4470 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4472 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4474 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4476 /* Set ifname to arp */
4477 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4478 strioc_if
.ic_timout
= 0;
4479 strioc_if
.ic_len
= sizeof(ifr
);
4480 strioc_if
.ic_dp
= (char *)&ifr
;
4481 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4482 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4485 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4486 syslog(LOG_ERR
, "Can't link TAP device to IP");
4490 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4491 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4495 memset(&ifr
, 0x0, sizeof(ifr
));
4496 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4497 ifr
.lifr_ip_muxid
= ip_muxid
;
4498 ifr
.lifr_arp_muxid
= arp_muxid
;
4500 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4502 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4503 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4504 syslog (LOG_ERR
, "Can't set multiplexor id");
4507 snprintf(dev
, dev_size
, "tap%d", ppa
);
4511 static int tap_open(char *ifname
, int ifname_size
)
4515 if( (fd
= tap_alloc(dev
, sizeof(dev
))) < 0 ){
4516 fprintf(stderr
, "Cannot allocate TAP device\n");
4519 pstrcpy(ifname
, ifname_size
, dev
);
4520 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4524 static int tap_open(char *ifname
, int ifname_size
)
4529 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4531 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4534 memset(&ifr
, 0, sizeof(ifr
));
4535 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4536 if (ifname
[0] != '\0')
4537 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4539 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4540 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4542 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4546 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4547 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4552 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4558 /* try to launch network script */
4562 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4563 for (i
= 0; i
< open_max
; i
++)
4564 if (i
!= STDIN_FILENO
&&
4565 i
!= STDOUT_FILENO
&&
4566 i
!= STDERR_FILENO
&&
4571 *parg
++ = (char *)setup_script
;
4572 *parg
++ = (char *)ifname
;
4574 execv(setup_script
, args
);
4577 while (waitpid(pid
, &status
, 0) != pid
);
4578 if (!WIFEXITED(status
) ||
4579 WEXITSTATUS(status
) != 0) {
4580 fprintf(stderr
, "%s: could not launch network script\n",
4588 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4589 const char *setup_script
, const char *down_script
)
4595 if (ifname1
!= NULL
)
4596 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4599 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4603 if (!setup_script
|| !strcmp(setup_script
, "no"))
4605 if (setup_script
[0] != '\0') {
4606 if (launch_script(setup_script
, ifname
, fd
))
4609 s
= net_tap_fd_init(vlan
, fd
);
4612 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4613 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4614 if (down_script
&& strcmp(down_script
, "no"))
4615 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4619 #endif /* !_WIN32 */
4621 #if defined(CONFIG_VDE)
4622 typedef struct VDEState
{
4623 VLANClientState
*vc
;
4627 static void vde_to_qemu(void *opaque
)
4629 VDEState
*s
= opaque
;
4633 size
= vde_recv(s
->vde
, buf
, sizeof(buf
), 0);
4635 qemu_send_packet(s
->vc
, buf
, size
);
4639 static void vde_from_qemu(void *opaque
, const uint8_t *buf
, int size
)
4641 VDEState
*s
= opaque
;
4644 ret
= vde_send(s
->vde
, buf
, size
, 0);
4645 if (ret
< 0 && errno
== EINTR
) {
4652 static int net_vde_init(VLANState
*vlan
, const char *sock
, int port
,
4653 const char *group
, int mode
)
4656 char *init_group
= strlen(group
) ? (char *)group
: NULL
;
4657 char *init_sock
= strlen(sock
) ? (char *)sock
: NULL
;
4659 struct vde_open_args args
= {
4661 .group
= init_group
,
4665 s
= qemu_mallocz(sizeof(VDEState
));
4668 s
->vde
= vde_open(init_sock
, "QEMU", &args
);
4673 s
->vc
= qemu_new_vlan_client(vlan
, vde_from_qemu
, NULL
, s
);
4674 qemu_set_fd_handler(vde_datafd(s
->vde
), vde_to_qemu
, NULL
, s
);
4675 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "vde: sock=%s fd=%d",
4676 sock
, vde_datafd(s
->vde
));
4681 /* network connection */
4682 typedef struct NetSocketState
{
4683 VLANClientState
*vc
;
4685 int state
; /* 0 = getting length, 1 = getting data */
4689 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4692 typedef struct NetSocketListenState
{
4695 } NetSocketListenState
;
4697 /* XXX: we consider we can send the whole packet without blocking */
4698 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4700 NetSocketState
*s
= opaque
;
4704 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4705 send_all(s
->fd
, buf
, size
);
4708 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4710 NetSocketState
*s
= opaque
;
4711 sendto(s
->fd
, buf
, size
, 0,
4712 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4715 static void net_socket_send(void *opaque
)
4717 NetSocketState
*s
= opaque
;
4722 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4724 err
= socket_error();
4725 if (err
!= EWOULDBLOCK
)
4727 } else if (size
== 0) {
4728 /* end of connection */
4730 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4736 /* reassemble a packet from the network */
4742 memcpy(s
->buf
+ s
->index
, buf
, l
);
4746 if (s
->index
== 4) {
4748 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4754 l
= s
->packet_len
- s
->index
;
4757 memcpy(s
->buf
+ s
->index
, buf
, l
);
4761 if (s
->index
>= s
->packet_len
) {
4762 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4771 static void net_socket_send_dgram(void *opaque
)
4773 NetSocketState
*s
= opaque
;
4776 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4780 /* end of connection */
4781 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4784 qemu_send_packet(s
->vc
, s
->buf
, size
);
4787 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4792 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4793 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4794 inet_ntoa(mcastaddr
->sin_addr
),
4795 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4799 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4801 perror("socket(PF_INET, SOCK_DGRAM)");
4806 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4807 (const char *)&val
, sizeof(val
));
4809 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4813 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4819 /* Add host to multicast group */
4820 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4821 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4823 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4824 (const char *)&imr
, sizeof(struct ip_mreq
));
4826 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4830 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4832 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4833 (const char *)&val
, sizeof(val
));
4835 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4839 socket_set_nonblock(fd
);
4847 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4850 struct sockaddr_in saddr
;
4852 socklen_t saddr_len
;
4855 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4856 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4857 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4861 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4863 if (saddr
.sin_addr
.s_addr
==0) {
4864 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4868 /* clone dgram socket */
4869 newfd
= net_socket_mcast_create(&saddr
);
4871 /* error already reported by net_socket_mcast_create() */
4875 /* clone newfd to fd, close newfd */
4880 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4881 fd
, strerror(errno
));
4886 s
= qemu_mallocz(sizeof(NetSocketState
));
4891 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4892 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4894 /* mcast: save bound address as dst */
4895 if (is_connected
) s
->dgram_dst
=saddr
;
4897 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4898 "socket: fd=%d (%s mcast=%s:%d)",
4899 fd
, is_connected
? "cloned" : "",
4900 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4904 static void net_socket_connect(void *opaque
)
4906 NetSocketState
*s
= opaque
;
4907 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4910 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4914 s
= qemu_mallocz(sizeof(NetSocketState
));
4918 s
->vc
= qemu_new_vlan_client(vlan
,
4919 net_socket_receive
, NULL
, s
);
4920 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4921 "socket: fd=%d", fd
);
4923 net_socket_connect(s
);
4925 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4930 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4933 int so_type
=-1, optlen
=sizeof(so_type
);
4935 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4936 (socklen_t
*)&optlen
)< 0) {
4937 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4942 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4944 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4946 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4947 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4948 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4953 static void net_socket_accept(void *opaque
)
4955 NetSocketListenState
*s
= opaque
;
4957 struct sockaddr_in saddr
;
4962 len
= sizeof(saddr
);
4963 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4964 if (fd
< 0 && errno
!= EINTR
) {
4966 } else if (fd
>= 0) {
4970 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4974 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4975 "socket: connection from %s:%d",
4976 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4980 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4982 NetSocketListenState
*s
;
4984 struct sockaddr_in saddr
;
4986 if (parse_host_port(&saddr
, host_str
) < 0)
4989 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4993 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4998 socket_set_nonblock(fd
);
5000 /* allow fast reuse */
5002 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
5004 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5009 ret
= listen(fd
, 0);
5016 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
5020 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
5023 int fd
, connected
, ret
, err
;
5024 struct sockaddr_in saddr
;
5026 if (parse_host_port(&saddr
, host_str
) < 0)
5029 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
5034 socket_set_nonblock(fd
);
5038 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
5040 err
= socket_error();
5041 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
5042 } else if (err
== EINPROGRESS
) {
5045 } else if (err
== WSAEALREADY
) {
5058 s
= net_socket_fd_init(vlan
, fd
, connected
);
5061 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5062 "socket: connect to %s:%d",
5063 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5067 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
5071 struct sockaddr_in saddr
;
5073 if (parse_host_port(&saddr
, host_str
) < 0)
5077 fd
= net_socket_mcast_create(&saddr
);
5081 s
= net_socket_fd_init(vlan
, fd
, 0);
5085 s
->dgram_dst
= saddr
;
5087 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
5088 "socket: mcast=%s:%d",
5089 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
5094 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
5099 while (*p
!= '\0' && *p
!= '=') {
5100 if (q
&& (q
- buf
) < buf_size
- 1)
5110 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
5115 while (*p
!= '\0') {
5117 if (*(p
+ 1) != ',')
5121 if (q
&& (q
- buf
) < buf_size
- 1)
5131 static int get_param_value(char *buf
, int buf_size
,
5132 const char *tag
, const char *str
)
5139 p
= get_opt_name(option
, sizeof(option
), p
);
5143 if (!strcmp(tag
, option
)) {
5144 (void)get_opt_value(buf
, buf_size
, p
);
5147 p
= get_opt_value(NULL
, 0, p
);
5156 static int check_params(char *buf
, int buf_size
,
5157 const char * const *params
, const char *str
)
5164 p
= get_opt_name(buf
, buf_size
, p
);
5168 for(i
= 0; params
[i
] != NULL
; i
++)
5169 if (!strcmp(params
[i
], buf
))
5171 if (params
[i
] == NULL
)
5173 p
= get_opt_value(NULL
, 0, p
);
5181 static int net_client_init(const char *device
, const char *p
)
5188 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
5189 vlan_id
= strtol(buf
, NULL
, 0);
5191 vlan
= qemu_find_vlan(vlan_id
);
5193 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
5196 if (!strcmp(device
, "nic")) {
5200 if (nb_nics
>= MAX_NICS
) {
5201 fprintf(stderr
, "Too Many NICs\n");
5204 nd
= &nd_table
[nb_nics
];
5205 macaddr
= nd
->macaddr
;
5211 macaddr
[5] = 0x56 + nb_nics
;
5213 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
5214 if (parse_macaddr(macaddr
, buf
) < 0) {
5215 fprintf(stderr
, "invalid syntax for ethernet address\n");
5219 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5220 nd
->model
= strdup(buf
);
5224 vlan
->nb_guest_devs
++;
5227 if (!strcmp(device
, "none")) {
5228 /* does nothing. It is needed to signal that no network cards
5233 if (!strcmp(device
, "user")) {
5234 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5235 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5237 vlan
->nb_host_devs
++;
5238 ret
= net_slirp_init(vlan
);
5242 if (!strcmp(device
, "tap")) {
5244 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5245 fprintf(stderr
, "tap: no interface name\n");
5248 vlan
->nb_host_devs
++;
5249 ret
= tap_win32_init(vlan
, ifname
);
5252 if (!strcmp(device
, "tap")) {
5254 char setup_script
[1024], down_script
[1024];
5256 vlan
->nb_host_devs
++;
5257 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5258 fd
= strtol(buf
, NULL
, 0);
5259 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5261 if (net_tap_fd_init(vlan
, fd
))
5264 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5267 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5268 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5270 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5271 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5273 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5277 if (!strcmp(device
, "socket")) {
5278 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5280 fd
= strtol(buf
, NULL
, 0);
5282 if (net_socket_fd_init(vlan
, fd
, 1))
5284 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5285 ret
= net_socket_listen_init(vlan
, buf
);
5286 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5287 ret
= net_socket_connect_init(vlan
, buf
);
5288 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5289 ret
= net_socket_mcast_init(vlan
, buf
);
5291 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5294 vlan
->nb_host_devs
++;
5297 if (!strcmp(device
, "vde")) {
5298 char vde_sock
[1024], vde_group
[512];
5299 int vde_port
, vde_mode
;
5300 vlan
->nb_host_devs
++;
5301 if (get_param_value(vde_sock
, sizeof(vde_sock
), "sock", p
) <= 0) {
5304 if (get_param_value(buf
, sizeof(buf
), "port", p
) > 0) {
5305 vde_port
= strtol(buf
, NULL
, 10);
5309 if (get_param_value(vde_group
, sizeof(vde_group
), "group", p
) <= 0) {
5310 vde_group
[0] = '\0';
5312 if (get_param_value(buf
, sizeof(buf
), "mode", p
) > 0) {
5313 vde_mode
= strtol(buf
, NULL
, 8);
5317 ret
= net_vde_init(vlan
, vde_sock
, vde_port
, vde_group
, vde_mode
);
5321 fprintf(stderr
, "Unknown network device: %s\n", device
);
5325 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5331 static int net_client_parse(const char *str
)
5339 while (*p
!= '\0' && *p
!= ',') {
5340 if ((q
- device
) < sizeof(device
) - 1)
5348 return net_client_init(device
, p
);
5351 void do_info_network(void)
5354 VLANClientState
*vc
;
5356 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5357 term_printf("VLAN %d devices:\n", vlan
->id
);
5358 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5359 term_printf(" %s\n", vc
->info_str
);
5363 #define HD_ALIAS "index=%d,media=disk"
5365 #define CDROM_ALIAS "index=1,media=cdrom"
5367 #define CDROM_ALIAS "index=2,media=cdrom"
5369 #define FD_ALIAS "index=%d,if=floppy"
5370 #define PFLASH_ALIAS "if=pflash"
5371 #define MTD_ALIAS "if=mtd"
5372 #define SD_ALIAS "index=0,if=sd"
5374 static int drive_add(const char *file
, const char *fmt
, ...)
5378 if (nb_drives_opt
>= MAX_DRIVES
) {
5379 fprintf(stderr
, "qemu: too many drives\n");
5383 drives_opt
[nb_drives_opt
].file
= file
;
5385 vsnprintf(drives_opt
[nb_drives_opt
].opt
,
5386 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5389 return nb_drives_opt
++;
5392 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5396 /* seek interface, bus and unit */
5398 for (index
= 0; index
< nb_drives
; index
++)
5399 if (drives_table
[index
].type
== type
&&
5400 drives_table
[index
].bus
== bus
&&
5401 drives_table
[index
].unit
== unit
)
5407 int drive_get_max_bus(BlockInterfaceType type
)
5413 for (index
= 0; index
< nb_drives
; index
++) {
5414 if(drives_table
[index
].type
== type
&&
5415 drives_table
[index
].bus
> max_bus
)
5416 max_bus
= drives_table
[index
].bus
;
5421 static void bdrv_format_print(void *opaque
, const char *name
)
5423 fprintf(stderr
, " %s", name
);
5426 static int drive_init(struct drive_opt
*arg
, int snapshot
,
5427 QEMUMachine
*machine
)
5432 const char *mediastr
= "";
5433 BlockInterfaceType type
;
5434 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5435 int bus_id
, unit_id
;
5436 int cyls
, heads
, secs
, translation
;
5437 BlockDriverState
*bdrv
;
5438 BlockDriver
*drv
= NULL
;
5443 char *str
= arg
->opt
;
5444 static const char * const params
[] = { "bus", "unit", "if", "index",
5445 "cyls", "heads", "secs", "trans",
5446 "media", "snapshot", "file",
5447 "cache", "format", NULL
};
5449 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5450 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5456 cyls
= heads
= secs
= 0;
5459 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5463 if (!strcmp(machine
->name
, "realview") ||
5464 !strcmp(machine
->name
, "SS-5") ||
5465 !strcmp(machine
->name
, "SS-10") ||
5466 !strcmp(machine
->name
, "SS-600MP") ||
5467 !strcmp(machine
->name
, "versatilepb") ||
5468 !strcmp(machine
->name
, "versatileab")) {
5470 max_devs
= MAX_SCSI_DEVS
;
5471 pstrcpy(devname
, sizeof(devname
), "scsi");
5474 max_devs
= MAX_IDE_DEVS
;
5475 pstrcpy(devname
, sizeof(devname
), "ide");
5479 /* extract parameters */
5481 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5482 bus_id
= strtol(buf
, NULL
, 0);
5484 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5489 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5490 unit_id
= strtol(buf
, NULL
, 0);
5492 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5497 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5498 pstrcpy(devname
, sizeof(devname
), buf
);
5499 if (!strcmp(buf
, "ide")) {
5501 max_devs
= MAX_IDE_DEVS
;
5502 } else if (!strcmp(buf
, "scsi")) {
5504 max_devs
= MAX_SCSI_DEVS
;
5505 } else if (!strcmp(buf
, "floppy")) {
5508 } else if (!strcmp(buf
, "pflash")) {
5511 } else if (!strcmp(buf
, "mtd")) {
5514 } else if (!strcmp(buf
, "sd")) {
5518 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5523 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5524 index
= strtol(buf
, NULL
, 0);
5526 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5531 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5532 cyls
= strtol(buf
, NULL
, 0);
5535 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5536 heads
= strtol(buf
, NULL
, 0);
5539 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5540 secs
= strtol(buf
, NULL
, 0);
5543 if (cyls
|| heads
|| secs
) {
5544 if (cyls
< 1 || cyls
> 16383) {
5545 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5548 if (heads
< 1 || heads
> 16) {
5549 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5552 if (secs
< 1 || secs
> 63) {
5553 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5558 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5561 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5565 if (!strcmp(buf
, "none"))
5566 translation
= BIOS_ATA_TRANSLATION_NONE
;
5567 else if (!strcmp(buf
, "lba"))
5568 translation
= BIOS_ATA_TRANSLATION_LBA
;
5569 else if (!strcmp(buf
, "auto"))
5570 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5572 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5577 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5578 if (!strcmp(buf
, "disk")) {
5580 } else if (!strcmp(buf
, "cdrom")) {
5581 if (cyls
|| secs
|| heads
) {
5583 "qemu: '%s' invalid physical CHS format\n", str
);
5586 media
= MEDIA_CDROM
;
5588 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5593 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5594 if (!strcmp(buf
, "on"))
5596 else if (!strcmp(buf
, "off"))
5599 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5604 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5605 if (!strcmp(buf
, "off"))
5607 else if (!strcmp(buf
, "on"))
5610 fprintf(stderr
, "qemu: invalid cache option\n");
5615 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5616 if (strcmp(buf
, "?") == 0) {
5617 fprintf(stderr
, "qemu: Supported formats:");
5618 bdrv_iterate_format(bdrv_format_print
, NULL
);
5619 fprintf(stderr
, "\n");
5622 drv
= bdrv_find_format(buf
);
5624 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5629 if (arg
->file
== NULL
)
5630 get_param_value(file
, sizeof(file
), "file", str
);
5632 pstrcpy(file
, sizeof(file
), arg
->file
);
5634 /* compute bus and unit according index */
5637 if (bus_id
!= 0 || unit_id
!= -1) {
5639 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5647 unit_id
= index
% max_devs
;
5648 bus_id
= index
/ max_devs
;
5652 /* if user doesn't specify a unit_id,
5653 * try to find the first free
5656 if (unit_id
== -1) {
5658 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5660 if (max_devs
&& unit_id
>= max_devs
) {
5661 unit_id
-= max_devs
;
5669 if (max_devs
&& unit_id
>= max_devs
) {
5670 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5671 str
, unit_id
, max_devs
- 1);
5676 * ignore multiple definitions
5679 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5684 if (type
== IF_IDE
|| type
== IF_SCSI
)
5685 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5687 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5688 devname
, bus_id
, mediastr
, unit_id
);
5690 snprintf(buf
, sizeof(buf
), "%s%s%i",
5691 devname
, mediastr
, unit_id
);
5692 bdrv
= bdrv_new(buf
);
5693 drives_table
[nb_drives
].bdrv
= bdrv
;
5694 drives_table
[nb_drives
].type
= type
;
5695 drives_table
[nb_drives
].bus
= bus_id
;
5696 drives_table
[nb_drives
].unit
= unit_id
;
5705 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5706 bdrv_set_translation_hint(bdrv
, translation
);
5710 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5715 /* FIXME: This isn't really a floppy, but it's a reasonable
5718 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5728 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5730 bdrv_flags
|= BDRV_O_DIRECT
;
5731 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5732 fprintf(stderr
, "qemu: could not open disk image %s\n",
5739 /***********************************************************/
5742 static USBPort
*used_usb_ports
;
5743 static USBPort
*free_usb_ports
;
5745 /* ??? Maybe change this to register a hub to keep track of the topology. */
5746 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5747 usb_attachfn attach
)
5749 port
->opaque
= opaque
;
5750 port
->index
= index
;
5751 port
->attach
= attach
;
5752 port
->next
= free_usb_ports
;
5753 free_usb_ports
= port
;
5756 int usb_device_add_dev(USBDevice
*dev
)
5760 /* Find a USB port to add the device to. */
5761 port
= free_usb_ports
;
5765 /* Create a new hub and chain it on. */
5766 free_usb_ports
= NULL
;
5767 port
->next
= used_usb_ports
;
5768 used_usb_ports
= port
;
5770 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5771 usb_attach(port
, hub
);
5772 port
= free_usb_ports
;
5775 free_usb_ports
= port
->next
;
5776 port
->next
= used_usb_ports
;
5777 used_usb_ports
= port
;
5778 usb_attach(port
, dev
);
5782 static int usb_device_add(const char *devname
)
5787 if (!free_usb_ports
)
5790 if (strstart(devname
, "host:", &p
)) {
5791 dev
= usb_host_device_open(p
);
5792 } else if (!strcmp(devname
, "mouse")) {
5793 dev
= usb_mouse_init();
5794 } else if (!strcmp(devname
, "tablet")) {
5795 dev
= usb_tablet_init();
5796 } else if (!strcmp(devname
, "keyboard")) {
5797 dev
= usb_keyboard_init();
5798 } else if (strstart(devname
, "disk:", &p
)) {
5799 dev
= usb_msd_init(p
);
5800 } else if (!strcmp(devname
, "wacom-tablet")) {
5801 dev
= usb_wacom_init();
5802 } else if (strstart(devname
, "serial:", &p
)) {
5803 dev
= usb_serial_init(p
);
5804 #ifdef CONFIG_BRLAPI
5805 } else if (!strcmp(devname
, "braille")) {
5806 dev
= usb_baum_init();
5808 } else if (strstart(devname
, "net:", &p
)) {
5811 if (net_client_init("nic", p
) < 0)
5813 nd_table
[nic
].model
= "usb";
5814 dev
= usb_net_init(&nd_table
[nic
]);
5821 return usb_device_add_dev(dev
);
5824 int usb_device_del_addr(int bus_num
, int addr
)
5830 if (!used_usb_ports
)
5836 lastp
= &used_usb_ports
;
5837 port
= used_usb_ports
;
5838 while (port
&& port
->dev
->addr
!= addr
) {
5839 lastp
= &port
->next
;
5847 *lastp
= port
->next
;
5848 usb_attach(port
, NULL
);
5849 dev
->handle_destroy(dev
);
5850 port
->next
= free_usb_ports
;
5851 free_usb_ports
= port
;
5855 static int usb_device_del(const char *devname
)
5860 if (strstart(devname
, "host:", &p
))
5861 return usb_host_device_close(p
);
5863 if (!used_usb_ports
)
5866 p
= strchr(devname
, '.');
5869 bus_num
= strtoul(devname
, NULL
, 0);
5870 addr
= strtoul(p
+ 1, NULL
, 0);
5872 return usb_device_del_addr(bus_num
, addr
);
5875 void do_usb_add(const char *devname
)
5877 usb_device_add(devname
);
5880 void do_usb_del(const char *devname
)
5882 usb_device_del(devname
);
5889 const char *speed_str
;
5892 term_printf("USB support not enabled\n");
5896 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5900 switch(dev
->speed
) {
5904 case USB_SPEED_FULL
:
5907 case USB_SPEED_HIGH
:
5914 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5915 0, dev
->addr
, speed_str
, dev
->devname
);
5919 /***********************************************************/
5920 /* PCMCIA/Cardbus */
5922 static struct pcmcia_socket_entry_s
{
5923 struct pcmcia_socket_s
*socket
;
5924 struct pcmcia_socket_entry_s
*next
;
5925 } *pcmcia_sockets
= 0;
5927 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5929 struct pcmcia_socket_entry_s
*entry
;
5931 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5932 entry
->socket
= socket
;
5933 entry
->next
= pcmcia_sockets
;
5934 pcmcia_sockets
= entry
;
5937 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5939 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5941 ptr
= &pcmcia_sockets
;
5942 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5943 if (entry
->socket
== socket
) {
5949 void pcmcia_info(void)
5951 struct pcmcia_socket_entry_s
*iter
;
5952 if (!pcmcia_sockets
)
5953 term_printf("No PCMCIA sockets\n");
5955 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5956 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5957 iter
->socket
->attached
? iter
->socket
->card_string
:
5961 /***********************************************************/
5964 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5968 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5972 static void dumb_refresh(DisplayState
*ds
)
5974 #if defined(CONFIG_SDL)
5979 static void dumb_display_init(DisplayState
*ds
)
5984 ds
->dpy_update
= dumb_update
;
5985 ds
->dpy_resize
= dumb_resize
;
5986 ds
->dpy_refresh
= dumb_refresh
;
5987 ds
->gui_timer_interval
= 500;
5991 /***********************************************************/
5994 #define MAX_IO_HANDLERS 64
5996 typedef struct IOHandlerRecord
{
5998 IOCanRWHandler
*fd_read_poll
;
6000 IOHandler
*fd_write
;
6003 /* temporary data */
6005 struct IOHandlerRecord
*next
;
6008 static IOHandlerRecord
*first_io_handler
;
6010 /* XXX: fd_read_poll should be suppressed, but an API change is
6011 necessary in the character devices to suppress fd_can_read(). */
6012 int qemu_set_fd_handler2(int fd
,
6013 IOCanRWHandler
*fd_read_poll
,
6015 IOHandler
*fd_write
,
6018 IOHandlerRecord
**pioh
, *ioh
;
6020 if (!fd_read
&& !fd_write
) {
6021 pioh
= &first_io_handler
;
6026 if (ioh
->fd
== fd
) {
6033 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6037 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
6040 ioh
->next
= first_io_handler
;
6041 first_io_handler
= ioh
;
6044 ioh
->fd_read_poll
= fd_read_poll
;
6045 ioh
->fd_read
= fd_read
;
6046 ioh
->fd_write
= fd_write
;
6047 ioh
->opaque
= opaque
;
6053 int qemu_set_fd_handler(int fd
,
6055 IOHandler
*fd_write
,
6058 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
6061 /***********************************************************/
6062 /* Polling handling */
6064 typedef struct PollingEntry
{
6067 struct PollingEntry
*next
;
6070 static PollingEntry
*first_polling_entry
;
6072 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
6074 PollingEntry
**ppe
, *pe
;
6075 pe
= qemu_mallocz(sizeof(PollingEntry
));
6079 pe
->opaque
= opaque
;
6080 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
6085 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
6087 PollingEntry
**ppe
, *pe
;
6088 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
6090 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
6099 /***********************************************************/
6100 /* Wait objects support */
6101 typedef struct WaitObjects
{
6103 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
6104 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
6105 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
6108 static WaitObjects wait_objects
= {0};
6110 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6112 WaitObjects
*w
= &wait_objects
;
6114 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
6116 w
->events
[w
->num
] = handle
;
6117 w
->func
[w
->num
] = func
;
6118 w
->opaque
[w
->num
] = opaque
;
6123 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
6126 WaitObjects
*w
= &wait_objects
;
6129 for (i
= 0; i
< w
->num
; i
++) {
6130 if (w
->events
[i
] == handle
)
6133 w
->events
[i
] = w
->events
[i
+ 1];
6134 w
->func
[i
] = w
->func
[i
+ 1];
6135 w
->opaque
[i
] = w
->opaque
[i
+ 1];
6143 /***********************************************************/
6144 /* savevm/loadvm support */
6146 #define IO_BUF_SIZE 32768
6150 BlockDriverState
*bs
;
6153 int64_t base_offset
;
6154 int64_t buf_offset
; /* start of buffer when writing, end of buffer
6157 int buf_size
; /* 0 when writing */
6158 uint8_t buf
[IO_BUF_SIZE
];
6161 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
6165 f
= qemu_mallocz(sizeof(QEMUFile
));
6168 if (!strcmp(mode
, "wb")) {
6170 } else if (!strcmp(mode
, "rb")) {
6175 f
->outfile
= fopen(filename
, mode
);
6187 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6191 f
= qemu_mallocz(sizeof(QEMUFile
));
6196 f
->is_writable
= is_writable
;
6197 f
->base_offset
= offset
;
6201 void qemu_fflush(QEMUFile
*f
)
6203 if (!f
->is_writable
)
6205 if (f
->buf_index
> 0) {
6207 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6208 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
6210 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6211 f
->buf
, f
->buf_index
);
6213 f
->buf_offset
+= f
->buf_index
;
6218 static void qemu_fill_buffer(QEMUFile
*f
)
6225 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
6226 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
6230 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
6231 f
->buf
, IO_BUF_SIZE
);
6237 f
->buf_offset
+= len
;
6240 void qemu_fclose(QEMUFile
*f
)
6250 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6254 l
= IO_BUF_SIZE
- f
->buf_index
;
6257 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6261 if (f
->buf_index
>= IO_BUF_SIZE
)
6266 void qemu_put_byte(QEMUFile
*f
, int v
)
6268 f
->buf
[f
->buf_index
++] = v
;
6269 if (f
->buf_index
>= IO_BUF_SIZE
)
6273 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6279 l
= f
->buf_size
- f
->buf_index
;
6281 qemu_fill_buffer(f
);
6282 l
= f
->buf_size
- f
->buf_index
;
6288 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6293 return size1
- size
;
6296 int qemu_get_byte(QEMUFile
*f
)
6298 if (f
->buf_index
>= f
->buf_size
) {
6299 qemu_fill_buffer(f
);
6300 if (f
->buf_index
>= f
->buf_size
)
6303 return f
->buf
[f
->buf_index
++];
6306 int64_t qemu_ftell(QEMUFile
*f
)
6308 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6311 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6313 if (whence
== SEEK_SET
) {
6315 } else if (whence
== SEEK_CUR
) {
6316 pos
+= qemu_ftell(f
);
6318 /* SEEK_END not supported */
6321 if (f
->is_writable
) {
6323 f
->buf_offset
= pos
;
6325 f
->buf_offset
= pos
;
6332 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6334 qemu_put_byte(f
, v
>> 8);
6335 qemu_put_byte(f
, v
);
6338 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6340 qemu_put_byte(f
, v
>> 24);
6341 qemu_put_byte(f
, v
>> 16);
6342 qemu_put_byte(f
, v
>> 8);
6343 qemu_put_byte(f
, v
);
6346 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6348 qemu_put_be32(f
, v
>> 32);
6349 qemu_put_be32(f
, v
);
6352 unsigned int qemu_get_be16(QEMUFile
*f
)
6355 v
= qemu_get_byte(f
) << 8;
6356 v
|= qemu_get_byte(f
);
6360 unsigned int qemu_get_be32(QEMUFile
*f
)
6363 v
= qemu_get_byte(f
) << 24;
6364 v
|= qemu_get_byte(f
) << 16;
6365 v
|= qemu_get_byte(f
) << 8;
6366 v
|= qemu_get_byte(f
);
6370 uint64_t qemu_get_be64(QEMUFile
*f
)
6373 v
= (uint64_t)qemu_get_be32(f
) << 32;
6374 v
|= qemu_get_be32(f
);
6378 typedef struct SaveStateEntry
{
6382 SaveStateHandler
*save_state
;
6383 LoadStateHandler
*load_state
;
6385 struct SaveStateEntry
*next
;
6388 static SaveStateEntry
*first_se
;
6390 /* TODO: Individual devices generally have very little idea about the rest
6391 of the system, so instance_id should be removed/replaced.
6392 Meanwhile pass -1 as instance_id if you do not already have a clearly
6393 distinguishing id for all instances of your device class. */
6394 int register_savevm(const char *idstr
,
6397 SaveStateHandler
*save_state
,
6398 LoadStateHandler
*load_state
,
6401 SaveStateEntry
*se
, **pse
;
6403 se
= qemu_malloc(sizeof(SaveStateEntry
));
6406 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6407 se
->instance_id
= (instance_id
== -1) ? 0 : instance_id
;
6408 se
->version_id
= version_id
;
6409 se
->save_state
= save_state
;
6410 se
->load_state
= load_state
;
6411 se
->opaque
= opaque
;
6414 /* add at the end of list */
6416 while (*pse
!= NULL
) {
6417 if (instance_id
== -1
6418 && strcmp(se
->idstr
, (*pse
)->idstr
) == 0
6419 && se
->instance_id
<= (*pse
)->instance_id
)
6420 se
->instance_id
= (*pse
)->instance_id
+ 1;
6421 pse
= &(*pse
)->next
;
6427 #define QEMU_VM_FILE_MAGIC 0x5145564d
6428 #define QEMU_VM_FILE_VERSION 0x00000002
6430 static int qemu_savevm_state(QEMUFile
*f
)
6434 int64_t cur_pos
, len_pos
, total_len_pos
;
6436 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6437 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6438 total_len_pos
= qemu_ftell(f
);
6439 qemu_put_be64(f
, 0); /* total size */
6441 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6442 if (se
->save_state
== NULL
)
6443 /* this one has a loader only, for backwards compatibility */
6447 len
= strlen(se
->idstr
);
6448 qemu_put_byte(f
, len
);
6449 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6451 qemu_put_be32(f
, se
->instance_id
);
6452 qemu_put_be32(f
, se
->version_id
);
6454 /* record size: filled later */
6455 len_pos
= qemu_ftell(f
);
6456 qemu_put_be32(f
, 0);
6457 se
->save_state(f
, se
->opaque
);
6459 /* fill record size */
6460 cur_pos
= qemu_ftell(f
);
6461 len
= cur_pos
- len_pos
- 4;
6462 qemu_fseek(f
, len_pos
, SEEK_SET
);
6463 qemu_put_be32(f
, len
);
6464 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6466 cur_pos
= qemu_ftell(f
);
6467 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6468 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6469 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6475 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6479 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6480 if (!strcmp(se
->idstr
, idstr
) &&
6481 instance_id
== se
->instance_id
)
6487 static int qemu_loadvm_state(QEMUFile
*f
)
6490 int len
, ret
, instance_id
, record_len
, version_id
;
6491 int64_t total_len
, end_pos
, cur_pos
;
6495 v
= qemu_get_be32(f
);
6496 if (v
!= QEMU_VM_FILE_MAGIC
)
6498 v
= qemu_get_be32(f
);
6499 if (v
!= QEMU_VM_FILE_VERSION
) {
6504 total_len
= qemu_get_be64(f
);
6505 end_pos
= total_len
+ qemu_ftell(f
);
6507 if (qemu_ftell(f
) >= end_pos
)
6509 len
= qemu_get_byte(f
);
6510 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6512 instance_id
= qemu_get_be32(f
);
6513 version_id
= qemu_get_be32(f
);
6514 record_len
= qemu_get_be32(f
);
6516 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6517 idstr
, instance_id
, version_id
, record_len
);
6519 cur_pos
= qemu_ftell(f
);
6520 se
= find_se(idstr
, instance_id
);
6522 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6523 instance_id
, idstr
);
6525 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6527 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6528 instance_id
, idstr
);
6531 /* always seek to exact end of record */
6532 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6539 /* device can contain snapshots */
6540 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6543 !bdrv_is_removable(bs
) &&
6544 !bdrv_is_read_only(bs
));
6547 /* device must be snapshots in order to have a reliable snapshot */
6548 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6551 !bdrv_is_removable(bs
) &&
6552 !bdrv_is_read_only(bs
));
6555 static BlockDriverState
*get_bs_snapshots(void)
6557 BlockDriverState
*bs
;
6561 return bs_snapshots
;
6562 for(i
= 0; i
<= nb_drives
; i
++) {
6563 bs
= drives_table
[i
].bdrv
;
6564 if (bdrv_can_snapshot(bs
))
6573 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6576 QEMUSnapshotInfo
*sn_tab
, *sn
;
6580 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6583 for(i
= 0; i
< nb_sns
; i
++) {
6585 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6595 void do_savevm(const char *name
)
6597 BlockDriverState
*bs
, *bs1
;
6598 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6599 int must_delete
, ret
, i
;
6600 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6602 int saved_vm_running
;
6609 bs
= get_bs_snapshots();
6611 term_printf("No block device can accept snapshots\n");
6615 /* ??? Should this occur after vm_stop? */
6618 saved_vm_running
= vm_running
;
6623 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6628 memset(sn
, 0, sizeof(*sn
));
6630 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6631 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6634 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6637 /* fill auxiliary fields */
6640 sn
->date_sec
= tb
.time
;
6641 sn
->date_nsec
= tb
.millitm
* 1000000;
6643 gettimeofday(&tv
, NULL
);
6644 sn
->date_sec
= tv
.tv_sec
;
6645 sn
->date_nsec
= tv
.tv_usec
* 1000;
6647 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6649 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6650 term_printf("Device %s does not support VM state snapshots\n",
6651 bdrv_get_device_name(bs
));
6655 /* save the VM state */
6656 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6658 term_printf("Could not open VM state file\n");
6661 ret
= qemu_savevm_state(f
);
6662 sn
->vm_state_size
= qemu_ftell(f
);
6665 term_printf("Error %d while writing VM\n", ret
);
6669 /* create the snapshots */
6671 for(i
= 0; i
< nb_drives
; i
++) {
6672 bs1
= drives_table
[i
].bdrv
;
6673 if (bdrv_has_snapshot(bs1
)) {
6675 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6677 term_printf("Error while deleting snapshot on '%s'\n",
6678 bdrv_get_device_name(bs1
));
6681 ret
= bdrv_snapshot_create(bs1
, sn
);
6683 term_printf("Error while creating snapshot on '%s'\n",
6684 bdrv_get_device_name(bs1
));
6690 if (saved_vm_running
)
6694 void do_loadvm(const char *name
)
6696 BlockDriverState
*bs
, *bs1
;
6697 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6700 int saved_vm_running
;
6702 bs
= get_bs_snapshots();
6704 term_printf("No block device supports snapshots\n");
6708 /* Flush all IO requests so they don't interfere with the new state. */
6711 saved_vm_running
= vm_running
;
6714 for(i
= 0; i
<= nb_drives
; i
++) {
6715 bs1
= drives_table
[i
].bdrv
;
6716 if (bdrv_has_snapshot(bs1
)) {
6717 ret
= bdrv_snapshot_goto(bs1
, name
);
6720 term_printf("Warning: ");
6723 term_printf("Snapshots not supported on device '%s'\n",
6724 bdrv_get_device_name(bs1
));
6727 term_printf("Could not find snapshot '%s' on device '%s'\n",
6728 name
, bdrv_get_device_name(bs1
));
6731 term_printf("Error %d while activating snapshot on '%s'\n",
6732 ret
, bdrv_get_device_name(bs1
));
6735 /* fatal on snapshot block device */
6742 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6743 term_printf("Device %s does not support VM state snapshots\n",
6744 bdrv_get_device_name(bs
));
6748 /* restore the VM state */
6749 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6751 term_printf("Could not open VM state file\n");
6754 ret
= qemu_loadvm_state(f
);
6757 term_printf("Error %d while loading VM state\n", ret
);
6760 if (saved_vm_running
)
6764 void do_delvm(const char *name
)
6766 BlockDriverState
*bs
, *bs1
;
6769 bs
= get_bs_snapshots();
6771 term_printf("No block device supports snapshots\n");
6775 for(i
= 0; i
<= nb_drives
; i
++) {
6776 bs1
= drives_table
[i
].bdrv
;
6777 if (bdrv_has_snapshot(bs1
)) {
6778 ret
= bdrv_snapshot_delete(bs1
, name
);
6780 if (ret
== -ENOTSUP
)
6781 term_printf("Snapshots not supported on device '%s'\n",
6782 bdrv_get_device_name(bs1
));
6784 term_printf("Error %d while deleting snapshot on '%s'\n",
6785 ret
, bdrv_get_device_name(bs1
));
6791 void do_info_snapshots(void)
6793 BlockDriverState
*bs
, *bs1
;
6794 QEMUSnapshotInfo
*sn_tab
, *sn
;
6798 bs
= get_bs_snapshots();
6800 term_printf("No available block device supports snapshots\n");
6803 term_printf("Snapshot devices:");
6804 for(i
= 0; i
<= nb_drives
; i
++) {
6805 bs1
= drives_table
[i
].bdrv
;
6806 if (bdrv_has_snapshot(bs1
)) {
6808 term_printf(" %s", bdrv_get_device_name(bs1
));
6813 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6815 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6818 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6819 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6820 for(i
= 0; i
< nb_sns
; i
++) {
6822 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6827 /***********************************************************/
6828 /* ram save/restore */
6830 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6834 v
= qemu_get_byte(f
);
6837 if (qemu_get_buffer(f
, buf
, len
) != len
)
6841 v
= qemu_get_byte(f
);
6842 memset(buf
, v
, len
);
6850 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6855 if (qemu_get_be32(f
) != phys_ram_size
)
6857 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6858 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6865 #define BDRV_HASH_BLOCK_SIZE 1024
6866 #define IOBUF_SIZE 4096
6867 #define RAM_CBLOCK_MAGIC 0xfabe
6869 typedef struct RamCompressState
{
6872 uint8_t buf
[IOBUF_SIZE
];
6875 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6878 memset(s
, 0, sizeof(*s
));
6880 ret
= deflateInit2(&s
->zstream
, 1,
6882 9, Z_DEFAULT_STRATEGY
);
6885 s
->zstream
.avail_out
= IOBUF_SIZE
;
6886 s
->zstream
.next_out
= s
->buf
;
6890 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6892 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6893 qemu_put_be16(s
->f
, len
);
6894 qemu_put_buffer(s
->f
, buf
, len
);
6897 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6901 s
->zstream
.avail_in
= len
;
6902 s
->zstream
.next_in
= (uint8_t *)buf
;
6903 while (s
->zstream
.avail_in
> 0) {
6904 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6907 if (s
->zstream
.avail_out
== 0) {
6908 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6909 s
->zstream
.avail_out
= IOBUF_SIZE
;
6910 s
->zstream
.next_out
= s
->buf
;
6916 static void ram_compress_close(RamCompressState
*s
)
6920 /* compress last bytes */
6922 ret
= deflate(&s
->zstream
, Z_FINISH
);
6923 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6924 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6926 ram_put_cblock(s
, s
->buf
, len
);
6928 s
->zstream
.avail_out
= IOBUF_SIZE
;
6929 s
->zstream
.next_out
= s
->buf
;
6930 if (ret
== Z_STREAM_END
)
6937 deflateEnd(&s
->zstream
);
6940 typedef struct RamDecompressState
{
6943 uint8_t buf
[IOBUF_SIZE
];
6944 } RamDecompressState
;
6946 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6949 memset(s
, 0, sizeof(*s
));
6951 ret
= inflateInit(&s
->zstream
);
6957 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6961 s
->zstream
.avail_out
= len
;
6962 s
->zstream
.next_out
= buf
;
6963 while (s
->zstream
.avail_out
> 0) {
6964 if (s
->zstream
.avail_in
== 0) {
6965 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6967 clen
= qemu_get_be16(s
->f
);
6968 if (clen
> IOBUF_SIZE
)
6970 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6971 s
->zstream
.avail_in
= clen
;
6972 s
->zstream
.next_in
= s
->buf
;
6974 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6975 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6982 static void ram_decompress_close(RamDecompressState
*s
)
6984 inflateEnd(&s
->zstream
);
6987 static void ram_save(QEMUFile
*f
, void *opaque
)
6990 RamCompressState s1
, *s
= &s1
;
6993 qemu_put_be32(f
, phys_ram_size
);
6994 if (ram_compress_open(s
, f
) < 0)
6996 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6998 if (tight_savevm_enabled
) {
7002 /* find if the memory block is available on a virtual
7005 for(j
= 0; j
< nb_drives
; j
++) {
7006 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7008 BDRV_HASH_BLOCK_SIZE
);
7009 if (sector_num
>= 0)
7013 goto normal_compress
;
7016 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7017 ram_compress_buf(s
, buf
, 10);
7023 ram_compress_buf(s
, buf
, 1);
7024 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7027 ram_compress_close(s
);
7030 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7032 RamDecompressState s1
, *s
= &s1
;
7036 if (version_id
== 1)
7037 return ram_load_v1(f
, opaque
);
7038 if (version_id
!= 2)
7040 if (qemu_get_be32(f
) != phys_ram_size
)
7042 if (ram_decompress_open(s
, f
) < 0)
7044 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7045 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7046 fprintf(stderr
, "Error while reading ram block header\n");
7050 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7051 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7060 ram_decompress_buf(s
, buf
+ 1, 9);
7062 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7063 if (bs_index
>= nb_drives
) {
7064 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7067 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7069 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7070 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7071 bs_index
, sector_num
);
7078 printf("Error block header\n");
7082 ram_decompress_close(s
);
7086 /***********************************************************/
7087 /* bottom halves (can be seen as timers which expire ASAP) */
7096 static QEMUBH
*first_bh
= NULL
;
7098 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7101 bh
= qemu_mallocz(sizeof(QEMUBH
));
7105 bh
->opaque
= opaque
;
7109 int qemu_bh_poll(void)
7128 void qemu_bh_schedule(QEMUBH
*bh
)
7130 CPUState
*env
= cpu_single_env
;
7134 bh
->next
= first_bh
;
7137 /* stop the currently executing CPU to execute the BH ASAP */
7139 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7143 void qemu_bh_cancel(QEMUBH
*bh
)
7146 if (bh
->scheduled
) {
7149 pbh
= &(*pbh
)->next
;
7155 void qemu_bh_delete(QEMUBH
*bh
)
7161 /***********************************************************/
7162 /* machine registration */
7164 QEMUMachine
*first_machine
= NULL
;
7166 int qemu_register_machine(QEMUMachine
*m
)
7169 pm
= &first_machine
;
7177 static QEMUMachine
*find_machine(const char *name
)
7181 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7182 if (!strcmp(m
->name
, name
))
7188 /***********************************************************/
7189 /* main execution loop */
7191 static void gui_update(void *opaque
)
7193 DisplayState
*ds
= opaque
;
7194 ds
->dpy_refresh(ds
);
7195 qemu_mod_timer(ds
->gui_timer
,
7196 (ds
->gui_timer_interval
?
7197 ds
->gui_timer_interval
:
7198 GUI_REFRESH_INTERVAL
)
7199 + qemu_get_clock(rt_clock
));
7202 struct vm_change_state_entry
{
7203 VMChangeStateHandler
*cb
;
7205 LIST_ENTRY (vm_change_state_entry
) entries
;
7208 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7210 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7213 VMChangeStateEntry
*e
;
7215 e
= qemu_mallocz(sizeof (*e
));
7221 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7225 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7227 LIST_REMOVE (e
, entries
);
7231 static void vm_state_notify(int running
)
7233 VMChangeStateEntry
*e
;
7235 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7236 e
->cb(e
->opaque
, running
);
7240 /* XXX: support several handlers */
7241 static VMStopHandler
*vm_stop_cb
;
7242 static void *vm_stop_opaque
;
7244 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7247 vm_stop_opaque
= opaque
;
7251 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7262 qemu_rearm_alarm_timer(alarm_timer
);
7266 void vm_stop(int reason
)
7269 cpu_disable_ticks();
7273 vm_stop_cb(vm_stop_opaque
, reason
);
7280 /* reset/shutdown handler */
7282 typedef struct QEMUResetEntry
{
7283 QEMUResetHandler
*func
;
7285 struct QEMUResetEntry
*next
;
7288 static QEMUResetEntry
*first_reset_entry
;
7289 static int reset_requested
;
7290 static int shutdown_requested
;
7291 static int powerdown_requested
;
7293 int qemu_shutdown_requested(void)
7295 int r
= shutdown_requested
;
7296 shutdown_requested
= 0;
7300 int qemu_reset_requested(void)
7302 int r
= reset_requested
;
7303 reset_requested
= 0;
7307 int qemu_powerdown_requested(void)
7309 int r
= powerdown_requested
;
7310 powerdown_requested
= 0;
7314 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7316 QEMUResetEntry
**pre
, *re
;
7318 pre
= &first_reset_entry
;
7319 while (*pre
!= NULL
)
7320 pre
= &(*pre
)->next
;
7321 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7323 re
->opaque
= opaque
;
7328 void qemu_system_reset(void)
7332 /* reset all devices */
7333 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7334 re
->func(re
->opaque
);
7338 void qemu_system_reset_request(void)
7341 shutdown_requested
= 1;
7343 reset_requested
= 1;
7346 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7349 void qemu_system_shutdown_request(void)
7351 shutdown_requested
= 1;
7353 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7356 void qemu_system_powerdown_request(void)
7358 powerdown_requested
= 1;
7360 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7363 void main_loop_wait(int timeout
)
7365 IOHandlerRecord
*ioh
;
7366 fd_set rfds
, wfds
, xfds
;
7375 /* XXX: need to suppress polling by better using win32 events */
7377 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7378 ret
|= pe
->func(pe
->opaque
);
7383 WaitObjects
*w
= &wait_objects
;
7385 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7386 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7387 if (w
->func
[ret
- WAIT_OBJECT_0
])
7388 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7390 /* Check for additional signaled events */
7391 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7393 /* Check if event is signaled */
7394 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7395 if(ret2
== WAIT_OBJECT_0
) {
7397 w
->func
[i
](w
->opaque
[i
]);
7398 } else if (ret2
== WAIT_TIMEOUT
) {
7400 err
= GetLastError();
7401 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7404 } else if (ret
== WAIT_TIMEOUT
) {
7406 err
= GetLastError();
7407 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7411 /* poll any events */
7412 /* XXX: separate device handlers from system ones */
7417 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7421 (!ioh
->fd_read_poll
||
7422 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7423 FD_SET(ioh
->fd
, &rfds
);
7427 if (ioh
->fd_write
) {
7428 FD_SET(ioh
->fd
, &wfds
);
7438 tv
.tv_usec
= timeout
* 1000;
7440 #if defined(CONFIG_SLIRP)
7442 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7445 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7447 IOHandlerRecord
**pioh
;
7449 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7450 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7451 ioh
->fd_read(ioh
->opaque
);
7453 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7454 ioh
->fd_write(ioh
->opaque
);
7458 /* remove deleted IO handlers */
7459 pioh
= &first_io_handler
;
7469 #if defined(CONFIG_SLIRP)
7476 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7481 if (likely(!(cur_cpu
->singlestep_enabled
& SSTEP_NOTIMER
)))
7482 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7483 qemu_get_clock(vm_clock
));
7484 /* run dma transfers, if any */
7488 /* real time timers */
7489 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7490 qemu_get_clock(rt_clock
));
7492 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7493 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7494 qemu_rearm_alarm_timer(alarm_timer
);
7497 /* Check bottom-halves last in case any of the earlier events triggered
7503 static int main_loop(void)
7506 #ifdef CONFIG_PROFILER
7511 cur_cpu
= first_cpu
;
7512 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7519 #ifdef CONFIG_PROFILER
7520 ti
= profile_getclock();
7525 qemu_icount
-= (env
->icount_decr
.u16
.low
+ env
->icount_extra
);
7526 env
->icount_decr
.u16
.low
= 0;
7527 env
->icount_extra
= 0;
7528 count
= qemu_next_deadline();
7529 count
= (count
+ (1 << icount_time_shift
) - 1)
7530 >> icount_time_shift
;
7531 qemu_icount
+= count
;
7532 decr
= (count
> 0xffff) ? 0xffff : count
;
7534 env
->icount_decr
.u16
.low
= decr
;
7535 env
->icount_extra
= count
;
7537 ret
= cpu_exec(env
);
7538 #ifdef CONFIG_PROFILER
7539 qemu_time
+= profile_getclock() - ti
;
7542 /* Fold pending instructions back into the
7543 instruction counter, and clear the interrupt flag. */
7544 qemu_icount
-= (env
->icount_decr
.u16
.low
7545 + env
->icount_extra
);
7546 env
->icount_decr
.u32
= 0;
7547 env
->icount_extra
= 0;
7549 next_cpu
= env
->next_cpu
?: first_cpu
;
7550 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7551 ret
= EXCP_INTERRUPT
;
7555 if (ret
== EXCP_HLT
) {
7556 /* Give the next CPU a chance to run. */
7560 if (ret
!= EXCP_HALTED
)
7562 /* all CPUs are halted ? */
7568 if (shutdown_requested
) {
7569 ret
= EXCP_INTERRUPT
;
7577 if (reset_requested
) {
7578 reset_requested
= 0;
7579 qemu_system_reset();
7580 ret
= EXCP_INTERRUPT
;
7582 if (powerdown_requested
) {
7583 powerdown_requested
= 0;
7584 qemu_system_powerdown();
7585 ret
= EXCP_INTERRUPT
;
7587 if (unlikely(ret
== EXCP_DEBUG
)) {
7588 vm_stop(EXCP_DEBUG
);
7590 /* If all cpus are halted then wait until the next IRQ */
7591 /* XXX: use timeout computed from timers */
7592 if (ret
== EXCP_HALTED
) {
7596 /* Advance virtual time to the next event. */
7597 if (use_icount
== 1) {
7598 /* When not using an adaptive execution frequency
7599 we tend to get badly out of sync with real time,
7600 so just delay for a reasonable amount of time. */
7603 delta
= cpu_get_icount() - cpu_get_clock();
7606 /* If virtual time is ahead of real time then just
7608 timeout
= (delta
/ 1000000) + 1;
7610 /* Wait for either IO to occur or the next
7612 add
= qemu_next_deadline();
7613 /* We advance the timer before checking for IO.
7614 Limit the amount we advance so that early IO
7615 activity won't get the guest too far ahead. */
7619 add
= (add
+ (1 << icount_time_shift
) - 1)
7620 >> icount_time_shift
;
7622 timeout
= delta
/ 1000000;
7633 if (shutdown_requested
)
7637 #ifdef CONFIG_PROFILER
7638 ti
= profile_getclock();
7640 main_loop_wait(timeout
);
7641 #ifdef CONFIG_PROFILER
7642 dev_time
+= profile_getclock() - ti
;
7645 cpu_disable_ticks();
7649 static void help(int exitcode
)
7651 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2008 Fabrice Bellard\n"
7652 "usage: %s [options] [disk_image]\n"
7654 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7656 "Standard options:\n"
7657 "-M machine select emulated machine (-M ? for list)\n"
7658 "-cpu cpu select CPU (-cpu ? for list)\n"
7659 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7660 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7661 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7662 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7663 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7664 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7665 " [,cache=on|off][,format=f]\n"
7666 " use 'file' as a drive image\n"
7667 "-mtdblock file use 'file' as on-board Flash memory image\n"
7668 "-sd file use 'file' as SecureDigital card image\n"
7669 "-pflash file use 'file' as a parallel flash image\n"
7670 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7671 "-snapshot write to temporary files instead of disk image files\n"
7673 "-no-frame open SDL window without a frame and window decorations\n"
7674 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7675 "-no-quit disable SDL window close capability\n"
7678 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7680 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7681 "-smp n set the number of CPUs to 'n' [default=1]\n"
7682 "-nographic disable graphical output and redirect serial I/Os to console\n"
7683 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7685 "-k language use keyboard layout (for example \"fr\" for French)\n"
7688 "-audio-help print list of audio drivers and their options\n"
7689 "-soundhw c1,... enable audio support\n"
7690 " and only specified sound cards (comma separated list)\n"
7691 " use -soundhw ? to get the list of supported cards\n"
7692 " use -soundhw all to enable all of them\n"
7694 "-localtime set the real time clock to local time [default=utc]\n"
7695 "-full-screen start in full screen\n"
7697 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7699 "-usb enable the USB driver (will be the default soon)\n"
7700 "-usbdevice name add the host or guest USB device 'name'\n"
7701 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7702 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7704 "-name string set the name of the guest\n"
7705 "-uuid %%08x-%%04x-%%04x-%%04x-%%012x specify machine UUID\n"
7707 "Network options:\n"
7708 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7709 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7711 "-net user[,vlan=n][,hostname=host]\n"
7712 " connect the user mode network stack to VLAN 'n' and send\n"
7713 " hostname 'host' to DHCP clients\n"
7716 "-net tap[,vlan=n],ifname=name\n"
7717 " connect the host TAP network interface to VLAN 'n'\n"
7719 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7720 " connect the host TAP network interface to VLAN 'n' and use the\n"
7721 " network scripts 'file' (default=%s)\n"
7722 " and 'dfile' (default=%s);\n"
7723 " use '[down]script=no' to disable script execution;\n"
7724 " use 'fd=h' to connect to an already opened TAP interface\n"
7726 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7727 " connect the vlan 'n' to another VLAN using a socket connection\n"
7728 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7729 " connect the vlan 'n' to multicast maddr and port\n"
7731 "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7732 " connect the vlan 'n' to port 'n' of a vde switch running\n"
7733 " on host and listening for incoming connections on 'socketpath'.\n"
7734 " Use group 'groupname' and mode 'octalmode' to change default\n"
7735 " ownership and permissions for communication port.\n"
7737 "-net none use it alone to have zero network devices; if no -net option\n"
7738 " is provided, the default is '-net nic -net user'\n"
7741 "-tftp dir allow tftp access to files in dir [-net user]\n"
7742 "-bootp file advertise file in BOOTP replies\n"
7744 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7746 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7747 " redirect TCP or UDP connections from host to guest [-net user]\n"
7750 "Linux boot specific:\n"
7751 "-kernel bzImage use 'bzImage' as kernel image\n"
7752 "-append cmdline use 'cmdline' as kernel command line\n"
7753 "-initrd file use 'file' as initial ram disk\n"
7755 "Debug/Expert options:\n"
7756 "-monitor dev redirect the monitor to char device 'dev'\n"
7757 "-serial dev redirect the serial port to char device 'dev'\n"
7758 "-parallel dev redirect the parallel port to char device 'dev'\n"
7759 "-pidfile file Write PID to 'file'\n"
7760 "-S freeze CPU at startup (use 'c' to start execution)\n"
7761 "-s wait gdb connection to port\n"
7762 "-p port set gdb connection port [default=%s]\n"
7763 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7764 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7765 " translation (t=none or lba) (usually qemu can guess them)\n"
7766 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7768 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7769 "-no-kqemu disable KQEMU kernel module usage\n"
7772 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7773 " (default is CL-GD5446 PCI VGA)\n"
7774 "-no-acpi disable ACPI\n"
7776 #ifdef CONFIG_CURSES
7777 "-curses use a curses/ncurses interface instead of SDL\n"
7779 "-no-reboot exit instead of rebooting\n"
7780 "-no-shutdown stop before shutdown\n"
7781 "-loadvm [tag|id] start right away with a saved state (loadvm in monitor)\n"
7782 "-vnc display start a VNC server on display\n"
7784 "-daemonize daemonize QEMU after initializing\n"
7786 "-option-rom rom load a file, rom, into the option ROM space\n"
7788 "-prom-env variable=value set OpenBIOS nvram variables\n"
7790 "-clock force the use of the given methods for timer alarm.\n"
7791 " To see what timers are available use -clock ?\n"
7792 "-startdate select initial date of the clock\n"
7793 "-icount [N|auto]\n"
7794 " Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7796 "During emulation, the following keys are useful:\n"
7797 "ctrl-alt-f toggle full screen\n"
7798 "ctrl-alt-n switch to virtual console 'n'\n"
7799 "ctrl-alt toggle mouse and keyboard grab\n"
7801 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7806 DEFAULT_NETWORK_SCRIPT
,
7807 DEFAULT_NETWORK_DOWN_SCRIPT
,
7809 DEFAULT_GDBSTUB_PORT
,
7814 #define HAS_ARG 0x0001
7829 QEMU_OPTION_mtdblock
,
7833 QEMU_OPTION_snapshot
,
7835 QEMU_OPTION_no_fd_bootchk
,
7838 QEMU_OPTION_nographic
,
7839 QEMU_OPTION_portrait
,
7841 QEMU_OPTION_audio_help
,
7842 QEMU_OPTION_soundhw
,
7863 QEMU_OPTION_localtime
,
7864 QEMU_OPTION_cirrusvga
,
7867 QEMU_OPTION_std_vga
,
7869 QEMU_OPTION_monitor
,
7871 QEMU_OPTION_parallel
,
7873 QEMU_OPTION_full_screen
,
7874 QEMU_OPTION_no_frame
,
7875 QEMU_OPTION_alt_grab
,
7876 QEMU_OPTION_no_quit
,
7877 QEMU_OPTION_pidfile
,
7878 QEMU_OPTION_no_kqemu
,
7879 QEMU_OPTION_kernel_kqemu
,
7880 QEMU_OPTION_win2k_hack
,
7882 QEMU_OPTION_usbdevice
,
7885 QEMU_OPTION_no_acpi
,
7887 QEMU_OPTION_no_reboot
,
7888 QEMU_OPTION_no_shutdown
,
7889 QEMU_OPTION_show_cursor
,
7890 QEMU_OPTION_daemonize
,
7891 QEMU_OPTION_option_rom
,
7892 QEMU_OPTION_semihosting
,
7894 QEMU_OPTION_prom_env
,
7895 QEMU_OPTION_old_param
,
7897 QEMU_OPTION_startdate
,
7898 QEMU_OPTION_tb_size
,
7903 typedef struct QEMUOption
{
7909 const QEMUOption qemu_options
[] = {
7910 { "h", 0, QEMU_OPTION_h
},
7911 { "help", 0, QEMU_OPTION_h
},
7913 { "M", HAS_ARG
, QEMU_OPTION_M
},
7914 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7915 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7916 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7917 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7918 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7919 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7920 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7921 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7922 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7923 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7924 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7925 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7926 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7927 { "snapshot", 0, QEMU_OPTION_snapshot
},
7929 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7931 { "m", HAS_ARG
, QEMU_OPTION_m
},
7932 { "nographic", 0, QEMU_OPTION_nographic
},
7933 { "portrait", 0, QEMU_OPTION_portrait
},
7934 { "k", HAS_ARG
, QEMU_OPTION_k
},
7936 { "audio-help", 0, QEMU_OPTION_audio_help
},
7937 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7940 { "net", HAS_ARG
, QEMU_OPTION_net
},
7942 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7943 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7945 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7947 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7950 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7951 { "append", HAS_ARG
, QEMU_OPTION_append
},
7952 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7954 { "S", 0, QEMU_OPTION_S
},
7955 { "s", 0, QEMU_OPTION_s
},
7956 { "p", HAS_ARG
, QEMU_OPTION_p
},
7957 { "d", HAS_ARG
, QEMU_OPTION_d
},
7958 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7959 { "L", HAS_ARG
, QEMU_OPTION_L
},
7960 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7962 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7963 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7965 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7966 { "g", 1, QEMU_OPTION_g
},
7968 { "localtime", 0, QEMU_OPTION_localtime
},
7969 { "std-vga", 0, QEMU_OPTION_std_vga
},
7970 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7971 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7972 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7973 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7974 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7975 { "full-screen", 0, QEMU_OPTION_full_screen
},
7977 { "no-frame", 0, QEMU_OPTION_no_frame
},
7978 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7979 { "no-quit", 0, QEMU_OPTION_no_quit
},
7981 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7982 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7983 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7984 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7985 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7986 #ifdef CONFIG_CURSES
7987 { "curses", 0, QEMU_OPTION_curses
},
7989 { "uuid", HAS_ARG
, QEMU_OPTION_uuid
},
7991 /* temporary options */
7992 { "usb", 0, QEMU_OPTION_usb
},
7993 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7994 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7995 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7996 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7997 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7998 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7999 { "daemonize", 0, QEMU_OPTION_daemonize
},
8000 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8001 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8002 { "semihosting", 0, QEMU_OPTION_semihosting
},
8004 { "name", HAS_ARG
, QEMU_OPTION_name
},
8005 #if defined(TARGET_SPARC)
8006 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8008 #if defined(TARGET_ARM)
8009 { "old-param", 0, QEMU_OPTION_old_param
},
8011 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8012 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8013 { "tb-size", HAS_ARG
, QEMU_OPTION_tb_size
},
8014 { "icount", HAS_ARG
, QEMU_OPTION_icount
},
8018 /* password input */
8020 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8025 if (!bdrv_is_encrypted(bs
))
8028 term_printf("%s is encrypted.\n", name
);
8029 for(i
= 0; i
< 3; i
++) {
8030 monitor_readline("Password: ", 1, password
, sizeof(password
));
8031 if (bdrv_set_key(bs
, password
) == 0)
8033 term_printf("invalid password\n");
8038 static BlockDriverState
*get_bdrv(int index
)
8040 if (index
> nb_drives
)
8042 return drives_table
[index
].bdrv
;
8045 static void read_passwords(void)
8047 BlockDriverState
*bs
;
8050 for(i
= 0; i
< 6; i
++) {
8053 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8058 struct soundhw soundhw
[] = {
8059 #ifdef HAS_AUDIO_CHOICE
8060 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8066 { .init_isa
= pcspk_audio_init
}
8071 "Creative Sound Blaster 16",
8074 { .init_isa
= SB16_init
}
8077 #ifdef CONFIG_CS4231A
8083 { .init_isa
= cs4231a_init
}
8091 "Yamaha YMF262 (OPL3)",
8093 "Yamaha YM3812 (OPL2)",
8097 { .init_isa
= Adlib_init
}
8104 "Gravis Ultrasound GF1",
8107 { .init_isa
= GUS_init
}
8114 "Intel 82801AA AC97 Audio",
8117 { .init_pci
= ac97_init
}
8123 "ENSONIQ AudioPCI ES1370",
8126 { .init_pci
= es1370_init
}
8130 { NULL
, NULL
, 0, 0, { NULL
} }
8133 static void select_soundhw (const char *optarg
)
8137 if (*optarg
== '?') {
8140 printf ("Valid sound card names (comma separated):\n");
8141 for (c
= soundhw
; c
->name
; ++c
) {
8142 printf ("%-11s %s\n", c
->name
, c
->descr
);
8144 printf ("\n-soundhw all will enable all of the above\n");
8145 exit (*optarg
!= '?');
8153 if (!strcmp (optarg
, "all")) {
8154 for (c
= soundhw
; c
->name
; ++c
) {
8162 e
= strchr (p
, ',');
8163 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8165 for (c
= soundhw
; c
->name
; ++c
) {
8166 if (!strncmp (c
->name
, p
, l
)) {
8175 "Unknown sound card name (too big to show)\n");
8178 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8183 p
+= l
+ (e
!= NULL
);
8187 goto show_valid_cards
;
8193 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8195 exit(STATUS_CONTROL_C_EXIT
);
8200 static int qemu_uuid_parse(const char *str
, uint8_t *uuid
)
8204 if(strlen(str
) != 36)
8207 ret
= sscanf(str
, UUID_FMT
, &uuid
[0], &uuid
[1], &uuid
[2], &uuid
[3],
8208 &uuid
[4], &uuid
[5], &uuid
[6], &uuid
[7], &uuid
[8], &uuid
[9],
8209 &uuid
[10], &uuid
[11], &uuid
[12], &uuid
[13], &uuid
[14], &uuid
[15]);
8217 #define MAX_NET_CLIENTS 32
8221 static void termsig_handler(int signal
)
8223 qemu_system_shutdown_request();
8226 static void termsig_setup(void)
8228 struct sigaction act
;
8230 memset(&act
, 0, sizeof(act
));
8231 act
.sa_handler
= termsig_handler
;
8232 sigaction(SIGINT
, &act
, NULL
);
8233 sigaction(SIGHUP
, &act
, NULL
);
8234 sigaction(SIGTERM
, &act
, NULL
);
8239 int main(int argc
, char **argv
)
8241 #ifdef CONFIG_GDBSTUB
8243 const char *gdbstub_port
;
8245 uint32_t boot_devices_bitmap
= 0;
8247 int snapshot
, linux_boot
, net_boot
;
8248 const char *initrd_filename
;
8249 const char *kernel_filename
, *kernel_cmdline
;
8250 const char *boot_devices
= "";
8251 DisplayState
*ds
= &display_state
;
8252 int cyls
, heads
, secs
, translation
;
8253 const char *net_clients
[MAX_NET_CLIENTS
];
8257 const char *r
, *optarg
;
8258 CharDriverState
*monitor_hd
;
8259 const char *monitor_device
;
8260 const char *serial_devices
[MAX_SERIAL_PORTS
];
8261 int serial_device_index
;
8262 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8263 int parallel_device_index
;
8264 const char *loadvm
= NULL
;
8265 QEMUMachine
*machine
;
8266 const char *cpu_model
;
8267 const char *usb_devices
[MAX_USB_CMDLINE
];
8268 int usb_devices_index
;
8271 const char *pid_file
= NULL
;
8274 LIST_INIT (&vm_change_state_head
);
8277 struct sigaction act
;
8278 sigfillset(&act
.sa_mask
);
8280 act
.sa_handler
= SIG_IGN
;
8281 sigaction(SIGPIPE
, &act
, NULL
);
8284 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8285 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8286 QEMU to run on a single CPU */
8291 h
= GetCurrentProcess();
8292 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8293 for(i
= 0; i
< 32; i
++) {
8294 if (mask
& (1 << i
))
8299 SetProcessAffinityMask(h
, mask
);
8305 register_machines();
8306 machine
= first_machine
;
8308 initrd_filename
= NULL
;
8310 vga_ram_size
= VGA_RAM_SIZE
;
8311 #ifdef CONFIG_GDBSTUB
8313 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8318 kernel_filename
= NULL
;
8319 kernel_cmdline
= "";
8320 cyls
= heads
= secs
= 0;
8321 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8322 monitor_device
= "vc";
8324 serial_devices
[0] = "vc:80Cx24C";
8325 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8326 serial_devices
[i
] = NULL
;
8327 serial_device_index
= 0;
8329 parallel_devices
[0] = "vc:640x480";
8330 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8331 parallel_devices
[i
] = NULL
;
8332 parallel_device_index
= 0;
8334 usb_devices_index
= 0;
8351 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8353 const QEMUOption
*popt
;
8356 /* Treat --foo the same as -foo. */
8359 popt
= qemu_options
;
8362 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8366 if (!strcmp(popt
->name
, r
+ 1))
8370 if (popt
->flags
& HAS_ARG
) {
8371 if (optind
>= argc
) {
8372 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8376 optarg
= argv
[optind
++];
8381 switch(popt
->index
) {
8383 machine
= find_machine(optarg
);
8386 printf("Supported machines are:\n");
8387 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8388 printf("%-10s %s%s\n",
8390 m
== first_machine
? " (default)" : "");
8392 exit(*optarg
!= '?');
8395 case QEMU_OPTION_cpu
:
8396 /* hw initialization will check this */
8397 if (*optarg
== '?') {
8398 /* XXX: implement xxx_cpu_list for targets that still miss it */
8399 #if defined(cpu_list)
8400 cpu_list(stdout
, &fprintf
);
8407 case QEMU_OPTION_initrd
:
8408 initrd_filename
= optarg
;
8410 case QEMU_OPTION_hda
:
8412 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8414 hda_index
= drive_add(optarg
, HD_ALIAS
8415 ",cyls=%d,heads=%d,secs=%d%s",
8416 0, cyls
, heads
, secs
,
8417 translation
== BIOS_ATA_TRANSLATION_LBA
?
8419 translation
== BIOS_ATA_TRANSLATION_NONE
?
8420 ",trans=none" : "");
8422 case QEMU_OPTION_hdb
:
8423 case QEMU_OPTION_hdc
:
8424 case QEMU_OPTION_hdd
:
8425 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8427 case QEMU_OPTION_drive
:
8428 drive_add(NULL
, "%s", optarg
);
8430 case QEMU_OPTION_mtdblock
:
8431 drive_add(optarg
, MTD_ALIAS
);
8433 case QEMU_OPTION_sd
:
8434 drive_add(optarg
, SD_ALIAS
);
8436 case QEMU_OPTION_pflash
:
8437 drive_add(optarg
, PFLASH_ALIAS
);
8439 case QEMU_OPTION_snapshot
:
8442 case QEMU_OPTION_hdachs
:
8446 cyls
= strtol(p
, (char **)&p
, 0);
8447 if (cyls
< 1 || cyls
> 16383)
8452 heads
= strtol(p
, (char **)&p
, 0);
8453 if (heads
< 1 || heads
> 16)
8458 secs
= strtol(p
, (char **)&p
, 0);
8459 if (secs
< 1 || secs
> 63)
8463 if (!strcmp(p
, "none"))
8464 translation
= BIOS_ATA_TRANSLATION_NONE
;
8465 else if (!strcmp(p
, "lba"))
8466 translation
= BIOS_ATA_TRANSLATION_LBA
;
8467 else if (!strcmp(p
, "auto"))
8468 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8471 } else if (*p
!= '\0') {
8473 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8476 if (hda_index
!= -1)
8477 snprintf(drives_opt
[hda_index
].opt
,
8478 sizeof(drives_opt
[hda_index
].opt
),
8479 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8480 0, cyls
, heads
, secs
,
8481 translation
== BIOS_ATA_TRANSLATION_LBA
?
8483 translation
== BIOS_ATA_TRANSLATION_NONE
?
8484 ",trans=none" : "");
8487 case QEMU_OPTION_nographic
:
8490 #ifdef CONFIG_CURSES
8491 case QEMU_OPTION_curses
:
8495 case QEMU_OPTION_portrait
:
8498 case QEMU_OPTION_kernel
:
8499 kernel_filename
= optarg
;
8501 case QEMU_OPTION_append
:
8502 kernel_cmdline
= optarg
;
8504 case QEMU_OPTION_cdrom
:
8505 drive_add(optarg
, CDROM_ALIAS
);
8507 case QEMU_OPTION_boot
:
8508 boot_devices
= optarg
;
8509 /* We just do some generic consistency checks */
8511 /* Could easily be extended to 64 devices if needed */
8514 boot_devices_bitmap
= 0;
8515 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8516 /* Allowed boot devices are:
8517 * a b : floppy disk drives
8518 * c ... f : IDE disk drives
8519 * g ... m : machine implementation dependant drives
8520 * n ... p : network devices
8521 * It's up to each machine implementation to check
8522 * if the given boot devices match the actual hardware
8523 * implementation and firmware features.
8525 if (*p
< 'a' || *p
> 'q') {
8526 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8529 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8531 "Boot device '%c' was given twice\n",*p
);
8534 boot_devices_bitmap
|= 1 << (*p
- 'a');
8538 case QEMU_OPTION_fda
:
8539 case QEMU_OPTION_fdb
:
8540 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8543 case QEMU_OPTION_no_fd_bootchk
:
8547 case QEMU_OPTION_net
:
8548 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8549 fprintf(stderr
, "qemu: too many network clients\n");
8552 net_clients
[nb_net_clients
] = optarg
;
8556 case QEMU_OPTION_tftp
:
8557 tftp_prefix
= optarg
;
8559 case QEMU_OPTION_bootp
:
8560 bootp_filename
= optarg
;
8563 case QEMU_OPTION_smb
:
8564 net_slirp_smb(optarg
);
8567 case QEMU_OPTION_redir
:
8568 net_slirp_redir(optarg
);
8572 case QEMU_OPTION_audio_help
:
8576 case QEMU_OPTION_soundhw
:
8577 select_soundhw (optarg
);
8583 case QEMU_OPTION_m
: {
8587 value
= strtoul(optarg
, &ptr
, 10);
8589 case 0: case 'M': case 'm':
8596 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8600 /* On 32-bit hosts, QEMU is limited by virtual address space */
8601 if (value
> (2047 << 20)
8603 && HOST_LONG_BITS
== 32
8606 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8609 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8610 fprintf(stderr
, "qemu: ram size too large\n");
8621 mask
= cpu_str_to_log_mask(optarg
);
8623 printf("Log items (comma separated):\n");
8624 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8625 printf("%-10s %s\n", item
->name
, item
->help
);
8632 #ifdef CONFIG_GDBSTUB
8637 gdbstub_port
= optarg
;
8643 case QEMU_OPTION_bios
:
8650 keyboard_layout
= optarg
;
8652 case QEMU_OPTION_localtime
:
8655 case QEMU_OPTION_cirrusvga
:
8656 cirrus_vga_enabled
= 1;
8659 case QEMU_OPTION_vmsvga
:
8660 cirrus_vga_enabled
= 0;
8663 case QEMU_OPTION_std_vga
:
8664 cirrus_vga_enabled
= 0;
8672 w
= strtol(p
, (char **)&p
, 10);
8675 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8681 h
= strtol(p
, (char **)&p
, 10);
8686 depth
= strtol(p
, (char **)&p
, 10);
8687 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8688 depth
!= 24 && depth
!= 32)
8690 } else if (*p
== '\0') {
8691 depth
= graphic_depth
;
8698 graphic_depth
= depth
;
8701 case QEMU_OPTION_echr
:
8704 term_escape_char
= strtol(optarg
, &r
, 0);
8706 printf("Bad argument to echr\n");
8709 case QEMU_OPTION_monitor
:
8710 monitor_device
= optarg
;
8712 case QEMU_OPTION_serial
:
8713 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8714 fprintf(stderr
, "qemu: too many serial ports\n");
8717 serial_devices
[serial_device_index
] = optarg
;
8718 serial_device_index
++;
8720 case QEMU_OPTION_parallel
:
8721 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8722 fprintf(stderr
, "qemu: too many parallel ports\n");
8725 parallel_devices
[parallel_device_index
] = optarg
;
8726 parallel_device_index
++;
8728 case QEMU_OPTION_loadvm
:
8731 case QEMU_OPTION_full_screen
:
8735 case QEMU_OPTION_no_frame
:
8738 case QEMU_OPTION_alt_grab
:
8741 case QEMU_OPTION_no_quit
:
8745 case QEMU_OPTION_pidfile
:
8749 case QEMU_OPTION_win2k_hack
:
8750 win2k_install_hack
= 1;
8754 case QEMU_OPTION_no_kqemu
:
8757 case QEMU_OPTION_kernel_kqemu
:
8761 case QEMU_OPTION_usb
:
8764 case QEMU_OPTION_usbdevice
:
8766 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8767 fprintf(stderr
, "Too many USB devices\n");
8770 usb_devices
[usb_devices_index
] = optarg
;
8771 usb_devices_index
++;
8773 case QEMU_OPTION_smp
:
8774 smp_cpus
= atoi(optarg
);
8775 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8776 fprintf(stderr
, "Invalid number of CPUs\n");
8780 case QEMU_OPTION_vnc
:
8781 vnc_display
= optarg
;
8783 case QEMU_OPTION_no_acpi
:
8786 case QEMU_OPTION_no_reboot
:
8789 case QEMU_OPTION_no_shutdown
:
8792 case QEMU_OPTION_show_cursor
:
8795 case QEMU_OPTION_uuid
:
8796 if(qemu_uuid_parse(optarg
, qemu_uuid
) < 0) {
8797 fprintf(stderr
, "Fail to parse UUID string."
8798 " Wrong format.\n");
8802 case QEMU_OPTION_daemonize
:
8805 case QEMU_OPTION_option_rom
:
8806 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8807 fprintf(stderr
, "Too many option ROMs\n");
8810 option_rom
[nb_option_roms
] = optarg
;
8813 case QEMU_OPTION_semihosting
:
8814 semihosting_enabled
= 1;
8816 case QEMU_OPTION_name
:
8820 case QEMU_OPTION_prom_env
:
8821 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8822 fprintf(stderr
, "Too many prom variables\n");
8825 prom_envs
[nb_prom_envs
] = optarg
;
8830 case QEMU_OPTION_old_param
:
8834 case QEMU_OPTION_clock
:
8835 configure_alarms(optarg
);
8837 case QEMU_OPTION_startdate
:
8840 time_t rtc_start_date
;
8841 if (!strcmp(optarg
, "now")) {
8842 rtc_date_offset
= -1;
8844 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8852 } else if (sscanf(optarg
, "%d-%d-%d",
8855 &tm
.tm_mday
) == 3) {
8864 rtc_start_date
= mktimegm(&tm
);
8865 if (rtc_start_date
== -1) {
8867 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8868 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8871 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8875 case QEMU_OPTION_tb_size
:
8876 tb_size
= strtol(optarg
, NULL
, 0);
8880 case QEMU_OPTION_icount
:
8882 if (strcmp(optarg
, "auto") == 0) {
8883 icount_time_shift
= -1;
8885 icount_time_shift
= strtol(optarg
, NULL
, 0);
8893 if (serial_device_index
== 0)
8894 serial_devices
[0] = "stdio";
8895 if (parallel_device_index
== 0)
8896 parallel_devices
[0] = "null";
8897 if (strncmp(monitor_device
, "vc", 2) == 0)
8898 monitor_device
= "stdio";
8905 if (pipe(fds
) == -1)
8916 len
= read(fds
[0], &status
, 1);
8917 if (len
== -1 && (errno
== EINTR
))
8922 else if (status
== 1) {
8923 fprintf(stderr
, "Could not acquire pidfile\n");
8940 signal(SIGTSTP
, SIG_IGN
);
8941 signal(SIGTTOU
, SIG_IGN
);
8942 signal(SIGTTIN
, SIG_IGN
);
8946 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8949 write(fds
[1], &status
, 1);
8951 fprintf(stderr
, "Could not acquire pid file\n");
8959 linux_boot
= (kernel_filename
!= NULL
);
8960 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8962 if (!linux_boot
&& net_boot
== 0 &&
8963 !machine
->nodisk_ok
&& nb_drives_opt
== 0)
8966 if (!linux_boot
&& *kernel_cmdline
!= '\0') {
8967 fprintf(stderr
, "-append only allowed with -kernel option\n");
8971 if (!linux_boot
&& initrd_filename
!= NULL
) {
8972 fprintf(stderr
, "-initrd only allowed with -kernel option\n");
8976 /* boot to floppy or the default cd if no hard disk defined yet */
8977 if (!boot_devices
[0]) {
8978 boot_devices
= "cad";
8980 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8984 if (use_icount
&& icount_time_shift
< 0) {
8986 /* 125MIPS seems a reasonable initial guess at the guest speed.
8987 It will be corrected fairly quickly anyway. */
8988 icount_time_shift
= 3;
8989 init_icount_adjust();
8996 /* init network clients */
8997 if (nb_net_clients
== 0) {
8998 /* if no clients, we use a default config */
8999 net_clients
[nb_net_clients
++] = "nic";
9001 net_clients
[nb_net_clients
++] = "user";
9005 for(i
= 0;i
< nb_net_clients
; i
++) {
9006 if (net_client_parse(net_clients
[i
]) < 0)
9009 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9010 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9012 if (vlan
->nb_guest_devs
== 0)
9013 fprintf(stderr
, "Warning: vlan %d with no nics\n", vlan
->id
);
9014 if (vlan
->nb_host_devs
== 0)
9016 "Warning: vlan %d is not connected to host network\n",
9021 /* XXX: this should be moved in the PC machine instantiation code */
9022 if (net_boot
!= 0) {
9024 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9025 const char *model
= nd_table
[i
].model
;
9027 if (net_boot
& (1 << i
)) {
9030 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9031 if (get_image_size(buf
) > 0) {
9032 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9033 fprintf(stderr
, "Too many option ROMs\n");
9036 option_rom
[nb_option_roms
] = strdup(buf
);
9043 fprintf(stderr
, "No valid PXE rom found for network device\n");
9049 /* init the memory */
9050 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9052 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9054 if (ram_size
< phys_ram_size
) {
9055 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9056 machine
->name
, (unsigned long long) phys_ram_size
);
9060 phys_ram_size
= ram_size
;
9062 ram_size
= phys_ram_size
;
9065 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9067 phys_ram_size
+= ram_size
;
9070 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9071 if (!phys_ram_base
) {
9072 fprintf(stderr
, "Could not allocate physical memory\n");
9076 /* init the dynamic translator */
9077 cpu_exec_init_all(tb_size
* 1024 * 1024);
9081 /* we always create the cdrom drive, even if no disk is there */
9083 if (nb_drives_opt
< MAX_DRIVES
)
9084 drive_add(NULL
, CDROM_ALIAS
);
9086 /* we always create at least one floppy */
9088 if (nb_drives_opt
< MAX_DRIVES
)
9089 drive_add(NULL
, FD_ALIAS
, 0);
9091 /* we always create one sd slot, even if no card is in it */
9093 if (nb_drives_opt
< MAX_DRIVES
)
9094 drive_add(NULL
, SD_ALIAS
);
9096 /* open the virtual block devices */
9098 for(i
= 0; i
< nb_drives_opt
; i
++)
9099 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9102 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9103 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
9106 memset(&display_state
, 0, sizeof(display_state
));
9109 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9112 /* nearly nothing to do */
9113 dumb_display_init(ds
);
9114 } else if (vnc_display
!= NULL
) {
9115 vnc_display_init(ds
);
9116 if (vnc_display_open(ds
, vnc_display
) < 0)
9119 #if defined(CONFIG_CURSES)
9121 curses_display_init(ds
, full_screen
);
9125 #if defined(CONFIG_SDL)
9126 sdl_display_init(ds
, full_screen
, no_frame
);
9127 #elif defined(CONFIG_COCOA)
9128 cocoa_display_init(ds
, full_screen
);
9130 dumb_display_init(ds
);
9135 /* must be after terminal init, SDL library changes signal handlers */
9139 /* Maintain compatibility with multiple stdio monitors */
9140 if (!strcmp(monitor_device
,"stdio")) {
9141 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9142 const char *devname
= serial_devices
[i
];
9143 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9144 monitor_device
= NULL
;
9146 } else if (devname
&& !strcmp(devname
,"stdio")) {
9147 monitor_device
= NULL
;
9148 serial_devices
[i
] = "mon:stdio";
9153 if (monitor_device
) {
9154 monitor_hd
= qemu_chr_open(monitor_device
);
9156 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9159 monitor_init(monitor_hd
, !nographic
);
9162 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9163 const char *devname
= serial_devices
[i
];
9164 if (devname
&& strcmp(devname
, "none")) {
9165 serial_hds
[i
] = qemu_chr_open(devname
);
9166 if (!serial_hds
[i
]) {
9167 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9171 if (strstart(devname
, "vc", 0))
9172 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9176 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9177 const char *devname
= parallel_devices
[i
];
9178 if (devname
&& strcmp(devname
, "none")) {
9179 parallel_hds
[i
] = qemu_chr_open(devname
);
9180 if (!parallel_hds
[i
]) {
9181 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9185 if (strstart(devname
, "vc", 0))
9186 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9190 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9191 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9193 /* init USB devices */
9195 for(i
= 0; i
< usb_devices_index
; i
++) {
9196 if (usb_device_add(usb_devices
[i
]) < 0) {
9197 fprintf(stderr
, "Warning: could not add USB device %s\n",
9203 if (display_state
.dpy_refresh
) {
9204 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9205 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9208 #ifdef CONFIG_GDBSTUB
9210 /* XXX: use standard host:port notation and modify options
9212 if (gdbserver_start(gdbstub_port
) < 0) {
9213 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9224 /* XXX: simplify init */
9237 len
= write(fds
[1], &status
, 1);
9238 if (len
== -1 && (errno
== EINTR
))
9245 TFR(fd
= open("/dev/null", O_RDWR
));
9259 #if !defined(_WIN32)
9260 /* close network clients */
9261 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9262 VLANClientState
*vc
;
9264 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9265 if (vc
->fd_read
== tap_receive
) {
9267 TAPState
*s
= vc
->opaque
;
9269 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9271 launch_script(s
->down_script
, ifname
, s
->fd
);
9273 #if defined(CONFIG_VDE)
9274 if (vc
->fd_read
== vde_from_qemu
) {
9275 VDEState
*s
= vc
->opaque
;