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 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3809 VLANState
*vlan
= vc1
->vlan
;
3810 VLANClientState
*vc
;
3813 printf("vlan %d send:\n", vlan
->id
);
3814 hex_dump(stdout
, buf
, size
);
3816 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3818 vc
->fd_read(vc
->opaque
, buf
, size
);
3823 #if defined(CONFIG_SLIRP)
3825 /* slirp network adapter */
3827 static int slirp_inited
;
3828 static VLANClientState
*slirp_vc
;
3830 int slirp_can_output(void)
3832 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3835 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3838 printf("slirp output:\n");
3839 hex_dump(stdout
, pkt
, pkt_len
);
3843 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3846 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3849 printf("slirp input:\n");
3850 hex_dump(stdout
, buf
, size
);
3852 slirp_input(buf
, size
);
3855 static int net_slirp_init(VLANState
*vlan
)
3857 if (!slirp_inited
) {
3861 slirp_vc
= qemu_new_vlan_client(vlan
,
3862 slirp_receive
, NULL
, NULL
);
3863 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3867 static void net_slirp_redir(const char *redir_str
)
3872 struct in_addr guest_addr
;
3873 int host_port
, guest_port
;
3875 if (!slirp_inited
) {
3881 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3883 if (!strcmp(buf
, "tcp")) {
3885 } else if (!strcmp(buf
, "udp")) {
3891 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3893 host_port
= strtol(buf
, &r
, 0);
3897 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3899 if (buf
[0] == '\0') {
3900 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3902 if (!inet_aton(buf
, &guest_addr
))
3905 guest_port
= strtol(p
, &r
, 0);
3909 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3910 fprintf(stderr
, "qemu: could not set up redirection\n");
3915 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3923 static void erase_dir(char *dir_name
)
3927 char filename
[1024];
3929 /* erase all the files in the directory */
3930 if ((d
= opendir(dir_name
)) != 0) {
3935 if (strcmp(de
->d_name
, ".") != 0 &&
3936 strcmp(de
->d_name
, "..") != 0) {
3937 snprintf(filename
, sizeof(filename
), "%s/%s",
3938 smb_dir
, de
->d_name
);
3939 if (unlink(filename
) != 0) /* is it a directory? */
3940 erase_dir(filename
);
3948 /* automatic user mode samba server configuration */
3949 static void smb_exit(void)
3954 /* automatic user mode samba server configuration */
3955 static void net_slirp_smb(const char *exported_dir
)
3957 char smb_conf
[1024];
3958 char smb_cmdline
[1024];
3961 if (!slirp_inited
) {
3966 /* XXX: better tmp dir construction */
3967 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3968 if (mkdir(smb_dir
, 0700) < 0) {
3969 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3972 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3974 f
= fopen(smb_conf
, "w");
3976 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3983 "socket address=127.0.0.1\n"
3984 "pid directory=%s\n"
3985 "lock directory=%s\n"
3986 "log file=%s/log.smbd\n"
3987 "smb passwd file=%s/smbpasswd\n"
3988 "security = share\n"
4003 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
4004 SMBD_COMMAND
, smb_conf
);
4006 slirp_add_exec(0, smb_cmdline
, 4, 139);
4009 #endif /* !defined(_WIN32) */
4010 void do_info_slirp(void)
4015 #endif /* CONFIG_SLIRP */
4017 #if !defined(_WIN32)
4019 typedef struct TAPState
{
4020 VLANClientState
*vc
;
4022 char down_script
[1024];
4026 static int tap_read_poll(void *opaque
)
4028 TAPState
*s
= opaque
;
4029 return (!s
->no_poll
);
4032 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
4034 TAPState
*s
= opaque
;
4037 ret
= write(s
->fd
, buf
, size
);
4038 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
4045 static void tap_send(void *opaque
)
4047 TAPState
*s
= opaque
;
4054 sbuf
.maxlen
= sizeof(buf
);
4056 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
4058 size
= read(s
->fd
, buf
, sizeof(buf
));
4061 qemu_send_packet(s
->vc
, buf
, size
);
4065 int hack_around_tap(void *opaque
)
4067 VLANClientState
*vc
= opaque
;
4068 TAPState
*ts
= vc
->opaque
;
4070 if (vc
->fd_read
!= tap_receive
)
4083 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
4087 s
= qemu_mallocz(sizeof(TAPState
));
4092 enable_sigio_timer(fd
);
4093 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
4094 qemu_set_fd_handler2(s
->fd
, tap_read_poll
, tap_send
, NULL
, s
);
4095 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
4099 #if defined (_BSD) || defined (__FreeBSD_kernel__)
4100 static int tap_open(char *ifname
, int ifname_size
)
4106 TFR(fd
= open("/dev/tap", O_RDWR
));
4108 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
4113 dev
= devname(s
.st_rdev
, S_IFCHR
);
4114 pstrcpy(ifname
, ifname_size
, dev
);
4116 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4119 #elif defined(__sun__)
4120 #define TUNNEWPPA (('T'<<16) | 0x0001)
4122 * Allocate TAP device, returns opened fd.
4123 * Stores dev name in the first arg(must be large enough).
4125 int tap_alloc(char *dev
)
4127 int tap_fd
, if_fd
, ppa
= -1;
4128 static int ip_fd
= 0;
4131 static int arp_fd
= 0;
4132 int ip_muxid
, arp_muxid
;
4133 struct strioctl strioc_if
, strioc_ppa
;
4134 int link_type
= I_PLINK
;;
4136 char actual_name
[32] = "";
4138 memset(&ifr
, 0x0, sizeof(ifr
));
4142 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
4146 /* Check if IP device was opened */
4150 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
4152 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
4156 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
4158 syslog(LOG_ERR
, "Can't open /dev/tap");
4162 /* Assign a new PPA and get its unit number. */
4163 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
4164 strioc_ppa
.ic_timout
= 0;
4165 strioc_ppa
.ic_len
= sizeof(ppa
);
4166 strioc_ppa
.ic_dp
= (char *)&ppa
;
4167 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
4168 syslog (LOG_ERR
, "Can't assign new interface");
4170 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
4172 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
4175 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
4176 syslog(LOG_ERR
, "Can't push IP module");
4180 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4181 syslog(LOG_ERR
, "Can't get flags\n");
4183 snprintf (actual_name
, 32, "tap%d", ppa
);
4184 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4187 /* Assign ppa according to the unit number returned by tun device */
4189 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4190 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4191 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4192 syslog (LOG_ERR
, "Can't get flags\n");
4193 /* Push arp module to if_fd */
4194 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4195 syslog (LOG_ERR
, "Can't push ARP module (2)");
4197 /* Push arp module to ip_fd */
4198 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4199 syslog (LOG_ERR
, "I_POP failed\n");
4200 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4201 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4203 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4205 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4207 /* Set ifname to arp */
4208 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4209 strioc_if
.ic_timout
= 0;
4210 strioc_if
.ic_len
= sizeof(ifr
);
4211 strioc_if
.ic_dp
= (char *)&ifr
;
4212 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4213 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4216 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4217 syslog(LOG_ERR
, "Can't link TAP device to IP");
4221 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4222 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4226 memset(&ifr
, 0x0, sizeof(ifr
));
4227 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4228 ifr
.lifr_ip_muxid
= ip_muxid
;
4229 ifr
.lifr_arp_muxid
= arp_muxid
;
4231 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4233 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4234 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4235 syslog (LOG_ERR
, "Can't set multiplexor id");
4238 sprintf(dev
, "tap%d", ppa
);
4242 static int tap_open(char *ifname
, int ifname_size
)
4246 if( (fd
= tap_alloc(dev
)) < 0 ){
4247 fprintf(stderr
, "Cannot allocate TAP device\n");
4250 pstrcpy(ifname
, ifname_size
, dev
);
4251 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4255 static int tap_open(char *ifname
, int ifname_size
)
4260 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4262 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4265 memset(&ifr
, 0, sizeof(ifr
));
4266 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4267 if (ifname
[0] != '\0')
4268 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4270 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4271 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4273 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4277 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4278 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4283 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4289 /* try to launch network script */
4293 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4294 for (i
= 0; i
< open_max
; i
++)
4295 if (i
!= STDIN_FILENO
&&
4296 i
!= STDOUT_FILENO
&&
4297 i
!= STDERR_FILENO
&&
4302 *parg
++ = (char *)setup_script
;
4303 *parg
++ = (char *)ifname
;
4305 execv(setup_script
, args
);
4308 while (waitpid(pid
, &status
, 0) != pid
);
4309 if (!WIFEXITED(status
) ||
4310 WEXITSTATUS(status
) != 0) {
4311 fprintf(stderr
, "%s: could not launch network script\n",
4319 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4320 const char *setup_script
, const char *down_script
)
4326 if (ifname1
!= NULL
)
4327 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4330 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4334 if (!setup_script
|| !strcmp(setup_script
, "no"))
4336 if (setup_script
[0] != '\0') {
4337 if (launch_script(setup_script
, ifname
, fd
))
4340 s
= net_tap_fd_init(vlan
, fd
);
4343 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4344 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4345 if (down_script
&& strcmp(down_script
, "no"))
4346 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4350 #endif /* !_WIN32 */
4352 /* network connection */
4353 typedef struct NetSocketState
{
4354 VLANClientState
*vc
;
4356 int state
; /* 0 = getting length, 1 = getting data */
4360 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4363 typedef struct NetSocketListenState
{
4366 } NetSocketListenState
;
4368 /* XXX: we consider we can send the whole packet without blocking */
4369 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4371 NetSocketState
*s
= opaque
;
4375 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4376 send_all(s
->fd
, buf
, size
);
4379 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4381 NetSocketState
*s
= opaque
;
4382 sendto(s
->fd
, buf
, size
, 0,
4383 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4386 static void net_socket_send(void *opaque
)
4388 NetSocketState
*s
= opaque
;
4393 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4395 err
= socket_error();
4396 if (err
!= EWOULDBLOCK
)
4398 } else if (size
== 0) {
4399 /* end of connection */
4401 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4407 /* reassemble a packet from the network */
4413 memcpy(s
->buf
+ s
->index
, buf
, l
);
4417 if (s
->index
== 4) {
4419 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4425 l
= s
->packet_len
- s
->index
;
4428 memcpy(s
->buf
+ s
->index
, buf
, l
);
4432 if (s
->index
>= s
->packet_len
) {
4433 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4442 static void net_socket_send_dgram(void *opaque
)
4444 NetSocketState
*s
= opaque
;
4447 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4451 /* end of connection */
4452 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4455 qemu_send_packet(s
->vc
, s
->buf
, size
);
4458 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4463 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4464 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4465 inet_ntoa(mcastaddr
->sin_addr
),
4466 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4470 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4472 perror("socket(PF_INET, SOCK_DGRAM)");
4477 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4478 (const char *)&val
, sizeof(val
));
4480 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4484 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4490 /* Add host to multicast group */
4491 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4492 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4494 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4495 (const char *)&imr
, sizeof(struct ip_mreq
));
4497 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4501 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4503 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4504 (const char *)&val
, sizeof(val
));
4506 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4510 socket_set_nonblock(fd
);
4518 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4521 struct sockaddr_in saddr
;
4523 socklen_t saddr_len
;
4526 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4527 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4528 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4532 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4534 if (saddr
.sin_addr
.s_addr
==0) {
4535 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4539 /* clone dgram socket */
4540 newfd
= net_socket_mcast_create(&saddr
);
4542 /* error already reported by net_socket_mcast_create() */
4546 /* clone newfd to fd, close newfd */
4551 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4552 fd
, strerror(errno
));
4557 s
= qemu_mallocz(sizeof(NetSocketState
));
4562 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4563 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4565 /* mcast: save bound address as dst */
4566 if (is_connected
) s
->dgram_dst
=saddr
;
4568 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4569 "socket: fd=%d (%s mcast=%s:%d)",
4570 fd
, is_connected
? "cloned" : "",
4571 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4575 static void net_socket_connect(void *opaque
)
4577 NetSocketState
*s
= opaque
;
4578 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4581 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4585 s
= qemu_mallocz(sizeof(NetSocketState
));
4589 s
->vc
= qemu_new_vlan_client(vlan
,
4590 net_socket_receive
, NULL
, s
);
4591 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4592 "socket: fd=%d", fd
);
4594 net_socket_connect(s
);
4596 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4601 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4604 int so_type
=-1, optlen
=sizeof(so_type
);
4606 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4607 (socklen_t
*)&optlen
)< 0) {
4608 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4613 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4615 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4617 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4618 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4619 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4624 static void net_socket_accept(void *opaque
)
4626 NetSocketListenState
*s
= opaque
;
4628 struct sockaddr_in saddr
;
4633 len
= sizeof(saddr
);
4634 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4635 if (fd
< 0 && errno
!= EINTR
) {
4637 } else if (fd
>= 0) {
4641 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4645 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4646 "socket: connection from %s:%d",
4647 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4651 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4653 NetSocketListenState
*s
;
4655 struct sockaddr_in saddr
;
4657 if (parse_host_port(&saddr
, host_str
) < 0)
4660 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4664 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4669 socket_set_nonblock(fd
);
4671 /* allow fast reuse */
4673 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4675 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4680 ret
= listen(fd
, 0);
4687 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4691 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4694 int fd
, connected
, ret
, err
;
4695 struct sockaddr_in saddr
;
4697 if (parse_host_port(&saddr
, host_str
) < 0)
4700 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4705 socket_set_nonblock(fd
);
4709 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4711 err
= socket_error();
4712 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4713 } else if (err
== EINPROGRESS
) {
4716 } else if (err
== WSAEALREADY
) {
4729 s
= net_socket_fd_init(vlan
, fd
, connected
);
4732 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4733 "socket: connect to %s:%d",
4734 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4738 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4742 struct sockaddr_in saddr
;
4744 if (parse_host_port(&saddr
, host_str
) < 0)
4748 fd
= net_socket_mcast_create(&saddr
);
4752 s
= net_socket_fd_init(vlan
, fd
, 0);
4756 s
->dgram_dst
= saddr
;
4758 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4759 "socket: mcast=%s:%d",
4760 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4765 static const char *get_opt_name(char *buf
, int buf_size
, const char *p
)
4770 while (*p
!= '\0' && *p
!= '=') {
4771 if (q
&& (q
- buf
) < buf_size
- 1)
4781 static const char *get_opt_value(char *buf
, int buf_size
, const char *p
)
4786 while (*p
!= '\0') {
4788 if (*(p
+ 1) != ',')
4792 if (q
&& (q
- buf
) < buf_size
- 1)
4802 int get_param_value(char *buf
, int buf_size
,
4803 const char *tag
, const char *str
)
4810 p
= get_opt_name(option
, sizeof(option
), p
);
4814 if (!strcmp(tag
, option
)) {
4815 (void)get_opt_value(buf
, buf_size
, p
);
4818 p
= get_opt_value(NULL
, 0, p
);
4827 int check_params(char *buf
, int buf_size
,
4828 char **params
, const char *str
)
4835 p
= get_opt_name(buf
, buf_size
, p
);
4839 for(i
= 0; params
[i
] != NULL
; i
++)
4840 if (!strcmp(params
[i
], buf
))
4842 if (params
[i
] == NULL
)
4844 p
= get_opt_value(NULL
, 0, p
);
4852 static int nic_get_free_idx(void)
4856 for (index
= 0; index
< MAX_NICS
; index
++)
4857 if (!nd_table
[index
].used
)
4862 int net_client_init(const char *str
)
4873 while (*p
!= '\0' && *p
!= ',') {
4874 if ((q
- device
) < sizeof(device
) - 1)
4882 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4883 vlan_id
= strtol(buf
, NULL
, 0);
4885 vlan
= qemu_find_vlan(vlan_id
);
4887 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4890 if (!strcmp(device
, "nic")) {
4893 int idx
= nic_get_free_idx();
4895 if (idx
== -1 || nb_nics
>= MAX_NICS
) {
4896 fprintf(stderr
, "Too Many NICs\n");
4899 nd
= &nd_table
[idx
];
4900 macaddr
= nd
->macaddr
;
4906 macaddr
[5] = 0x56 + idx
;
4908 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4909 if (parse_macaddr(macaddr
, buf
) < 0) {
4910 fprintf(stderr
, "invalid syntax for ethernet address\n");
4914 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4915 nd
->model
= strdup(buf
);
4920 vlan
->nb_guest_devs
++;
4923 if (!strcmp(device
, "none")) {
4924 /* does nothing. It is needed to signal that no network cards
4929 if (!strcmp(device
, "user")) {
4930 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4931 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4933 vlan
->nb_host_devs
++;
4934 ret
= net_slirp_init(vlan
);
4938 if (!strcmp(device
, "tap")) {
4940 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4941 fprintf(stderr
, "tap: no interface name\n");
4944 vlan
->nb_host_devs
++;
4945 ret
= tap_win32_init(vlan
, ifname
);
4948 if (!strcmp(device
, "tap")) {
4950 char setup_script
[1024], down_script
[1024];
4952 vlan
->nb_host_devs
++;
4953 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4954 fd
= strtol(buf
, NULL
, 0);
4955 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4957 if (net_tap_fd_init(vlan
, fd
))
4960 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4963 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4964 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4966 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
4967 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
4969 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
4973 if (!strcmp(device
, "socket")) {
4974 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4976 fd
= strtol(buf
, NULL
, 0);
4978 if (net_socket_fd_init(vlan
, fd
, 1))
4980 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4981 ret
= net_socket_listen_init(vlan
, buf
);
4982 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4983 ret
= net_socket_connect_init(vlan
, buf
);
4984 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4985 ret
= net_socket_mcast_init(vlan
, buf
);
4987 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4990 vlan
->nb_host_devs
++;
4993 fprintf(stderr
, "Unknown network device: %s\n", device
);
4997 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
5003 void net_client_uninit(NICInfo
*nd
)
5005 nd
->vlan
->nb_guest_devs
--; /* XXX: free vlan on last reference */
5008 free((void *)nd
->model
);
5011 void do_info_network(void)
5014 VLANClientState
*vc
;
5016 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
5017 term_printf("VLAN %d devices:\n", vlan
->id
);
5018 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
5019 term_printf(" %s\n", vc
->info_str
);
5023 #define HD_ALIAS "index=%d,media=disk"
5025 #define CDROM_ALIAS "index=1,media=cdrom"
5027 #define CDROM_ALIAS "index=2,media=cdrom"
5029 #define FD_ALIAS "index=%d,if=floppy"
5030 #define PFLASH_ALIAS "if=pflash"
5031 #define MTD_ALIAS "if=mtd"
5032 #define SD_ALIAS "index=0,if=sd"
5034 static int drive_opt_get_free_idx(void)
5038 for (index
= 0; index
< MAX_DRIVES
; index
++)
5039 if (!drives_opt
[index
].used
) {
5040 drives_opt
[index
].used
= 1;
5047 static int drive_get_free_idx(void)
5051 for (index
= 0; index
< MAX_DRIVES
; index
++)
5052 if (!drives_table
[index
].used
) {
5053 drives_table
[index
].used
= 1;
5060 int drive_add(const char *file
, const char *fmt
, ...)
5063 int index
= drive_opt_get_free_idx();
5065 if (nb_drives_opt
>= MAX_DRIVES
|| index
== -1) {
5066 fprintf(stderr
, "qemu: too many drives\n");
5070 drives_opt
[index
].file
= file
;
5072 vsnprintf(drives_opt
[index
].opt
,
5073 sizeof(drives_opt
[0].opt
), fmt
, ap
);
5080 void drive_remove(int index
)
5082 drives_opt
[index
].used
= 0;
5086 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
5090 /* seek interface, bus and unit */
5092 for (index
= 0; index
< MAX_DRIVES
; index
++)
5093 if (drives_table
[index
].type
== type
&&
5094 drives_table
[index
].bus
== bus
&&
5095 drives_table
[index
].unit
== unit
&&
5096 drives_table
[index
].used
)
5102 int drive_get_max_bus(BlockInterfaceType type
)
5108 for (index
= 0; index
< nb_drives
; index
++) {
5109 if(drives_table
[index
].type
== type
&&
5110 drives_table
[index
].bus
> max_bus
)
5111 max_bus
= drives_table
[index
].bus
;
5116 static void bdrv_format_print(void *opaque
, const char *name
)
5118 fprintf(stderr
, " %s", name
);
5121 void drive_uninit(BlockDriverState
*bdrv
)
5125 for (i
= 0; i
< MAX_DRIVES
; i
++)
5126 if (drives_table
[i
].bdrv
== bdrv
) {
5127 drives_table
[i
].bdrv
= NULL
;
5128 drives_table
[i
].used
= 0;
5129 drive_remove(drives_table
[i
].drive_opt_idx
);
5135 int drive_init(struct drive_opt
*arg
, int snapshot
,
5136 QEMUMachine
*machine
)
5141 const char *mediastr
= "";
5142 BlockInterfaceType type
;
5143 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
5144 int bus_id
, unit_id
;
5145 int cyls
, heads
, secs
, translation
;
5146 BlockDriverState
*bdrv
;
5147 BlockDriver
*drv
= NULL
;
5152 int drives_table_idx
;
5153 char *str
= arg
->opt
;
5154 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
5155 "secs", "trans", "media", "snapshot", "file",
5156 "cache", "format", "boot", NULL
};
5158 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
5159 fprintf(stderr
, "qemu: unknown parameter '%s' in '%s'\n",
5165 cyls
= heads
= secs
= 0;
5168 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5172 if (!strcmp(machine
->name
, "realview") ||
5173 !strcmp(machine
->name
, "SS-5") ||
5174 !strcmp(machine
->name
, "SS-10") ||
5175 !strcmp(machine
->name
, "SS-600MP") ||
5176 !strcmp(machine
->name
, "versatilepb") ||
5177 !strcmp(machine
->name
, "versatileab")) {
5179 max_devs
= MAX_SCSI_DEVS
;
5180 strcpy(devname
, "scsi");
5183 max_devs
= MAX_IDE_DEVS
;
5184 strcpy(devname
, "ide");
5188 /* extract parameters */
5190 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
5191 bus_id
= strtol(buf
, NULL
, 0);
5193 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
5198 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
5199 unit_id
= strtol(buf
, NULL
, 0);
5201 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
5206 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
5207 strncpy(devname
, buf
, sizeof(devname
));
5208 if (!strcmp(buf
, "ide")) {
5210 max_devs
= MAX_IDE_DEVS
;
5211 } else if (!strcmp(buf
, "scsi")) {
5213 max_devs
= MAX_SCSI_DEVS
;
5214 } else if (!strcmp(buf
, "floppy")) {
5217 } else if (!strcmp(buf
, "pflash")) {
5220 } else if (!strcmp(buf
, "mtd")) {
5223 } else if (!strcmp(buf
, "sd")) {
5226 } else if (!strcmp(buf
, "virtio")) {
5230 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
5235 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
5236 index
= strtol(buf
, NULL
, 0);
5238 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
5243 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
5244 cyls
= strtol(buf
, NULL
, 0);
5247 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
5248 heads
= strtol(buf
, NULL
, 0);
5251 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
5252 secs
= strtol(buf
, NULL
, 0);
5255 if (cyls
|| heads
|| secs
) {
5256 if (cyls
< 1 || cyls
> 16383) {
5257 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
5260 if (heads
< 1 || heads
> 16) {
5261 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
5264 if (secs
< 1 || secs
> 63) {
5265 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
5270 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
5273 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5277 if (!strcmp(buf
, "none"))
5278 translation
= BIOS_ATA_TRANSLATION_NONE
;
5279 else if (!strcmp(buf
, "lba"))
5280 translation
= BIOS_ATA_TRANSLATION_LBA
;
5281 else if (!strcmp(buf
, "auto"))
5282 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5284 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5289 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5290 if (!strcmp(buf
, "disk")) {
5292 } else if (!strcmp(buf
, "cdrom")) {
5293 if (cyls
|| secs
|| heads
) {
5295 "qemu: '%s' invalid physical CHS format\n", str
);
5298 media
= MEDIA_CDROM
;
5300 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5305 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5306 if (!strcmp(buf
, "on"))
5308 else if (!strcmp(buf
, "off"))
5311 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5316 if (get_param_value(buf
, sizeof(buf
), "cache", str
)) {
5317 if (!strcmp(buf
, "off"))
5319 else if (!strcmp(buf
, "on"))
5322 fprintf(stderr
, "qemu: invalid cache option\n");
5327 if (get_param_value(buf
, sizeof(buf
), "format", str
)) {
5328 if (strcmp(buf
, "?") == 0) {
5329 fprintf(stderr
, "qemu: Supported formats:");
5330 bdrv_iterate_format(bdrv_format_print
, NULL
);
5331 fprintf(stderr
, "\n");
5334 drv
= bdrv_find_format(buf
);
5336 fprintf(stderr
, "qemu: '%s' invalid format\n", buf
);
5341 if (get_param_value(buf
, sizeof(buf
), "boot", str
)) {
5342 if (!strcmp(buf
, "on")) {
5343 if (extboot_drive
!= -1) {
5344 fprintf(stderr
, "qemu: two bootable drives specified\n");
5347 extboot_drive
= nb_drives
;
5348 } else if (strcmp(buf
, "off")) {
5349 fprintf(stderr
, "qemu: '%s' invalid boot option\n", str
);
5354 if (arg
->file
== NULL
)
5355 get_param_value(file
, sizeof(file
), "file", str
);
5357 pstrcpy(file
, sizeof(file
), arg
->file
);
5359 /* compute bus and unit according index */
5362 if (bus_id
!= 0 || unit_id
!= -1) {
5364 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5372 unit_id
= index
% max_devs
;
5373 bus_id
= index
/ max_devs
;
5377 /* if user doesn't specify a unit_id,
5378 * try to find the first free
5381 if (unit_id
== -1) {
5383 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5385 if (max_devs
&& unit_id
>= max_devs
) {
5386 unit_id
-= max_devs
;
5394 if (max_devs
&& unit_id
>= max_devs
) {
5395 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5396 str
, unit_id
, max_devs
- 1);
5401 * ignore multiple definitions
5404 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5409 if (type
== IF_IDE
|| type
== IF_SCSI
)
5410 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5412 snprintf(buf
, sizeof(buf
), "%s%i%s%i",
5413 devname
, bus_id
, mediastr
, unit_id
);
5415 snprintf(buf
, sizeof(buf
), "%s%s%i",
5416 devname
, mediastr
, unit_id
);
5417 bdrv
= bdrv_new(buf
);
5418 drives_table_idx
= drive_get_free_idx();
5419 drives_table
[drives_table_idx
].bdrv
= bdrv
;
5420 drives_table
[drives_table_idx
].type
= type
;
5421 drives_table
[drives_table_idx
].bus
= bus_id
;
5422 drives_table
[drives_table_idx
].unit
= unit_id
;
5423 drives_table
[drives_table_idx
].drive_opt_idx
= arg
- drives_opt
;
5432 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5433 bdrv_set_translation_hint(bdrv
, translation
);
5437 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5442 /* FIXME: This isn't really a floppy, but it's a reasonable
5445 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5456 bdrv_flags
|= BDRV_O_SNAPSHOT
;
5458 bdrv_flags
|= BDRV_O_DIRECT
;
5459 if (bdrv_open2(bdrv
, file
, bdrv_flags
, drv
) < 0 || qemu_key_check(bdrv
, file
)) {
5460 fprintf(stderr
, "qemu: could not open disk image %s\n",
5464 return drives_table_idx
;
5467 /***********************************************************/
5470 static USBPort
*used_usb_ports
;
5471 static USBPort
*free_usb_ports
;
5473 /* ??? Maybe change this to register a hub to keep track of the topology. */
5474 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5475 usb_attachfn attach
)
5477 port
->opaque
= opaque
;
5478 port
->index
= index
;
5479 port
->attach
= attach
;
5480 port
->next
= free_usb_ports
;
5481 free_usb_ports
= port
;
5484 static int usb_device_add(const char *devname
)
5490 if (!free_usb_ports
)
5493 if (strstart(devname
, "host:", &p
)) {
5494 dev
= usb_host_device_open(p
);
5495 } else if (!strcmp(devname
, "mouse")) {
5496 dev
= usb_mouse_init();
5497 } else if (!strcmp(devname
, "tablet")) {
5498 dev
= usb_tablet_init();
5499 } else if (!strcmp(devname
, "keyboard")) {
5500 dev
= usb_keyboard_init();
5501 } else if (strstart(devname
, "disk:", &p
)) {
5502 dev
= usb_msd_init(p
);
5503 } else if (!strcmp(devname
, "wacom-tablet")) {
5504 dev
= usb_wacom_init();
5505 } else if (strstart(devname
, "serial:", &p
)) {
5506 dev
= usb_serial_init(p
);
5507 #ifdef CONFIG_BRLAPI
5508 } else if (!strcmp(devname
, "braille")) {
5509 dev
= usb_baum_init();
5517 /* Find a USB port to add the device to. */
5518 port
= free_usb_ports
;
5522 /* Create a new hub and chain it on. */
5523 free_usb_ports
= NULL
;
5524 port
->next
= used_usb_ports
;
5525 used_usb_ports
= port
;
5527 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5528 usb_attach(port
, hub
);
5529 port
= free_usb_ports
;
5532 free_usb_ports
= port
->next
;
5533 port
->next
= used_usb_ports
;
5534 used_usb_ports
= port
;
5535 usb_attach(port
, dev
);
5539 static int usb_device_del(const char *devname
)
5547 if (!used_usb_ports
)
5550 p
= strchr(devname
, '.');
5553 bus_num
= strtoul(devname
, NULL
, 0);
5554 addr
= strtoul(p
+ 1, NULL
, 0);
5558 lastp
= &used_usb_ports
;
5559 port
= used_usb_ports
;
5560 while (port
&& port
->dev
->addr
!= addr
) {
5561 lastp
= &port
->next
;
5569 *lastp
= port
->next
;
5570 usb_attach(port
, NULL
);
5571 dev
->handle_destroy(dev
);
5572 port
->next
= free_usb_ports
;
5573 free_usb_ports
= port
;
5577 void do_usb_add(const char *devname
)
5580 ret
= usb_device_add(devname
);
5582 term_printf("Could not add USB device '%s'\n", devname
);
5585 void do_usb_del(const char *devname
)
5588 ret
= usb_device_del(devname
);
5590 term_printf("Could not remove USB device '%s'\n", devname
);
5597 const char *speed_str
;
5600 term_printf("USB support not enabled\n");
5604 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5608 switch(dev
->speed
) {
5612 case USB_SPEED_FULL
:
5615 case USB_SPEED_HIGH
:
5622 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5623 0, dev
->addr
, speed_str
, dev
->devname
);
5627 /***********************************************************/
5628 /* PCMCIA/Cardbus */
5630 static struct pcmcia_socket_entry_s
{
5631 struct pcmcia_socket_s
*socket
;
5632 struct pcmcia_socket_entry_s
*next
;
5633 } *pcmcia_sockets
= 0;
5635 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5637 struct pcmcia_socket_entry_s
*entry
;
5639 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5640 entry
->socket
= socket
;
5641 entry
->next
= pcmcia_sockets
;
5642 pcmcia_sockets
= entry
;
5645 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5647 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5649 ptr
= &pcmcia_sockets
;
5650 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5651 if (entry
->socket
== socket
) {
5657 void pcmcia_info(void)
5659 struct pcmcia_socket_entry_s
*iter
;
5660 if (!pcmcia_sockets
)
5661 term_printf("No PCMCIA sockets\n");
5663 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5664 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5665 iter
->socket
->attached
? iter
->socket
->card_string
:
5669 /***********************************************************/
5672 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5676 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5680 static void dumb_refresh(DisplayState
*ds
)
5682 #if defined(CONFIG_SDL)
5687 static void dumb_display_init(DisplayState
*ds
)
5692 ds
->dpy_update
= dumb_update
;
5693 ds
->dpy_resize
= dumb_resize
;
5694 ds
->dpy_refresh
= dumb_refresh
;
5697 /***********************************************************/
5700 #define MAX_IO_HANDLERS 64
5702 typedef struct IOHandlerRecord
{
5704 IOCanRWHandler
*fd_read_poll
;
5706 IOHandler
*fd_write
;
5709 /* temporary data */
5711 struct IOHandlerRecord
*next
;
5714 static IOHandlerRecord
*first_io_handler
;
5716 /* XXX: fd_read_poll should be suppressed, but an API change is
5717 necessary in the character devices to suppress fd_can_read(). */
5718 int qemu_set_fd_handler2(int fd
,
5719 IOCanRWHandler
*fd_read_poll
,
5721 IOHandler
*fd_write
,
5724 IOHandlerRecord
**pioh
, *ioh
;
5726 if (!fd_read
&& !fd_write
) {
5727 pioh
= &first_io_handler
;
5732 if (ioh
->fd
== fd
) {
5739 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5743 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5746 ioh
->next
= first_io_handler
;
5747 first_io_handler
= ioh
;
5750 ioh
->fd_read_poll
= fd_read_poll
;
5751 ioh
->fd_read
= fd_read
;
5752 ioh
->fd_write
= fd_write
;
5753 ioh
->opaque
= opaque
;
5760 int qemu_set_fd_handler(int fd
,
5762 IOHandler
*fd_write
,
5765 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5768 /***********************************************************/
5769 /* Polling handling */
5771 typedef struct PollingEntry
{
5774 struct PollingEntry
*next
;
5777 static PollingEntry
*first_polling_entry
;
5779 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5781 PollingEntry
**ppe
, *pe
;
5782 pe
= qemu_mallocz(sizeof(PollingEntry
));
5786 pe
->opaque
= opaque
;
5787 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5792 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5794 PollingEntry
**ppe
, *pe
;
5795 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5797 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5806 /***********************************************************/
5807 /* Wait objects support */
5808 typedef struct WaitObjects
{
5810 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
5811 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
5812 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
5815 static WaitObjects wait_objects
= {0};
5817 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5819 WaitObjects
*w
= &wait_objects
;
5821 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
5823 w
->events
[w
->num
] = handle
;
5824 w
->func
[w
->num
] = func
;
5825 w
->opaque
[w
->num
] = opaque
;
5830 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5833 WaitObjects
*w
= &wait_objects
;
5836 for (i
= 0; i
< w
->num
; i
++) {
5837 if (w
->events
[i
] == handle
)
5840 w
->events
[i
] = w
->events
[i
+ 1];
5841 w
->func
[i
] = w
->func
[i
+ 1];
5842 w
->opaque
[i
] = w
->opaque
[i
+ 1];
5850 #define SELF_ANNOUNCE_ROUNDS 5
5851 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
5852 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
5853 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
5855 static int announce_self_create(uint8_t *buf
,
5858 uint32_t magic
= EXPERIMENTAL_MAGIC
;
5859 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
5861 /* FIXME: should we send a different packet (arp/rarp/ping)? */
5863 memset(buf
, 0xff, 6); /* h_dst */
5864 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
5865 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
5866 memcpy(buf
+ 14, &magic
, 4); /* magic */
5868 return 18; /* len */
5871 static void qemu_announce_self(void)
5875 VLANClientState
*vc
;
5878 for (i
= 0; i
< nb_nics
; i
++) {
5879 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
5880 vlan
= nd_table
[i
].vlan
;
5881 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
5882 if (vc
->fd_read
== tap_receive
) /* send only if tap */
5883 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
5884 vc
->fd_read(vc
->opaque
, buf
, len
);
5889 /***********************************************************/
5890 /* savevm/loadvm support */
5892 #define IO_BUF_SIZE 32768
5895 QEMUFilePutBufferFunc
*put_buffer
;
5896 QEMUFileGetBufferFunc
*get_buffer
;
5897 QEMUFileCloseFunc
*close
;
5900 int64_t buf_offset
; /* start of buffer when writing, end of buffer
5903 int buf_size
; /* 0 when writing */
5904 uint8_t buf
[IO_BUF_SIZE
];
5907 typedef struct QEMUFileFD
5912 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
5914 QEMUFileFD
*s
= opaque
;
5919 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
5921 if (errno
== EINTR
|| errno
== EAGAIN
)
5928 QEMUFile
*qemu_fopen_fd(int fd
)
5930 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
5932 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
5935 typedef struct QEMUFileUnix
5940 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
5942 QEMUFileUnix
*s
= opaque
;
5943 fseek(s
->outfile
, pos
, SEEK_SET
);
5944 fwrite(buf
, 1, size
, s
->outfile
);
5947 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
5949 QEMUFileUnix
*s
= opaque
;
5950 fseek(s
->outfile
, pos
, SEEK_SET
);
5951 return fread(buf
, 1, size
, s
->outfile
);
5954 static void file_close(void *opaque
)
5956 QEMUFileUnix
*s
= opaque
;
5961 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
5965 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
5969 s
->outfile
= fopen(filename
, mode
);
5973 if (!strcmp(mode
, "wb"))
5974 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
5975 else if (!strcmp(mode
, "rb"))
5976 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
5985 typedef struct QEMUFileBdrv
5987 BlockDriverState
*bs
;
5988 int64_t base_offset
;
5991 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
5993 QEMUFileBdrv
*s
= opaque
;
5994 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
5997 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
5999 QEMUFileBdrv
*s
= opaque
;
6000 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
6003 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
6007 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
6012 s
->base_offset
= offset
;
6015 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
6017 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
6020 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
6021 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
6025 f
= qemu_mallocz(sizeof(QEMUFile
));
6030 f
->put_buffer
= put_buffer
;
6031 f
->get_buffer
= get_buffer
;
6037 void qemu_fflush(QEMUFile
*f
)
6042 if (f
->buf_index
> 0) {
6043 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
6044 f
->buf_offset
+= f
->buf_index
;
6049 static void qemu_fill_buffer(QEMUFile
*f
)
6056 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
6062 f
->buf_offset
+= len
;
6065 void qemu_fclose(QEMUFile
*f
)
6069 f
->close(f
->opaque
);
6073 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
6077 l
= IO_BUF_SIZE
- f
->buf_index
;
6080 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
6084 if (f
->buf_index
>= IO_BUF_SIZE
)
6089 void qemu_put_byte(QEMUFile
*f
, int v
)
6091 f
->buf
[f
->buf_index
++] = v
;
6092 if (f
->buf_index
>= IO_BUF_SIZE
)
6096 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
6102 l
= f
->buf_size
- f
->buf_index
;
6104 qemu_fill_buffer(f
);
6105 l
= f
->buf_size
- f
->buf_index
;
6111 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
6116 return size1
- size
;
6119 int qemu_get_byte(QEMUFile
*f
)
6121 if (f
->buf_index
>= f
->buf_size
) {
6122 qemu_fill_buffer(f
);
6123 if (f
->buf_index
>= f
->buf_size
)
6126 return f
->buf
[f
->buf_index
++];
6129 int64_t qemu_ftell(QEMUFile
*f
)
6131 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
6134 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
6136 if (whence
== SEEK_SET
) {
6138 } else if (whence
== SEEK_CUR
) {
6139 pos
+= qemu_ftell(f
);
6141 /* SEEK_END not supported */
6144 if (f
->put_buffer
) {
6146 f
->buf_offset
= pos
;
6148 f
->buf_offset
= pos
;
6155 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
6157 qemu_put_byte(f
, v
>> 8);
6158 qemu_put_byte(f
, v
);
6161 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
6163 qemu_put_byte(f
, v
>> 24);
6164 qemu_put_byte(f
, v
>> 16);
6165 qemu_put_byte(f
, v
>> 8);
6166 qemu_put_byte(f
, v
);
6169 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
6171 qemu_put_be32(f
, v
>> 32);
6172 qemu_put_be32(f
, v
);
6175 unsigned int qemu_get_be16(QEMUFile
*f
)
6178 v
= qemu_get_byte(f
) << 8;
6179 v
|= qemu_get_byte(f
);
6183 unsigned int qemu_get_be32(QEMUFile
*f
)
6186 v
= qemu_get_byte(f
) << 24;
6187 v
|= qemu_get_byte(f
) << 16;
6188 v
|= qemu_get_byte(f
) << 8;
6189 v
|= qemu_get_byte(f
);
6193 uint64_t qemu_get_be64(QEMUFile
*f
)
6196 v
= (uint64_t)qemu_get_be32(f
) << 32;
6197 v
|= qemu_get_be32(f
);
6201 typedef struct SaveStateEntry
{
6205 SaveStateHandler
*save_state
;
6206 LoadStateHandler
*load_state
;
6208 struct SaveStateEntry
*next
;
6211 static SaveStateEntry
*first_se
;
6213 int register_savevm(const char *idstr
,
6216 SaveStateHandler
*save_state
,
6217 LoadStateHandler
*load_state
,
6220 SaveStateEntry
*se
, **pse
;
6222 se
= qemu_malloc(sizeof(SaveStateEntry
));
6225 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
6226 se
->instance_id
= instance_id
;
6227 se
->version_id
= version_id
;
6228 se
->save_state
= save_state
;
6229 se
->load_state
= load_state
;
6230 se
->opaque
= opaque
;
6233 /* add at the end of list */
6235 while (*pse
!= NULL
)
6236 pse
= &(*pse
)->next
;
6241 #define QEMU_VM_FILE_MAGIC 0x5145564d
6242 #define QEMU_VM_FILE_VERSION 0x00000002
6244 static int qemu_savevm_state(QEMUFile
*f
)
6248 int64_t cur_pos
, len_pos
, total_len_pos
;
6250 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6251 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6252 total_len_pos
= qemu_ftell(f
);
6253 qemu_put_be64(f
, 0); /* total size */
6255 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6257 len
= strlen(se
->idstr
);
6258 qemu_put_byte(f
, len
);
6259 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
6261 qemu_put_be32(f
, se
->instance_id
);
6262 qemu_put_be32(f
, se
->version_id
);
6264 /* record size: filled later */
6265 len_pos
= qemu_ftell(f
);
6266 qemu_put_be32(f
, 0);
6267 se
->save_state(f
, se
->opaque
);
6269 /* fill record size */
6270 cur_pos
= qemu_ftell(f
);
6271 len
= cur_pos
- len_pos
- 4;
6272 qemu_fseek(f
, len_pos
, SEEK_SET
);
6273 qemu_put_be32(f
, len
);
6274 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6276 cur_pos
= qemu_ftell(f
);
6277 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
6278 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
6279 qemu_fseek(f
, cur_pos
, SEEK_SET
);
6285 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
6289 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6290 if (!strcmp(se
->idstr
, idstr
) &&
6291 instance_id
== se
->instance_id
)
6297 static int qemu_loadvm_state(QEMUFile
*f
)
6300 int len
, ret
, instance_id
, record_len
, version_id
;
6301 int64_t total_len
, end_pos
, cur_pos
;
6305 v
= qemu_get_be32(f
);
6306 if (v
!= QEMU_VM_FILE_MAGIC
)
6308 v
= qemu_get_be32(f
);
6309 if (v
!= QEMU_VM_FILE_VERSION
) {
6314 total_len
= qemu_get_be64(f
);
6315 end_pos
= total_len
+ qemu_ftell(f
);
6317 if (qemu_ftell(f
) >= end_pos
)
6319 len
= qemu_get_byte(f
);
6320 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
6322 instance_id
= qemu_get_be32(f
);
6323 version_id
= qemu_get_be32(f
);
6324 record_len
= qemu_get_be32(f
);
6326 printf("idstr=%s instance=0x%x version=%d len=%d\n",
6327 idstr
, instance_id
, version_id
, record_len
);
6329 cur_pos
= qemu_ftell(f
);
6330 se
= find_se(idstr
, instance_id
);
6332 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6333 instance_id
, idstr
);
6335 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6337 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6338 instance_id
, idstr
);
6342 /* always seek to exact end of record */
6343 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
6350 int qemu_live_savevm_state(QEMUFile
*f
)
6355 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
6356 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
6358 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
6359 len
= strlen(se
->idstr
);
6361 qemu_put_byte(f
, len
);
6362 qemu_put_buffer(f
, se
->idstr
, len
);
6363 qemu_put_be32(f
, se
->instance_id
);
6364 qemu_put_be32(f
, se
->version_id
);
6366 se
->save_state(f
, se
->opaque
);
6369 qemu_put_byte(f
, 0);
6375 int qemu_live_loadvm_state(QEMUFile
*f
)
6378 int len
, ret
, instance_id
, version_id
;
6382 v
= qemu_get_be32(f
);
6383 if (v
!= QEMU_VM_FILE_MAGIC
)
6385 v
= qemu_get_be32(f
);
6386 if (v
!= QEMU_VM_FILE_VERSION
) {
6393 len
= qemu_get_byte(f
);
6396 qemu_get_buffer(f
, idstr
, len
);
6398 instance_id
= qemu_get_be32(f
);
6399 version_id
= qemu_get_be32(f
);
6400 se
= find_se(idstr
, instance_id
);
6402 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6403 instance_id
, idstr
);
6405 if (version_id
> se
->version_id
) { /* src version > dst version */
6406 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
6407 idstr
, version_id
, se
->version_id
);
6411 ret
= se
->load_state(f
, se
->opaque
, version_id
);
6413 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6414 instance_id
, idstr
);
6421 qemu_announce_self();
6427 /* device can contain snapshots */
6428 static int bdrv_can_snapshot(BlockDriverState
*bs
)
6431 !bdrv_is_removable(bs
) &&
6432 !bdrv_is_read_only(bs
));
6435 /* device must be snapshots in order to have a reliable snapshot */
6436 static int bdrv_has_snapshot(BlockDriverState
*bs
)
6439 !bdrv_is_removable(bs
) &&
6440 !bdrv_is_read_only(bs
));
6443 static BlockDriverState
*get_bs_snapshots(void)
6445 BlockDriverState
*bs
;
6449 return bs_snapshots
;
6450 for(i
= 0; i
<= nb_drives
; i
++) {
6451 bs
= drives_table
[i
].bdrv
;
6452 if (bdrv_can_snapshot(bs
))
6461 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
6464 QEMUSnapshotInfo
*sn_tab
, *sn
;
6468 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6471 for(i
= 0; i
< nb_sns
; i
++) {
6473 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
6483 void do_savevm(const char *name
)
6485 BlockDriverState
*bs
, *bs1
;
6486 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
6487 int must_delete
, ret
, i
;
6488 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6490 int saved_vm_running
;
6497 bs
= get_bs_snapshots();
6499 term_printf("No block device can accept snapshots\n");
6503 /* ??? Should this occur after vm_stop? */
6506 saved_vm_running
= vm_running
;
6511 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
6516 memset(sn
, 0, sizeof(*sn
));
6518 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
6519 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
6522 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
6525 /* fill auxiliary fields */
6528 sn
->date_sec
= tb
.time
;
6529 sn
->date_nsec
= tb
.millitm
* 1000000;
6531 gettimeofday(&tv
, NULL
);
6532 sn
->date_sec
= tv
.tv_sec
;
6533 sn
->date_nsec
= tv
.tv_usec
* 1000;
6535 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6537 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6538 term_printf("Device %s does not support VM state snapshots\n",
6539 bdrv_get_device_name(bs
));
6543 /* save the VM state */
6544 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6546 term_printf("Could not open VM state file\n");
6549 ret
= qemu_savevm_state(f
);
6550 sn
->vm_state_size
= qemu_ftell(f
);
6553 term_printf("Error %d while writing VM\n", ret
);
6557 /* create the snapshots */
6559 for(i
= 0; i
< nb_drives
; i
++) {
6560 bs1
= drives_table
[i
].bdrv
;
6561 if (bdrv_has_snapshot(bs1
)) {
6563 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6565 term_printf("Error while deleting snapshot on '%s'\n",
6566 bdrv_get_device_name(bs1
));
6569 ret
= bdrv_snapshot_create(bs1
, sn
);
6571 term_printf("Error while creating snapshot on '%s'\n",
6572 bdrv_get_device_name(bs1
));
6578 if (saved_vm_running
)
6582 void do_loadvm(const char *name
)
6584 BlockDriverState
*bs
, *bs1
;
6585 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6588 int saved_vm_running
;
6590 bs
= get_bs_snapshots();
6592 term_printf("No block device supports snapshots\n");
6596 /* Flush all IO requests so they don't interfere with the new state. */
6599 saved_vm_running
= vm_running
;
6602 for(i
= 0; i
<= nb_drives
; i
++) {
6603 bs1
= drives_table
[i
].bdrv
;
6604 if (bdrv_has_snapshot(bs1
)) {
6605 ret
= bdrv_snapshot_goto(bs1
, name
);
6608 term_printf("Warning: ");
6611 term_printf("Snapshots not supported on device '%s'\n",
6612 bdrv_get_device_name(bs1
));
6615 term_printf("Could not find snapshot '%s' on device '%s'\n",
6616 name
, bdrv_get_device_name(bs1
));
6619 term_printf("Error %d while activating snapshot on '%s'\n",
6620 ret
, bdrv_get_device_name(bs1
));
6623 /* fatal on snapshot block device */
6630 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6631 term_printf("Device %s does not support VM state snapshots\n",
6632 bdrv_get_device_name(bs
));
6636 /* restore the VM state */
6637 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6639 term_printf("Could not open VM state file\n");
6642 ret
= qemu_loadvm_state(f
);
6645 term_printf("Error %d while loading VM state\n", ret
);
6648 if (saved_vm_running
)
6652 void do_delvm(const char *name
)
6654 BlockDriverState
*bs
, *bs1
;
6657 bs
= get_bs_snapshots();
6659 term_printf("No block device supports snapshots\n");
6663 for(i
= 0; i
<= nb_drives
; i
++) {
6664 bs1
= drives_table
[i
].bdrv
;
6665 if (bdrv_has_snapshot(bs1
)) {
6666 ret
= bdrv_snapshot_delete(bs1
, name
);
6668 if (ret
== -ENOTSUP
)
6669 term_printf("Snapshots not supported on device '%s'\n",
6670 bdrv_get_device_name(bs1
));
6672 term_printf("Error %d while deleting snapshot on '%s'\n",
6673 ret
, bdrv_get_device_name(bs1
));
6679 void do_info_snapshots(void)
6681 BlockDriverState
*bs
, *bs1
;
6682 QEMUSnapshotInfo
*sn_tab
, *sn
;
6686 bs
= get_bs_snapshots();
6688 term_printf("No available block device supports snapshots\n");
6691 term_printf("Snapshot devices:");
6692 for(i
= 0; i
<= nb_drives
; i
++) {
6693 bs1
= drives_table
[i
].bdrv
;
6694 if (bdrv_has_snapshot(bs1
)) {
6696 term_printf(" %s", bdrv_get_device_name(bs1
));
6701 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6703 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6706 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6707 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6708 for(i
= 0; i
< nb_sns
; i
++) {
6710 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6715 /***********************************************************/
6716 /* ram save/restore */
6718 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6722 v
= qemu_get_byte(f
);
6725 if (qemu_get_buffer(f
, buf
, len
) != len
)
6729 v
= qemu_get_byte(f
);
6730 memset(buf
, v
, len
);
6738 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6743 if (qemu_get_be32(f
) != phys_ram_size
)
6745 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6746 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6748 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6755 #define BDRV_HASH_BLOCK_SIZE 1024
6756 #define IOBUF_SIZE 4096
6757 #define RAM_CBLOCK_MAGIC 0xfabe
6759 typedef struct RamCompressState
{
6762 uint8_t buf
[IOBUF_SIZE
];
6765 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6768 memset(s
, 0, sizeof(*s
));
6770 ret
= deflateInit2(&s
->zstream
, 1,
6772 9, Z_DEFAULT_STRATEGY
);
6775 s
->zstream
.avail_out
= IOBUF_SIZE
;
6776 s
->zstream
.next_out
= s
->buf
;
6780 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6782 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6783 qemu_put_be16(s
->f
, len
);
6784 qemu_put_buffer(s
->f
, buf
, len
);
6787 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6791 s
->zstream
.avail_in
= len
;
6792 s
->zstream
.next_in
= (uint8_t *)buf
;
6793 while (s
->zstream
.avail_in
> 0) {
6794 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6797 if (s
->zstream
.avail_out
== 0) {
6798 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6799 s
->zstream
.avail_out
= IOBUF_SIZE
;
6800 s
->zstream
.next_out
= s
->buf
;
6806 static void ram_compress_close(RamCompressState
*s
)
6810 /* compress last bytes */
6812 ret
= deflate(&s
->zstream
, Z_FINISH
);
6813 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6814 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6816 ram_put_cblock(s
, s
->buf
, len
);
6818 s
->zstream
.avail_out
= IOBUF_SIZE
;
6819 s
->zstream
.next_out
= s
->buf
;
6820 if (ret
== Z_STREAM_END
)
6827 deflateEnd(&s
->zstream
);
6830 typedef struct RamDecompressState
{
6833 uint8_t buf
[IOBUF_SIZE
];
6834 } RamDecompressState
;
6836 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6839 memset(s
, 0, sizeof(*s
));
6841 ret
= inflateInit(&s
->zstream
);
6847 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6851 s
->zstream
.avail_out
= len
;
6852 s
->zstream
.next_out
= buf
;
6853 while (s
->zstream
.avail_out
> 0) {
6854 if (s
->zstream
.avail_in
== 0) {
6855 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6857 clen
= qemu_get_be16(s
->f
);
6858 if (clen
> IOBUF_SIZE
)
6860 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6861 s
->zstream
.avail_in
= clen
;
6862 s
->zstream
.next_in
= s
->buf
;
6864 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6865 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6872 static void ram_decompress_close(RamDecompressState
*s
)
6874 inflateEnd(&s
->zstream
);
6877 static void ram_save_live(QEMUFile
*f
, void *opaque
)
6881 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
6882 if (kvm_enabled() && (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
6884 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
6885 qemu_put_be32(f
, addr
);
6886 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
6889 qemu_put_be32(f
, 1);
6892 static void ram_save_static(QEMUFile
*f
, void *opaque
)
6895 RamCompressState s1
, *s
= &s1
;
6898 qemu_put_be32(f
, phys_ram_size
);
6899 if (ram_compress_open(s
, f
) < 0)
6901 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6902 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6905 if (tight_savevm_enabled
) {
6909 /* find if the memory block is available on a virtual
6912 for(j
= 0; j
< nb_drives
; j
++) {
6913 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
6915 BDRV_HASH_BLOCK_SIZE
);
6916 if (sector_num
>= 0)
6920 goto normal_compress
;
6923 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
6924 ram_compress_buf(s
, buf
, 10);
6930 ram_compress_buf(s
, buf
, 1);
6931 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
6934 ram_compress_close(s
);
6937 static void ram_save(QEMUFile
*f
, void *opaque
)
6939 int in_migration
= cpu_physical_memory_get_dirty_tracking();
6941 qemu_put_byte(f
, in_migration
);
6944 ram_save_live(f
, opaque
);
6946 ram_save_static(f
, opaque
);
6949 static int ram_load_live(QEMUFile
*f
, void *opaque
)
6954 addr
= qemu_get_be32(f
);
6958 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
6964 static int ram_load_static(QEMUFile
*f
, void *opaque
)
6966 RamDecompressState s1
, *s
= &s1
;
6970 if (qemu_get_be32(f
) != phys_ram_size
)
6972 if (ram_decompress_open(s
, f
) < 0)
6974 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6975 if (kvm_enabled() && (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
6977 if (ram_decompress_buf(s
, buf
, 1) < 0) {
6978 fprintf(stderr
, "Error while reading ram block header\n");
6982 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
6983 fprintf(stderr
, "Error while reading ram block address=0x%08" PRIx64
, (uint64_t)i
);
6992 ram_decompress_buf(s
, buf
+ 1, 9);
6994 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
6995 if (bs_index
>= nb_drives
) {
6996 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
6999 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
7001 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
7002 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
7003 bs_index
, sector_num
);
7010 printf("Error block header\n");
7014 ram_decompress_close(s
);
7018 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
7022 switch (version_id
) {
7024 ret
= ram_load_v1(f
, opaque
);
7027 if (qemu_get_byte(f
)) {
7028 ret
= ram_load_live(f
, opaque
);
7032 ret
= ram_load_static(f
, opaque
);
7042 /***********************************************************/
7043 /* bottom halves (can be seen as timers which expire ASAP) */
7052 static QEMUBH
*first_bh
= NULL
;
7054 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7057 bh
= qemu_mallocz(sizeof(QEMUBH
));
7061 bh
->opaque
= opaque
;
7065 int qemu_bh_poll(void)
7084 void qemu_bh_schedule(QEMUBH
*bh
)
7086 CPUState
*env
= cpu_single_env
;
7090 bh
->next
= first_bh
;
7093 /* stop the currently executing CPU to execute the BH ASAP */
7095 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7100 void qemu_bh_cancel(QEMUBH
*bh
)
7103 if (bh
->scheduled
) {
7106 pbh
= &(*pbh
)->next
;
7112 void qemu_bh_delete(QEMUBH
*bh
)
7118 /***********************************************************/
7119 /* machine registration */
7121 QEMUMachine
*first_machine
= NULL
;
7122 QEMUMachine
*current_machine
= NULL
;
7124 int qemu_register_machine(QEMUMachine
*m
)
7127 pm
= &first_machine
;
7135 static QEMUMachine
*find_machine(const char *name
)
7139 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7140 if (!strcmp(m
->name
, name
))
7146 /***********************************************************/
7147 /* main execution loop */
7149 static void gui_update(void *opaque
)
7151 DisplayState
*ds
= opaque
;
7152 ds
->dpy_refresh(ds
);
7153 qemu_mod_timer(ds
->gui_timer
,
7154 (ds
->gui_timer_interval
?
7155 ds
->gui_timer_interval
:
7156 GUI_REFRESH_INTERVAL
)
7157 + qemu_get_clock(rt_clock
));
7160 struct vm_change_state_entry
{
7161 VMChangeStateHandler
*cb
;
7163 LIST_ENTRY (vm_change_state_entry
) entries
;
7166 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7168 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7171 VMChangeStateEntry
*e
;
7173 e
= qemu_mallocz(sizeof (*e
));
7179 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7183 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7185 LIST_REMOVE (e
, entries
);
7189 static void vm_state_notify(int running
)
7191 VMChangeStateEntry
*e
;
7193 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7194 e
->cb(e
->opaque
, running
);
7198 /* XXX: support several handlers */
7199 static VMStopHandler
*vm_stop_cb
;
7200 static void *vm_stop_opaque
;
7202 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7205 vm_stop_opaque
= opaque
;
7209 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7220 qemu_rearm_alarm_timer(alarm_timer
);
7224 void vm_stop(int reason
)
7227 cpu_disable_ticks();
7231 vm_stop_cb(vm_stop_opaque
, reason
);
7238 /* reset/shutdown handler */
7240 typedef struct QEMUResetEntry
{
7241 QEMUResetHandler
*func
;
7243 struct QEMUResetEntry
*next
;
7246 static QEMUResetEntry
*first_reset_entry
;
7247 static int reset_requested
;
7248 static int shutdown_requested
;
7249 static int powerdown_requested
;
7251 int qemu_shutdown_requested(void)
7253 int r
= shutdown_requested
;
7254 shutdown_requested
= 0;
7258 int qemu_reset_requested(void)
7260 int r
= reset_requested
;
7261 reset_requested
= 0;
7265 int qemu_powerdown_requested(void)
7267 int r
= powerdown_requested
;
7268 powerdown_requested
= 0;
7272 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7274 QEMUResetEntry
**pre
, *re
;
7276 pre
= &first_reset_entry
;
7277 while (*pre
!= NULL
)
7278 pre
= &(*pre
)->next
;
7279 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7281 re
->opaque
= opaque
;
7286 void qemu_system_reset(void)
7290 /* reset all devices */
7291 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7292 re
->func(re
->opaque
);
7296 void qemu_system_reset_request(void)
7299 shutdown_requested
= 1;
7301 reset_requested
= 1;
7304 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7308 qemu_kvm_system_reset_request();
7312 void qemu_system_shutdown_request(void)
7314 shutdown_requested
= 1;
7316 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7319 void qemu_system_powerdown_request(void)
7321 powerdown_requested
= 1;
7323 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7326 /* boot_set handler */
7327 QEMUBootSetHandler
*qemu_boot_set_handler
= NULL
;
7329 void qemu_register_boot_set(QEMUBootSetHandler
*func
)
7331 qemu_boot_set_handler
= func
;
7334 static int qemu_select(int max_fd
, fd_set
*rfds
, fd_set
*wfds
, fd_set
*xfds
,
7339 /* KVM holds a mutex while QEMU code is running, we need hooks to
7340 release the mutex whenever QEMU code sleeps. */
7344 ret
= select(max_fd
, rfds
, wfds
, xfds
, tv
);
7351 void main_loop_wait(int timeout
)
7353 IOHandlerRecord
*ioh
;
7354 fd_set rfds
, wfds
, xfds
;
7363 /* XXX: need to suppress polling by better using win32 events */
7365 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7366 ret
|= pe
->func(pe
->opaque
);
7371 WaitObjects
*w
= &wait_objects
;
7373 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7374 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7375 if (w
->func
[ret
- WAIT_OBJECT_0
])
7376 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7378 /* Check for additional signaled events */
7379 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7381 /* Check if event is signaled */
7382 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7383 if(ret2
== WAIT_OBJECT_0
) {
7385 w
->func
[i
](w
->opaque
[i
]);
7386 } else if (ret2
== WAIT_TIMEOUT
) {
7388 err
= GetLastError();
7389 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7392 } else if (ret
== WAIT_TIMEOUT
) {
7394 err
= GetLastError();
7395 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7399 /* poll any events */
7400 /* XXX: separate device handlers from system ones */
7405 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7409 (!ioh
->fd_read_poll
||
7410 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7411 FD_SET(ioh
->fd
, &rfds
);
7415 if (ioh
->fd_write
) {
7416 FD_SET(ioh
->fd
, &wfds
);
7426 tv
.tv_sec
= timeout
/ 1000;
7427 tv
.tv_usec
= (timeout
% 1000) * 1000;
7429 #if defined(CONFIG_SLIRP)
7431 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7434 ret
= qemu_select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7436 IOHandlerRecord
**pioh
;
7438 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7439 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7440 ioh
->fd_read(ioh
->opaque
);
7441 if (!(ioh
->fd_read_poll
&& ioh
->fd_read_poll(ioh
->opaque
)))
7442 FD_CLR(ioh
->fd
, &rfds
);
7444 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7445 ioh
->fd_write(ioh
->opaque
);
7449 /* remove deleted IO handlers */
7450 pioh
= &first_io_handler
;
7460 #if defined(CONFIG_SLIRP)
7467 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7475 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7476 qemu_get_clock(vm_clock
));
7477 /* run dma transfers, if any */
7481 /* real time timers */
7482 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7483 qemu_get_clock(rt_clock
));
7485 if (alarm_timer
->flags
& ALARM_FLAG_EXPIRED
) {
7486 alarm_timer
->flags
&= ~(ALARM_FLAG_EXPIRED
);
7487 qemu_rearm_alarm_timer(alarm_timer
);
7490 /* Check bottom-halves last in case any of the earlier events triggered
7496 static int main_loop(void)
7499 #ifdef CONFIG_PROFILER
7505 if (kvm_enabled()) {
7507 cpu_disable_ticks();
7511 cur_cpu
= first_cpu
;
7512 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7519 #ifdef CONFIG_PROFILER
7520 ti
= profile_getclock();
7522 ret
= cpu_exec(env
);
7523 #ifdef CONFIG_PROFILER
7524 qemu_time
+= profile_getclock() - ti
;
7526 next_cpu
= env
->next_cpu
?: first_cpu
;
7527 if (event_pending
&& likely(ret
!= EXCP_DEBUG
)) {
7528 ret
= EXCP_INTERRUPT
;
7532 if (ret
== EXCP_HLT
) {
7533 /* Give the next CPU a chance to run. */
7537 if (ret
!= EXCP_HALTED
)
7539 /* all CPUs are halted ? */
7545 if (shutdown_requested
) {
7546 ret
= EXCP_INTERRUPT
;
7554 if (reset_requested
) {
7555 reset_requested
= 0;
7556 qemu_system_reset();
7558 kvm_load_registers(env
);
7559 ret
= EXCP_INTERRUPT
;
7561 if (powerdown_requested
) {
7562 powerdown_requested
= 0;
7563 qemu_system_powerdown();
7564 ret
= EXCP_INTERRUPT
;
7566 if (unlikely(ret
== EXCP_DEBUG
)) {
7567 vm_stop(EXCP_DEBUG
);
7569 /* If all cpus are halted then wait until the next IRQ */
7570 /* XXX: use timeout computed from timers */
7571 if (ret
== EXCP_HALTED
)
7578 #ifdef CONFIG_PROFILER
7579 ti
= profile_getclock();
7581 main_loop_wait(timeout
);
7582 #ifdef CONFIG_PROFILER
7583 dev_time
+= profile_getclock() - ti
;
7586 cpu_disable_ticks();
7590 static void help(int exitcode
)
7592 printf("QEMU PC emulator version " QEMU_VERSION
" (" KVM_VERSION
")"
7593 ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7594 "usage: %s [options] [disk_image]\n"
7596 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7598 "Standard options:\n"
7599 "-M machine select emulated machine (-M ? for list)\n"
7600 "-cpu cpu select CPU (-cpu ? for list)\n"
7601 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7602 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7603 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7604 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7605 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7606 " [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7607 " [,cache=on|off][,format=f][,boot=on|off]\n"
7608 " use 'file' as a drive image\n"
7609 "-mtdblock file use 'file' as on-board Flash memory image\n"
7610 "-sd file use 'file' as SecureDigital card image\n"
7611 "-pflash file use 'file' as a parallel flash image\n"
7612 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7613 "-snapshot write to temporary files instead of disk image files\n"
7615 "-no-frame open SDL window without a frame and window decorations\n"
7616 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7617 "-no-quit disable SDL window close capability\n"
7620 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7622 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7623 "-smp n set the number of CPUs to 'n' [default=1]\n"
7624 "-nographic disable graphical output and redirect serial I/Os to console\n"
7625 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7627 "-k language use keyboard layout (for example \"fr\" for French)\n"
7630 "-audio-help print list of audio drivers and their options\n"
7631 "-soundhw c1,... enable audio support\n"
7632 " and only specified sound cards (comma separated list)\n"
7633 " use -soundhw ? to get the list of supported cards\n"
7634 " use -soundhw all to enable all of them\n"
7636 "-localtime set the real time clock to local time [default=utc]\n"
7637 "-full-screen start in full screen\n"
7639 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7641 "-usb enable the USB driver (will be the default soon)\n"
7642 "-usbdevice name add the host or guest USB device 'name'\n"
7643 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7644 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7646 "-name string set the name of the guest\n"
7648 "Network options:\n"
7649 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7650 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7652 "-net user[,vlan=n][,hostname=host]\n"
7653 " connect the user mode network stack to VLAN 'n' and send\n"
7654 " hostname 'host' to DHCP clients\n"
7657 "-net tap[,vlan=n],ifname=name\n"
7658 " connect the host TAP network interface to VLAN 'n'\n"
7660 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7661 " connect the host TAP network interface to VLAN 'n' and use the\n"
7662 " network scripts 'file' (default=%s)\n"
7663 " and 'dfile' (default=%s);\n"
7664 " use '[down]script=no' to disable script execution;\n"
7665 " use 'fd=h' to connect to an already opened TAP interface\n"
7667 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7668 " connect the vlan 'n' to another VLAN using a socket connection\n"
7669 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7670 " connect the vlan 'n' to multicast maddr and port\n"
7671 "-net none use it alone to have zero network devices; if no -net option\n"
7672 " is provided, the default is '-net nic -net user'\n"
7675 "-tftp dir allow tftp access to files in dir [-net user]\n"
7676 "-bootp file advertise file in BOOTP replies\n"
7678 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7680 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7681 " redirect TCP or UDP connections from host to guest [-net user]\n"
7684 "Linux boot specific:\n"
7685 "-kernel bzImage use 'bzImage' as kernel image\n"
7686 "-append cmdline use 'cmdline' as kernel command line\n"
7687 "-initrd file use 'file' as initial ram disk\n"
7689 "Debug/Expert options:\n"
7690 "-monitor dev redirect the monitor to char device 'dev'\n"
7691 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
7692 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
7693 "-serial dev redirect the serial port to char device 'dev'\n"
7694 "-parallel dev redirect the parallel port to char device 'dev'\n"
7695 "-pidfile file Write PID to 'file'\n"
7696 "-S freeze CPU at startup (use 'c' to start execution)\n"
7697 "-s wait gdb connection to port\n"
7698 "-p port set gdb connection port [default=%s]\n"
7699 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7700 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7701 " translation (t=none or lba) (usually qemu can guess them)\n"
7702 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7704 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7705 "-no-kqemu disable KQEMU kernel module usage\n"
7708 #ifndef NO_CPU_EMULATION
7709 "-no-kvm disable KVM hardware virtualization\n"
7711 "-no-kvm-irqchip disable KVM kernel mode PIC/IOAPIC/LAPIC\n"
7712 "-no-kvm-pit disable KVM kernel mode PIT\n"
7715 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7716 " (default is CL-GD5446 PCI VGA)\n"
7717 "-no-acpi disable ACPI\n"
7719 #ifdef CONFIG_CURSES
7720 "-curses use a curses/ncurses interface instead of SDL\n"
7722 "-no-reboot exit instead of rebooting\n"
7723 "-no-shutdown stop before shutdown\n"
7724 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7725 "-vnc display start a VNC server on display\n"
7727 "-daemonize daemonize QEMU after initializing\n"
7729 "-tdf inject timer interrupts that got lost\n"
7730 "-kvm-shadow-memory megs set the amount of shadow pages to be allocated\n"
7731 "-mem-path set the path to hugetlbfs/tmpfs mounted directory, also enables allocation of guest memory with huge pages\n"
7732 "-option-rom rom load a file, rom, into the option ROM space\n"
7734 "-prom-env variable=value set OpenBIOS nvram variables\n"
7736 "-clock force the use of the given methods for timer alarm.\n"
7737 " To see what timers are available use -clock ?\n"
7738 "-startdate select initial date of the clock\n"
7740 "During emulation, the following keys are useful:\n"
7741 "ctrl-alt-f toggle full screen\n"
7742 "ctrl-alt-n switch to virtual console 'n'\n"
7743 "ctrl-alt toggle mouse and keyboard grab\n"
7745 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7750 DEFAULT_NETWORK_SCRIPT
,
7751 DEFAULT_NETWORK_DOWN_SCRIPT
,
7753 DEFAULT_GDBSTUB_PORT
,
7758 #define HAS_ARG 0x0001
7773 QEMU_OPTION_mtdblock
,
7777 QEMU_OPTION_snapshot
,
7779 QEMU_OPTION_no_fd_bootchk
,
7782 QEMU_OPTION_nographic
,
7783 QEMU_OPTION_portrait
,
7785 QEMU_OPTION_audio_help
,
7786 QEMU_OPTION_soundhw
,
7806 QEMU_OPTION_no_code_copy
,
7808 QEMU_OPTION_localtime
,
7809 QEMU_OPTION_cirrusvga
,
7812 QEMU_OPTION_std_vga
,
7814 QEMU_OPTION_monitor
,
7815 QEMU_OPTION_balloon
,
7816 QEMU_OPTION_vmchannel
,
7818 QEMU_OPTION_parallel
,
7820 QEMU_OPTION_full_screen
,
7821 QEMU_OPTION_no_frame
,
7822 QEMU_OPTION_alt_grab
,
7823 QEMU_OPTION_no_quit
,
7824 QEMU_OPTION_pidfile
,
7825 QEMU_OPTION_no_kqemu
,
7826 QEMU_OPTION_kernel_kqemu
,
7827 QEMU_OPTION_win2k_hack
,
7829 QEMU_OPTION_usbdevice
,
7832 QEMU_OPTION_no_acpi
,
7835 QEMU_OPTION_no_kvm_irqchip
,
7836 QEMU_OPTION_no_kvm_pit
,
7837 QEMU_OPTION_no_reboot
,
7838 QEMU_OPTION_no_shutdown
,
7839 QEMU_OPTION_show_cursor
,
7840 QEMU_OPTION_daemonize
,
7841 QEMU_OPTION_option_rom
,
7842 QEMU_OPTION_semihosting
,
7843 QEMU_OPTION_cpu_vendor
,
7845 QEMU_OPTION_prom_env
,
7846 QEMU_OPTION_old_param
,
7848 QEMU_OPTION_startdate
,
7849 QEMU_OPTION_translation
,
7850 QEMU_OPTION_incoming
,
7852 QEMU_OPTION_kvm_shadow_memory
,
7853 QEMU_OPTION_mempath
,
7856 typedef struct QEMUOption
{
7862 const QEMUOption qemu_options
[] = {
7863 { "h", 0, QEMU_OPTION_h
},
7864 { "help", 0, QEMU_OPTION_h
},
7866 { "M", HAS_ARG
, QEMU_OPTION_M
},
7867 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7868 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7869 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7870 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7871 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7872 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7873 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7874 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7875 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7876 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7877 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7878 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7879 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7880 { "snapshot", 0, QEMU_OPTION_snapshot
},
7882 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7884 { "m", HAS_ARG
, QEMU_OPTION_m
},
7885 { "nographic", 0, QEMU_OPTION_nographic
},
7886 { "portrait", 0, QEMU_OPTION_portrait
},
7887 { "k", HAS_ARG
, QEMU_OPTION_k
},
7889 { "audio-help", 0, QEMU_OPTION_audio_help
},
7890 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7893 { "net", HAS_ARG
, QEMU_OPTION_net
},
7895 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7896 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7898 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7900 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7903 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7904 { "append", HAS_ARG
, QEMU_OPTION_append
},
7905 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7907 { "S", 0, QEMU_OPTION_S
},
7908 { "s", 0, QEMU_OPTION_s
},
7909 { "p", HAS_ARG
, QEMU_OPTION_p
},
7910 { "d", HAS_ARG
, QEMU_OPTION_d
},
7911 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7912 { "L", HAS_ARG
, QEMU_OPTION_L
},
7913 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7914 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
7916 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7917 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7920 #ifndef NO_CPU_EMULATION
7921 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
7923 { "no-kvm-irqchip", 0, QEMU_OPTION_no_kvm_irqchip
},
7924 { "no-kvm-pit", 0, QEMU_OPTION_no_kvm_pit
},
7926 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7927 { "g", 1, QEMU_OPTION_g
},
7929 { "localtime", 0, QEMU_OPTION_localtime
},
7930 { "std-vga", 0, QEMU_OPTION_std_vga
},
7931 { "monitor", 1, QEMU_OPTION_monitor
},
7932 { "balloon", 1, QEMU_OPTION_balloon
},
7933 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
7934 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7935 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7936 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7937 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7938 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7939 { "incoming", 1, QEMU_OPTION_incoming
},
7940 { "full-screen", 0, QEMU_OPTION_full_screen
},
7942 { "no-frame", 0, QEMU_OPTION_no_frame
},
7943 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7944 { "no-quit", 0, QEMU_OPTION_no_quit
},
7946 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7947 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7948 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7949 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7950 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7951 #ifdef CONFIG_CURSES
7952 { "curses", 0, QEMU_OPTION_curses
},
7955 /* temporary options */
7956 { "usb", 0, QEMU_OPTION_usb
},
7957 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7958 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7959 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7960 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7961 { "no-shutdown", 0, QEMU_OPTION_no_shutdown
},
7962 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7963 { "daemonize", 0, QEMU_OPTION_daemonize
},
7964 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7965 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7966 { "semihosting", 0, QEMU_OPTION_semihosting
},
7968 { "tdf", 0, QEMU_OPTION_tdf
}, /* enable time drift fix */
7969 { "kvm-shadow-memory", HAS_ARG
, QEMU_OPTION_kvm_shadow_memory
},
7970 { "name", HAS_ARG
, QEMU_OPTION_name
},
7971 #if defined(TARGET_SPARC)
7972 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7974 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
7975 #if defined(TARGET_ARM)
7976 { "old-param", 0, QEMU_OPTION_old_param
},
7978 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7979 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7980 { "mem-path", HAS_ARG
, QEMU_OPTION_mempath
},
7984 /* password input */
7986 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
7991 if (!bdrv_is_encrypted(bs
))
7994 term_printf("%s is encrypted.\n", name
);
7995 for(i
= 0; i
< 3; i
++) {
7996 monitor_readline("Password: ", 1, password
, sizeof(password
));
7997 if (bdrv_set_key(bs
, password
) == 0)
7999 term_printf("invalid password\n");
8004 static BlockDriverState
*get_bdrv(int index
)
8006 if (index
> nb_drives
)
8008 return drives_table
[index
].bdrv
;
8011 static void read_passwords(void)
8013 BlockDriverState
*bs
;
8016 for(i
= 0; i
< 6; i
++) {
8019 qemu_key_check(bs
, bdrv_get_device_name(bs
));
8024 struct soundhw soundhw
[] = {
8025 #ifdef HAS_AUDIO_CHOICE
8026 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8032 { .init_isa
= pcspk_audio_init
}
8037 "Creative Sound Blaster 16",
8040 { .init_isa
= SB16_init
}
8047 "Yamaha YMF262 (OPL3)",
8049 "Yamaha YM3812 (OPL2)",
8053 { .init_isa
= Adlib_init
}
8060 "Gravis Ultrasound GF1",
8063 { .init_isa
= GUS_init
}
8070 "Intel 82801AA AC97 Audio",
8073 { .init_pci
= ac97_init
}
8079 "ENSONIQ AudioPCI ES1370",
8082 { .init_pci
= es1370_init
}
8086 { NULL
, NULL
, 0, 0, { NULL
} }
8089 static void select_soundhw (const char *optarg
)
8093 if (*optarg
== '?') {
8096 printf ("Valid sound card names (comma separated):\n");
8097 for (c
= soundhw
; c
->name
; ++c
) {
8098 printf ("%-11s %s\n", c
->name
, c
->descr
);
8100 printf ("\n-soundhw all will enable all of the above\n");
8101 exit (*optarg
!= '?');
8109 if (!strcmp (optarg
, "all")) {
8110 for (c
= soundhw
; c
->name
; ++c
) {
8118 e
= strchr (p
, ',');
8119 l
= !e
? strlen (p
) : (size_t) (e
- p
);
8121 for (c
= soundhw
; c
->name
; ++c
) {
8122 if (!strncmp (c
->name
, p
, l
)) {
8131 "Unknown sound card name (too big to show)\n");
8134 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8139 p
+= l
+ (e
!= NULL
);
8143 goto show_valid_cards
;
8149 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8151 exit(STATUS_CONTROL_C_EXIT
);
8156 #define MAX_NET_CLIENTS 32
8158 static int saved_argc
;
8159 static char **saved_argv
;
8161 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
8165 *opt_daemonize
= daemonize
;
8166 *opt_incoming
= incoming
;
8170 static int gethugepagesize(void)
8174 char *needle
= "Hugepagesize:";
8176 unsigned long hugepagesize
;
8178 fd
= open("/proc/meminfo", O_RDONLY
);
8184 ret
= read(fd
, buf
, sizeof(buf
));
8190 size
= strstr(buf
, needle
);
8193 size
+= strlen(needle
);
8194 hugepagesize
= strtol(size
, NULL
, 0);
8195 return hugepagesize
;
8198 void *alloc_mem_area(unsigned long memory
, const char *path
)
8204 if (asprintf(&filename
, "%s/kvm.XXXXXX", path
) == -1)
8207 hpagesize
= gethugepagesize() * 1024;
8211 fd
= mkstemp(filename
);
8220 memory
= (memory
+hpagesize
-1) & ~(hpagesize
-1);
8223 * ftruncate is not supported by hugetlbfs in older
8224 * hosts, so don't bother checking for errors.
8225 * If anything goes wrong with it under other filesystems,
8228 ftruncate(fd
, memory
);
8230 area
= mmap(0, memory
, PROT_READ
|PROT_WRITE
, MAP_PRIVATE
, fd
, 0);
8231 if (area
== MAP_FAILED
) {
8240 void *qemu_alloc_physram(unsigned long memory
)
8245 area
= alloc_mem_area(memory
, mem_path
);
8247 area
= qemu_vmalloc(memory
);
8252 int main(int argc
, char **argv
)
8254 #ifdef CONFIG_GDBSTUB
8256 const char *gdbstub_port
;
8258 uint32_t boot_devices_bitmap
= 0;
8260 int snapshot
, linux_boot
, net_boot
;
8261 const char *initrd_filename
;
8262 const char *kernel_filename
, *kernel_cmdline
;
8263 const char *boot_devices
= "";
8264 DisplayState
*ds
= &display_state
;
8265 int cyls
, heads
, secs
, translation
;
8266 const char *net_clients
[MAX_NET_CLIENTS
];
8270 const char *r
, *optarg
;
8271 CharDriverState
*monitor_hd
;
8272 const char *monitor_device
;
8273 const char *serial_devices
[MAX_SERIAL_PORTS
];
8274 int serial_device_index
;
8275 char vmchannel_devices
[MAX_VMCHANNEL_DEVICES
][128];
8276 int vmchannel_device_index
;
8277 const char *parallel_devices
[MAX_PARALLEL_PORTS
];
8278 int parallel_device_index
;
8279 const char *loadvm
= NULL
;
8280 QEMUMachine
*machine
;
8281 const char *cpu_model
;
8282 const char *usb_devices
[MAX_USB_CMDLINE
];
8283 int usb_devices_index
;
8285 const char *pid_file
= NULL
;
8291 LIST_INIT (&vm_change_state_head
);
8294 struct sigaction act
;
8295 sigfillset(&act
.sa_mask
);
8297 act
.sa_handler
= SIG_IGN
;
8298 sigaction(SIGPIPE
, &act
, NULL
);
8301 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8302 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8303 QEMU to run on a single CPU */
8308 h
= GetCurrentProcess();
8309 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8310 for(i
= 0; i
< 32; i
++) {
8311 if (mask
& (1 << i
))
8316 SetProcessAffinityMask(h
, mask
);
8322 register_machines();
8323 machine
= first_machine
;
8325 initrd_filename
= NULL
;
8327 vga_ram_size
= VGA_RAM_SIZE
;
8328 #ifdef CONFIG_GDBSTUB
8330 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8335 kernel_filename
= NULL
;
8336 kernel_cmdline
= "";
8337 cyls
= heads
= secs
= 0;
8338 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8339 monitor_device
= "vc:800x600";
8341 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++)
8342 vmchannel_devices
[i
][0] = '\0';
8343 vmchannel_device_index
= 0;
8345 serial_devices
[0] = "vc:80Cx24C";
8346 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8347 serial_devices
[i
] = NULL
;
8348 serial_device_index
= 0;
8350 parallel_devices
[0] = "vc:640x480";
8351 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8352 parallel_devices
[i
] = NULL
;
8353 parallel_device_index
= 0;
8355 usb_devices_index
= 0;
8363 /* default mac address of the first network interface */
8371 hda_index
= drive_add(argv
[optind
++], HD_ALIAS
, 0);
8373 const QEMUOption
*popt
;
8376 /* Treat --foo the same as -foo. */
8379 popt
= qemu_options
;
8382 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8386 if (!strcmp(popt
->name
, r
+ 1))
8390 if (popt
->flags
& HAS_ARG
) {
8391 if (optind
>= argc
) {
8392 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8396 optarg
= argv
[optind
++];
8401 switch(popt
->index
) {
8403 machine
= find_machine(optarg
);
8406 printf("Supported machines are:\n");
8407 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8408 printf("%-10s %s%s\n",
8410 m
== first_machine
? " (default)" : "");
8412 exit(*optarg
!= '?');
8415 case QEMU_OPTION_cpu
:
8416 /* hw initialization will check this */
8417 if (*optarg
== '?') {
8418 /* XXX: implement xxx_cpu_list for targets that still miss it */
8419 #if defined(cpu_list)
8420 cpu_list(stdout
, &fprintf
);
8427 case QEMU_OPTION_initrd
:
8428 initrd_filename
= optarg
;
8430 case QEMU_OPTION_hda
:
8432 hda_index
= drive_add(optarg
, HD_ALIAS
, 0);
8434 hda_index
= drive_add(optarg
, HD_ALIAS
8435 ",cyls=%d,heads=%d,secs=%d%s",
8436 0, cyls
, heads
, secs
,
8437 translation
== BIOS_ATA_TRANSLATION_LBA
?
8439 translation
== BIOS_ATA_TRANSLATION_NONE
?
8440 ",trans=none" : "");
8442 case QEMU_OPTION_hdb
:
8443 case QEMU_OPTION_hdc
:
8444 case QEMU_OPTION_hdd
:
8445 drive_add(optarg
, HD_ALIAS
, popt
->index
- QEMU_OPTION_hda
);
8447 case QEMU_OPTION_drive
:
8448 drive_add(NULL
, "%s", optarg
);
8450 case QEMU_OPTION_mtdblock
:
8451 drive_add(optarg
, MTD_ALIAS
);
8453 case QEMU_OPTION_sd
:
8454 drive_add(optarg
, SD_ALIAS
);
8456 case QEMU_OPTION_pflash
:
8457 drive_add(optarg
, PFLASH_ALIAS
);
8459 case QEMU_OPTION_snapshot
:
8462 case QEMU_OPTION_hdachs
:
8466 cyls
= strtol(p
, (char **)&p
, 0);
8467 if (cyls
< 1 || cyls
> 16383)
8472 heads
= strtol(p
, (char **)&p
, 0);
8473 if (heads
< 1 || heads
> 16)
8478 secs
= strtol(p
, (char **)&p
, 0);
8479 if (secs
< 1 || secs
> 63)
8483 if (!strcmp(p
, "none"))
8484 translation
= BIOS_ATA_TRANSLATION_NONE
;
8485 else if (!strcmp(p
, "lba"))
8486 translation
= BIOS_ATA_TRANSLATION_LBA
;
8487 else if (!strcmp(p
, "auto"))
8488 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8491 } else if (*p
!= '\0') {
8493 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8496 if (hda_index
!= -1)
8497 snprintf(drives_opt
[hda_index
].opt
,
8498 sizeof(drives_opt
[hda_index
].opt
),
8499 HD_ALIAS
",cyls=%d,heads=%d,secs=%d%s",
8500 0, cyls
, heads
, secs
,
8501 translation
== BIOS_ATA_TRANSLATION_LBA
?
8503 translation
== BIOS_ATA_TRANSLATION_NONE
?
8504 ",trans=none" : "");
8507 case QEMU_OPTION_nographic
:
8508 serial_devices
[0] = "stdio";
8509 parallel_devices
[0] = "null";
8510 monitor_device
= "stdio";
8513 #ifdef CONFIG_CURSES
8514 case QEMU_OPTION_curses
:
8518 case QEMU_OPTION_portrait
:
8521 case QEMU_OPTION_kernel
:
8522 kernel_filename
= optarg
;
8524 case QEMU_OPTION_append
:
8525 kernel_cmdline
= optarg
;
8527 case QEMU_OPTION_cdrom
:
8528 drive_add(optarg
, CDROM_ALIAS
);
8530 case QEMU_OPTION_boot
:
8531 boot_devices
= optarg
;
8532 /* We just do some generic consistency checks */
8534 /* Could easily be extended to 64 devices if needed */
8537 boot_devices_bitmap
= 0;
8538 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8539 /* Allowed boot devices are:
8540 * a b : floppy disk drives
8541 * c ... f : IDE disk drives
8542 * g ... m : machine implementation dependant drives
8543 * n ... p : network devices
8544 * It's up to each machine implementation to check
8545 * if the given boot devices match the actual hardware
8546 * implementation and firmware features.
8548 if (*p
< 'a' || *p
> 'q') {
8549 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8552 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8554 "Boot device '%c' was given twice\n",*p
);
8557 boot_devices_bitmap
|= 1 << (*p
- 'a');
8561 case QEMU_OPTION_fda
:
8562 case QEMU_OPTION_fdb
:
8563 drive_add(optarg
, FD_ALIAS
, popt
->index
- QEMU_OPTION_fda
);
8566 case QEMU_OPTION_no_fd_bootchk
:
8570 case QEMU_OPTION_no_code_copy
:
8571 code_copy_enabled
= 0;
8573 case QEMU_OPTION_net
:
8574 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8575 fprintf(stderr
, "qemu: too many network clients\n");
8578 net_clients
[nb_net_clients
] = optarg
;
8582 case QEMU_OPTION_tftp
:
8583 tftp_prefix
= optarg
;
8585 case QEMU_OPTION_bootp
:
8586 bootp_filename
= optarg
;
8589 case QEMU_OPTION_smb
:
8590 net_slirp_smb(optarg
);
8593 case QEMU_OPTION_redir
:
8594 net_slirp_redir(optarg
);
8598 case QEMU_OPTION_audio_help
:
8602 case QEMU_OPTION_soundhw
:
8603 select_soundhw (optarg
);
8609 case QEMU_OPTION_m
: {
8613 value
= strtoul(optarg
, &ptr
, 10);
8615 case 0: case 'M': case 'm':
8622 fprintf(stderr
, "qemu: invalid ram size: %s\n", optarg
);
8626 /* On 32-bit hosts, QEMU is limited by virtual address space */
8627 if (value
> (2047 << 20)
8629 && HOST_LONG_BITS
== 32
8632 fprintf(stderr
, "qemu: at most 2047 MB RAM can be simulated\n");
8635 if (value
!= (uint64_t)(ram_addr_t
)value
) {
8636 fprintf(stderr
, "qemu: ram size too large\n");
8647 mask
= cpu_str_to_log_mask(optarg
);
8649 printf("Log items (comma separated):\n");
8650 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8651 printf("%-10s %s\n", item
->name
, item
->help
);
8658 #ifdef CONFIG_GDBSTUB
8663 gdbstub_port
= optarg
;
8669 case QEMU_OPTION_bios
:
8676 keyboard_layout
= optarg
;
8678 case QEMU_OPTION_localtime
:
8681 case QEMU_OPTION_cirrusvga
:
8682 cirrus_vga_enabled
= 1;
8685 case QEMU_OPTION_vmsvga
:
8686 cirrus_vga_enabled
= 0;
8689 case QEMU_OPTION_std_vga
:
8690 cirrus_vga_enabled
= 0;
8698 w
= strtol(p
, (char **)&p
, 10);
8701 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8707 h
= strtol(p
, (char **)&p
, 10);
8712 depth
= strtol(p
, (char **)&p
, 10);
8713 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8714 depth
!= 24 && depth
!= 32)
8716 } else if (*p
== '\0') {
8717 depth
= graphic_depth
;
8724 graphic_depth
= depth
;
8727 case QEMU_OPTION_echr
:
8730 term_escape_char
= strtol(optarg
, &r
, 0);
8732 printf("Bad argument to echr\n");
8735 case QEMU_OPTION_monitor
:
8736 monitor_device
= optarg
;
8738 case QEMU_OPTION_balloon
:
8739 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
8740 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
8744 fprintf(stderr
, "qemu: only one balloon device can be used\n");
8747 sprintf(vmchannel_devices
[vmchannel_device_index
],"di:cdcd,%s", optarg
);
8748 vmchannel_device_index
++;
8751 case QEMU_OPTION_vmchannel
:
8752 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
8753 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
8756 pstrcpy(vmchannel_devices
[vmchannel_device_index
],
8757 sizeof(vmchannel_devices
[0]), optarg
);
8758 vmchannel_device_index
++;
8760 case QEMU_OPTION_serial
:
8761 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8762 fprintf(stderr
, "qemu: too many serial ports\n");
8765 serial_devices
[serial_device_index
] = optarg
;
8766 serial_device_index
++;
8768 case QEMU_OPTION_parallel
:
8769 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8770 fprintf(stderr
, "qemu: too many parallel ports\n");
8773 parallel_devices
[parallel_device_index
] = optarg
;
8774 parallel_device_index
++;
8776 case QEMU_OPTION_loadvm
:
8779 case QEMU_OPTION_incoming
:
8782 case QEMU_OPTION_full_screen
:
8786 case QEMU_OPTION_no_frame
:
8789 case QEMU_OPTION_alt_grab
:
8792 case QEMU_OPTION_no_quit
:
8796 case QEMU_OPTION_pidfile
:
8800 case QEMU_OPTION_win2k_hack
:
8801 win2k_install_hack
= 1;
8805 case QEMU_OPTION_no_kqemu
:
8808 case QEMU_OPTION_kernel_kqemu
:
8813 case QEMU_OPTION_no_kvm
:
8816 case QEMU_OPTION_no_kvm_irqchip
: {
8817 extern int kvm_irqchip
, kvm_pit
;
8822 case QEMU_OPTION_no_kvm_pit
: {
8828 case QEMU_OPTION_usb
:
8831 case QEMU_OPTION_usbdevice
:
8833 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8834 fprintf(stderr
, "Too many USB devices\n");
8837 usb_devices
[usb_devices_index
] = optarg
;
8838 usb_devices_index
++;
8840 case QEMU_OPTION_smp
:
8841 smp_cpus
= atoi(optarg
);
8842 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8843 fprintf(stderr
, "Invalid number of CPUs\n");
8847 case QEMU_OPTION_vnc
:
8848 vnc_display
= optarg
;
8850 case QEMU_OPTION_no_acpi
:
8853 case QEMU_OPTION_no_reboot
:
8856 case QEMU_OPTION_no_shutdown
:
8859 case QEMU_OPTION_show_cursor
:
8862 case QEMU_OPTION_daemonize
:
8865 case QEMU_OPTION_option_rom
:
8866 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8867 fprintf(stderr
, "Too many option ROMs\n");
8870 option_rom
[nb_option_roms
] = optarg
;
8873 case QEMU_OPTION_semihosting
:
8874 semihosting_enabled
= 1;
8876 case QEMU_OPTION_tdf
:
8879 case QEMU_OPTION_kvm_shadow_memory
:
8880 kvm_shadow_memory
= (int64_t)atoi(optarg
) * 1024 * 1024 / 4096;
8882 case QEMU_OPTION_mempath
:
8885 case QEMU_OPTION_name
:
8889 case QEMU_OPTION_prom_env
:
8890 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8891 fprintf(stderr
, "Too many prom variables\n");
8894 prom_envs
[nb_prom_envs
] = optarg
;
8898 case QEMU_OPTION_cpu_vendor
:
8899 cpu_vendor_string
= optarg
;
8902 case QEMU_OPTION_old_param
:
8906 case QEMU_OPTION_clock
:
8907 configure_alarms(optarg
);
8909 case QEMU_OPTION_startdate
:
8912 time_t rtc_start_date
;
8913 if (!strcmp(optarg
, "now")) {
8914 rtc_date_offset
= -1;
8916 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8924 } else if (sscanf(optarg
, "%d-%d-%d",
8927 &tm
.tm_mday
) == 3) {
8936 rtc_start_date
= mktimegm(&tm
);
8937 if (rtc_start_date
== -1) {
8939 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8940 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8943 rtc_date_offset
= time(NULL
) - rtc_start_date
;
8955 if (pipe(fds
) == -1)
8966 len
= read(fds
[0], &status
, 1);
8967 if (len
== -1 && (errno
== EINTR
))
8972 else if (status
== 1) {
8973 fprintf(stderr
, "Could not acquire pidfile\n");
8990 signal(SIGTSTP
, SIG_IGN
);
8991 signal(SIGTTOU
, SIG_IGN
);
8992 signal(SIGTTIN
, SIG_IGN
);
8997 if (kvm_enabled()) {
8998 if (kvm_qemu_init() < 0) {
8999 extern int kvm_allowed
;
9000 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
9001 #ifdef NO_CPU_EMULATION
9002 fprintf(stderr
, "Compiled with --disable-cpu-emulation, exiting.\n");
9010 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
9013 write(fds
[1], &status
, 1);
9015 fprintf(stderr
, "Could not acquire pid file\n");
9023 linux_boot
= (kernel_filename
!= NULL
);
9024 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
9026 /* XXX: this should not be: some embedded targets just have flash */
9027 if (!linux_boot
&& net_boot
== 0 &&
9031 /* boot to floppy or the default cd if no hard disk defined yet */
9032 if (!boot_devices
[0]) {
9033 boot_devices
= "cad";
9035 setvbuf(stdout
, NULL
, _IOLBF
, 0);
9045 /* init network clients */
9046 if (nb_net_clients
== 0) {
9047 /* if no clients, we use a default config */
9048 net_clients
[0] = "nic";
9049 net_clients
[1] = "user";
9053 for(i
= 0;i
< nb_net_clients
; i
++) {
9054 if (net_client_init(net_clients
[i
]) < 0)
9057 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9058 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
9060 if (vlan
->nb_guest_devs
== 0) {
9061 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
9064 if (vlan
->nb_host_devs
== 0)
9066 "Warning: vlan %d is not connected to host network\n",
9071 /* XXX: this should be moved in the PC machine instantiation code */
9072 if (net_boot
!= 0) {
9074 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
9075 const char *model
= nd_table
[i
].model
;
9077 if (net_boot
& (1 << i
)) {
9080 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
9081 if (get_image_size(buf
) > 0) {
9082 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
9083 fprintf(stderr
, "Too many option ROMs\n");
9086 option_rom
[nb_option_roms
] = strdup(buf
);
9093 fprintf(stderr
, "No valid PXE rom found for network device\n");
9099 /* init the memory */
9100 phys_ram_size
= machine
->ram_require
& ~RAMSIZE_FIXED
;
9102 if (machine
->ram_require
& RAMSIZE_FIXED
) {
9104 if (ram_size
< phys_ram_size
) {
9105 fprintf(stderr
, "Machine `%s' requires %llu bytes of memory\n",
9106 machine
->name
, (unsigned long long) phys_ram_size
);
9110 phys_ram_size
= ram_size
;
9112 ram_size
= phys_ram_size
;
9115 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
9117 phys_ram_size
+= ram_size
;
9120 /* Initialize kvm */
9121 #if defined(TARGET_I386) || defined(TARGET_X86_64)
9122 #define KVM_EXTRA_PAGES 3
9124 #define KVM_EXTRA_PAGES 0
9126 if (kvm_enabled()) {
9127 phys_ram_size
+= KVM_EXTRA_PAGES
* TARGET_PAGE_SIZE
;
9128 if (kvm_qemu_create_context() < 0) {
9129 fprintf(stderr
, "Could not create KVM context\n");
9132 #ifdef KVM_CAP_USER_MEMORY
9136 ret
= kvm_qemu_check_extension(KVM_CAP_USER_MEMORY
);
9138 phys_ram_base
= qemu_alloc_physram(phys_ram_size
);
9139 if (!phys_ram_base
) {
9140 fprintf(stderr
, "Could not allocate physical memory\n");
9147 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
9148 if (!phys_ram_base
) {
9149 fprintf(stderr
, "Could not allocate physical memory\n");
9156 /* we always create the cdrom drive, even if no disk is there */
9158 if (nb_drives_opt
< MAX_DRIVES
)
9159 drive_add(NULL
, CDROM_ALIAS
);
9161 /* we always create at least one floppy */
9163 if (nb_drives_opt
< MAX_DRIVES
)
9164 drive_add(NULL
, FD_ALIAS
, 0);
9166 /* we always create one sd slot, even if no card is in it */
9168 if (nb_drives_opt
< MAX_DRIVES
)
9169 drive_add(NULL
, SD_ALIAS
);
9171 /* open the virtual block devices
9172 * note that migration with device
9173 * hot add/remove is broken.
9175 for(i
= 0; i
< nb_drives_opt
; i
++)
9176 if (drive_init(&drives_opt
[i
], snapshot
, machine
) == -1)
9179 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
9180 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
9185 memset(&display_state
, 0, sizeof(display_state
));
9188 fprintf(stderr
, "fatal: -nographic can't be used with -curses\n");
9191 /* nearly nothing to do */
9192 dumb_display_init(ds
);
9193 } else if (vnc_display
!= NULL
) {
9194 vnc_display_init(ds
);
9195 if (vnc_display_open(ds
, vnc_display
) < 0)
9198 #if defined(CONFIG_CURSES)
9200 curses_display_init(ds
, full_screen
);
9204 #if defined(CONFIG_SDL)
9205 sdl_display_init(ds
, full_screen
, no_frame
);
9206 #elif defined(CONFIG_COCOA)
9207 cocoa_display_init(ds
, full_screen
);
9209 dumb_display_init(ds
);
9213 /* Maintain compatibility with multiple stdio monitors */
9214 if (!strcmp(monitor_device
,"stdio")) {
9215 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9216 const char *devname
= serial_devices
[i
];
9217 if (devname
&& !strcmp(devname
,"mon:stdio")) {
9218 monitor_device
= NULL
;
9220 } else if (devname
&& !strcmp(devname
,"stdio")) {
9221 monitor_device
= NULL
;
9222 serial_devices
[i
] = "mon:stdio";
9227 if (monitor_device
) {
9228 monitor_hd
= qemu_chr_open(monitor_device
);
9230 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
9233 monitor_init(monitor_hd
, !nographic
);
9236 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++) {
9237 const char *devname
= vmchannel_devices
[i
];
9238 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
9242 if (strstart(devname
, "di:", &devname
)) {
9243 devid
= strtol(devname
, &termn
, 16);
9244 devname
= termn
+ 1;
9247 fprintf(stderr
, "qemu: could not find vmchannel device id '%s'\n",
9251 vmchannel_hds
[i
] = qemu_chr_open(devname
);
9252 if (!vmchannel_hds
[i
]) {
9253 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n",
9257 vmchannel_init(vmchannel_hds
[i
], devid
, i
);
9261 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
9262 const char *devname
= serial_devices
[i
];
9263 if (devname
&& strcmp(devname
, "none")) {
9264 serial_hds
[i
] = qemu_chr_open(devname
);
9265 if (!serial_hds
[i
]) {
9266 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
9270 if (strstart(devname
, "vc", 0))
9271 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
9275 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
9276 const char *devname
= parallel_devices
[i
];
9277 if (devname
&& strcmp(devname
, "none")) {
9278 parallel_hds
[i
] = qemu_chr_open(devname
);
9279 if (!parallel_hds
[i
]) {
9280 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
9284 if (strstart(devname
, "vc", 0))
9285 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
9292 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
9293 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
9295 current_machine
= machine
;
9297 /* init USB devices */
9299 for(i
= 0; i
< usb_devices_index
; i
++) {
9300 if (usb_device_add(usb_devices
[i
]) < 0) {
9301 fprintf(stderr
, "Warning: could not add USB device %s\n",
9307 if (display_state
.dpy_refresh
) {
9308 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
9309 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
9312 #ifdef CONFIG_GDBSTUB
9314 /* XXX: use standard host:port notation and modify options
9316 if (gdbserver_start(gdbstub_port
) < 0) {
9317 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
9329 rc
= migrate_incoming(incoming
);
9331 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
9337 /* XXX: simplify init */
9350 len
= write(fds
[1], &status
, 1);
9351 if (len
== -1 && (errno
== EINTR
))
9358 TFR(fd
= open("/dev/null", O_RDWR
));
9372 #if !defined(_WIN32)
9373 /* close network clients */
9374 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
9375 VLANClientState
*vc
;
9377 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
9378 if (vc
->fd_read
== tap_receive
) {
9380 TAPState
*s
= vc
->opaque
;
9382 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
9384 launch_script(s
->down_script
, ifname
, s
->fd
);