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"
40 #include "migration.h"
52 #include <sys/times.h>
57 #include <sys/ioctl.h>
58 #include <sys/socket.h>
59 #include <netinet/in.h>
62 #include <sys/select.h>
63 #include <arpa/inet.h>
69 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
70 #include <freebsd/stdlib.h>
74 #include <linux/if_tun.h>
77 #include <linux/rtc.h>
79 /* For the benefit of older linux systems which don't supply it,
80 we use a local copy of hpet.h. */
81 /* #include <linux/hpet.h> */
84 #include <linux/ppdev.h>
85 #include <linux/parport.h>
88 #include <sys/ethernet.h>
89 #include <sys/sockio.h>
90 #include <netinet/arp.h>
91 #include <netinet/in.h>
92 #include <netinet/in_systm.h>
93 #include <netinet/ip.h>
94 #include <netinet/ip_icmp.h> // must come after ip.h
95 #include <netinet/udp.h>
96 #include <netinet/tcp.h>
103 #include <winsock2.h>
104 int inet_aton(const char *cp
, struct in_addr
*ia
);
107 #if defined(CONFIG_SLIRP)
108 #include "libslirp.h"
113 #include <sys/timeb.h>
114 #include <mmsystem.h>
115 #define getopt_long_only getopt_long
116 #define memalign(align, size) malloc(size)
119 #include "qemu_socket.h"
125 #endif /* CONFIG_SDL */
129 #define main qemu_main
130 #endif /* CONFIG_COCOA */
134 #include "exec-all.h"
136 #include "qemu-kvm.h"
138 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
139 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
141 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
143 #define SMBD_COMMAND "/usr/sbin/smbd"
146 //#define DEBUG_UNUSED_IOPORT
147 //#define DEBUG_IOPORT
150 #define DEFAULT_RAM_SIZE 144
152 #define DEFAULT_RAM_SIZE 128
155 #define GUI_REFRESH_INTERVAL 30
157 /* Max number of USB devices that can be specified on the commandline. */
158 #define MAX_USB_CMDLINE 8
160 /* XXX: use a two level table to limit memory usage */
161 #define MAX_IOPORTS 65536
163 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
164 const char *bios_name
= NULL
;
165 void *ioport_opaque
[MAX_IOPORTS
];
166 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
167 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
168 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
169 to store the VM snapshots */
170 DriveInfo drives_table
[MAX_DRIVES
+1];
172 int extboot_drive
= -1;
173 /* point to the block driver where the snapshots are managed */
174 BlockDriverState
*bs_snapshots
;
176 static DisplayState display_state
;
179 const char* keyboard_layout
= NULL
;
180 int64_t ticks_per_sec
;
182 int pit_min_timer_count
= 0;
184 NICInfo nd_table
[MAX_NICS
];
186 static int rtc_utc
= 1;
187 static int rtc_date_offset
= -1; /* -1 means no change */
188 int cirrus_vga_enabled
= 1;
189 int vmsvga_enabled
= 0;
191 int graphic_width
= 1024;
192 int graphic_height
= 768;
193 int graphic_depth
= 8;
195 int graphic_width
= 800;
196 int graphic_height
= 600;
197 int graphic_depth
= 15;
202 int balloon_used
= 0;
203 CharDriverState
*vmchannel_hds
[MAX_VMCHANNEL_DEVICES
];
204 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
205 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
207 int win2k_install_hack
= 0;
210 static VLANState
*first_vlan
;
212 const char *vnc_display
;
213 #if defined(TARGET_SPARC)
215 #elif defined(TARGET_I386)
217 #elif defined(TARGET_IA64)
222 int acpi_enabled
= 1;
227 int graphic_rotate
= 0;
229 const char *incoming
;
230 const char *option_rom
[MAX_OPTION_ROMS
];
232 int semihosting_enabled
= 0;
234 int time_drift_fix
= 0;
235 unsigned int kvm_shadow_memory
= 0;
236 const char *mem_path
= NULL
;
238 const char *cpu_vendor_string
;
242 const char *qemu_name
;
245 unsigned int nb_prom_envs
= 0;
246 const char *prom_envs
[MAX_PROM_ENVS
];
249 struct drive_opt drives_opt
[MAX_DRIVES
];
251 static CPUState
*cur_cpu
;
252 static CPUState
*next_cpu
;
253 static int event_pending
= 1;
255 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
257 /* KVM runs the main loop in a separate thread. If we update one of the lists
258 * that are polled before or after select(), we need to make sure to break out
259 * of the select() to ensure the new item is serviced.
261 static void main_loop_break(void)
264 qemu_kvm_notify_work();
267 void decorate_application_name(char *appname
, int max_len
)
271 int remain
= max_len
- strlen(appname
) - 1;
274 strncat(appname
, "/KVM", remain
);
278 /***********************************************************/
279 /* x86 ISA bus support */
281 target_phys_addr_t isa_mem_base
= 0;
284 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
286 #ifdef DEBUG_UNUSED_IOPORT
287 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
292 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
299 /* default is to make two byte accesses */
300 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
303 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
304 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
305 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
309 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
311 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
312 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
313 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
316 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
318 #ifdef DEBUG_UNUSED_IOPORT
319 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
324 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
326 #ifdef DEBUG_UNUSED_IOPORT
327 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
331 static void init_ioports(void)
335 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
336 ioport_read_table
[0][i
] = default_ioport_readb
;
337 ioport_write_table
[0][i
] = default_ioport_writeb
;
338 ioport_read_table
[1][i
] = default_ioport_readw
;
339 ioport_write_table
[1][i
] = default_ioport_writew
;
340 ioport_read_table
[2][i
] = default_ioport_readl
;
341 ioport_write_table
[2][i
] = default_ioport_writel
;
345 /* size is the word size in byte */
346 int register_ioport_read(int start
, int length
, int size
,
347 IOPortReadFunc
*func
, void *opaque
)
353 } else if (size
== 2) {
355 } else if (size
== 4) {
358 hw_error("register_ioport_read: invalid size");
361 for(i
= start
; i
< start
+ length
; i
+= size
) {
362 ioport_read_table
[bsize
][i
] = func
;
363 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
364 hw_error("register_ioport_read: invalid opaque");
365 ioport_opaque
[i
] = opaque
;
370 /* size is the word size in byte */
371 int register_ioport_write(int start
, int length
, int size
,
372 IOPortWriteFunc
*func
, void *opaque
)
378 } else if (size
== 2) {
380 } else if (size
== 4) {
383 hw_error("register_ioport_write: invalid size");
386 for(i
= start
; i
< start
+ length
; i
+= size
) {
387 ioport_write_table
[bsize
][i
] = func
;
388 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
389 hw_error("register_ioport_write: invalid opaque");
390 ioport_opaque
[i
] = opaque
;
395 void isa_unassign_ioport(int start
, int length
)
399 for(i
= start
; i
< start
+ length
; i
++) {
400 ioport_read_table
[0][i
] = default_ioport_readb
;
401 ioport_read_table
[1][i
] = default_ioport_readw
;
402 ioport_read_table
[2][i
] = default_ioport_readl
;
404 ioport_write_table
[0][i
] = default_ioport_writeb
;
405 ioport_write_table
[1][i
] = default_ioport_writew
;
406 ioport_write_table
[2][i
] = default_ioport_writel
;
408 ioport_opaque
[i
] = NULL
;
412 /***********************************************************/
414 void cpu_outb(CPUState
*env
, int addr
, int val
)
417 if (loglevel
& CPU_LOG_IOPORT
)
418 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
420 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
423 env
->last_io_time
= cpu_get_time_fast();
427 void cpu_outw(CPUState
*env
, int addr
, int val
)
430 if (loglevel
& CPU_LOG_IOPORT
)
431 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
433 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
436 env
->last_io_time
= cpu_get_time_fast();
440 void cpu_outl(CPUState
*env
, int addr
, int val
)
443 if (loglevel
& CPU_LOG_IOPORT
)
444 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
446 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
449 env
->last_io_time
= cpu_get_time_fast();
453 int cpu_inb(CPUState
*env
, int addr
)
456 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
458 if (loglevel
& CPU_LOG_IOPORT
)
459 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
463 env
->last_io_time
= cpu_get_time_fast();
468 int cpu_inw(CPUState
*env
, int addr
)
471 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
473 if (loglevel
& CPU_LOG_IOPORT
)
474 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
478 env
->last_io_time
= cpu_get_time_fast();
483 int cpu_inl(CPUState
*env
, int addr
)
486 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
488 if (loglevel
& CPU_LOG_IOPORT
)
489 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
493 env
->last_io_time
= cpu_get_time_fast();
498 /***********************************************************/
499 void hw_error(const char *fmt
, ...)
505 fprintf(stderr
, "qemu: hardware error: ");
506 vfprintf(stderr
, fmt
, ap
);
507 fprintf(stderr
, "\n");
508 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
509 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
511 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
513 cpu_dump_state(env
, stderr
, fprintf
, 0);
520 /***********************************************************/
523 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
524 static void *qemu_put_kbd_event_opaque
;
525 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
526 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
528 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
530 qemu_put_kbd_event_opaque
= opaque
;
531 qemu_put_kbd_event
= func
;
534 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
535 void *opaque
, int absolute
,
538 QEMUPutMouseEntry
*s
, *cursor
;
540 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
544 s
->qemu_put_mouse_event
= func
;
545 s
->qemu_put_mouse_event_opaque
= opaque
;
546 s
->qemu_put_mouse_event_absolute
= absolute
;
547 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
550 if (!qemu_put_mouse_event_head
) {
551 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
555 cursor
= qemu_put_mouse_event_head
;
556 while (cursor
->next
!= NULL
)
557 cursor
= cursor
->next
;
560 qemu_put_mouse_event_current
= s
;
565 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
567 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
569 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
572 cursor
= qemu_put_mouse_event_head
;
573 while (cursor
!= NULL
&& cursor
!= entry
) {
575 cursor
= cursor
->next
;
578 if (cursor
== NULL
) // does not exist or list empty
580 else if (prev
== NULL
) { // entry is head
581 qemu_put_mouse_event_head
= cursor
->next
;
582 if (qemu_put_mouse_event_current
== entry
)
583 qemu_put_mouse_event_current
= cursor
->next
;
584 qemu_free(entry
->qemu_put_mouse_event_name
);
589 prev
->next
= entry
->next
;
591 if (qemu_put_mouse_event_current
== entry
)
592 qemu_put_mouse_event_current
= prev
;
594 qemu_free(entry
->qemu_put_mouse_event_name
);
598 void kbd_put_keycode(int keycode
)
600 if (qemu_put_kbd_event
) {
601 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
605 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
607 QEMUPutMouseEvent
*mouse_event
;
608 void *mouse_event_opaque
;
611 if (!qemu_put_mouse_event_current
) {
616 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
618 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
621 if (graphic_rotate
) {
622 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
625 width
= graphic_width
- 1;
626 mouse_event(mouse_event_opaque
,
627 width
- dy
, dx
, dz
, buttons_state
);
629 mouse_event(mouse_event_opaque
,
630 dx
, dy
, dz
, buttons_state
);
634 int kbd_mouse_is_absolute(void)
636 if (!qemu_put_mouse_event_current
)
639 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
642 void do_info_mice(void)
644 QEMUPutMouseEntry
*cursor
;
647 if (!qemu_put_mouse_event_head
) {
648 term_printf("No mouse devices connected\n");
652 term_printf("Mouse devices available:\n");
653 cursor
= qemu_put_mouse_event_head
;
654 while (cursor
!= NULL
) {
655 term_printf("%c Mouse #%d: %s\n",
656 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
657 index
, cursor
->qemu_put_mouse_event_name
);
659 cursor
= cursor
->next
;
663 void do_mouse_set(int index
)
665 QEMUPutMouseEntry
*cursor
;
668 if (!qemu_put_mouse_event_head
) {
669 term_printf("No mouse devices connected\n");
673 cursor
= qemu_put_mouse_event_head
;
674 while (cursor
!= NULL
&& index
!= i
) {
676 cursor
= cursor
->next
;
680 qemu_put_mouse_event_current
= cursor
;
682 term_printf("Mouse at given index not found\n");
685 /* compute with 96 bit intermediate result: (a*b)/c */
686 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
691 #ifdef WORDS_BIGENDIAN
701 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
702 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
705 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
709 /***********************************************************/
710 /* real time host monotonic timer */
712 #define QEMU_TIMER_BASE 1000000000LL
716 static int64_t clock_freq
;
718 static void init_get_clock(void)
722 ret
= QueryPerformanceFrequency(&freq
);
724 fprintf(stderr
, "Could not calibrate ticks\n");
727 clock_freq
= freq
.QuadPart
;
730 static int64_t get_clock(void)
733 QueryPerformanceCounter(&ti
);
734 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
739 static int use_rt_clock
;
741 static void init_get_clock(void)
744 #if defined(__linux__)
747 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
754 static int64_t get_clock(void)
756 #if defined(__linux__)
759 clock_gettime(CLOCK_MONOTONIC
, &ts
);
760 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
764 /* XXX: using gettimeofday leads to problems if the date
765 changes, so it should be avoided. */
767 gettimeofday(&tv
, NULL
);
768 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
774 /***********************************************************/
775 /* guest cycle counter */
777 static int64_t cpu_ticks_prev
;
778 static int64_t cpu_ticks_offset
;
779 static int64_t cpu_clock_offset
;
780 static int cpu_ticks_enabled
;
782 /* return the host CPU cycle counter and handle stop/restart */
783 int64_t cpu_get_ticks(void)
785 if (!cpu_ticks_enabled
) {
786 return cpu_ticks_offset
;
789 ticks
= cpu_get_real_ticks();
790 if (cpu_ticks_prev
> ticks
) {
791 /* Note: non increasing ticks may happen if the host uses
793 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
795 cpu_ticks_prev
= ticks
;
796 return ticks
+ cpu_ticks_offset
;
800 /* return the host CPU monotonic timer and handle stop/restart */
801 static int64_t cpu_get_clock(void)
804 if (!cpu_ticks_enabled
) {
805 return cpu_clock_offset
;
808 return ti
+ cpu_clock_offset
;
812 /* enable cpu_get_ticks() */
813 void cpu_enable_ticks(void)
815 if (!cpu_ticks_enabled
) {
816 cpu_ticks_offset
-= cpu_get_real_ticks();
817 cpu_clock_offset
-= get_clock();
818 cpu_ticks_enabled
= 1;
822 /* disable cpu_get_ticks() : the clock is stopped. You must not call
823 cpu_get_ticks() after that. */
824 void cpu_disable_ticks(void)
826 if (cpu_ticks_enabled
) {
827 cpu_ticks_offset
= cpu_get_ticks();
828 cpu_clock_offset
= cpu_get_clock();
829 cpu_ticks_enabled
= 0;
833 /***********************************************************/
836 #define QEMU_TIMER_REALTIME 0
837 #define QEMU_TIMER_VIRTUAL 1
841 /* XXX: add frequency */
849 struct QEMUTimer
*next
;
852 struct qemu_alarm_timer
{
856 int (*start
)(struct qemu_alarm_timer
*t
);
857 void (*stop
)(struct qemu_alarm_timer
*t
);
858 void (*rearm
)(struct qemu_alarm_timer
*t
);
862 #define ALARM_FLAG_DYNTICKS 0x1
863 #define ALARM_FLAG_EXPIRED 0x2
865 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
867 return t
->flags
& ALARM_FLAG_DYNTICKS
;
870 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
872 if (!alarm_has_dynticks(t
))
878 /* TODO: MIN_TIMER_REARM_US should be optimized */
879 #define MIN_TIMER_REARM_US 250
881 static struct qemu_alarm_timer
*alarm_timer
;
885 struct qemu_alarm_win32
{
889 } alarm_win32_data
= {0, NULL
, -1};
891 static int win32_start_timer(struct qemu_alarm_timer
*t
);
892 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
893 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
897 static int unix_start_timer(struct qemu_alarm_timer
*t
);
898 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
902 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
903 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
904 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
906 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
907 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
909 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
910 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
912 #endif /* __linux__ */
916 static struct qemu_alarm_timer alarm_timers
[] = {
919 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
920 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
921 /* HPET - if available - is preferred */
922 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
923 /* ...otherwise try RTC */
924 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
926 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
928 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
929 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
930 {"win32", 0, win32_start_timer
,
931 win32_stop_timer
, NULL
, &alarm_win32_data
},
936 static void show_available_alarms(void)
940 printf("Available alarm timers, in order of precedence:\n");
941 for (i
= 0; alarm_timers
[i
].name
; i
++)
942 printf("%s\n", alarm_timers
[i
].name
);
945 static void configure_alarms(char const *opt
)
949 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
953 if (!strcmp(opt
, "?")) {
954 show_available_alarms();
960 /* Reorder the array */
961 name
= strtok(arg
, ",");
963 struct qemu_alarm_timer tmp
;
965 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
966 if (!strcmp(alarm_timers
[i
].name
, name
))
971 fprintf(stderr
, "Unknown clock %s\n", name
);
980 tmp
= alarm_timers
[i
];
981 alarm_timers
[i
] = alarm_timers
[cur
];
982 alarm_timers
[cur
] = tmp
;
986 name
= strtok(NULL
, ",");
992 /* Disable remaining timers */
993 for (i
= cur
; i
< count
; i
++)
994 alarm_timers
[i
].name
= NULL
;
996 show_available_alarms();
1001 QEMUClock
*rt_clock
;
1002 QEMUClock
*vm_clock
;
1004 static QEMUTimer
*active_timers
[2];
1006 static QEMUClock
*qemu_new_clock(int type
)
1009 clock
= qemu_mallocz(sizeof(QEMUClock
));
1016 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
1020 ts
= qemu_mallocz(sizeof(QEMUTimer
));
1023 ts
->opaque
= opaque
;
1027 void qemu_free_timer(QEMUTimer
*ts
)
1032 /* stop a timer, but do not dealloc it */
1033 void qemu_del_timer(QEMUTimer
*ts
)
1037 /* NOTE: this code must be signal safe because
1038 qemu_timer_expired() can be called from a signal. */
1039 pt
= &active_timers
[ts
->clock
->type
];
1052 /* modify the current timer so that it will be fired when current_time
1053 >= expire_time. The corresponding callback will be called. */
1054 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1060 /* add the timer in the sorted list */
1061 /* NOTE: this code must be signal safe because
1062 qemu_timer_expired() can be called from a signal. */
1063 pt
= &active_timers
[ts
->clock
->type
];
1068 if (t
->expire_time
> expire_time
)
1072 ts
->expire_time
= expire_time
;
1076 /* Rearm if necessary */
1077 if ((alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) == 0 &&
1078 pt
== &active_timers
[ts
->clock
->type
])
1079 qemu_rearm_alarm_timer(alarm_timer
);
1082 int qemu_timer_pending(QEMUTimer
*ts
)
1085 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1092 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1096 return (timer_head
->expire_time
<= current_time
);
1099 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1105 if (!ts
|| ts
->expire_time
> current_time
)
1107 /* remove timer from the list before calling the callback */
1108 *ptimer_head
= ts
->next
;
1111 /* run the callback (the timer list can be modified) */
1116 int64_t qemu_get_clock(QEMUClock
*clock
)
1118 switch(clock
->type
) {
1119 case QEMU_TIMER_REALTIME
:
1120 return get_clock() / 1000000;
1122 case QEMU_TIMER_VIRTUAL
:
1123 return cpu_get_clock();
1127 static void init_timers(void)
1130 ticks_per_sec
= QEMU_TIMER_BASE
;
1131 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1132 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1136 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1138 uint64_t expire_time
;
1140 if (qemu_timer_pending(ts
)) {
1141 expire_time
= ts
->expire_time
;
1145 qemu_put_be64(f
, expire_time
);
1148 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1150 uint64_t expire_time
;
1152 expire_time
= qemu_get_be64(f
);
1153 if (expire_time
!= -1) {
1154 qemu_mod_timer(ts
, expire_time
);
1160 static void timer_save(QEMUFile
*f
, void *opaque
)
1162 if (cpu_ticks_enabled
) {
1163 hw_error("cannot save state if virtual timers are running");
1165 qemu_put_be64(f
, cpu_ticks_offset
);
1166 qemu_put_be64(f
, ticks_per_sec
);
1167 qemu_put_be64(f
, cpu_clock_offset
);
1170 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1172 if (version_id
!= 1 && version_id
!= 2)
1174 if (cpu_ticks_enabled
) {
1177 cpu_ticks_offset
=qemu_get_be64(f
);
1178 ticks_per_sec
=qemu_get_be64(f
);
1179 if (version_id
== 2) {
1180 cpu_clock_offset
=qemu_get_be64(f
);
1186 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1187 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1189 static void host_alarm_handler(int host_signum
)
1193 #define DISP_FREQ 1000
1195 static int64_t delta_min
= INT64_MAX
;
1196 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1198 ti
= qemu_get_clock(vm_clock
);
1199 if (last_clock
!= 0) {
1200 delta
= ti
- last_clock
;
1201 if (delta
< delta_min
)
1203 if (delta
> delta_max
)
1206 if (++count
== DISP_FREQ
) {
1207 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1208 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1209 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1210 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1211 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1213 delta_min
= INT64_MAX
;
1222 alarm_has_dynticks(alarm_timer
) ||
1223 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1224 qemu_get_clock(vm_clock
)) ||
1225 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1226 qemu_get_clock(rt_clock
))) {
1228 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1229 SetEvent(data
->host_alarm
);
1231 CPUState
*env
= next_cpu
;
1233 alarm_timer
->flags
|= ALARM_FLAG_EXPIRED
;
1236 /* stop the currently executing cpu because a timer occured */
1237 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1239 if (env
->kqemu_enabled
) {
1240 kqemu_cpu_interrupt(env
);
1248 static uint64_t qemu_next_deadline(void)
1250 int64_t nearest_delta_us
= INT64_MAX
;
1253 if (active_timers
[QEMU_TIMER_REALTIME
])
1254 nearest_delta_us
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1255 qemu_get_clock(rt_clock
))*1000;
1257 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1259 vmdelta_us
= (active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1260 qemu_get_clock(vm_clock
)+999)/1000;
1261 if (vmdelta_us
< nearest_delta_us
)
1262 nearest_delta_us
= vmdelta_us
;
1265 /* Avoid arming the timer to negative, zero, or too low values */
1266 if (nearest_delta_us
<= MIN_TIMER_REARM_US
)
1267 nearest_delta_us
= MIN_TIMER_REARM_US
;
1269 return nearest_delta_us
;
1274 #if defined(__linux__)
1276 #define RTC_FREQ 1024
1278 static void enable_sigio_timer(int fd
)
1280 struct sigaction act
;
1283 sigfillset(&act
.sa_mask
);
1285 act
.sa_handler
= host_alarm_handler
;
1287 sigaction(SIGIO
, &act
, NULL
);
1288 fcntl(fd
, F_SETFL
, O_ASYNC
);
1289 fcntl(fd
, F_SETOWN
, getpid());
1292 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1294 struct hpet_info info
;
1297 fd
= open("/dev/hpet", O_RDONLY
);
1302 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1304 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1305 "error, but for better emulation accuracy type:\n"
1306 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1310 /* Check capabilities */
1311 r
= ioctl(fd
, HPET_INFO
, &info
);
1315 /* Enable periodic mode */
1316 r
= ioctl(fd
, HPET_EPI
, 0);
1317 if (info
.hi_flags
&& (r
< 0))
1320 /* Enable interrupt */
1321 r
= ioctl(fd
, HPET_IE_ON
, 0);
1325 enable_sigio_timer(fd
);
1326 t
->priv
= (void *)(long)fd
;
1334 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1336 int fd
= (long)t
->priv
;
1341 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1344 unsigned long current_rtc_freq
= 0;
1346 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1349 ioctl(rtc_fd
, RTC_IRQP_READ
, ¤t_rtc_freq
);
1350 if (current_rtc_freq
!= RTC_FREQ
&&
1351 ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1352 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1353 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1354 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1357 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1363 enable_sigio_timer(rtc_fd
);
1365 t
->priv
= (void *)(long)rtc_fd
;
1370 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1372 int rtc_fd
= (long)t
->priv
;
1377 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1381 struct sigaction act
;
1383 sigfillset(&act
.sa_mask
);
1385 act
.sa_handler
= host_alarm_handler
;
1387 sigaction(SIGALRM
, &act
, NULL
);
1389 ev
.sigev_value
.sival_int
= 0;
1390 ev
.sigev_notify
= SIGEV_SIGNAL
;
1391 ev
.sigev_signo
= SIGALRM
;
1393 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1394 perror("timer_create");
1396 /* disable dynticks */
1397 fprintf(stderr
, "Dynamic Ticks disabled\n");
1402 t
->priv
= (void *)host_timer
;
1407 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1409 timer_t host_timer
= (timer_t
)t
->priv
;
1411 timer_delete(host_timer
);
1414 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1416 timer_t host_timer
= (timer_t
)t
->priv
;
1417 struct itimerspec timeout
;
1418 int64_t nearest_delta_us
= INT64_MAX
;
1421 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1422 !active_timers
[QEMU_TIMER_VIRTUAL
])
1425 nearest_delta_us
= qemu_next_deadline();
1427 /* check whether a timer is already running */
1428 if (timer_gettime(host_timer
, &timeout
)) {
1430 fprintf(stderr
, "Internal timer error: aborting\n");
1433 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1434 if (current_us
&& current_us
<= nearest_delta_us
)
1437 timeout
.it_interval
.tv_sec
= 0;
1438 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1439 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1440 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1441 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1443 fprintf(stderr
, "Internal timer error: aborting\n");
1448 #endif /* defined(__linux__) */
1450 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1452 struct sigaction act
;
1453 struct itimerval itv
;
1457 sigfillset(&act
.sa_mask
);
1459 act
.sa_handler
= host_alarm_handler
;
1461 sigaction(SIGALRM
, &act
, NULL
);
1463 itv
.it_interval
.tv_sec
= 0;
1464 /* for i386 kernel 2.6 to get 1 ms */
1465 itv
.it_interval
.tv_usec
= 999;
1466 itv
.it_value
.tv_sec
= 0;
1467 itv
.it_value
.tv_usec
= 10 * 1000;
1469 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1476 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1478 struct itimerval itv
;
1480 memset(&itv
, 0, sizeof(itv
));
1481 setitimer(ITIMER_REAL
, &itv
, NULL
);
1484 #endif /* !defined(_WIN32) */
1488 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1491 struct qemu_alarm_win32
*data
= t
->priv
;
1494 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1495 if (!data
->host_alarm
) {
1496 perror("Failed CreateEvent");
1500 memset(&tc
, 0, sizeof(tc
));
1501 timeGetDevCaps(&tc
, sizeof(tc
));
1503 if (data
->period
< tc
.wPeriodMin
)
1504 data
->period
= tc
.wPeriodMin
;
1506 timeBeginPeriod(data
->period
);
1508 flags
= TIME_CALLBACK_FUNCTION
;
1509 if (alarm_has_dynticks(t
))
1510 flags
|= TIME_ONESHOT
;
1512 flags
|= TIME_PERIODIC
;
1514 data
->timerId
= timeSetEvent(1, // interval (ms)
1515 data
->period
, // resolution
1516 host_alarm_handler
, // function
1517 (DWORD
)t
, // parameter
1520 if (!data
->timerId
) {
1521 perror("Failed to initialize win32 alarm timer");
1523 timeEndPeriod(data
->period
);
1524 CloseHandle(data
->host_alarm
);
1528 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1533 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1535 struct qemu_alarm_win32
*data
= t
->priv
;
1537 timeKillEvent(data
->timerId
);
1538 timeEndPeriod(data
->period
);
1540 CloseHandle(data
->host_alarm
);
1543 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1545 struct qemu_alarm_win32
*data
= t
->priv
;
1546 uint64_t nearest_delta_us
;
1548 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1549 !active_timers
[QEMU_TIMER_VIRTUAL
])
1552 nearest_delta_us
= qemu_next_deadline();
1553 nearest_delta_us
/= 1000;
1555 timeKillEvent(data
->timerId
);
1557 data
->timerId
= timeSetEvent(1,
1561 TIME_ONESHOT
| TIME_PERIODIC
);
1563 if (!data
->timerId
) {
1564 perror("Failed to re-arm win32 alarm timer");
1566 timeEndPeriod(data
->period
);
1567 CloseHandle(data
->host_alarm
);
1574 static void init_timer_alarm(void)
1576 struct qemu_alarm_timer
*t
;
1579 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1580 t
= &alarm_timers
[i
];
1588 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1589 fprintf(stderr
, "Terminating\n");
1596 static void quit_timers(void)
1598 alarm_timer
->stop(alarm_timer
);
1602 /***********************************************************/
1603 /* host time/date access */
1604 void qemu_get_timedate(struct tm
*tm
, int offset
)
1611 if (rtc_date_offset
== -1) {
1615 ret
= localtime(&ti
);
1617 ti
-= rtc_date_offset
;
1621 memcpy(tm
, ret
, sizeof(struct tm
));
1624 int qemu_timedate_diff(struct tm
*tm
)
1628 if (rtc_date_offset
== -1)
1630 seconds
= mktimegm(tm
);
1632 seconds
= mktime(tm
);
1634 seconds
= mktimegm(tm
) + rtc_date_offset
;
1636 return seconds
- time(NULL
);
1639 /***********************************************************/
1640 /* character device */
1642 static void qemu_chr_event(CharDriverState
*s
, int event
)
1646 s
->chr_event(s
->handler_opaque
, event
);
1649 static void qemu_chr_reset_bh(void *opaque
)
1651 CharDriverState
*s
= opaque
;
1652 qemu_chr_event(s
, CHR_EVENT_RESET
);
1653 qemu_bh_delete(s
->bh
);
1657 void qemu_chr_reset(CharDriverState
*s
)
1659 if (s
->bh
== NULL
) {
1660 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1661 qemu_bh_schedule(s
->bh
);
1665 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1667 return s
->chr_write(s
, buf
, len
);
1670 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1674 return s
->chr_ioctl(s
, cmd
, arg
);
1677 int qemu_chr_can_read(CharDriverState
*s
)
1679 if (!s
->chr_can_read
)
1681 return s
->chr_can_read(s
->handler_opaque
);
1684 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1686 s
->chr_read(s
->handler_opaque
, buf
, len
);
1689 void qemu_chr_accept_input(CharDriverState
*s
)
1691 if (s
->chr_accept_input
)
1692 s
->chr_accept_input(s
);
1695 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1700 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1701 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1705 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1707 if (s
->chr_send_event
)
1708 s
->chr_send_event(s
, event
);
1711 void qemu_chr_add_handlers(CharDriverState
*s
,
1712 IOCanRWHandler
*fd_can_read
,
1713 IOReadHandler
*fd_read
,
1714 IOEventHandler
*fd_event
,
1717 s
->chr_can_read
= fd_can_read
;
1718 s
->chr_read
= fd_read
;
1719 s
->chr_event
= fd_event
;
1720 s
->handler_opaque
= opaque
;
1721 if (s
->chr_update_read_handler
)
1722 s
->chr_update_read_handler(s
);
1725 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1730 static CharDriverState
*qemu_chr_open_null(void)
1732 CharDriverState
*chr
;
1734 chr
= qemu_mallocz(sizeof(CharDriverState
));
1737 chr
->chr_write
= null_chr_write
;
1741 /* MUX driver for serial I/O splitting */
1742 static int term_timestamps
;
1743 static int64_t term_timestamps_start
;
1745 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1746 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1748 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1749 IOReadHandler
*chr_read
[MAX_MUX
];
1750 IOEventHandler
*chr_event
[MAX_MUX
];
1751 void *ext_opaque
[MAX_MUX
];
1752 CharDriverState
*drv
;
1753 unsigned char buffer
[MUX_BUFFER_SIZE
];
1757 int term_got_escape
;
1762 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1764 MuxDriver
*d
= chr
->opaque
;
1766 if (!term_timestamps
) {
1767 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1772 for(i
= 0; i
< len
; i
++) {
1773 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1774 if (buf
[i
] == '\n') {
1780 if (term_timestamps_start
== -1)
1781 term_timestamps_start
= ti
;
1782 ti
-= term_timestamps_start
;
1783 secs
= ti
/ 1000000000;
1784 snprintf(buf1
, sizeof(buf1
),
1785 "[%02d:%02d:%02d.%03d] ",
1789 (int)((ti
/ 1000000) % 1000));
1790 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1797 static char *mux_help
[] = {
1798 "% h print this help\n\r",
1799 "% x exit emulator\n\r",
1800 "% s save disk data back to file (if -snapshot)\n\r",
1801 "% t toggle console timestamps\n\r"
1802 "% b send break (magic sysrq)\n\r",
1803 "% c switch between console and monitor\n\r",
1808 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1809 static void mux_print_help(CharDriverState
*chr
)
1812 char ebuf
[15] = "Escape-Char";
1813 char cbuf
[50] = "\n\r";
1815 if (term_escape_char
> 0 && term_escape_char
< 26) {
1816 sprintf(cbuf
,"\n\r");
1817 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1819 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1822 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1823 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1824 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1825 if (mux_help
[i
][j
] == '%')
1826 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1828 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1833 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1835 if (d
->term_got_escape
) {
1836 d
->term_got_escape
= 0;
1837 if (ch
== term_escape_char
)
1842 mux_print_help(chr
);
1846 char *term
= "QEMU: Terminated\n\r";
1847 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1854 for (i
= 0; i
< nb_drives
; i
++) {
1855 bdrv_commit(drives_table
[i
].bdrv
);
1860 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1863 /* Switch to the next registered device */
1865 if (chr
->focus
>= d
->mux_cnt
)
1869 term_timestamps
= !term_timestamps
;
1870 term_timestamps_start
= -1;
1873 } else if (ch
== term_escape_char
) {
1874 d
->term_got_escape
= 1;
1882 static void mux_chr_accept_input(CharDriverState
*chr
)
1885 MuxDriver
*d
= chr
->opaque
;
1887 while (d
->prod
!= d
->cons
&&
1888 d
->chr_can_read
[m
] &&
1889 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1890 d
->chr_read
[m
](d
->ext_opaque
[m
],
1891 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1895 static int mux_chr_can_read(void *opaque
)
1897 CharDriverState
*chr
= opaque
;
1898 MuxDriver
*d
= chr
->opaque
;
1900 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
1902 if (d
->chr_can_read
[chr
->focus
])
1903 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1907 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1909 CharDriverState
*chr
= opaque
;
1910 MuxDriver
*d
= chr
->opaque
;
1914 mux_chr_accept_input (opaque
);
1916 for(i
= 0; i
< size
; i
++)
1917 if (mux_proc_byte(chr
, d
, buf
[i
])) {
1918 if (d
->prod
== d
->cons
&&
1919 d
->chr_can_read
[m
] &&
1920 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
1921 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
1923 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
1927 static void mux_chr_event(void *opaque
, int event
)
1929 CharDriverState
*chr
= opaque
;
1930 MuxDriver
*d
= chr
->opaque
;
1933 /* Send the event to all registered listeners */
1934 for (i
= 0; i
< d
->mux_cnt
; i
++)
1935 if (d
->chr_event
[i
])
1936 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1939 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1941 MuxDriver
*d
= chr
->opaque
;
1943 if (d
->mux_cnt
>= MAX_MUX
) {
1944 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1947 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1948 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1949 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1950 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1951 /* Fix up the real driver with mux routines */
1952 if (d
->mux_cnt
== 0) {
1953 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1954 mux_chr_event
, chr
);
1956 chr
->focus
= d
->mux_cnt
;
1960 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1962 CharDriverState
*chr
;
1965 chr
= qemu_mallocz(sizeof(CharDriverState
));
1968 d
= qemu_mallocz(sizeof(MuxDriver
));
1977 chr
->chr_write
= mux_chr_write
;
1978 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1979 chr
->chr_accept_input
= mux_chr_accept_input
;
1986 static void socket_cleanup(void)
1991 static int socket_init(void)
1996 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1998 err
= WSAGetLastError();
1999 fprintf(stderr
, "WSAStartup: %d\n", err
);
2002 atexit(socket_cleanup
);
2006 static int send_all(int fd
, const uint8_t *buf
, int len1
)
2012 ret
= send(fd
, buf
, len
, 0);
2015 errno
= WSAGetLastError();
2016 if (errno
!= WSAEWOULDBLOCK
) {
2019 } else if (ret
== 0) {
2029 void socket_set_nonblock(int fd
)
2031 unsigned long opt
= 1;
2032 ioctlsocket(fd
, FIONBIO
, &opt
);
2037 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
2043 ret
= write(fd
, buf
, len
);
2045 if (errno
!= EINTR
&& errno
!= EAGAIN
)
2047 } else if (ret
== 0) {
2057 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
2059 return unix_write(fd
, buf
, len1
);
2062 void socket_set_nonblock(int fd
)
2064 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2066 #endif /* !_WIN32 */
2075 #define STDIO_MAX_CLIENTS 1
2076 static int stdio_nb_clients
= 0;
2078 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2080 FDCharDriver
*s
= chr
->opaque
;
2081 return unix_write(s
->fd_out
, buf
, len
);
2084 static int fd_chr_read_poll(void *opaque
)
2086 CharDriverState
*chr
= opaque
;
2087 FDCharDriver
*s
= chr
->opaque
;
2089 s
->max_size
= qemu_chr_can_read(chr
);
2093 static void fd_chr_read(void *opaque
)
2095 CharDriverState
*chr
= opaque
;
2096 FDCharDriver
*s
= chr
->opaque
;
2101 if (len
> s
->max_size
)
2105 size
= read(s
->fd_in
, buf
, len
);
2107 /* FD has been closed. Remove it from the active list. */
2108 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2112 qemu_chr_read(chr
, buf
, size
);
2116 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2118 FDCharDriver
*s
= chr
->opaque
;
2120 if (s
->fd_in
>= 0) {
2121 if (nographic
&& s
->fd_in
== 0) {
2123 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2124 fd_chr_read
, NULL
, chr
);
2129 static void fd_chr_close(struct CharDriverState
*chr
)
2131 FDCharDriver
*s
= chr
->opaque
;
2133 if (s
->fd_in
>= 0) {
2134 if (nographic
&& s
->fd_in
== 0) {
2136 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2143 /* open a character device to a unix fd */
2144 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2146 CharDriverState
*chr
;
2149 chr
= qemu_mallocz(sizeof(CharDriverState
));
2152 s
= qemu_mallocz(sizeof(FDCharDriver
));
2160 chr
->chr_write
= fd_chr_write
;
2161 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2162 chr
->chr_close
= fd_chr_close
;
2164 qemu_chr_reset(chr
);
2169 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2173 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2176 return qemu_chr_open_fd(-1, fd_out
);
2179 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2182 char filename_in
[256], filename_out
[256];
2184 snprintf(filename_in
, 256, "%s.in", filename
);
2185 snprintf(filename_out
, 256, "%s.out", filename
);
2186 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2187 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2188 if (fd_in
< 0 || fd_out
< 0) {
2193 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2197 return qemu_chr_open_fd(fd_in
, fd_out
);
2201 /* for STDIO, we handle the case where several clients use it
2204 #define TERM_FIFO_MAX_SIZE 1
2206 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2207 static int term_fifo_size
;
2209 static int stdio_read_poll(void *opaque
)
2211 CharDriverState
*chr
= opaque
;
2213 /* try to flush the queue if needed */
2214 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2215 qemu_chr_read(chr
, term_fifo
, 1);
2218 /* see if we can absorb more chars */
2219 if (term_fifo_size
== 0)
2225 static void stdio_read(void *opaque
)
2229 CharDriverState
*chr
= opaque
;
2231 size
= read(0, buf
, 1);
2233 /* stdin has been closed. Remove it from the active list. */
2234 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2238 if (qemu_chr_can_read(chr
) > 0) {
2239 qemu_chr_read(chr
, buf
, 1);
2240 } else if (term_fifo_size
== 0) {
2241 term_fifo
[term_fifo_size
++] = buf
[0];
2246 /* init terminal so that we can grab keys */
2247 static struct termios oldtty
;
2248 static int old_fd0_flags
;
2249 static int term_atexit_done
;
2251 static void term_exit(void)
2253 tcsetattr (0, TCSANOW
, &oldtty
);
2254 fcntl(0, F_SETFL
, old_fd0_flags
);
2257 static void term_init(void)
2261 tcgetattr (0, &tty
);
2263 old_fd0_flags
= fcntl(0, F_GETFL
);
2265 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2266 |INLCR
|IGNCR
|ICRNL
|IXON
);
2267 tty
.c_oflag
|= OPOST
;
2268 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2269 /* if graphical mode, we allow Ctrl-C handling */
2271 tty
.c_lflag
&= ~ISIG
;
2272 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2275 tty
.c_cc
[VTIME
] = 0;
2277 tcsetattr (0, TCSANOW
, &tty
);
2279 if (!term_atexit_done
++)
2282 fcntl(0, F_SETFL
, O_NONBLOCK
);
2285 static void qemu_chr_close_stdio(struct CharDriverState
*chr
)
2289 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2293 static CharDriverState
*qemu_chr_open_stdio(void)
2295 CharDriverState
*chr
;
2297 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2299 chr
= qemu_chr_open_fd(0, 1);
2300 chr
->chr_close
= qemu_chr_close_stdio
;
2301 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2309 /* Once Solaris has openpty(), this is going to be removed. */
2310 int openpty(int *amaster
, int *aslave
, char *name
,
2311 struct termios
*termp
, struct winsize
*winp
)
2314 int mfd
= -1, sfd
= -1;
2316 *amaster
= *aslave
= -1;
2318 mfd
= open("/dev/ptmx", O_RDWR
| O_NOCTTY
);
2322 if (grantpt(mfd
) == -1 || unlockpt(mfd
) == -1)
2325 if ((slave
= ptsname(mfd
)) == NULL
)
2328 if ((sfd
= open(slave
, O_RDONLY
| O_NOCTTY
)) == -1)
2331 if (ioctl(sfd
, I_PUSH
, "ptem") == -1 ||
2332 (termp
!= NULL
&& tcgetattr(sfd
, termp
) < 0))
2340 ioctl(sfd
, TIOCSWINSZ
, winp
);
2351 void cfmakeraw (struct termios
*termios_p
)
2353 termios_p
->c_iflag
&=
2354 ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
|INLCR
|IGNCR
|ICRNL
|IXON
);
2355 termios_p
->c_oflag
&= ~OPOST
;
2356 termios_p
->c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|ISIG
|IEXTEN
);
2357 termios_p
->c_cflag
&= ~(CSIZE
|PARENB
);
2358 termios_p
->c_cflag
|= CS8
;
2360 termios_p
->c_cc
[VMIN
] = 0;
2361 termios_p
->c_cc
[VTIME
] = 0;
2365 #if defined(__linux__) || defined(__sun__)
2366 static CharDriverState
*qemu_chr_open_pty(void)
2369 int master_fd
, slave_fd
;
2371 if (openpty(&master_fd
, &slave_fd
, NULL
, NULL
, NULL
) < 0) {
2375 /* Set raw attributes on the pty. */
2377 tcsetattr(slave_fd
, TCSAFLUSH
, &tty
);
2379 fprintf(stderr
, "char device redirected to %s\n", ptsname(master_fd
));
2380 return qemu_chr_open_fd(master_fd
, master_fd
);
2383 static void tty_serial_init(int fd
, int speed
,
2384 int parity
, int data_bits
, int stop_bits
)
2390 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2391 speed
, parity
, data_bits
, stop_bits
);
2393 tcgetattr (fd
, &tty
);
2396 if (speed
<= 50 * MARGIN
)
2398 else if (speed
<= 75 * MARGIN
)
2400 else if (speed
<= 300 * MARGIN
)
2402 else if (speed
<= 600 * MARGIN
)
2404 else if (speed
<= 1200 * MARGIN
)
2406 else if (speed
<= 2400 * MARGIN
)
2408 else if (speed
<= 4800 * MARGIN
)
2410 else if (speed
<= 9600 * MARGIN
)
2412 else if (speed
<= 19200 * MARGIN
)
2414 else if (speed
<= 38400 * MARGIN
)
2416 else if (speed
<= 57600 * MARGIN
)
2418 else if (speed
<= 115200 * MARGIN
)
2423 cfsetispeed(&tty
, spd
);
2424 cfsetospeed(&tty
, spd
);
2426 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2427 |INLCR
|IGNCR
|ICRNL
|IXON
);
2428 tty
.c_oflag
|= OPOST
;
2429 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2430 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2451 tty
.c_cflag
|= PARENB
;
2454 tty
.c_cflag
|= PARENB
| PARODD
;
2458 tty
.c_cflag
|= CSTOPB
;
2460 tcsetattr (fd
, TCSANOW
, &tty
);
2463 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2465 FDCharDriver
*s
= chr
->opaque
;
2468 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2470 QEMUSerialSetParams
*ssp
= arg
;
2471 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2472 ssp
->data_bits
, ssp
->stop_bits
);
2475 case CHR_IOCTL_SERIAL_SET_BREAK
:
2477 int enable
= *(int *)arg
;
2479 tcsendbreak(s
->fd_in
, 1);
2488 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2490 CharDriverState
*chr
;
2493 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2494 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2495 tty_serial_init(fd
, 115200, 'N', 8, 1);
2496 chr
= qemu_chr_open_fd(fd
, fd
);
2501 chr
->chr_ioctl
= tty_serial_ioctl
;
2502 qemu_chr_reset(chr
);
2505 #else /* ! __linux__ && ! __sun__ */
2506 static CharDriverState
*qemu_chr_open_pty(void)
2510 #endif /* __linux__ || __sun__ */
2512 #if defined(__linux__)
2516 } ParallelCharDriver
;
2518 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2520 if (s
->mode
!= mode
) {
2522 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2529 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2531 ParallelCharDriver
*drv
= chr
->opaque
;
2536 case CHR_IOCTL_PP_READ_DATA
:
2537 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2539 *(uint8_t *)arg
= b
;
2541 case CHR_IOCTL_PP_WRITE_DATA
:
2542 b
= *(uint8_t *)arg
;
2543 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2546 case CHR_IOCTL_PP_READ_CONTROL
:
2547 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2549 /* Linux gives only the lowest bits, and no way to know data
2550 direction! For better compatibility set the fixed upper
2552 *(uint8_t *)arg
= b
| 0xc0;
2554 case CHR_IOCTL_PP_WRITE_CONTROL
:
2555 b
= *(uint8_t *)arg
;
2556 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2559 case CHR_IOCTL_PP_READ_STATUS
:
2560 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2562 *(uint8_t *)arg
= b
;
2564 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2565 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2566 struct ParallelIOArg
*parg
= arg
;
2567 int n
= read(fd
, parg
->buffer
, parg
->count
);
2568 if (n
!= parg
->count
) {
2573 case CHR_IOCTL_PP_EPP_READ
:
2574 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2575 struct ParallelIOArg
*parg
= arg
;
2576 int n
= read(fd
, parg
->buffer
, parg
->count
);
2577 if (n
!= parg
->count
) {
2582 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2583 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2584 struct ParallelIOArg
*parg
= arg
;
2585 int n
= write(fd
, parg
->buffer
, parg
->count
);
2586 if (n
!= parg
->count
) {
2591 case CHR_IOCTL_PP_EPP_WRITE
:
2592 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2593 struct ParallelIOArg
*parg
= arg
;
2594 int n
= write(fd
, parg
->buffer
, parg
->count
);
2595 if (n
!= parg
->count
) {
2606 static void pp_close(CharDriverState
*chr
)
2608 ParallelCharDriver
*drv
= chr
->opaque
;
2611 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2612 ioctl(fd
, PPRELEASE
);
2617 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2619 CharDriverState
*chr
;
2620 ParallelCharDriver
*drv
;
2623 TFR(fd
= open(filename
, O_RDWR
));
2627 if (ioctl(fd
, PPCLAIM
) < 0) {
2632 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2638 drv
->mode
= IEEE1284_MODE_COMPAT
;
2640 chr
= qemu_mallocz(sizeof(CharDriverState
));
2646 chr
->chr_write
= null_chr_write
;
2647 chr
->chr_ioctl
= pp_ioctl
;
2648 chr
->chr_close
= pp_close
;
2651 qemu_chr_reset(chr
);
2655 #endif /* __linux__ */
2661 HANDLE hcom
, hrecv
, hsend
;
2662 OVERLAPPED orecv
, osend
;
2667 #define NSENDBUF 2048
2668 #define NRECVBUF 2048
2669 #define MAXCONNECT 1
2670 #define NTIMEOUT 5000
2672 static int win_chr_poll(void *opaque
);
2673 static int win_chr_pipe_poll(void *opaque
);
2675 static void win_chr_close(CharDriverState
*chr
)
2677 WinCharState
*s
= chr
->opaque
;
2680 CloseHandle(s
->hsend
);
2684 CloseHandle(s
->hrecv
);
2688 CloseHandle(s
->hcom
);
2692 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2694 qemu_del_polling_cb(win_chr_poll
, chr
);
2697 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2699 WinCharState
*s
= chr
->opaque
;
2701 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2706 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2708 fprintf(stderr
, "Failed CreateEvent\n");
2711 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2713 fprintf(stderr
, "Failed CreateEvent\n");
2717 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2718 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2719 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2720 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2725 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2726 fprintf(stderr
, "Failed SetupComm\n");
2730 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2731 size
= sizeof(COMMCONFIG
);
2732 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2733 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2734 CommConfigDialog(filename
, NULL
, &comcfg
);
2736 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2737 fprintf(stderr
, "Failed SetCommState\n");
2741 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2742 fprintf(stderr
, "Failed SetCommMask\n");
2746 cto
.ReadIntervalTimeout
= MAXDWORD
;
2747 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2748 fprintf(stderr
, "Failed SetCommTimeouts\n");
2752 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2753 fprintf(stderr
, "Failed ClearCommError\n");
2756 qemu_add_polling_cb(win_chr_poll
, chr
);
2764 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2766 WinCharState
*s
= chr
->opaque
;
2767 DWORD len
, ret
, size
, err
;
2770 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2771 s
->osend
.hEvent
= s
->hsend
;
2774 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2776 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2778 err
= GetLastError();
2779 if (err
== ERROR_IO_PENDING
) {
2780 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2798 static int win_chr_read_poll(CharDriverState
*chr
)
2800 WinCharState
*s
= chr
->opaque
;
2802 s
->max_size
= qemu_chr_can_read(chr
);
2806 static void win_chr_readfile(CharDriverState
*chr
)
2808 WinCharState
*s
= chr
->opaque
;
2813 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2814 s
->orecv
.hEvent
= s
->hrecv
;
2815 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2817 err
= GetLastError();
2818 if (err
== ERROR_IO_PENDING
) {
2819 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2824 qemu_chr_read(chr
, buf
, size
);
2828 static void win_chr_read(CharDriverState
*chr
)
2830 WinCharState
*s
= chr
->opaque
;
2832 if (s
->len
> s
->max_size
)
2833 s
->len
= s
->max_size
;
2837 win_chr_readfile(chr
);
2840 static int win_chr_poll(void *opaque
)
2842 CharDriverState
*chr
= opaque
;
2843 WinCharState
*s
= chr
->opaque
;
2847 ClearCommError(s
->hcom
, &comerr
, &status
);
2848 if (status
.cbInQue
> 0) {
2849 s
->len
= status
.cbInQue
;
2850 win_chr_read_poll(chr
);
2857 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2859 CharDriverState
*chr
;
2862 chr
= qemu_mallocz(sizeof(CharDriverState
));
2865 s
= qemu_mallocz(sizeof(WinCharState
));
2871 chr
->chr_write
= win_chr_write
;
2872 chr
->chr_close
= win_chr_close
;
2874 if (win_chr_init(chr
, filename
) < 0) {
2879 qemu_chr_reset(chr
);
2883 static int win_chr_pipe_poll(void *opaque
)
2885 CharDriverState
*chr
= opaque
;
2886 WinCharState
*s
= chr
->opaque
;
2889 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2892 win_chr_read_poll(chr
);
2899 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2901 WinCharState
*s
= chr
->opaque
;
2909 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2911 fprintf(stderr
, "Failed CreateEvent\n");
2914 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2916 fprintf(stderr
, "Failed CreateEvent\n");
2920 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2921 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2922 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2924 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2925 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2926 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2931 ZeroMemory(&ov
, sizeof(ov
));
2932 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2933 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2935 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2939 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2941 fprintf(stderr
, "Failed GetOverlappedResult\n");
2943 CloseHandle(ov
.hEvent
);
2950 CloseHandle(ov
.hEvent
);
2953 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2962 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2964 CharDriverState
*chr
;
2967 chr
= qemu_mallocz(sizeof(CharDriverState
));
2970 s
= qemu_mallocz(sizeof(WinCharState
));
2976 chr
->chr_write
= win_chr_write
;
2977 chr
->chr_close
= win_chr_close
;
2979 if (win_chr_pipe_init(chr
, filename
) < 0) {
2984 qemu_chr_reset(chr
);
2988 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2990 CharDriverState
*chr
;
2993 chr
= qemu_mallocz(sizeof(CharDriverState
));
2996 s
= qemu_mallocz(sizeof(WinCharState
));
3003 chr
->chr_write
= win_chr_write
;
3004 qemu_chr_reset(chr
);
3008 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
3010 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
3013 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
3017 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
3018 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
3019 if (fd_out
== INVALID_HANDLE_VALUE
)
3022 return qemu_chr_open_win_file(fd_out
);
3024 #endif /* !_WIN32 */
3026 /***********************************************************/
3027 /* UDP Net console */
3031 struct sockaddr_in daddr
;
3038 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3040 NetCharDriver
*s
= chr
->opaque
;
3042 return sendto(s
->fd
, buf
, len
, 0,
3043 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
3046 static int udp_chr_read_poll(void *opaque
)
3048 CharDriverState
*chr
= opaque
;
3049 NetCharDriver
*s
= chr
->opaque
;
3051 s
->max_size
= qemu_chr_can_read(chr
);
3053 /* If there were any stray characters in the queue process them
3056 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3057 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3059 s
->max_size
= qemu_chr_can_read(chr
);
3064 static void udp_chr_read(void *opaque
)
3066 CharDriverState
*chr
= opaque
;
3067 NetCharDriver
*s
= chr
->opaque
;
3069 if (s
->max_size
== 0)
3071 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3072 s
->bufptr
= s
->bufcnt
;
3077 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
3078 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
3080 s
->max_size
= qemu_chr_can_read(chr
);
3084 static void udp_chr_update_read_handler(CharDriverState
*chr
)
3086 NetCharDriver
*s
= chr
->opaque
;
3089 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
3090 udp_chr_read
, NULL
, chr
);
3095 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
3097 int parse_host_src_port(struct sockaddr_in
*haddr
,
3098 struct sockaddr_in
*saddr
,
3101 static CharDriverState
*qemu_chr_open_udp(const char *def
)
3103 CharDriverState
*chr
= NULL
;
3104 NetCharDriver
*s
= NULL
;
3106 struct sockaddr_in saddr
;
3108 chr
= qemu_mallocz(sizeof(CharDriverState
));
3111 s
= qemu_mallocz(sizeof(NetCharDriver
));
3115 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3117 perror("socket(PF_INET, SOCK_DGRAM)");
3121 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
3122 printf("Could not parse: %s\n", def
);
3126 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
3136 chr
->chr_write
= udp_chr_write
;
3137 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3150 /***********************************************************/
3151 /* TCP Net console */
3162 static void tcp_chr_accept(void *opaque
);
3164 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3166 TCPCharDriver
*s
= chr
->opaque
;
3168 return send_all(s
->fd
, buf
, len
);
3170 /* XXX: indicate an error ? */
3175 static int tcp_chr_read_poll(void *opaque
)
3177 CharDriverState
*chr
= opaque
;
3178 TCPCharDriver
*s
= chr
->opaque
;
3181 s
->max_size
= qemu_chr_can_read(chr
);
3186 #define IAC_BREAK 243
3187 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3189 uint8_t *buf
, int *size
)
3191 /* Handle any telnet client's basic IAC options to satisfy char by
3192 * char mode with no echo. All IAC options will be removed from
3193 * the buf and the do_telnetopt variable will be used to track the
3194 * state of the width of the IAC information.
3196 * IAC commands come in sets of 3 bytes with the exception of the
3197 * "IAC BREAK" command and the double IAC.
3203 for (i
= 0; i
< *size
; i
++) {
3204 if (s
->do_telnetopt
> 1) {
3205 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3206 /* Double IAC means send an IAC */
3210 s
->do_telnetopt
= 1;
3212 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3213 /* Handle IAC break commands by sending a serial break */
3214 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3219 if (s
->do_telnetopt
>= 4) {
3220 s
->do_telnetopt
= 1;
3223 if ((unsigned char)buf
[i
] == IAC
) {
3224 s
->do_telnetopt
= 2;
3235 static void tcp_chr_read(void *opaque
)
3237 CharDriverState
*chr
= opaque
;
3238 TCPCharDriver
*s
= chr
->opaque
;
3242 if (!s
->connected
|| s
->max_size
<= 0)
3245 if (len
> s
->max_size
)
3247 size
= recv(s
->fd
, buf
, len
, 0);
3249 /* connection closed */
3251 if (s
->listen_fd
>= 0) {
3252 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3254 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3257 } else if (size
> 0) {
3258 if (s
->do_telnetopt
)
3259 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3261 qemu_chr_read(chr
, buf
, size
);
3265 static void tcp_chr_connect(void *opaque
)
3267 CharDriverState
*chr
= opaque
;
3268 TCPCharDriver
*s
= chr
->opaque
;
3271 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3272 tcp_chr_read
, NULL
, chr
);
3273 qemu_chr_reset(chr
);
3276 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3277 static void tcp_chr_telnet_init(int fd
)
3280 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3281 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3282 send(fd
, (char *)buf
, 3, 0);
3283 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3284 send(fd
, (char *)buf
, 3, 0);
3285 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3286 send(fd
, (char *)buf
, 3, 0);
3287 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3288 send(fd
, (char *)buf
, 3, 0);
3291 static void socket_set_nodelay(int fd
)
3294 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3297 static void tcp_chr_accept(void *opaque
)
3299 CharDriverState
*chr
= opaque
;
3300 TCPCharDriver
*s
= chr
->opaque
;
3301 struct sockaddr_in saddr
;
3303 struct sockaddr_un uaddr
;
3305 struct sockaddr
*addr
;
3312 len
= sizeof(uaddr
);
3313 addr
= (struct sockaddr
*)&uaddr
;
3317 len
= sizeof(saddr
);
3318 addr
= (struct sockaddr
*)&saddr
;
3320 fd
= accept(s
->listen_fd
, addr
, &len
);
3321 if (fd
< 0 && errno
!= EINTR
) {
3323 } else if (fd
>= 0) {
3324 if (s
->do_telnetopt
)
3325 tcp_chr_telnet_init(fd
);
3329 socket_set_nonblock(fd
);
3331 socket_set_nodelay(fd
);
3333 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3334 tcp_chr_connect(chr
);
3337 static void tcp_chr_close(CharDriverState
*chr
)
3339 TCPCharDriver
*s
= chr
->opaque
;
3342 if (s
->listen_fd
>= 0)
3343 closesocket(s
->listen_fd
);
3347 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3351 CharDriverState
*chr
= NULL
;
3352 TCPCharDriver
*s
= NULL
;
3353 int fd
= -1, ret
, err
, val
;
3355 int is_waitconnect
= 1;
3358 struct sockaddr_in saddr
;
3360 struct sockaddr_un uaddr
;
3362 struct sockaddr
*addr
;
3367 addr
= (struct sockaddr
*)&uaddr
;
3368 addrlen
= sizeof(uaddr
);
3369 if (parse_unix_path(&uaddr
, host_str
) < 0)
3374 addr
= (struct sockaddr
*)&saddr
;
3375 addrlen
= sizeof(saddr
);
3376 if (parse_host_port(&saddr
, host_str
) < 0)
3381 while((ptr
= strchr(ptr
,','))) {
3383 if (!strncmp(ptr
,"server",6)) {
3385 } else if (!strncmp(ptr
,"nowait",6)) {
3387 } else if (!strncmp(ptr
,"nodelay",6)) {
3390 printf("Unknown option: %s\n", ptr
);
3397 chr
= qemu_mallocz(sizeof(CharDriverState
));
3400 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3406 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3409 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3414 if (!is_waitconnect
)
3415 socket_set_nonblock(fd
);
3420 s
->is_unix
= is_unix
;
3421 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3424 chr
->chr_write
= tcp_chr_write
;
3425 chr
->chr_close
= tcp_chr_close
;
3428 /* allow fast reuse */
3432 strncpy(path
, uaddr
.sun_path
, 108);
3439 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3442 ret
= bind(fd
, addr
, addrlen
);
3446 ret
= listen(fd
, 0);
3451 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3453 s
->do_telnetopt
= 1;
3456 ret
= connect(fd
, addr
, addrlen
);
3458 err
= socket_error();
3459 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3460 } else if (err
== EINPROGRESS
) {
3463 } else if (err
== WSAEALREADY
) {
3475 socket_set_nodelay(fd
);
3477 tcp_chr_connect(chr
);
3479 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3482 if (is_listen
&& is_waitconnect
) {
3483 printf("QEMU waiting for connection on: %s\n", host_str
);
3484 tcp_chr_accept(chr
);
3485 socket_set_nonblock(s
->listen_fd
);
3497 CharDriverState
*qemu_chr_open(const char *filename
)
3501 if (!strcmp(filename
, "vc")) {
3502 return text_console_init(&display_state
, 0);
3503 } else if (strstart(filename
, "vc:", &p
)) {
3504 return text_console_init(&display_state
, p
);
3505 } else if (!strcmp(filename
, "null")) {
3506 return qemu_chr_open_null();
3508 if (strstart(filename
, "tcp:", &p
)) {
3509 return qemu_chr_open_tcp(p
, 0, 0);
3511 if (strstart(filename
, "telnet:", &p
)) {
3512 return qemu_chr_open_tcp(p
, 1, 0);
3514 if (strstart(filename
, "udp:", &p
)) {
3515 return qemu_chr_open_udp(p
);
3517 if (strstart(filename
, "mon:", &p
)) {
3518 CharDriverState
*drv
= qemu_chr_open(p
);
3520 drv
= qemu_chr_open_mux(drv
);
3521 monitor_init(drv
, !nographic
);
3524 printf("Unable to open driver: %s\n", p
);
3528 if (strstart(filename
, "unix:", &p
)) {
3529 return qemu_chr_open_tcp(p
, 0, 1);
3530 } else if (strstart(filename
, "file:", &p
)) {
3531 return qemu_chr_open_file_out(p
);
3532 } else if (strstart(filename
, "pipe:", &p
)) {
3533 return qemu_chr_open_pipe(p
);
3534 } else if (!strcmp(filename
, "pty")) {
3535 return qemu_chr_open_pty();
3536 } else if (!strcmp(filename
, "stdio")) {
3537 return qemu_chr_open_stdio();
3539 #if defined(__linux__)
3540 if (strstart(filename
, "/dev/parport", NULL
)) {
3541 return qemu_chr_open_pp(filename
);
3544 #if defined(__linux__) || defined(__sun__)
3545 if (strstart(filename
, "/dev/", NULL
)) {
3546 return qemu_chr_open_tty(filename
);
3550 if (strstart(filename
, "COM", NULL
)) {
3551 return qemu_chr_open_win(filename
);
3553 if (strstart(filename
, "pipe:", &p
)) {
3554 return qemu_chr_open_win_pipe(p
);
3556 if (strstart(filename
, "con:", NULL
)) {
3557 return qemu_chr_open_win_con(filename
);
3559 if (strstart(filename
, "file:", &p
)) {
3560 return qemu_chr_open_win_file_out(p
);
3563 #ifdef CONFIG_BRLAPI
3564 if (!strcmp(filename
, "braille")) {
3565 return chr_baum_init();
3573 void qemu_chr_close(CharDriverState
*chr
)
3576 chr
->chr_close(chr
);
3580 /***********************************************************/
3581 /* network device redirectors */
3583 __attribute__ (( unused
))
3584 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3588 for(i
=0;i
<size
;i
+=16) {
3592 fprintf(f
, "%08x ", i
);
3595 fprintf(f
, " %02x", buf
[i
+j
]);
3600 for(j
=0;j
<len
;j
++) {
3602 if (c
< ' ' || c
> '~')
3604 fprintf(f
, "%c", c
);
3610 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3617 offset
= strtol(p
, &last_char
, 0);
3618 if (0 == errno
&& '\0' == *last_char
&&
3619 offset
>= 0 && offset
<= 0xFFFFFF) {
3620 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3621 macaddr
[4] = (offset
& 0xFF00) >> 8;
3622 macaddr
[5] = offset
& 0xFF;
3625 for(i
= 0; i
< 6; i
++) {
3626 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3631 if (*p
!= ':' && *p
!= '-')
3642 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3647 p1
= strchr(p
, sep
);
3653 if (len
> buf_size
- 1)
3655 memcpy(buf
, p
, len
);
3662 int parse_host_src_port(struct sockaddr_in
*haddr
,
3663 struct sockaddr_in
*saddr
,
3664 const char *input_str
)
3666 char *str
= strdup(input_str
);
3667 char *host_str
= str
;
3672 * Chop off any extra arguments at the end of the string which
3673 * would start with a comma, then fill in the src port information
3674 * if it was provided else use the "any address" and "any port".
3676 if ((ptr
= strchr(str
,',')))
3679 if ((src_str
= strchr(input_str
,'@'))) {
3684 if (parse_host_port(haddr
, host_str
) < 0)
3687 if (!src_str
|| *src_str
== '\0')
3690 if (parse_host_port(saddr
, src_str
) < 0)
3701 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3709 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3711 saddr
->sin_family
= AF_INET
;
3712 if (buf
[0] == '\0') {
3713 saddr
->sin_addr
.s_addr
= 0;
3715 if (isdigit(buf
[0])) {
3716 if (!inet_aton(buf
, &saddr
->sin_addr
))
3719 if ((he
= gethostbyname(buf
)) == NULL
)
3721 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3724 port
= strtol(p
, (char **)&r
, 0);
3727 saddr
->sin_port
= htons(port
);
3732 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3737 len
= MIN(108, strlen(str
));
3738 p
= strchr(str
, ',');
3740 len
= MIN(len
, p
- str
);
3742 memset(uaddr
, 0, sizeof(*uaddr
));
3744 uaddr
->sun_family
= AF_UNIX
;
3745 memcpy(uaddr
->sun_path
, str
, len
);
3751 /* find or alloc a new VLAN */
3752 VLANState
*qemu_find_vlan(int id
)
3754 VLANState
**pvlan
, *vlan
;
3755 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3759 vlan
= qemu_mallocz(sizeof(VLANState
));
3764 pvlan
= &first_vlan
;
3765 while (*pvlan
!= NULL
)
3766 pvlan
= &(*pvlan
)->next
;
3771 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3772 IOReadHandler
*fd_read
,
3773 IOCanRWHandler
*fd_can_read
,
3776 VLANClientState
*vc
, **pvc
;
3777 vc
= qemu_mallocz(sizeof(VLANClientState
));
3780 vc
->fd_read
= fd_read
;
3781 vc
->fd_can_read
= fd_can_read
;
3782 vc
->opaque
= opaque
;
3786 pvc
= &vlan
->first_client
;
3787 while (*pvc
!= NULL
)
3788 pvc
= &(*pvc
)->next
;
3793 int qemu_can_send_packet(VLANClientState
*vc1
)
3795 VLANState
*vlan
= vc1
->vlan
;
3796 VLANClientState
*vc
;
3798 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3800 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
3807 int qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3809 VLANState
*vlan
= vc1
->vlan
;
3810 VLANClientState
*vc
;
3814 printf("vlan %d send:\n", vlan
->id
);
3815 hex_dump(stdout
, buf
, size
);
3817 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3819 if (!vc
->fd_can_read
|| vc
->fd_can_read(vc
->opaque
)) {
3820 vc
->fd_read(vc
->opaque
, buf
, size
);
3829 static ssize_t
vc_sendv_compat(VLANClientState
*vc
, const struct iovec
*iov
,
3836 for (i
= 0; i
< iovcnt
; i
++) {
3839 len
= MIN(sizeof(buffer
) - offset
, iov
[i
].iov_len
);
3840 memcpy(buffer
+ offset
, iov
[i
].iov_base
, len
);
3844 vc
->fd_read(vc
->opaque
, buffer
, offset
);
3849 ssize_t
qemu_sendv_packet(VLANClientState
*vc1
, const struct iovec
*iov
,
3852 VLANState
*vlan
= vc1
->vlan
;
3853 VLANClientState
*vc
;
3854 ssize_t max_len
= 0;
3856 for (vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3863 len
= vc
->fd_readv(vc
->opaque
, iov
, iovcnt
);
3864 else if (vc
->fd_read
)
3865 len
= vc_sendv_compat(vc
, iov
, iovcnt
);
3867 max_len
= MAX(max_len
, len
);
3873 #if defined(CONFIG_SLIRP)
3875 /* slirp network adapter */
3877 static int slirp_inited
;
3878 static VLANClientState
*slirp_vc
;
3880 int slirp_can_output(void)
3882 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3885 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3888 printf("slirp output:\n");
3889 hex_dump(stdout
, pkt
, pkt_len
);
3893 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3896 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3899 printf("slirp input:\n");
3900 hex_dump(stdout
, buf
, size
);
3902 slirp_input(buf
, size
);
3905 static int net_slirp_init(VLANState
*vlan
)
3907 if (!slirp_inited
) {
3911 slirp_vc
= qemu_new_vlan_client(vlan
,
3912 slirp_receive
, NULL
, NULL
);
3913 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3917 static void net_slirp_redir(const char *redir_str
)
3922 struct in_addr guest_addr
;
3923 int host_port
, guest_port
;
3925 if (!slirp_inited
) {
3931 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3933 if (!strcmp(buf
, "tcp")) {
3935 } else if (!strcmp(buf
, "udp")) {
3941 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3943 host_port
= strtol(buf
, &r
, 0);
3947 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3949 if (buf
[0] == '\0') {
3950 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3952 if (!inet_aton(buf
, &guest_addr
))
3955 guest_port
= strtol(p
, &r
, 0);
3959 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3960 fprintf(stderr
, "qemu: could not set up redirection\n");
3965 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3973 static void erase_dir(char *dir_name
)
3977 char filename
[1024];
3979 /* erase all the files in the directory */
3980 if ((d
= opendir(dir_name
)) != 0) {
3985 if (strcmp(de
->d_name
, ".") != 0 &&
3986 strcmp(de
->d_name
, "..") != 0) {
3987 snprintf(filename
, sizeof(filename
), "%s/%s",
3988 smb_dir
, de
->d_name
);
3989 if (unlink(filename
) != 0) /* is it a directory? */
3990 erase_dir(filename
);
3998 /* automatic user mode samba server configuration */
3999 static void smb_exit(void)
4004 /* automatic user mode samba server configuration */
4005 static void net_slirp_smb(const char *exported_dir
)
4007 char smb_conf
[1024];
4008 char smb_cmdline
[1024];
4011 if (!slirp_inited
) {
4016 /* XXX: better tmp dir construction */
4017 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
4018 if (mkdir(smb_dir
, 0700) < 0) {
4019 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
4022 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
4024 f
= fopen(smb_conf
, "w");
4026 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
4033 "socket address=127.0.0.1\n"
4034 "pid directory=%s\n"
4035 "lock directory=%s\n"
4036 "log file=%s/log.smbd\n"
4037 "smb passwd file=%s/smbpasswd\n"
4038 "security = share\n"
4053 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4054 SMBD_COMMAND
, smb_conf
);
4056 slirp_add_exec(0, smb_cmdline
, 4, 139);
4059 #endif /* !defined(_WIN32) */
4060 void do_info_slirp(void)
4065 #endif /* CONFIG_SLIRP */
4067 #if !defined(_WIN32)
4069 typedef struct TAPState
{
4070 VLANClientState
*vc
;
4072 char down_script
[1024];
4077 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4079 TAPState
*s
= opaque
;
4082 ret
= write(s
->fd
, buf
, size
);
4083 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4090 static ssize_t
tap_readv(void *opaque
, const struct iovec
*iov
,
4093 TAPState
*s
= opaque
;
4097 len
= writev(s
->fd
, iov
, iovcnt
);
4098 } while (len
== -1 && (errno
== EINTR
|| errno
== EAGAIN
));
4103 static int tap_can_send(void *opaque
)
4105 TAPState
*s
= opaque
;
4106 VLANClientState
*vc
;
4107 int can_receive
= 0;
4109 /* Check to see if any of our clients can receive a packet */
4110 for (vc
= s
->vc
->vlan
->first_client
; vc
; vc
= vc
->next
) {
4111 /* Skip ourselves */
4115 if (!vc
->fd_can_read
) {
4116 /* no fd_can_read handler, they always can receive */
4119 can_receive
= vc
->fd_can_read(vc
->opaque
);
4121 /* Once someone can receive, we try to send a packet */
4129 static void tap_send(void *opaque
)
4131 TAPState
*s
= opaque
;
4133 /* First try to send any buffered packet */
4137 /* If noone can receive the packet, buffer it */
4138 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4143 /* Read packets until we hit EAGAIN */
4148 sbuf
.maxlen
= sizeof(s
->buf
);
4150 s
->size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4152 s
->size
= read(s
->fd
, s
->buf
, sizeof(s
->buf
));
4155 if (s
->size
== -1 && errno
== EINTR
)
4161 /* If noone can receive the packet, buffer it */
4162 err
= qemu_send_packet(s
->vc
, s
->buf
, s
->size
);
4166 } while (s
->size
> 0);
4171 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4175 s
= qemu_mallocz(sizeof(TAPState
));
4179 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4180 s
->vc
->fd_readv
= tap_readv
;
4181 qemu_set_fd_handler2(s
->fd
, tap_can_send
, tap_send
, NULL
, s
);
4182 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4186 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4187 static int tap_open(char *ifname
, int ifname_size
)
4193 TFR(fd
= open("/dev/tap", O_RDWR
));
4195 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4200 dev
= devname(s
.st_rdev
, S_IFCHR
);
4201 pstrcpy(ifname
, ifname_size
, dev
);
4203 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4206 #elif defined(__sun__)
4207 #define TUNNEWPPA (('T'<<16) | 0x0001)
4209 * Allocate TAP device, returns opened fd.
4210 * Stores dev name in the first arg(must be large enough).
4212 int tap_alloc(char *dev
)
4214 int tap_fd
, if_fd
, ppa
= -1;
4215 static int ip_fd
= 0;
4218 static int arp_fd
= 0;
4219 int ip_muxid
, arp_muxid
;
4220 struct strioctl strioc_if
, strioc_ppa
;
4221 int link_type
= I_PLINK
;;
4223 char actual_name
[32] = "";
4225 memset(&ifr
, 0x0, sizeof(ifr
));
4229 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4233 /* Check if IP device was opened */
4237 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4239 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4243 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4245 syslog(LOG_ERR
, "Can't open /dev/tap");
4249 /* Assign a new PPA and get its unit number. */
4250 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4251 strioc_ppa
.ic_timout
= 0;
4252 strioc_ppa
.ic_len
= sizeof(ppa
);
4253 strioc_ppa
.ic_dp
= (char *)&ppa
;
4254 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4255 syslog (LOG_ERR
, "Can't assign new interface");
4257 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4259 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4262 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4263 syslog(LOG_ERR
, "Can't push IP module");
4267 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4268 syslog(LOG_ERR
, "Can't get flags\n");
4270 snprintf (actual_name
, 32, "tap%d", ppa
);
4271 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4274 /* Assign ppa according to the unit number returned by tun device */
4276 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4277 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4278 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4279 syslog (LOG_ERR
, "Can't get flags\n");
4280 /* Push arp module to if_fd */
4281 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4282 syslog (LOG_ERR
, "Can't push ARP module (2)");
4284 /* Push arp module to ip_fd */
4285 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4286 syslog (LOG_ERR
, "I_POP failed\n");
4287 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4288 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4290 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4292 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4294 /* Set ifname to arp */
4295 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4296 strioc_if
.ic_timout
= 0;
4297 strioc_if
.ic_len
= sizeof(ifr
);
4298 strioc_if
.ic_dp
= (char *)&ifr
;
4299 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4300 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4303 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4304 syslog(LOG_ERR
, "Can't link TAP device to IP");
4308 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4309 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4313 memset(&ifr
, 0x0, sizeof(ifr
));
4314 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4315 ifr
.lifr_ip_muxid
= ip_muxid
;
4316 ifr
.lifr_arp_muxid
= arp_muxid
;
4318 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4320 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4321 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4322 syslog (LOG_ERR
, "Can't set multiplexor id");
4325 sprintf(dev
, "tap%d", ppa
);
4329 static int tap_open(char *ifname
, int ifname_size
)
4333 if( (fd
= tap_alloc(dev
)) < 0 ){
4334 fprintf(stderr
, "Cannot allocate TAP device\n");
4337 pstrcpy(ifname
, ifname_size
, dev
);
4338 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4342 static int tap_open(char *ifname
, int ifname_size
)
4347 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4349 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4352 memset(&ifr
, 0, sizeof(ifr
));
4353 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4354 if (ifname
[0] != '\0')
4355 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4357 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4358 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4360 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4364 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4365 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4370 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4376 /* try to launch network script */
4380 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4381 for (i
= 0; i
< open_max
; i
++)
4382 if (i
!= STDIN_FILENO
&&
4383 i
!= STDOUT_FILENO
&&
4384 i
!= STDERR_FILENO
&&
4389 *parg
++ = (char *)setup_script
;
4390 *parg
++ = (char *)ifname
;
4392 execv(setup_script
, args
);
4395 while (waitpid(pid
, &status
, 0) != pid
);
4396 if (!WIFEXITED(status
) ||
4397 WEXITSTATUS(status
) != 0) {
4398 fprintf(stderr
, "%s: could not launch network script\n",
4406 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4407 const char *setup_script
, const char *down_script
)
4413 if (ifname1
!= NULL
)
4414 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4417 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4421 if (!setup_script
|| !strcmp(setup_script
, "no"))
4423 if (setup_script
[0] != '\0') {
4424 if (launch_script(setup_script
, ifname
, fd
))
4427 s
= net_tap_fd_init(vlan
, fd
);
4430 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4431 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4432 if (down_script
&& strcmp(down_script
, "no"))
4433 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4437 #endif /* !_WIN32 */
4439 /* network connection */
4440 typedef struct NetSocketState
{
4441 VLANClientState
*vc
;
4443 int state
; /* 0 = getting length, 1 = getting data */
4447 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4450 typedef struct NetSocketListenState
{
4453 } NetSocketListenState
;
4455 /* XXX: we consider we can send the whole packet without blocking */
4456 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4458 NetSocketState
*s
= opaque
;
4462 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4463 send_all(s
->fd
, buf
, size
);
4466 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4468 NetSocketState
*s
= opaque
;
4469 sendto(s
->fd
, buf
, size
, 0,
4470 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4473 static void net_socket_send(void *opaque
)
4475 NetSocketState
*s
= opaque
;
4480 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4482 err
= socket_error();
4483 if (err
!= EWOULDBLOCK
)
4485 } else if (size
== 0) {
4486 /* end of connection */
4488 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4494 /* reassemble a packet from the network */
4500 memcpy(s
->buf
+ s
->index
, buf
, l
);
4504 if (s
->index
== 4) {
4506 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4512 l
= s
->packet_len
- s
->index
;
4515 memcpy(s
->buf
+ s
->index
, buf
, l
);
4519 if (s
->index
>= s
->packet_len
) {
4520 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4529 static void net_socket_send_dgram(void *opaque
)
4531 NetSocketState
*s
= opaque
;
4534 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4538 /* end of connection */
4539 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4542 qemu_send_packet(s
->vc
, s
->buf
, size
);
4545 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4550 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4551 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4552 inet_ntoa(mcastaddr
->sin_addr
),
4553 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4557 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4559 perror("socket(PF_INET, SOCK_DGRAM)");
4564 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4565 (const char *)&val
, sizeof(val
));
4567 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4571 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4577 /* Add host to multicast group */
4578 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4579 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4581 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4582 (const char *)&imr
, sizeof(struct ip_mreq
));
4584 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4588 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4590 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4591 (const char *)&val
, sizeof(val
));
4593 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4597 socket_set_nonblock(fd
);
4605 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4608 struct sockaddr_in saddr
;
4610 socklen_t saddr_len
;
4613 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4614 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4615 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4619 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4621 if (saddr
.sin_addr
.s_addr
==0) {
4622 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4626 /* clone dgram socket */
4627 newfd
= net_socket_mcast_create(&saddr
);
4629 /* error already reported by net_socket_mcast_create() */
4633 /* clone newfd to fd, close newfd */
4638 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4639 fd
, strerror(errno
));
4644 s
= qemu_mallocz(sizeof(NetSocketState
));
4649 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4650 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4652 /* mcast: save bound address as dst */
4653 if (is_connected
) s
->dgram_dst
=saddr
;
4655 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4656 "socket: fd=%d (%s mcast=%s:%d)",
4657 fd
, is_connected
? "cloned" : "",
4658 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4662 static void net_socket_connect(void *opaque
)
4664 NetSocketState
*s
= opaque
;
4665 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4668 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4672 s
= qemu_mallocz(sizeof(NetSocketState
));
4676 s
->vc
= qemu_new_vlan_client(vlan
,
4677 net_socket_receive
, NULL
, s
);
4678 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4679 "socket: fd=%d", fd
);
4681 net_socket_connect(s
);
4683 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4688 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4691 int so_type
=-1, optlen
=sizeof(so_type
);
4693 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4694 (socklen_t
*)&optlen
)< 0) {
4695 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4700 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4702 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4704 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4705 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4706 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4711 static void net_socket_accept(void *opaque
)
4713 NetSocketListenState
*s
= opaque
;
4715 struct sockaddr_in saddr
;
4720 len
= sizeof(saddr
);
4721 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4722 if (fd
< 0 && errno
!= EINTR
) {
4724 } else if (fd
>= 0) {
4728 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4732 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4733 "socket: connection from %s:%d",
4734 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4738 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4740 NetSocketListenState
*s
;
4742 struct sockaddr_in saddr
;
4744 if (parse_host_port(&saddr
, host_str
) < 0)
4747 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4751 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4756 socket_set_nonblock(fd
);
4758 /* allow fast reuse */
4760 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4762 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4767 ret
= listen(fd
, 0);
4774 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4778 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4781 int fd
, connected
, ret
, err
;
4782 struct sockaddr_in saddr
;
4784 if (parse_host_port(&saddr
, host_str
) < 0)
4787 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4792 socket_set_nonblock(fd
);
4796 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4798 err
= socket_error();
4799 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4800 } else if (err
== EINPROGRESS
) {
4803 } else if (err
== WSAEALREADY
) {
4816 s
= net_socket_fd_init(vlan
, fd
, connected
);
4819 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4820 "socket: connect to %s:%d",
4821 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4825 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4829 struct sockaddr_in saddr
;
4831 if (parse_host_port(&saddr
, host_str
) < 0)
4835 fd
= net_socket_mcast_create(&saddr
);
4839 s
= net_socket_fd_init(vlan
, fd
, 0);
4843 s
->dgram_dst
= saddr
;
4845 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4846 "socket: mcast=%s:%d",
4847 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4852 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
4857 while (*p
!= '\0' && *p
!= '=') {
4858 if (q
&& (q
- buf
) < buf_size
- 1)
4868 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
4873 while (*p
!= '\0') {
4875 if (*(p
+ 1) != ',')
4879 if (q
&& (q
- buf
) < buf_size
- 1)
4889 int get_param_value(char *buf
, int buf_size
,
4890 const char *tag
, const char *str
)
4897 p
= get_opt_name(option
, sizeof(option
), p
);
4901 if (!strcmp(tag
, option
)) {
4902 (void)get_opt_value(buf
, buf_size
, p
);
4905 p
= get_opt_value(NULL
, 0, p
);
4914 int check_params(char *buf
, int buf_size
,
4915 char **params
, const char *str
)
4922 p
= get_opt_name(buf
, buf_size
, p
);
4926 for(i
= 0; params
[i
] != NULL
; i
++)
4927 if (!strcmp(params
[i
], buf
))
4929 if (params
[i
] == NULL
)
4931 p
= get_opt_value(NULL
, 0, p
);
4939 static int nic_get_free_idx(void)
4943 for (index
= 0; index
< MAX_NICS
; index
++)
4944 if (!nd_table
[index
].used
)
4949 int net_client_init(const char *str
)
4960 while (*p
!= '\0' && *p
!= ',') {
4961 if ((q
- device
) < sizeof(device
) - 1)
4969 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4970 vlan_id
= strtol(buf
, NULL
, 0);
4972 vlan
= qemu_find_vlan(vlan_id
);
4974 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4977 if (!strcmp(device
, "nic")) {
4980 int idx
= nic_get_free_idx();
4982 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
4983 fprintf(stderr
, "Too Many NICs\n");
4986 nd
= &nd_table
[idx
];
4987 macaddr
= nd
->macaddr
;
4993 macaddr
[5] = 0x56 + idx
;
4995 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4996 if (parse_macaddr(macaddr
, buf
) < 0) {
4997 fprintf(stderr
, "invalid syntax for ethernet address\n");
5001 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
5002 nd
->model
= strdup(buf
);
5007 vlan
->nb_guest_devs
++;
5010 if (!strcmp(device
, "none")) {
5011 /* does nothing. It is needed to signal that no network cards
5016 if (!strcmp(device
, "user")) {
5017 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
5018 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
5020 vlan
->nb_host_devs
++;
5021 ret
= net_slirp_init(vlan
);
5025 if (!strcmp(device
, "tap")) {
5027 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5028 fprintf(stderr
, "tap: no interface name\n");
5031 vlan
->nb_host_devs
++;
5032 ret
= tap_win32_init(vlan
, ifname
);
5035 if (!strcmp(device
, "tap")) {
5037 char setup_script
[1024], down_script
[1024];
5039 vlan
->nb_host_devs
++;
5040 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5041 fd
= strtol(buf
, NULL
, 0);
5042 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
5044 if (net_tap_fd_init(vlan
, fd
))
5047 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
5050 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
5051 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
5053 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
5054 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
5056 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
5060 if (!strcmp(device
, "socket")) {
5061 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
5063 fd
= strtol(buf
, NULL
, 0);
5065 if (net_socket_fd_init(vlan
, fd
, 1))
5067 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
5068 ret
= net_socket_listen_init(vlan
, buf
);
5069 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
5070 ret
= net_socket_connect_init(vlan
, buf
);
5071 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
5072 ret
= net_socket_mcast_init(vlan
, buf
);
5074 fprintf(stderr
, "Unknown socket options: %s\n", p
);
5077 vlan
->nb_host_devs
++;
5080 fprintf(stderr
, "Unknown network device: %s\n", device
);
5084 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5090 void net_client_uninit(NICInfo
*nd
)
5092 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5095 free((void *)nd
->model
);
5098 void do_info_network(void)
5101 VLANClientState
*vc
;
5103 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5104 term_printf("VLAN %d devices:\n", vlan
->id
);
5105 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5106 term_printf(" %s\n", vc
->info_str
);
5110 #define HD_ALIAS "index=%d,media=disk"
5112 #define CDROM_ALIAS "index=1,media=cdrom"
5114 #define CDROM_ALIAS "index=2,media=cdrom"
5116 #define FD_ALIAS "index=%d,if=floppy"
5117 #define PFLASH_ALIAS "if=pflash"
5118 #define MTD_ALIAS "if=mtd"
5119 #define SD_ALIAS "index=0,if=sd"
5121 static int drive_opt_get_free_idx(void)
5125 for (index
= 0; index
< MAX_DRIVES
; index
++)
5126 if (!drives_opt
[index
].used
) {
5127 drives_opt
[index
].used
= 1;
5134 static int drive_get_free_idx(void)
5138 for (index
= 0; index
< MAX_DRIVES
; index
++)
5139 if (!drives_table
[index
].used
) {
5140 drives_table
[index
].used
= 1;
5147 int drive_add(const char *file
, const char *fmt
, ...)
5150 int index
= drive_opt_get_free_idx();
5152 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5153 fprintf(stderr
, "qemu: too many drives\n");
5157 drives_opt
[index
].file
= file
;
5159 vsnprintf(drives_opt
[index
].opt
,
5160 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5167 void drive_remove(int index
)
5169 drives_opt
[index
].used
= 0;
5173 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5177 /* seek interface, bus and unit */
5179 for (index
= 0; index
< MAX_DRIVES
; index
++)
5180 if (drives_table
[index
].type
== type
&&
5181 drives_table
[index
].bus
== bus
&&
5182 drives_table
[index
].unit
== unit
&&
5183 drives_table
[index
].used
)
5189 int drive_get_max_bus(BlockInterfaceType type
)
5195 for (index
= 0; index
< nb_drives
; index
++) {
5196 if(drives_table
[index
].type
== type
&&
5197 drives_table
[index
].bus
> max_bus
)
5198 max_bus
= drives_table
[index
].bus
;
5203 static void bdrv_format_print(void *opaque
, const char *name
)
5205 fprintf(stderr
, " %s", name
);
5208 void drive_uninit(BlockDriverState
*bdrv
)
5212 for (i
= 0; i
< MAX_DRIVES
; i
++)
5213 if (drives_table
[i
].bdrv
== bdrv
) {
5214 drives_table
[i
].bdrv
= NULL
;
5215 drives_table
[i
].used
= 0;
5216 drive_remove(drives_table
[i
].drive_opt_idx
);
5222 int drive_init(struct drive_opt
*arg
, int snapshot
,
5223 QEMUMachine
*machine
)
5228 const char *mediastr
= "";
5229 BlockInterfaceType type
;
5230 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5231 int bus_id
, unit_id
;
5232 int cyls
, heads
, secs
, translation
;
5233 BlockDriverState
*bdrv
;
5234 BlockDriver
*drv
= NULL
;
5239 int drives_table_idx
;
5240 char *str
= arg
->opt
;
5241 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5242 "secs", "trans", "media", "snapshot", "file",
5243 "cache", "format", "boot", NULL
};
5245 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5246 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5252 cyls
= heads
= secs
= 0;
5255 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5259 if (!strcmp(machine
->name
, "realview") ||
5260 !strcmp(machine
->name
, "SS-5") ||
5261 !strcmp(machine
->name
, "SS-10") ||
5262 !strcmp(machine
->name
, "SS-600MP") ||
5263 !strcmp(machine
->name
, "versatilepb") ||
5264 !strcmp(machine
->name
, "versatileab")) {
5266 max_devs
= MAX_SCSI_DEVS
;
5267 strcpy(devname
, "scsi");
5270 max_devs
= MAX_IDE_DEVS
;
5271 strcpy(devname
, "ide");
5275 /* extract parameters */
5277 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5278 bus_id
= strtol(buf
, NULL
, 0);
5280 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5285 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5286 unit_id
= strtol(buf
, NULL
, 0);
5288 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5293 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5294 strncpy(devname
, buf
, sizeof(devname
));
5295 if (!strcmp(buf
, "ide")) {
5297 max_devs
= MAX_IDE_DEVS
;
5298 } else if (!strcmp(buf
, "scsi")) {
5300 max_devs
= MAX_SCSI_DEVS
;
5301 } else if (!strcmp(buf
, "floppy")) {
5304 } else if (!strcmp(buf
, "pflash")) {
5307 } else if (!strcmp(buf
, "mtd")) {
5310 } else if (!strcmp(buf
, "sd")) {
5313 } else if (!strcmp(buf
, "virtio")) {
5317 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5322 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5323 index
= strtol(buf
, NULL
, 0);
5325 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5330 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5331 cyls
= strtol(buf
, NULL
, 0);
5334 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5335 heads
= strtol(buf
, NULL
, 0);
5338 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5339 secs
= strtol(buf
, NULL
, 0);
5342 if (cyls
|| heads
|| secs
) {
5343 if (cyls
< 1 || cyls
> 16383) {
5344 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5347 if (heads
< 1 || heads
> 16) {
5348 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5351 if (secs
< 1 || secs
> 63) {
5352 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5357 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5360 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5364 if (!strcmp(buf
, "none"))
5365 translation
= BIOS_ATA_TRANSLATION_NONE
;
5366 else if (!strcmp(buf
, "lba"))
5367 translation
= BIOS_ATA_TRANSLATION_LBA
;
5368 else if (!strcmp(buf
, "auto"))
5369 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5371 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5376 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5377 if (!strcmp(buf
, "disk")) {
5379 } else if (!strcmp(buf
, "cdrom")) {
5380 if (cyls
|| secs
|| heads
) {
5382 "qemu: '%s' invalid physical CHS format\n", str
);
5385 media
= MEDIA_CDROM
;
5387 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5392 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5393 if (!strcmp(buf
, "on"))
5395 else if (!strcmp(buf
, "off"))
5398 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5403 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5404 if (!strcmp(buf
, "off"))
5406 else if (!strcmp(buf
, "on"))
5409 fprintf(stderr
, "qemu: invalid cache option\n");
5414 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5415 if (strcmp(buf
, "?") == 0) {
5416 fprintf(stderr
, "qemu: Supported formats:");
5417 bdrv_iterate_format(bdrv_format_print
, NULL
);
5418 fprintf(stderr
, "\n");
5421 drv
= bdrv_find_format(buf
);
5423 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5428 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5429 if (!strcmp(buf
, "on")) {
5430 if (extboot_drive
!= -1) {
5431 fprintf(stderr
, "qemu: two bootable drives specified\n");
5434 extboot_drive
= nb_drives
;
5435 } else if (strcmp(buf
, "off")) {
5436 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5441 if (arg
->file
== NULL
)
5442 get_param_value(file
, sizeof(file
), "file", str
);
5444 pstrcpy(file
, sizeof(file
), arg
->file
);
5446 /* compute bus and unit according index */
5449 if (bus_id
!= 0 || unit_id
!= -1) {
5451 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5459 unit_id
= index
% max_devs
;
5460 bus_id
= index
/ max_devs
;
5464 /* if user doesn't specify a unit_id,
5465 * try to find the first free
5468 if (unit_id
== -1) {
5470 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5472 if (max_devs
&& unit_id
>= max_devs
) {
5473 unit_id
-= max_devs
;
5481 if (max_devs
&& unit_id
>= max_devs
) {
5482 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5483 str
, unit_id
, max_devs
- 1);
5488 * ignore multiple definitions
5491 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5496 if (type
== IF_IDE
|| type
== IF_SCSI
)
5497 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5499 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5500 devname
, bus_id
, mediastr
, unit_id
);
5502 snprintf(buf
, sizeof(buf
), "%s%s%i",
5503 devname
, mediastr
, unit_id
);
5504 bdrv
= bdrv_new(buf
);
5505 drives_table_idx
= drive_get_free_idx();
5506 drives_table
[drives_table_idx
].bdrv
= bdrv
;
5507 drives_table
[drives_table_idx
].type
= type
;
5508 drives_table
[drives_table_idx
].bus
= bus_id
;
5509 drives_table
[drives_table_idx
].unit
= unit_id
;
5510 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
5519 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5520 bdrv_set_translation_hint(bdrv
, translation
);
5524 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5529 /* FIXME: This isn't really a floppy, but it's a reasonable
5532 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5543 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5545 bdrv_flags
|= BDRV_O_DIRECT
;
5546 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5547 fprintf(stderr
, "qemu: could not open disk image %s\n",
5551 return drives_table_idx
;
5554 /***********************************************************/
5557 static USBPort
*used_usb_ports
;
5558 static USBPort
*free_usb_ports
;
5560 /* ??? Maybe change this to register a hub to keep track of the topology. */
5561 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5562 usb_attachfn attach
)
5564 port
->opaque
= opaque
;
5565 port
->index
= index
;
5566 port
->attach
= attach
;
5567 port
->next
= free_usb_ports
;
5568 free_usb_ports
= port
;
5571 static int usb_device_add(const char *devname
)
5577 if (!free_usb_ports
)
5580 if (strstart(devname
, "host:", &p
)) {
5581 dev
= usb_host_device_open(p
);
5582 } else if (!strcmp(devname
, "mouse")) {
5583 dev
= usb_mouse_init();
5584 } else if (!strcmp(devname
, "tablet")) {
5585 dev
= usb_tablet_init();
5586 } else if (!strcmp(devname
, "keyboard")) {
5587 dev
= usb_keyboard_init();
5588 } else if (strstart(devname
, "disk:", &p
)) {
5589 dev
= usb_msd_init(p
);
5590 } else if (!strcmp(devname
, "wacom-tablet")) {
5591 dev
= usb_wacom_init();
5592 } else if (strstart(devname
, "serial:", &p
)) {
5593 dev
= usb_serial_init(p
);
5594 #ifdef CONFIG_BRLAPI
5595 } else if (!strcmp(devname
, "braille")) {
5596 dev
= usb_baum_init();
5604 /* Find a USB port to add the device to. */
5605 port
= free_usb_ports
;
5609 /* Create a new hub and chain it on. */
5610 free_usb_ports
= NULL
;
5611 port
->next
= used_usb_ports
;
5612 used_usb_ports
= port
;
5614 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5615 usb_attach(port
, hub
);
5616 port
= free_usb_ports
;
5619 free_usb_ports
= port
->next
;
5620 port
->next
= used_usb_ports
;
5621 used_usb_ports
= port
;
5622 usb_attach(port
, dev
);
5626 static int usb_device_del(const char *devname
)
5634 if (!used_usb_ports
)
5637 p
= strchr(devname
, '.');
5640 bus_num
= strtoul(devname
, NULL
, 0);
5641 addr
= strtoul(p
+ 1, NULL
, 0);
5645 lastp
= &used_usb_ports
;
5646 port
= used_usb_ports
;
5647 while (port
&& port
->dev
->addr
!= addr
) {
5648 lastp
= &port
->next
;
5656 *lastp
= port
->next
;
5657 usb_attach(port
, NULL
);
5658 dev
->handle_destroy(dev
);
5659 port
->next
= free_usb_ports
;
5660 free_usb_ports
= port
;
5664 void do_usb_add(const char *devname
)
5667 ret
= usb_device_add(devname
);
5669 term_printf("Could not add USB device '%s'\n", devname
);
5672 void do_usb_del(const char *devname
)
5675 ret
= usb_device_del(devname
);
5677 term_printf("Could not remove USB device '%s'\n", devname
);
5684 const char *speed_str
;
5687 term_printf("USB support not enabled\n");
5691 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5695 switch(dev
->speed
) {
5699 case USB_SPEED_FULL
:
5702 case USB_SPEED_HIGH
:
5709 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5710 0, dev
->addr
, speed_str
, dev
->devname
);
5714 /***********************************************************/
5715 /* PCMCIA/Cardbus */
5717 static struct pcmcia_socket_entry_s
{
5718 struct pcmcia_socket_s
*socket
;
5719 struct pcmcia_socket_entry_s
*next
;
5720 } *pcmcia_sockets
= 0;
5722 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5724 struct pcmcia_socket_entry_s
*entry
;
5726 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5727 entry
->socket
= socket
;
5728 entry
->next
= pcmcia_sockets
;
5729 pcmcia_sockets
= entry
;
5732 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5734 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5736 ptr
= &pcmcia_sockets
;
5737 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5738 if (entry
->socket
== socket
) {
5744 void pcmcia_info(void)
5746 struct pcmcia_socket_entry_s
*iter
;
5747 if (!pcmcia_sockets
)
5748 term_printf("No PCMCIA sockets\n");
5750 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5751 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5752 iter
->socket
->attached
? iter
->socket
->card_string
:
5756 /***********************************************************/
5759 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5763 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5767 static void dumb_refresh(DisplayState
*ds
)
5769 #if defined(CONFIG_SDL)
5774 static void dumb_display_init(DisplayState
*ds
)
5779 ds
->dpy_update
= dumb_update
;
5780 ds
->dpy_resize
= dumb_resize
;
5781 ds
->dpy_refresh
= dumb_refresh
;
5784 /***********************************************************/
5787 #define MAX_IO_HANDLERS 64
5789 typedef struct IOHandlerRecord
{
5791 IOCanRWHandler
*fd_read_poll
;
5793 IOHandler
*fd_write
;
5796 /* temporary data */
5798 struct IOHandlerRecord
*next
;
5801 static IOHandlerRecord
*first_io_handler
;
5803 /* XXX: fd_read_poll should be suppressed, but an API change is
5804 necessary in the character devices to suppress fd_can_read(). */
5805 int qemu_set_fd_handler2(int fd
,
5806 IOCanRWHandler
*fd_read_poll
,
5808 IOHandler
*fd_write
,
5811 IOHandlerRecord
**pioh
, *ioh
;
5813 if (!fd_read
&& !fd_write
) {
5814 pioh
= &first_io_handler
;
5819 if (ioh
->fd
== fd
) {
5826 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5830 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5833 ioh
->next
= first_io_handler
;
5834 first_io_handler
= ioh
;
5837 ioh
->fd_read_poll
= fd_read_poll
;
5838 ioh
->fd_read
= fd_read
;
5839 ioh
->fd_write
= fd_write
;
5840 ioh
->opaque
= opaque
;
5847 int qemu_set_fd_handler(int fd
,
5849 IOHandler
*fd_write
,
5852 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5855 /***********************************************************/
5856 /* Polling handling */
5858 typedef struct PollingEntry
{
5861 struct PollingEntry
*next
;
5864 static PollingEntry
*first_polling_entry
;
5866 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5868 PollingEntry
**ppe
, *pe
;
5869 pe
= qemu_mallocz(sizeof(PollingEntry
));
5873 pe
->opaque
= opaque
;
5874 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5879 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5881 PollingEntry
**ppe
, *pe
;
5882 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5884 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5893 /***********************************************************/
5894 /* Wait objects support */
5895 typedef struct WaitObjects
{
5897 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
5898 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
5899 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
5902 static WaitObjects wait_objects
= {0};
5904 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5906 WaitObjects
*w
= &wait_objects
;
5908 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
5910 w
->events
[w
->num
] = handle
;
5911 w
->func
[w
->num
] = func
;
5912 w
->opaque
[w
->num
] = opaque
;
5917 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5920 WaitObjects
*w
= &wait_objects
;
5923 for (i
= 0; i
< w
->num
; i
++) {
5924 if (w
->events
[i
] == handle
)
5927 w
->events
[i
] = w
->events
[i
+ 1];
5928 w
->func
[i
] = w
->func
[i
+ 1];
5929 w
->opaque
[i
] = w
->opaque
[i
+ 1];
5937 #define SELF_ANNOUNCE_ROUNDS 5
5938 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5939 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5940 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5942 static int announce_self_create(uint8_t *buf
,
5945 uint32_t magic
= EXPERIMENTAL_MAGIC
;
5946 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
5948 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5950 memset(buf
, 0xff, 6); /* h_dst */
5951 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
5952 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
5953 memcpy(buf
+ 14, &magic
, 4); /* magic */
5955 return 18; /* len */
5958 static void qemu_announce_self(void)
5962 VLANClientState
*vc
;
5965 for (i
= 0; i
< nb_nics
; i
++) {
5966 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
5967 vlan
= nd_table
[i
].vlan
;
5968 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
5969 if (vc
->fd_read
== tap_receive
) /* send only if tap */
5970 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
5971 vc
->fd_read(vc
->opaque
, buf
, len
);
5976 /***********************************************************/
5977 /* savevm/loadvm support */
5979 #define IO_BUF_SIZE 32768
5982 QEMUFilePutBufferFunc
*put_buffer
;
5983 QEMUFileGetBufferFunc
*get_buffer
;
5984 QEMUFileCloseFunc
*close
;
5987 int64_t buf_offset
; /* start of buffer when writing, end of buffer
5990 int buf_size
; /* 0 when writing */
5991 uint8_t buf
[IO_BUF_SIZE
];
5994 typedef struct QEMUFileFD
5999 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6001 QEMUFileFD
*s
= opaque
;
6006 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
6008 if (errno
== EINTR
|| errno
== EAGAIN
)
6015 QEMUFile
*qemu_fopen_fd(int fd
)
6017 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
6019 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
6022 typedef struct QEMUFileUnix
6027 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6029 QEMUFileUnix
*s
= opaque
;
6030 fseek(s
->outfile
, pos
, SEEK_SET
);
6031 fwrite(buf
, 1, size
, s
->outfile
);
6034 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6036 QEMUFileUnix
*s
= opaque
;
6037 fseek(s
->outfile
, pos
, SEEK_SET
);
6038 return fread(buf
, 1, size
, s
->outfile
);
6041 static void file_close(void *opaque
)
6043 QEMUFileUnix
*s
= opaque
;
6048 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
6052 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
6056 s
->outfile
= fopen(filename
, mode
);
6060 if (!strcmp(mode
, "wb"))
6061 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
6062 else if (!strcmp(mode
, "rb"))
6063 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
6072 typedef struct QEMUFileBdrv
6074 BlockDriverState
*bs
;
6075 int64_t base_offset
;
6078 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
6080 QEMUFileBdrv
*s
= opaque
;
6081 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6084 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
6086 QEMUFileBdrv
*s
= opaque
;
6087 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6090 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6094 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6099 s
->base_offset
= offset
;
6102 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6104 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6107 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6108 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6112 f
= qemu_mallocz(sizeof(QEMUFile
));
6117 f
->put_buffer
= put_buffer
;
6118 f
->get_buffer
= get_buffer
;
6124 void qemu_fflush(QEMUFile
*f
)
6129 if (f
->buf_index
> 0) {
6130 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6131 f
->buf_offset
+= f
->buf_index
;
6136 static void qemu_fill_buffer(QEMUFile
*f
)
6143 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6149 f
->buf_offset
+= len
;
6152 void qemu_fclose(QEMUFile
*f
)
6156 f
->close(f
->opaque
);
6160 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6164 l
= IO_BUF_SIZE
- f
->buf_index
;
6167 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6171 if (f
->buf_index
>= IO_BUF_SIZE
)
6176 void qemu_put_byte(QEMUFile
*f
, int v
)
6178 f
->buf
[f
->buf_index
++] = v
;
6179 if (f
->buf_index
>= IO_BUF_SIZE
)
6183 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6189 l
= f
->buf_size
- f
->buf_index
;
6191 qemu_fill_buffer(f
);
6192 l
= f
->buf_size
- f
->buf_index
;
6198 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6203 return size1
- size
;
6206 int qemu_get_byte(QEMUFile
*f
)
6208 if (f
->buf_index
>= f
->buf_size
) {
6209 qemu_fill_buffer(f
);
6210 if (f
->buf_index
>= f
->buf_size
)
6213 return f
->buf
[f
->buf_index
++];
6216 int64_t qemu_ftell(QEMUFile
*f
)
6218 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6221 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6223 if (whence
== SEEK_SET
) {
6225 } else if (whence
== SEEK_CUR
) {
6226 pos
+= qemu_ftell(f
);
6228 /* SEEK_END not supported */
6231 if (f
->put_buffer
) {
6233 f
->buf_offset
= pos
;
6235 f
->buf_offset
= pos
;
6242 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6244 qemu_put_byte(f
, v
>> 8);
6245 qemu_put_byte(f
, v
);
6248 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6250 qemu_put_byte(f
, v
>> 24);
6251 qemu_put_byte(f
, v
>> 16);
6252 qemu_put_byte(f
, v
>> 8);
6253 qemu_put_byte(f
, v
);
6256 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6258 qemu_put_be32(f
, v
>> 32);
6259 qemu_put_be32(f
, v
);
6262 unsigned int qemu_get_be16(QEMUFile
*f
)
6265 v
= qemu_get_byte(f
) << 8;
6266 v
|= qemu_get_byte(f
);
6270 unsigned int qemu_get_be32(QEMUFile
*f
)
6273 v
= qemu_get_byte(f
) << 24;
6274 v
|= qemu_get_byte(f
) << 16;
6275 v
|= qemu_get_byte(f
) << 8;
6276 v
|= qemu_get_byte(f
);
6280 uint64_t qemu_get_be64(QEMUFile
*f
)
6283 v
= (uint64_t)qemu_get_be32(f
) << 32;
6284 v
|= qemu_get_be32(f
);
6288 typedef struct SaveStateEntry
{
6292 SaveStateHandler
*save_state
;
6293 LoadStateHandler
*load_state
;
6295 struct SaveStateEntry
*next
;
6298 static SaveStateEntry
*first_se
;
6300 int register_savevm(const char *idstr
,
6303 SaveStateHandler
*save_state
,
6304 LoadStateHandler
*load_state
,
6307 SaveStateEntry
*se
, **pse
;
6309 se
= qemu_malloc(sizeof(SaveStateEntry
));
6312 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6313 se
->instance_id
= instance_id
;
6314 se
->version_id
= version_id
;
6315 se
->save_state
= save_state
;
6316 se
->load_state
= load_state
;
6317 se
->opaque
= opaque
;
6320 /* add at the end of list */
6322 while (*pse
!= NULL
)
6323 pse
= &(*pse
)->next
;
6328 #define QEMU_VM_FILE_MAGIC 0x5145564d
6329 #define QEMU_VM_FILE_VERSION 0x00000002
6331 static int qemu_savevm_state(QEMUFile
*f
)
6335 int64_t cur_pos
, len_pos
, total_len_pos
;
6337 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6338 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6339 total_len_pos
= qemu_ftell(f
);
6340 qemu_put_be64(f
, 0); /* total size */
6342 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6344 len
= strlen(se
->idstr
);
6345 qemu_put_byte(f
, len
);
6346 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6348 qemu_put_be32(f
, se
->instance_id
);
6349 qemu_put_be32(f
, se
->version_id
);
6351 /* record size: filled later */
6352 len_pos
= qemu_ftell(f
);
6353 qemu_put_be32(f
, 0);
6354 se
->save_state(f
, se
->opaque
);
6356 /* fill record size */
6357 cur_pos
= qemu_ftell(f
);
6358 len
= cur_pos
- len_pos
- 4;
6359 qemu_fseek(f
, len_pos
, SEEK_SET
);
6360 qemu_put_be32(f
, len
);
6361 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6363 cur_pos
= qemu_ftell(f
);
6364 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6365 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6366 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6372 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6376 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6377 if (!strcmp(se
->idstr
, idstr
) &&
6378 instance_id
== se
->instance_id
)
6384 static int qemu_loadvm_state(QEMUFile
*f
)
6387 int len
, ret
, instance_id
, record_len
, version_id
;
6388 int64_t total_len
, end_pos
, cur_pos
;
6392 v
= qemu_get_be32(f
);
6393 if (v
!= QEMU_VM_FILE_MAGIC
)
6395 v
= qemu_get_be32(f
);
6396 if (v
!= QEMU_VM_FILE_VERSION
) {
6401 total_len
= qemu_get_be64(f
);
6402 end_pos
= total_len
+ qemu_ftell(f
);
6404 if (qemu_ftell(f
) >= end_pos
)
6406 len
= qemu_get_byte(f
);
6407 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6409 instance_id
= qemu_get_be32(f
);
6410 version_id
= qemu_get_be32(f
);
6411 record_len
= qemu_get_be32(f
);
6413 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6414 idstr
, instance_id
, version_id
, record_len
);
6416 cur_pos
= qemu_ftell(f
);
6417 se
= find_se(idstr
, instance_id
);
6419 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6420 instance_id
, idstr
);
6422 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6424 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6425 instance_id
, idstr
);
6429 /* always seek to exact end of record */
6430 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6437 int qemu_live_savevm_state(QEMUFile
*f
)
6442 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6443 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6445 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6446 len
= strlen(se
->idstr
);
6448 qemu_put_byte(f
, len
);
6449 qemu_put_buffer(f
, se
->idstr
, len
);
6450 qemu_put_be32(f
, se
->instance_id
);
6451 qemu_put_be32(f
, se
->version_id
);
6453 se
->save_state(f
, se
->opaque
);
6456 qemu_put_byte(f
, 0);
6462 int qemu_live_loadvm_state(QEMUFile
*f
)
6465 int len
, ret
, instance_id
, version_id
;
6469 v
= qemu_get_be32(f
);
6470 if (v
!= QEMU_VM_FILE_MAGIC
)
6472 v
= qemu_get_be32(f
);
6473 if (v
!= QEMU_VM_FILE_VERSION
) {
6480 len
= qemu_get_byte(f
);
6483 qemu_get_buffer(f
, idstr
, len
);
6485 instance_id
= qemu_get_be32(f
);
6486 version_id
= qemu_get_be32(f
);
6487 se
= find_se(idstr
, instance_id
);
6489 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6490 instance_id
, idstr
);
6492 if (version_id
> se
->version_id
) { /* src version > dst version */
6493 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6494 idstr
, version_id
, se
->version_id
);
6498 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6500 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6501 instance_id
, idstr
);
6508 qemu_announce_self();
6514 /* device can contain snapshots */
6515 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6518 !bdrv_is_removable(bs
) &&
6519 !bdrv_is_read_only(bs
));
6522 /* device must be snapshots in order to have a reliable snapshot */
6523 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6526 !bdrv_is_removable(bs
) &&
6527 !bdrv_is_read_only(bs
));
6530 static BlockDriverState
*get_bs_snapshots(void)
6532 BlockDriverState
*bs
;
6536 return bs_snapshots
;
6537 for(i
= 0; i
<= nb_drives
; i
++) {
6538 bs
= drives_table
[i
].bdrv
;
6539 if (bdrv_can_snapshot(bs
))
6548 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6551 QEMUSnapshotInfo
*sn_tab
, *sn
;
6555 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6558 for(i
= 0; i
< nb_sns
; i
++) {
6560 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6570 void do_savevm(const char *name
)
6572 BlockDriverState
*bs
, *bs1
;
6573 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6574 int must_delete
, ret
, i
;
6575 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6577 int saved_vm_running
;
6584 bs
= get_bs_snapshots();
6586 term_printf("No block device can accept snapshots\n");
6590 /* ??? Should this occur after vm_stop? */
6593 saved_vm_running
= vm_running
;
6598 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6603 memset(sn
, 0, sizeof(*sn
));
6605 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6606 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6609 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6612 /* fill auxiliary fields */
6615 sn
->date_sec
= tb
.time
;
6616 sn
->date_nsec
= tb
.millitm
* 1000000;
6618 gettimeofday(&tv
, NULL
);
6619 sn
->date_sec
= tv
.tv_sec
;
6620 sn
->date_nsec
= tv
.tv_usec
* 1000;
6622 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6624 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6625 term_printf("Device %s does not support VM state snapshots\n",
6626 bdrv_get_device_name(bs
));
6630 /* save the VM state */
6631 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6633 term_printf("Could not open VM state file\n");
6636 ret
= qemu_savevm_state(f
);
6637 sn
->vm_state_size
= qemu_ftell(f
);
6640 term_printf("Error %d while writing VM\n", ret
);
6644 /* create the snapshots */
6646 for(i
= 0; i
< nb_drives
; i
++) {
6647 bs1
= drives_table
[i
].bdrv
;
6648 if (bdrv_has_snapshot(bs1
)) {
6650 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6652 term_printf("Error while deleting snapshot on '%s'\n",
6653 bdrv_get_device_name(bs1
));
6656 ret
= bdrv_snapshot_create(bs1
, sn
);
6658 term_printf("Error while creating snapshot on '%s'\n",
6659 bdrv_get_device_name(bs1
));
6665 if (saved_vm_running
)
6669 void do_loadvm(const char *name
)
6671 BlockDriverState
*bs
, *bs1
;
6672 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6675 int saved_vm_running
;
6677 bs
= get_bs_snapshots();
6679 term_printf("No block device supports snapshots\n");
6683 /* Flush all IO requests so they don't interfere with the new state. */
6686 saved_vm_running
= vm_running
;
6689 for(i
= 0; i
<= nb_drives
; i
++) {
6690 bs1
= drives_table
[i
].bdrv
;
6691 if (bdrv_has_snapshot(bs1
)) {
6692 ret
= bdrv_snapshot_goto(bs1
, name
);
6695 term_printf("Warning: ");
6698 term_printf("Snapshots not supported on device '%s'\n",
6699 bdrv_get_device_name(bs1
));
6702 term_printf("Could not find snapshot '%s' on device '%s'\n",
6703 name
, bdrv_get_device_name(bs1
));
6706 term_printf("Error %d while activating snapshot on '%s'\n",
6707 ret
, bdrv_get_device_name(bs1
));
6710 /* fatal on snapshot block device */
6717 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6718 term_printf("Device %s does not support VM state snapshots\n",
6719 bdrv_get_device_name(bs
));
6723 /* restore the VM state */
6724 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6726 term_printf("Could not open VM state file\n");
6729 ret
= qemu_loadvm_state(f
);
6732 term_printf("Error %d while loading VM state\n", ret
);
6735 if (saved_vm_running
)
6739 void do_delvm(const char *name
)
6741 BlockDriverState
*bs
, *bs1
;
6744 bs
= get_bs_snapshots();
6746 term_printf("No block device supports snapshots\n");
6750 for(i
= 0; i
<= nb_drives
; i
++) {
6751 bs1
= drives_table
[i
].bdrv
;
6752 if (bdrv_has_snapshot(bs1
)) {
6753 ret
= bdrv_snapshot_delete(bs1
, name
);
6755 if (ret
== -ENOTSUP
)
6756 term_printf("Snapshots not supported on device '%s'\n",
6757 bdrv_get_device_name(bs1
));
6759 term_printf("Error %d while deleting snapshot on '%s'\n",
6760 ret
, bdrv_get_device_name(bs1
));
6766 void do_info_snapshots(void)
6768 BlockDriverState
*bs
, *bs1
;
6769 QEMUSnapshotInfo
*sn_tab
, *sn
;
6773 bs
= get_bs_snapshots();
6775 term_printf("No available block device supports snapshots\n");
6778 term_printf("Snapshot devices:");
6779 for(i
= 0; i
<= nb_drives
; i
++) {
6780 bs1
= drives_table
[i
].bdrv
;
6781 if (bdrv_has_snapshot(bs1
)) {
6783 term_printf(" %s", bdrv_get_device_name(bs1
));
6788 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6790 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6793 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6794 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6795 for(i
= 0; i
< nb_sns
; i
++) {
6797 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6802 /***********************************************************/
6803 /* ram save/restore */
6805 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6809 v
= qemu_get_byte(f
);
6812 if (qemu_get_buffer(f
, buf
, len
) != len
)
6816 v
= qemu_get_byte(f
);
6817 memset(buf
, v
, len
);
6825 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6830 if (qemu_get_be32(f
) != phys_ram_size
)
6832 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6833 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6835 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6842 #define BDRV_HASH_BLOCK_SIZE 1024
6843 #define IOBUF_SIZE 4096
6844 #define RAM_CBLOCK_MAGIC 0xfabe
6846 typedef struct RamCompressState
{
6849 uint8_t buf
[IOBUF_SIZE
];
6852 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6855 memset(s
, 0, sizeof(*s
));
6857 ret
= deflateInit2(&s
->zstream
, 1,
6859 9, Z_DEFAULT_STRATEGY
);
6862 s
->zstream
.avail_out
= IOBUF_SIZE
;
6863 s
->zstream
.next_out
= s
->buf
;
6867 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6869 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6870 qemu_put_be16(s
->f
, len
);
6871 qemu_put_buffer(s
->f
, buf
, len
);
6874 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6878 s
->zstream
.avail_in
= len
;
6879 s
->zstream
.next_in
= (uint8_t *)buf
;
6880 while (s
->zstream
.avail_in
> 0) {
6881 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6884 if (s
->zstream
.avail_out
== 0) {
6885 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6886 s
->zstream
.avail_out
= IOBUF_SIZE
;
6887 s
->zstream
.next_out
= s
->buf
;
6893 static void ram_compress_close(RamCompressState
*s
)
6897 /* compress last bytes */
6899 ret
= deflate(&s
->zstream
, Z_FINISH
);
6900 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6901 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6903 ram_put_cblock(s
, s
->buf
, len
);
6905 s
->zstream
.avail_out
= IOBUF_SIZE
;
6906 s
->zstream
.next_out
= s
->buf
;
6907 if (ret
== Z_STREAM_END
)
6914 deflateEnd(&s
->zstream
);
6917 typedef struct RamDecompressState
{
6920 uint8_t buf
[IOBUF_SIZE
];
6921 } RamDecompressState
;
6923 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6926 memset(s
, 0, sizeof(*s
));
6928 ret
= inflateInit(&s
->zstream
);
6934 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6938 s
->zstream
.avail_out
= len
;
6939 s
->zstream
.next_out
= buf
;
6940 while (s
->zstream
.avail_out
> 0) {
6941 if (s
->zstream
.avail_in
== 0) {
6942 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6944 clen
= qemu_get_be16(s
->f
);
6945 if (clen
> IOBUF_SIZE
)
6947 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6948 s
->zstream
.avail_in
= clen
;
6949 s
->zstream
.next_in
= s
->buf
;
6951 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6952 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6959 static void ram_decompress_close(RamDecompressState
*s
)
6961 inflateEnd(&s
->zstream
);
6964 static void ram_save_live(QEMUFile
*f
, void *opaque
)
6968 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
6969 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
6971 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
6972 qemu_put_be32(f
, addr
);
6973 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
6976 qemu_put_be32(f
, 1);
6979 static void ram_save_static(QEMUFile
*f
, void *opaque
)
6982 RamCompressState s1
, *s
= &s1
;
6985 qemu_put_be32(f
, phys_ram_size
);
6986 if (ram_compress_open(s
, f
) < 0)
6988 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6989 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6992 if (tight_savevm_enabled
) {
6996 /* find if the memory block is available on a virtual
6999 for(j
= 0; j
< nb_drives
; j
++) {
7000 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
7002 BDRV_HASH_BLOCK_SIZE
);
7003 if (sector_num
>= 0)
7007 goto normal_compress
;
7010 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
7011 ram_compress_buf(s
, buf
, 10);
7017 ram_compress_buf(s
, buf
, 1);
7018 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
7021 ram_compress_close(s
);
7024 static void ram_save(QEMUFile
*f
, void *opaque
)
7026 int in_migration
= cpu_physical_memory_get_dirty_tracking();
7028 qemu_put_byte(f
, in_migration
);
7031 ram_save_live(f
, opaque
);
7033 ram_save_static(f
, opaque
);
7036 static int ram_load_live(QEMUFile
*f
, void *opaque
)
7041 addr
= qemu_get_be32(f
);
7045 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
7051 static int ram_load_static(QEMUFile
*f
, void *opaque
)
7053 RamDecompressState s1
, *s
= &s1
;
7057 if (qemu_get_be32(f
) != phys_ram_size
)
7059 if (ram_decompress_open(s
, f
) < 0)
7061 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
7062 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
7064 if (ram_decompress_buf(s
, buf
, 1) < 0) {
7065 fprintf(stderr
, "Error while reading ram block header\n");
7069 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
7070 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
7079 ram_decompress_buf(s
, buf
+ 1, 9);
7081 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
7082 if (bs_index
>= nb_drives
) {
7083 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
7086 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7088 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7089 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7090 bs_index
, sector_num
);
7097 printf("Error block header\n");
7101 ram_decompress_close(s
);
7105 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7109 switch (version_id
) {
7111 ret
= ram_load_v1(f
, opaque
);
7114 if (qemu_get_byte(f
)) {
7115 ret
= ram_load_live(f
, opaque
);
7119 ret
= ram_load_static(f
, opaque
);
7129 /***********************************************************/
7130 /* bottom halves (can be seen as timers which expire ASAP) */
7139 static QEMUBH
*first_bh
= NULL
;
7141 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7144 bh
= qemu_mallocz(sizeof(QEMUBH
));
7148 bh
->opaque
= opaque
;
7152 int qemu_bh_poll(void)
7171 void qemu_bh_schedule(QEMUBH
*bh
)
7173 CPUState
*env
= cpu_single_env
;
7177 bh
->next
= first_bh
;
7180 /* stop the currently executing CPU to execute the BH ASAP */
7182 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7187 void qemu_bh_cancel(QEMUBH
*bh
)
7190 if (bh
->scheduled
) {
7193 pbh
= &(*pbh
)->next
;
7199 void qemu_bh_delete(QEMUBH
*bh
)
7205 /***********************************************************/
7206 /* machine registration */
7208 QEMUMachine
*first_machine
= NULL
;
7209 QEMUMachine
*current_machine
= NULL
;
7211 int qemu_register_machine(QEMUMachine
*m
)
7214 pm
= &first_machine
;
7222 static QEMUMachine
*find_machine(const char *name
)
7226 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7227 if (!strcmp(m
->name
, name
))
7233 /***********************************************************/
7234 /* main execution loop */
7236 static void gui_update(void *opaque
)
7238 DisplayState
*ds
= opaque
;
7239 ds
->dpy_refresh(ds
);
7240 qemu_mod_timer(ds
->gui_timer
,
7241 (ds
->gui_timer_interval
?
7242 ds
->gui_timer_interval
:
7243 GUI_REFRESH_INTERVAL
)
7244 + qemu_get_clock(rt_clock
));
7247 struct vm_change_state_entry
{
7248 VMChangeStateHandler
*cb
;
7250 LIST_ENTRY (vm_change_state_entry
) entries
;
7253 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7255 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7258 VMChangeStateEntry
*e
;
7260 e
= qemu_mallocz(sizeof (*e
));
7266 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7270 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7272 LIST_REMOVE (e
, entries
);
7276 static void vm_state_notify(int running
)
7278 VMChangeStateEntry
*e
;
7280 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7281 e
->cb(e
->opaque
, running
);
7285 /* XXX: support several handlers */
7286 static VMStopHandler
*vm_stop_cb
;
7287 static void *vm_stop_opaque
;
7289 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7292 vm_stop_opaque
= opaque
;
7296 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7307 qemu_rearm_alarm_timer(alarm_timer
);
7311 void vm_stop(int reason
)
7314 cpu_disable_ticks();
7318 vm_stop_cb(vm_stop_opaque
, reason
);
7325 /* reset/shutdown handler */
7327 typedef struct QEMUResetEntry
{
7328 QEMUResetHandler
*func
;
7330 struct QEMUResetEntry
*next
;
7333 static QEMUResetEntry
*first_reset_entry
;
7334 static int reset_requested
;
7335 static int shutdown_requested
;
7336 static int powerdown_requested
;
7338 int qemu_shutdown_requested(void)
7340 int r
= shutdown_requested
;
7341 shutdown_requested
= 0;
7345 int qemu_reset_requested(void)
7347 int r
= reset_requested
;
7348 reset_requested
= 0;
7352 int qemu_powerdown_requested(void)
7354 int r
= powerdown_requested
;
7355 powerdown_requested
= 0;
7359 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7361 QEMUResetEntry
**pre
, *re
;
7363 pre
= &first_reset_entry
;
7364 while (*pre
!= NULL
)
7365 pre
= &(*pre
)->next
;
7366 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7368 re
->opaque
= opaque
;
7373 void qemu_system_reset(void)
7377 /* reset all devices */
7378 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7379 re
->func(re
->opaque
);
7383 void qemu_system_reset_request(void)
7386 shutdown_requested
= 1;
7388 reset_requested
= 1;
7391 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7395 void qemu_system_shutdown_request(void)
7397 shutdown_requested
= 1;
7399 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7402 void qemu_system_powerdown_request(void)
7404 powerdown_requested
= 1;
7406 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7409 /* boot_set handler */
7410 QEMUBootSetHandler
*qemu_boot_set_handler
= NULL
;
7412 void qemu_register_boot_set(QEMUBootSetHandler
*func
)
7414 qemu_boot_set_handler
= func
;
7417 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
7422 /* KVM holds a mutex while QEMU code is running, we need hooks to
7423 release the mutex whenever QEMU code sleeps. */
7427 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
7434 void main_loop_wait(int timeout
)
7436 IOHandlerRecord
*ioh
;
7437 fd_set rfds
, wfds
, xfds
;
7446 /* XXX: need to suppress polling by better using win32 events */
7448 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7449 ret
|= pe
->func(pe
->opaque
);
7454 WaitObjects
*w
= &wait_objects
;
7456 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7457 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7458 if (w
->func
[ret
- WAIT_OBJECT_0
])
7459 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7461 /* Check for additional signaled events */
7462 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7464 /* Check if event is signaled */
7465 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7466 if(ret2
== WAIT_OBJECT_0
) {
7468 w
->func
[i
](w
->opaque
[i
]);
7469 } else if (ret2
== WAIT_TIMEOUT
) {
7471 err
= GetLastError();
7472 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7475 } else if (ret
== WAIT_TIMEOUT
) {
7477 err
= GetLastError();
7478 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7482 /* poll any events */
7483 /* XXX: separate device handlers from system ones */
7488 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7492 (!ioh
->fd_read_poll
||
7493 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7494 FD_SET(ioh
->fd
, &rfds
);
7498 if (ioh
->fd_write
) {
7499 FD_SET(ioh
->fd
, &wfds
);
7509 tv
.tv_sec
= timeout
/ 1000;
7510 tv
.tv_usec
= (timeout
% 1000) * 1000;
7512 #if defined(CONFIG_SLIRP)
7514 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7517 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7519 IOHandlerRecord
**pioh
;
7521 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7522 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7523 ioh
->fd_read(ioh
->opaque
);
7524 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
7525 FD_CLR(ioh
->fd
, &rfds
);
7527 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7528 ioh
->fd_write(ioh
->opaque
);
7532 /* remove deleted IO handlers */
7533 pioh
= &first_io_handler
;
7543 #if defined(CONFIG_SLIRP)
7550 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7555 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7556 qemu_get_clock(vm_clock
));
7557 /* run dma transfers, if any */
7561 /* real time timers */
7562 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7563 qemu_get_clock(rt_clock
));
7565 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7566 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7567 qemu_rearm_alarm_timer(alarm_timer
);
7570 /* Check bottom-halves last in case any of the earlier events triggered
7576 static int main_loop(void)
7579 #ifdef CONFIG_PROFILER
7585 if (kvm_enabled()) {
7587 cpu_disable_ticks();
7591 cur_cpu
= first_cpu
;
7592 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7599 #ifdef CONFIG_PROFILER
7600 ti
= profile_getclock();
7602 ret
= cpu_exec(env
);
7603 #ifdef CONFIG_PROFILER
7604 qemu_time
+= profile_getclock() - ti
;
7606 next_cpu
= env
->next_cpu
?: first_cpu
;
7607 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7608 ret
= EXCP_INTERRUPT
;
7612 if (ret
== EXCP_HLT
) {
7613 /* Give the next CPU a chance to run. */
7617 if (ret
!= EXCP_HALTED
)
7619 /* all CPUs are halted ? */
7625 if (shutdown_requested
) {
7626 ret
= EXCP_INTERRUPT
;
7634 if (reset_requested
) {
7635 reset_requested
= 0;
7636 qemu_system_reset();
7638 kvm_load_registers(env
);
7639 ret
= EXCP_INTERRUPT
;
7641 if (powerdown_requested
) {
7642 powerdown_requested
= 0;
7643 qemu_system_powerdown();
7644 ret
= EXCP_INTERRUPT
;
7646 if (unlikely(ret
== EXCP_DEBUG
)) {
7647 vm_stop(EXCP_DEBUG
);
7649 /* If all cpus are halted then wait until the next IRQ */
7650 /* XXX: use timeout computed from timers */
7651 if (ret
== EXCP_HALTED
)
7658 #ifdef CONFIG_PROFILER
7659 ti
= profile_getclock();
7661 main_loop_wait(timeout
);
7662 #ifdef CONFIG_PROFILER
7663 dev_time
+= profile_getclock() - ti
;
7666 cpu_disable_ticks();
7670 static void help(int exitcode
)
7672 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
7673 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7674 "usage: %s [options] [disk_image]\n"
7676 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7678 "Standard options:\n"
7679 "-M machine select emulated machine (-M ? for list)\n"
7680 "-cpu cpu select CPU (-cpu ? for list)\n"
7681 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7682 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7683 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7684 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7685 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7686 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7687 " [,cache=on|off][,format=f][,boot=on|off]\n"
7688 " use 'file' as a drive image\n"
7689 "-mtdblock file use 'file' as on-board Flash memory image\n"
7690 "-sd file use 'file' as SecureDigital card image\n"
7691 "-pflash file use 'file' as a parallel flash image\n"
7692 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7693 "-snapshot write to temporary files instead of disk image files\n"
7695 "-no-frame open SDL window without a frame and window decorations\n"
7696 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7697 "-no-quit disable SDL window close capability\n"
7700 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7702 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7703 "-smp n set the number of CPUs to 'n' [default=1]\n"
7704 "-nographic disable graphical output and redirect serial I/Os to console\n"
7705 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7707 "-k language use keyboard layout (for example \"fr\" for French)\n"
7710 "-audio-help print list of audio drivers and their options\n"
7711 "-soundhw c1,... enable audio support\n"
7712 " and only specified sound cards (comma separated list)\n"
7713 " use -soundhw ? to get the list of supported cards\n"
7714 " use -soundhw all to enable all of them\n"
7716 "-localtime set the real time clock to local time [default=utc]\n"
7717 "-full-screen start in full screen\n"
7719 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7721 "-usb enable the USB driver (will be the default soon)\n"
7722 "-usbdevice name add the host or guest USB device 'name'\n"
7723 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7724 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7726 "-name string set the name of the guest\n"
7728 "Network options:\n"
7729 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7730 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7732 "-net user[,vlan=n][,hostname=host]\n"
7733 " connect the user mode network stack to VLAN 'n' and send\n"
7734 " hostname 'host' to DHCP clients\n"
7737 "-net tap[,vlan=n],ifname=name\n"
7738 " connect the host TAP network interface to VLAN 'n'\n"
7740 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7741 " connect the host TAP network interface to VLAN 'n' and use the\n"
7742 " network scripts 'file' (default=%s)\n"
7743 " and 'dfile' (default=%s);\n"
7744 " use '[down]script=no' to disable script execution;\n"
7745 " use 'fd=h' to connect to an already opened TAP interface\n"
7747 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7748 " connect the vlan 'n' to another VLAN using a socket connection\n"
7749 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7750 " connect the vlan 'n' to multicast maddr and port\n"
7751 "-net none use it alone to have zero network devices; if no -net option\n"
7752 " is provided, the default is '-net nic -net user'\n"
7755 "-tftp dir allow tftp access to files in dir [-net user]\n"
7756 "-bootp file advertise file in BOOTP replies\n"
7758 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7760 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7761 " redirect TCP or UDP connections from host to guest [-net user]\n"
7764 "Linux boot specific:\n"
7765 "-kernel bzImage use 'bzImage' as kernel image\n"
7766 "-append cmdline use 'cmdline' as kernel command line\n"
7767 "-initrd file use 'file' as initial ram disk\n"
7769 "Debug/Expert options:\n"
7770 "-monitor dev redirect the monitor to char device 'dev'\n"
7771 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7772 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7773 "-serial dev redirect the serial port to char device 'dev'\n"
7774 "-parallel dev redirect the parallel port to char device 'dev'\n"
7775 "-pidfile file Write PID to 'file'\n"
7776 "-S freeze CPU at startup (use 'c' to start execution)\n"
7777 "-s wait gdb connection to port\n"
7778 "-p port set gdb connection port [default=%s]\n"
7779 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7780 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7781 " translation (t=none or lba) (usually qemu can guess them)\n"
7782 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7784 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7785 "-no-kqemu disable KQEMU kernel module usage\n"
7788 #ifndef NO_CPU_EMULATION
7789 "-no-kvm disable KVM hardware virtualization\n"
7791 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7792 "-no-kvm-pit disable KVM kernel mode PIT\n"
7795 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7796 " (default is CL-GD5446 PCI VGA)\n"
7797 "-no-acpi disable ACPI\n"
7799 #ifdef CONFIG_CURSES
7800 "-curses use a curses/ncurses interface instead of SDL\n"
7802 "-no-reboot exit instead of rebooting\n"
7803 "-no-shutdown stop before shutdown\n"
7804 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7805 "-vnc display start a VNC server on display\n"
7807 "-daemonize daemonize QEMU after initializing\n"
7809 "-tdf inject timer interrupts that got lost\n"
7810 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7811 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
7812 "-option-rom rom load a file, rom, into the option ROM space\n"
7814 "-prom-env variable=value set OpenBIOS nvram variables\n"
7816 "-clock force the use of the given methods for timer alarm.\n"
7817 " To see what timers are available use -clock ?\n"
7818 "-startdate select initial date of the clock\n"
7820 "During emulation, the following keys are useful:\n"
7821 "ctrl-alt-f toggle full screen\n"
7822 "ctrl-alt-n switch to virtual console 'n'\n"
7823 "ctrl-alt toggle mouse and keyboard grab\n"
7825 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7830 DEFAULT_NETWORK_SCRIPT
,
7831 DEFAULT_NETWORK_DOWN_SCRIPT
,
7833 DEFAULT_GDBSTUB_PORT
,
7838 #define HAS_ARG 0x0001
7853 QEMU_OPTION_mtdblock
,
7857 QEMU_OPTION_snapshot
,
7859 QEMU_OPTION_no_fd_bootchk
,
7862 QEMU_OPTION_nographic
,
7863 QEMU_OPTION_portrait
,
7865 QEMU_OPTION_audio_help
,
7866 QEMU_OPTION_soundhw
,
7886 QEMU_OPTION_no_code_copy
,
7888 QEMU_OPTION_localtime
,
7889 QEMU_OPTION_cirrusvga
,
7892 QEMU_OPTION_std_vga
,
7894 QEMU_OPTION_monitor
,
7895 QEMU_OPTION_balloon
,
7896 QEMU_OPTION_vmchannel
,
7898 QEMU_OPTION_parallel
,
7900 QEMU_OPTION_full_screen
,
7901 QEMU_OPTION_no_frame
,
7902 QEMU_OPTION_alt_grab
,
7903 QEMU_OPTION_no_quit
,
7904 QEMU_OPTION_pidfile
,
7905 QEMU_OPTION_no_kqemu
,
7906 QEMU_OPTION_kernel_kqemu
,
7907 QEMU_OPTION_win2k_hack
,
7909 QEMU_OPTION_usbdevice
,
7912 QEMU_OPTION_no_acpi
,
7915 QEMU_OPTION_no_kvm_irqchip
,
7916 QEMU_OPTION_no_kvm_pit
,
7917 QEMU_OPTION_no_reboot
,
7918 QEMU_OPTION_no_shutdown
,
7919 QEMU_OPTION_show_cursor
,
7920 QEMU_OPTION_daemonize
,
7921 QEMU_OPTION_option_rom
,
7922 QEMU_OPTION_semihosting
,
7923 QEMU_OPTION_cpu_vendor
,
7925 QEMU_OPTION_prom_env
,
7926 QEMU_OPTION_old_param
,
7928 QEMU_OPTION_startdate
,
7929 QEMU_OPTION_translation
,
7930 QEMU_OPTION_incoming
,
7932 QEMU_OPTION_kvm_shadow_memory
,
7933 QEMU_OPTION_mempath
,
7936 typedef struct QEMUOption
{
7942 const QEMUOption qemu_options
[] = {
7943 { "h", 0, QEMU_OPTION_h
},
7944 { "help", 0, QEMU_OPTION_h
},
7946 { "M", HAS_ARG
, QEMU_OPTION_M
},
7947 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7948 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7949 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7950 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7951 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7952 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7953 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7954 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7955 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7956 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7957 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7958 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7959 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7960 { "snapshot", 0, QEMU_OPTION_snapshot
},
7962 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7964 { "m", HAS_ARG
, QEMU_OPTION_m
},
7965 { "nographic", 0, QEMU_OPTION_nographic
},
7966 { "portrait", 0, QEMU_OPTION_portrait
},
7967 { "k", HAS_ARG
, QEMU_OPTION_k
},
7969 { "audio-help", 0, QEMU_OPTION_audio_help
},
7970 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7973 { "net", HAS_ARG
, QEMU_OPTION_net
},
7975 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7976 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7978 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7980 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7983 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7984 { "append", HAS_ARG
, QEMU_OPTION_append
},
7985 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7987 { "S", 0, QEMU_OPTION_S
},
7988 { "s", 0, QEMU_OPTION_s
},
7989 { "p", HAS_ARG
, QEMU_OPTION_p
},
7990 { "d", HAS_ARG
, QEMU_OPTION_d
},
7991 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7992 { "L", HAS_ARG
, QEMU_OPTION_L
},
7993 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7994 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
7996 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7997 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
8000 #ifndef NO_CPU_EMULATION
8001 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
8003 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
8004 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
8006 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
8007 { "g", 1, QEMU_OPTION_g
},
8009 { "localtime", 0, QEMU_OPTION_localtime
},
8010 { "std-vga", 0, QEMU_OPTION_std_vga
},
8011 { "monitor", 1, QEMU_OPTION_monitor
},
8012 { "balloon", 1, QEMU_OPTION_balloon
},
8013 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
8014 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
8015 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
8016 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
8017 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
8018 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
8019 { "incoming", 1, QEMU_OPTION_incoming
},
8020 { "full-screen", 0, QEMU_OPTION_full_screen
},
8022 { "no-frame", 0, QEMU_OPTION_no_frame
},
8023 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
8024 { "no-quit", 0, QEMU_OPTION_no_quit
},
8026 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
8027 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
8028 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
8029 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
8030 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
8031 #ifdef CONFIG_CURSES
8032 { "curses", 0, QEMU_OPTION_curses
},
8035 /* temporary options */
8036 { "usb", 0, QEMU_OPTION_usb
},
8037 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
8038 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
8039 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
8040 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
8041 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
8042 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
8043 { "daemonize", 0, QEMU_OPTION_daemonize
},
8044 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
8045 #if defined(TARGET_ARM) || defined(TARGET_M68K)
8046 { "semihosting", 0, QEMU_OPTION_semihosting
},
8048 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
8049 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
8050 { "name", HAS_ARG
, QEMU_OPTION_name
},
8051 #if defined(TARGET_SPARC)
8052 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
8054 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
8055 #if defined(TARGET_ARM)
8056 { "old-param", 0, QEMU_OPTION_old_param
},
8058 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
8059 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
8060 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
8064 /* password input */
8066 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
8071 if (!bdrv_is_encrypted(bs
))
8074 term_printf("%s is encrypted.\n", name
);
8075 for(i
= 0; i
< 3; i
++) {
8076 monitor_readline("Password: ", 1, password
, sizeof(password
));
8077 if (bdrv_set_key(bs
, password
) == 0)
8079 term_printf("invalid password\n");
8084 static BlockDriverState
*get_bdrv(int index
)
8086 if (index
> nb_drives
)
8088 return drives_table
[index
].bdrv
;
8091 static void read_passwords(void)
8093 BlockDriverState
*bs
;
8096 for(i
= 0; i
< 6; i
++) {
8099 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8104 struct soundhw soundhw
[] = {
8105 #ifdef HAS_AUDIO_CHOICE
8106 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8112 { .init_isa
= pcspk_audio_init
}
8117 "Creative Sound Blaster 16",
8120 { .init_isa
= SB16_init
}
8127 "Yamaha YMF262 (OPL3)",
8129 "Yamaha YM3812 (OPL2)",
8133 { .init_isa
= Adlib_init
}
8140 "Gravis Ultrasound GF1",
8143 { .init_isa
= GUS_init
}
8150 "Intel 82801AA AC97 Audio",
8153 { .init_pci
= ac97_init
}
8159 "ENSONIQ AudioPCI ES1370",
8162 { .init_pci
= es1370_init
}
8166 { NULL
, NULL
, 0, 0, { NULL
} }
8169 static void select_soundhw (const char *optarg
)
8173 if (*optarg
== '?') {
8176 printf ("Valid sound card names (comma separated):\n");
8177 for (c
= soundhw
; c
->name
; ++c
) {
8178 printf ("%-11s %s\n", c
->name
, c
->descr
);
8180 printf ("\n-soundhw all will enable all of the above\n");
8181 exit (*optarg
!= '?');
8189 if (!strcmp (optarg
, "all")) {
8190 for (c
= soundhw
; c
->name
; ++c
) {
8198 e
= strchr (p
, ',');
8199 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8201 for (c
= soundhw
; c
->name
; ++c
) {
8202 if (!strncmp (c
->name
, p
, l
)) {
8211 "Unknown sound card name (too big to show)\n");
8214 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8219 p
+= l
+ (e
!= NULL
);
8223 goto show_valid_cards
;
8229 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8231 exit(STATUS_CONTROL_C_EXIT
);
8236 #define MAX_NET_CLIENTS 32
8238 static int saved_argc
;
8239 static char **saved_argv
;
8241 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8245 *opt_daemonize
= daemonize
;
8246 *opt_incoming
= incoming
;
8250 static int gethugepagesize(void)
8254 char *needle
= "Hugepagesize:";
8256 unsigned long hugepagesize
;
8258 fd
= open("/proc/meminfo", O_RDONLY
);
8264 ret
= read(fd
, buf
, sizeof(buf
));
8270 size
= strstr(buf
, needle
);
8273 size
+= strlen(needle
);
8274 hugepagesize
= strtol(size
, NULL
, 0);
8275 return hugepagesize
;
8278 void *alloc_mem_area(unsigned long memory
, const char *path
)
8284 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8287 hpagesize
= gethugepagesize() * 1024;
8291 fd
= mkstemp(filename
);
8300 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8303 * ftruncate is not supported by hugetlbfs in older
8304 * hosts, so don't bother checking for errors.
8305 * If anything goes wrong with it under other filesystems,
8308 ftruncate(fd
, memory
);
8310 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8311 if (area
== MAP_FAILED
) {
8320 void *qemu_alloc_physram(unsigned long memory
)
8325 area
= alloc_mem_area(memory
, mem_path
);
8327 area
= qemu_vmalloc(memory
);
8332 int main(int argc
, char **argv
)
8334 #ifdef CONFIG_GDBSTUB
8336 const char *gdbstub_port
;
8338 uint32_t boot_devices_bitmap
= 0;
8340 int snapshot
, linux_boot
, net_boot
;
8341 const char *initrd_filename
;
8342 const char *kernel_filename
, *kernel_cmdline
;
8343 const char *boot_devices
= "";
8344 DisplayState
*ds
= &display_state
;
8345 int cyls
, heads
, secs
, translation
;
8346 const char *net_clients
[MAX_NET_CLIENTS
];
8350 const char *r
, *optarg
;
8351 CharDriverState
*monitor_hd
;
8352 const char *monitor_device
;
8353 const char *serial_devices
[MAX_SERIAL_PORTS
];
8354 int serial_device_index
;
8355 char vmchannel_devices
[MAX_VMCHANNEL_DEVICES
][128];
8356 int vmchannel_device_index
;
8357 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8358 int parallel_device_index
;
8359 const char *loadvm
= NULL
;
8360 QEMUMachine
*machine
;
8361 const char *cpu_model
;
8362 const char *usb_devices
[MAX_USB_CMDLINE
];
8363 int usb_devices_index
;
8365 const char *pid_file
= NULL
;
8371 LIST_INIT (&vm_change_state_head
);
8374 struct sigaction act
;
8375 sigfillset(&act
.sa_mask
);
8377 act
.sa_handler
= SIG_IGN
;
8378 sigaction(SIGPIPE
, &act
, NULL
);
8381 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8382 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8383 QEMU to run on a single CPU */
8388 h
= GetCurrentProcess();
8389 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8390 for(i
= 0; i
< 32; i
++) {
8391 if (mask
& (1 << i
))
8396 SetProcessAffinityMask(h
, mask
);
8402 register_machines();
8403 machine
= first_machine
;
8405 initrd_filename
= NULL
;
8407 vga_ram_size
= VGA_RAM_SIZE
;
8408 #ifdef CONFIG_GDBSTUB
8410 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8415 kernel_filename
= NULL
;
8416 kernel_cmdline
= "";
8417 cyls
= heads
= secs
= 0;
8418 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8419 monitor_device
= "vc:800x600";
8421 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++)
8422 vmchannel_devices
[i
][0] = '\0';
8423 vmchannel_device_index
= 0;
8425 serial_devices
[0] = "vc:80Cx24C";
8426 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8427 serial_devices
[i
] = NULL
;
8428 serial_device_index
= 0;
8430 parallel_devices
[0] = "vc:640x480";
8431 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8432 parallel_devices
[i
] = NULL
;
8433 parallel_device_index
= 0;
8435 usb_devices_index
= 0;
8443 /* default mac address of the first network interface */
8451 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8453 const QEMUOption
*popt
;
8456 /* Treat --foo the same as -foo. */
8459 popt
= qemu_options
;
8462 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8466 if (!strcmp(popt
->name
, r
+ 1))
8470 if (popt
->flags
& HAS_ARG
) {
8471 if (optind
>= argc
) {
8472 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8476 optarg
= argv
[optind
++];
8481 switch(popt
->index
) {
8483 machine
= find_machine(optarg
);
8486 printf("Supported machines are:\n");
8487 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8488 printf("%-10s %s%s\n",
8490 m
== first_machine
? " (default)" : "");
8492 exit(*optarg
!= '?');
8495 case QEMU_OPTION_cpu
:
8496 /* hw initialization will check this */
8497 if (*optarg
== '?') {
8498 /* XXX: implement xxx_cpu_list for targets that still miss it */
8499 #if defined(cpu_list)
8500 cpu_list(stdout
, &fprintf
);
8507 case QEMU_OPTION_initrd
:
8508 initrd_filename
= optarg
;
8510 case QEMU_OPTION_hda
:
8512 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8514 hda_index
= drive_add(optarg
, HD_ALIAS
8515 ",cyls=%d,heads=%d,secs=%d%s",
8516 0, cyls
, heads
, secs
,
8517 translation
== BIOS_ATA_TRANSLATION_LBA
?
8519 translation
== BIOS_ATA_TRANSLATION_NONE
?
8520 ",trans=none" : "");
8522 case QEMU_OPTION_hdb
:
8523 case QEMU_OPTION_hdc
:
8524 case QEMU_OPTION_hdd
:
8525 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8527 case QEMU_OPTION_drive
:
8528 drive_add(NULL
, "%s", optarg
);
8530 case QEMU_OPTION_mtdblock
:
8531 drive_add(optarg
, MTD_ALIAS
);
8533 case QEMU_OPTION_sd
:
8534 drive_add(optarg
, SD_ALIAS
);
8536 case QEMU_OPTION_pflash
:
8537 drive_add(optarg
, PFLASH_ALIAS
);
8539 case QEMU_OPTION_snapshot
:
8542 case QEMU_OPTION_hdachs
:
8546 cyls
= strtol(p
, (char **)&p
, 0);
8547 if (cyls
< 1 || cyls
> 16383)
8552 heads
= strtol(p
, (char **)&p
, 0);
8553 if (heads
< 1 || heads
> 16)
8558 secs
= strtol(p
, (char **)&p
, 0);
8559 if (secs
< 1 || secs
> 63)
8563 if (!strcmp(p
, "none"))
8564 translation
= BIOS_ATA_TRANSLATION_NONE
;
8565 else if (!strcmp(p
, "lba"))
8566 translation
= BIOS_ATA_TRANSLATION_LBA
;
8567 else if (!strcmp(p
, "auto"))
8568 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8571 } else if (*p
!= '\0') {
8573 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8576 if (hda_index
!= -1)
8577 snprintf(drives_opt
[hda_index
].opt
,
8578 sizeof(drives_opt
[hda_index
].opt
),
8579 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8580 0, cyls
, heads
, secs
,
8581 translation
== BIOS_ATA_TRANSLATION_LBA
?
8583 translation
== BIOS_ATA_TRANSLATION_NONE
?
8584 ",trans=none" : "");
8587 case QEMU_OPTION_nographic
:
8588 serial_devices
[0] = "stdio";
8589 parallel_devices
[0] = "null";
8590 monitor_device
= "stdio";
8593 #ifdef CONFIG_CURSES
8594 case QEMU_OPTION_curses
:
8598 case QEMU_OPTION_portrait
:
8601 case QEMU_OPTION_kernel
:
8602 kernel_filename
= optarg
;
8604 case QEMU_OPTION_append
:
8605 kernel_cmdline
= optarg
;
8607 case QEMU_OPTION_cdrom
:
8608 drive_add(optarg
, CDROM_ALIAS
);
8610 case QEMU_OPTION_boot
:
8611 boot_devices
= optarg
;
8612 /* We just do some generic consistency checks */
8614 /* Could easily be extended to 64 devices if needed */
8617 boot_devices_bitmap
= 0;
8618 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8619 /* Allowed boot devices are:
8620 * a b : floppy disk drives
8621 * c ... f : IDE disk drives
8622 * g ... m : machine implementation dependant drives
8623 * n ... p : network devices
8624 * It's up to each machine implementation to check
8625 * if the given boot devices match the actual hardware
8626 * implementation and firmware features.
8628 if (*p
< 'a' || *p
> 'q') {
8629 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8632 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8634 "Boot device '%c' was given twice\n",*p
);
8637 boot_devices_bitmap
|= 1 << (*p
- 'a');
8641 case QEMU_OPTION_fda
:
8642 case QEMU_OPTION_fdb
:
8643 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8646 case QEMU_OPTION_no_fd_bootchk
:
8650 case QEMU_OPTION_no_code_copy
:
8651 code_copy_enabled
= 0;
8653 case QEMU_OPTION_net
:
8654 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8655 fprintf(stderr
, "qemu: too many network clients\n");
8658 net_clients
[nb_net_clients
] = optarg
;
8662 case QEMU_OPTION_tftp
:
8663 tftp_prefix
= optarg
;
8665 case QEMU_OPTION_bootp
:
8666 bootp_filename
= optarg
;
8669 case QEMU_OPTION_smb
:
8670 net_slirp_smb(optarg
);
8673 case QEMU_OPTION_redir
:
8674 net_slirp_redir(optarg
);
8678 case QEMU_OPTION_audio_help
:
8682 case QEMU_OPTION_soundhw
:
8683 select_soundhw (optarg
);
8689 case QEMU_OPTION_m
: {
8693 value
= strtoul(optarg
, &ptr
, 10);
8695 case 0: case 'M': case 'm':
8702 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8706 /* On 32-bit hosts, QEMU is limited by virtual address space */
8707 if (value
> (2047 << 20)
8709 && HOST_LONG_BITS
== 32
8712 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8715 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8716 fprintf(stderr
, "qemu: ram size too large\n");
8727 mask
= cpu_str_to_log_mask(optarg
);
8729 printf("Log items (comma separated):\n");
8730 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8731 printf("%-10s %s\n", item
->name
, item
->help
);
8738 #ifdef CONFIG_GDBSTUB
8743 gdbstub_port
= optarg
;
8749 case QEMU_OPTION_bios
:
8756 keyboard_layout
= optarg
;
8758 case QEMU_OPTION_localtime
:
8761 case QEMU_OPTION_cirrusvga
:
8762 cirrus_vga_enabled
= 1;
8765 case QEMU_OPTION_vmsvga
:
8766 cirrus_vga_enabled
= 0;
8769 case QEMU_OPTION_std_vga
:
8770 cirrus_vga_enabled
= 0;
8778 w
= strtol(p
, (char **)&p
, 10);
8781 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8787 h
= strtol(p
, (char **)&p
, 10);
8792 depth
= strtol(p
, (char **)&p
, 10);
8793 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8794 depth
!= 24 && depth
!= 32)
8796 } else if (*p
== '\0') {
8797 depth
= graphic_depth
;
8804 graphic_depth
= depth
;
8807 case QEMU_OPTION_echr
:
8810 term_escape_char
= strtol(optarg
, &r
, 0);
8812 printf("Bad argument to echr\n");
8815 case QEMU_OPTION_monitor
:
8816 monitor_device
= optarg
;
8818 case QEMU_OPTION_balloon
:
8819 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
8820 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
8824 fprintf(stderr
, "qemu: only one balloon device can be used\n");
8827 sprintf(vmchannel_devices
[vmchannel_device_index
],"di:cdcd,%s", optarg
);
8828 vmchannel_device_index
++;
8831 case QEMU_OPTION_vmchannel
:
8832 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
8833 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
8836 pstrcpy(vmchannel_devices
[vmchannel_device_index
],
8837 sizeof(vmchannel_devices
[0]), optarg
);
8838 vmchannel_device_index
++;
8840 case QEMU_OPTION_serial
:
8841 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8842 fprintf(stderr
, "qemu: too many serial ports\n");
8845 serial_devices
[serial_device_index
] = optarg
;
8846 serial_device_index
++;
8848 case QEMU_OPTION_parallel
:
8849 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8850 fprintf(stderr
, "qemu: too many parallel ports\n");
8853 parallel_devices
[parallel_device_index
] = optarg
;
8854 parallel_device_index
++;
8856 case QEMU_OPTION_loadvm
:
8859 case QEMU_OPTION_incoming
:
8862 case QEMU_OPTION_full_screen
:
8866 case QEMU_OPTION_no_frame
:
8869 case QEMU_OPTION_alt_grab
:
8872 case QEMU_OPTION_no_quit
:
8876 case QEMU_OPTION_pidfile
:
8880 case QEMU_OPTION_win2k_hack
:
8881 win2k_install_hack
= 1;
8885 case QEMU_OPTION_no_kqemu
:
8888 case QEMU_OPTION_kernel_kqemu
:
8893 case QEMU_OPTION_no_kvm
:
8896 case QEMU_OPTION_no_kvm_irqchip
: {
8897 extern int kvm_irqchip
, kvm_pit
;
8902 case QEMU_OPTION_no_kvm_pit
: {
8908 case QEMU_OPTION_usb
:
8911 case QEMU_OPTION_usbdevice
:
8913 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8914 fprintf(stderr
, "Too many USB devices\n");
8917 usb_devices
[usb_devices_index
] = optarg
;
8918 usb_devices_index
++;
8920 case QEMU_OPTION_smp
:
8921 smp_cpus
= atoi(optarg
);
8922 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8923 fprintf(stderr
, "Invalid number of CPUs\n");
8927 case QEMU_OPTION_vnc
:
8928 vnc_display
= optarg
;
8930 case QEMU_OPTION_no_acpi
:
8933 case QEMU_OPTION_no_reboot
:
8936 case QEMU_OPTION_no_shutdown
:
8939 case QEMU_OPTION_show_cursor
:
8942 case QEMU_OPTION_daemonize
:
8945 case QEMU_OPTION_option_rom
:
8946 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8947 fprintf(stderr
, "Too many option ROMs\n");
8950 option_rom
[nb_option_roms
] = optarg
;
8953 case QEMU_OPTION_semihosting
:
8954 semihosting_enabled
= 1;
8956 case QEMU_OPTION_tdf
:
8959 case QEMU_OPTION_kvm_shadow_memory
:
8960 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
8962 case QEMU_OPTION_mempath
:
8965 case QEMU_OPTION_name
:
8969 case QEMU_OPTION_prom_env
:
8970 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8971 fprintf(stderr
, "Too many prom variables\n");
8974 prom_envs
[nb_prom_envs
] = optarg
;
8978 case QEMU_OPTION_cpu_vendor
:
8979 cpu_vendor_string
= optarg
;
8982 case QEMU_OPTION_old_param
:
8986 case QEMU_OPTION_clock
:
8987 configure_alarms(optarg
);
8989 case QEMU_OPTION_startdate
:
8992 time_t rtc_start_date
;
8993 if (!strcmp(optarg
, "now")) {
8994 rtc_date_offset
= -1;
8996 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
9004 } else if (sscanf(optarg
, "%d-%d-%d",
9007 &tm
.tm_mday
) == 3) {
9016 rtc_start_date
= mktimegm(&tm
);
9017 if (rtc_start_date
== -1) {
9019 fprintf(stderr
, "Invalid date format. Valid format are:\n"
9020 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
9023 rtc_date_offset
= time(NULL
) - rtc_start_date
;
9035 if (pipe(fds
) == -1)
9046 len
= read(fds
[0], &status
, 1);
9047 if (len
== -1 && (errno
== EINTR
))
9052 else if (status
== 1) {
9053 fprintf(stderr
, "Could not acquire pidfile\n");
9070 signal(SIGTSTP
, SIG_IGN
);
9071 signal(SIGTTOU
, SIG_IGN
);
9072 signal(SIGTTIN
, SIG_IGN
);
9077 if (kvm_enabled()) {
9078 if (kvm_qemu_init() < 0) {
9079 extern int kvm_allowed
;
9080 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9081 #ifdef NO_CPU_EMULATION
9082 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9090 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9093 write(fds
[1], &status
, 1);
9095 fprintf(stderr
, "Could not acquire pid file\n");
9103 linux_boot
= (kernel_filename
!= NULL
);
9104 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9106 /* XXX: this should not be: some embedded targets just have flash */
9107 if (!linux_boot
&& net_boot
== 0 &&
9111 /* boot to floppy or the default cd if no hard disk defined yet */
9112 if (!boot_devices
[0]) {
9113 boot_devices
= "cad";
9115 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9125 /* init network clients */
9126 if (nb_net_clients
== 0) {
9127 /* if no clients, we use a default config */
9128 net_clients
[0] = "nic";
9129 net_clients
[1] = "user";
9133 for(i
= 0;i
< nb_net_clients
; i
++) {
9134 if (net_client_init(net_clients
[i
]) < 0)
9137 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9138 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9140 if (vlan
->nb_guest_devs
== 0) {
9141 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
9144 if (vlan
->nb_host_devs
== 0)
9146 "Warning: vlan %d is not connected to host network\n",
9151 /* XXX: this should be moved in the PC machine instantiation code */
9152 if (net_boot
!= 0) {
9154 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9155 const char *model
= nd_table
[i
].model
;
9157 if (net_boot
& (1 << i
)) {
9160 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9161 if (get_image_size(buf
) > 0) {
9162 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9163 fprintf(stderr
, "Too many option ROMs\n");
9166 option_rom
[nb_option_roms
] = strdup(buf
);
9173 fprintf(stderr
, "No valid PXE rom found for network device\n");
9179 /* init the memory */
9180 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9182 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9184 if (ram_size
< phys_ram_size
) {
9185 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9186 machine
->name
, (unsigned long long) phys_ram_size
);
9190 phys_ram_size
= ram_size
;
9192 ram_size
= phys_ram_size
;
9195 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9197 phys_ram_size
+= ram_size
;
9200 /* Initialize kvm */
9201 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9202 #define KVM_EXTRA_PAGES 3
9204 #define KVM_EXTRA_PAGES 0
9206 if (kvm_enabled()) {
9207 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9208 if (kvm_qemu_create_context() < 0) {
9209 fprintf(stderr
, "Could not create KVM context\n");
9212 #ifdef KVM_CAP_USER_MEMORY
9216 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9218 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9219 if (!phys_ram_base
) {
9220 fprintf(stderr
, "Could not allocate physical memory\n");
9227 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9228 if (!phys_ram_base
) {
9229 fprintf(stderr
, "Could not allocate physical memory\n");
9236 /* we always create the cdrom drive, even if no disk is there */
9238 if (nb_drives_opt
< MAX_DRIVES
)
9239 drive_add(NULL
, CDROM_ALIAS
);
9241 /* we always create at least one floppy */
9243 if (nb_drives_opt
< MAX_DRIVES
)
9244 drive_add(NULL
, FD_ALIAS
, 0);
9246 /* we always create one sd slot, even if no card is in it */
9248 if (nb_drives_opt
< MAX_DRIVES
)
9249 drive_add(NULL
, SD_ALIAS
);
9251 /* open the virtual block devices
9252 * note that migration with device
9253 * hot add/remove is broken.
9255 for(i
= 0; i
< nb_drives_opt
; i
++)
9256 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9259 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9260 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9265 memset(&display_state
, 0, sizeof(display_state
));
9268 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9271 /* nearly nothing to do */
9272 dumb_display_init(ds
);
9273 } else if (vnc_display
!= NULL
) {
9274 vnc_display_init(ds
);
9275 if (vnc_display_open(ds
, vnc_display
) < 0)
9278 #if defined(CONFIG_CURSES)
9280 curses_display_init(ds
, full_screen
);
9284 #if defined(CONFIG_SDL)
9285 sdl_display_init(ds
, full_screen
, no_frame
);
9286 #elif defined(CONFIG_COCOA)
9287 cocoa_display_init(ds
, full_screen
);
9289 dumb_display_init(ds
);
9293 /* Maintain compatibility with multiple stdio monitors */
9294 if (!strcmp(monitor_device
,"stdio")) {
9295 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9296 const char *devname
= serial_devices
[i
];
9297 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9298 monitor_device
= NULL
;
9300 } else if (devname
&& !strcmp(devname
,"stdio")) {
9301 monitor_device
= NULL
;
9302 serial_devices
[i
] = "mon:stdio";
9307 if (monitor_device
) {
9308 monitor_hd
= qemu_chr_open(monitor_device
);
9310 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9313 monitor_init(monitor_hd
, !nographic
);
9316 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++) {
9317 const char *devname
= vmchannel_devices
[i
];
9318 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
9322 if (strstart(devname
, "di:", &devname
)) {
9323 devid
= strtol(devname
, &termn
, 16);
9324 devname
= termn
+ 1;
9327 fprintf(stderr
, "qemu: could not find vmchannel device id '%s'\n",
9331 vmchannel_hds
[i
] = qemu_chr_open(devname
);
9332 if (!vmchannel_hds
[i
]) {
9333 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n",
9337 vmchannel_init(vmchannel_hds
[i
], devid
, i
);
9341 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9342 const char *devname
= serial_devices
[i
];
9343 if (devname
&& strcmp(devname
, "none")) {
9344 serial_hds
[i
] = qemu_chr_open(devname
);
9345 if (!serial_hds
[i
]) {
9346 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9350 if (strstart(devname
, "vc", 0))
9351 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9355 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9356 const char *devname
= parallel_devices
[i
];
9357 if (devname
&& strcmp(devname
, "none")) {
9358 parallel_hds
[i
] = qemu_chr_open(devname
);
9359 if (!parallel_hds
[i
]) {
9360 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9364 if (strstart(devname
, "vc", 0))
9365 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9372 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9373 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9375 current_machine
= machine
;
9377 /* init USB devices */
9379 for(i
= 0; i
< usb_devices_index
; i
++) {
9380 if (usb_device_add(usb_devices
[i
]) < 0) {
9381 fprintf(stderr
, "Warning: could not add USB device %s\n",
9387 if (display_state
.dpy_refresh
) {
9388 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9389 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9392 #ifdef CONFIG_GDBSTUB
9394 /* XXX: use standard host:port notation and modify options
9396 if (gdbserver_start(gdbstub_port
) < 0) {
9397 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9409 rc
= migrate_incoming(incoming
);
9411 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
9417 /* XXX: simplify init */
9430 len
= write(fds
[1], &status
, 1);
9431 if (len
== -1 && (errno
== EINTR
))
9438 TFR(fd
= open("/dev/null", O_RDWR
));
9452 #if !defined(_WIN32)
9453 /* close network clients */
9454 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9455 VLANClientState
*vc
;
9457 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9458 if (vc
->fd_read
== tap_receive
) {
9460 TAPState
*s
= vc
->opaque
;
9462 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9464 launch_script(s
->down_script
, ifname
, s
->fd
);