4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
30 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
72 #include <linux/if_tun.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
101 #include <winsock2.h>
102 int inet_aton(const char *cp
, struct in_addr
*ia
);
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
111 #include <sys/timeb.h>
112 #include <mmsystem.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
117 #include "qemu_socket.h"
123 #endif /* CONFIG_SDL */
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
139 #define SMBD_COMMAND "/usr/sbin/smbd"
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
145 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
148 #define DEFAULT_RAM_SIZE 144
150 #define DEFAULT_RAM_SIZE 128
153 #define GUI_REFRESH_INTERVAL 30
155 /* Max number of USB devices that can be specified on the commandline. */
156 #define MAX_USB_CMDLINE 8
158 /* XXX: use a two level table to limit memory usage */
159 #define MAX_IOPORTS 65536
161 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
162 const char *bios_name
= NULL
;
163 void *ioport_opaque
[MAX_IOPORTS
];
164 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
165 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
166 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
167 to store the VM snapshots */
168 DriveInfo drives_table
[MAX_DRIVES
+1];
170 /* point to the block driver where the snapshots are managed */
171 BlockDriverState
*bs_snapshots
;
173 static DisplayState display_state
;
175 const char* keyboard_layout
= NULL
;
176 int64_t ticks_per_sec
;
178 int pit_min_timer_count
= 0;
180 NICInfo nd_table
[MAX_NICS
];
183 int rtc_start_date
= -1; /* -1 means now */
184 int cirrus_vga_enabled
= 1;
185 int vmsvga_enabled
= 0;
187 int graphic_width
= 1024;
188 int graphic_height
= 768;
189 int graphic_depth
= 8;
191 int graphic_width
= 800;
192 int graphic_height
= 600;
193 int graphic_depth
= 15;
198 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
199 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
201 int win2k_install_hack
= 0;
204 static VLANState
*first_vlan
;
206 const char *vnc_display
;
207 #if defined(TARGET_SPARC)
209 #elif defined(TARGET_I386)
214 int acpi_enabled
= 1;
218 int graphic_rotate
= 0;
220 const char *option_rom
[MAX_OPTION_ROMS
];
222 int semihosting_enabled
= 0;
227 const char *qemu_name
;
230 unsigned int nb_prom_envs
= 0;
231 const char *prom_envs
[MAX_PROM_ENVS
];
234 char drives_opt
[MAX_DRIVES
][1024];
236 static CPUState
*cur_cpu
;
237 static CPUState
*next_cpu
;
238 static int event_pending
= 1;
240 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
242 /***********************************************************/
243 /* x86 ISA bus support */
245 target_phys_addr_t isa_mem_base
= 0;
248 static uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
250 #ifdef DEBUG_UNUSED_IOPORT
251 fprintf(stderr
, "unused inb: port=0x%04x\n", address
);
256 static void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
258 #ifdef DEBUG_UNUSED_IOPORT
259 fprintf(stderr
, "unused outb: port=0x%04x data=0x%02x\n", address
, data
);
263 /* default is to make two byte accesses */
264 static uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
267 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
268 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
269 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
273 static void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
275 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
276 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
277 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
280 static uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
282 #ifdef DEBUG_UNUSED_IOPORT
283 fprintf(stderr
, "unused inl: port=0x%04x\n", address
);
288 static void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
290 #ifdef DEBUG_UNUSED_IOPORT
291 fprintf(stderr
, "unused outl: port=0x%04x data=0x%02x\n", address
, data
);
295 static void init_ioports(void)
299 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
300 ioport_read_table
[0][i
] = default_ioport_readb
;
301 ioport_write_table
[0][i
] = default_ioport_writeb
;
302 ioport_read_table
[1][i
] = default_ioport_readw
;
303 ioport_write_table
[1][i
] = default_ioport_writew
;
304 ioport_read_table
[2][i
] = default_ioport_readl
;
305 ioport_write_table
[2][i
] = default_ioport_writel
;
309 /* size is the word size in byte */
310 int register_ioport_read(int start
, int length
, int size
,
311 IOPortReadFunc
*func
, void *opaque
)
317 } else if (size
== 2) {
319 } else if (size
== 4) {
322 hw_error("register_ioport_read: invalid size");
325 for(i
= start
; i
< start
+ length
; i
+= size
) {
326 ioport_read_table
[bsize
][i
] = func
;
327 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
328 hw_error("register_ioport_read: invalid opaque");
329 ioport_opaque
[i
] = opaque
;
334 /* size is the word size in byte */
335 int register_ioport_write(int start
, int length
, int size
,
336 IOPortWriteFunc
*func
, void *opaque
)
342 } else if (size
== 2) {
344 } else if (size
== 4) {
347 hw_error("register_ioport_write: invalid size");
350 for(i
= start
; i
< start
+ length
; i
+= size
) {
351 ioport_write_table
[bsize
][i
] = func
;
352 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
353 hw_error("register_ioport_write: invalid opaque");
354 ioport_opaque
[i
] = opaque
;
359 void isa_unassign_ioport(int start
, int length
)
363 for(i
= start
; i
< start
+ length
; i
++) {
364 ioport_read_table
[0][i
] = default_ioport_readb
;
365 ioport_read_table
[1][i
] = default_ioport_readw
;
366 ioport_read_table
[2][i
] = default_ioport_readl
;
368 ioport_write_table
[0][i
] = default_ioport_writeb
;
369 ioport_write_table
[1][i
] = default_ioport_writew
;
370 ioport_write_table
[2][i
] = default_ioport_writel
;
374 /***********************************************************/
376 void cpu_outb(CPUState
*env
, int addr
, int val
)
379 if (loglevel
& CPU_LOG_IOPORT
)
380 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
382 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
385 env
->last_io_time
= cpu_get_time_fast();
389 void cpu_outw(CPUState
*env
, int addr
, int val
)
392 if (loglevel
& CPU_LOG_IOPORT
)
393 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
395 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
398 env
->last_io_time
= cpu_get_time_fast();
402 void cpu_outl(CPUState
*env
, int addr
, int val
)
405 if (loglevel
& CPU_LOG_IOPORT
)
406 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
408 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
411 env
->last_io_time
= cpu_get_time_fast();
415 int cpu_inb(CPUState
*env
, int addr
)
418 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
420 if (loglevel
& CPU_LOG_IOPORT
)
421 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
425 env
->last_io_time
= cpu_get_time_fast();
430 int cpu_inw(CPUState
*env
, int addr
)
433 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
435 if (loglevel
& CPU_LOG_IOPORT
)
436 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
440 env
->last_io_time
= cpu_get_time_fast();
445 int cpu_inl(CPUState
*env
, int addr
)
448 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
450 if (loglevel
& CPU_LOG_IOPORT
)
451 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
455 env
->last_io_time
= cpu_get_time_fast();
460 /***********************************************************/
461 void hw_error(const char *fmt
, ...)
467 fprintf(stderr
, "qemu: hardware error: ");
468 vfprintf(stderr
, fmt
, ap
);
469 fprintf(stderr
, "\n");
470 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
471 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
473 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
475 cpu_dump_state(env
, stderr
, fprintf
, 0);
482 /***********************************************************/
485 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
486 static void *qemu_put_kbd_event_opaque
;
487 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
488 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
490 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
492 qemu_put_kbd_event_opaque
= opaque
;
493 qemu_put_kbd_event
= func
;
496 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
497 void *opaque
, int absolute
,
500 QEMUPutMouseEntry
*s
, *cursor
;
502 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
506 s
->qemu_put_mouse_event
= func
;
507 s
->qemu_put_mouse_event_opaque
= opaque
;
508 s
->qemu_put_mouse_event_absolute
= absolute
;
509 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
512 if (!qemu_put_mouse_event_head
) {
513 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
517 cursor
= qemu_put_mouse_event_head
;
518 while (cursor
->next
!= NULL
)
519 cursor
= cursor
->next
;
522 qemu_put_mouse_event_current
= s
;
527 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
529 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
531 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
534 cursor
= qemu_put_mouse_event_head
;
535 while (cursor
!= NULL
&& cursor
!= entry
) {
537 cursor
= cursor
->next
;
540 if (cursor
== NULL
) // does not exist or list empty
542 else if (prev
== NULL
) { // entry is head
543 qemu_put_mouse_event_head
= cursor
->next
;
544 if (qemu_put_mouse_event_current
== entry
)
545 qemu_put_mouse_event_current
= cursor
->next
;
546 qemu_free(entry
->qemu_put_mouse_event_name
);
551 prev
->next
= entry
->next
;
553 if (qemu_put_mouse_event_current
== entry
)
554 qemu_put_mouse_event_current
= prev
;
556 qemu_free(entry
->qemu_put_mouse_event_name
);
560 void kbd_put_keycode(int keycode
)
562 if (qemu_put_kbd_event
) {
563 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
567 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
569 QEMUPutMouseEvent
*mouse_event
;
570 void *mouse_event_opaque
;
573 if (!qemu_put_mouse_event_current
) {
578 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
580 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
583 if (graphic_rotate
) {
584 if (qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
)
587 width
= graphic_width
;
588 mouse_event(mouse_event_opaque
,
589 width
- dy
, dx
, dz
, buttons_state
);
591 mouse_event(mouse_event_opaque
,
592 dx
, dy
, dz
, buttons_state
);
596 int kbd_mouse_is_absolute(void)
598 if (!qemu_put_mouse_event_current
)
601 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
604 void do_info_mice(void)
606 QEMUPutMouseEntry
*cursor
;
609 if (!qemu_put_mouse_event_head
) {
610 term_printf("No mouse devices connected\n");
614 term_printf("Mouse devices available:\n");
615 cursor
= qemu_put_mouse_event_head
;
616 while (cursor
!= NULL
) {
617 term_printf("%c Mouse #%d: %s\n",
618 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
619 index
, cursor
->qemu_put_mouse_event_name
);
621 cursor
= cursor
->next
;
625 void do_mouse_set(int index
)
627 QEMUPutMouseEntry
*cursor
;
630 if (!qemu_put_mouse_event_head
) {
631 term_printf("No mouse devices connected\n");
635 cursor
= qemu_put_mouse_event_head
;
636 while (cursor
!= NULL
&& index
!= i
) {
638 cursor
= cursor
->next
;
642 qemu_put_mouse_event_current
= cursor
;
644 term_printf("Mouse at given index not found\n");
647 /* compute with 96 bit intermediate result: (a*b)/c */
648 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
653 #ifdef WORDS_BIGENDIAN
663 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
664 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
667 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
671 /***********************************************************/
672 /* real time host monotonic timer */
674 #define QEMU_TIMER_BASE 1000000000LL
678 static int64_t clock_freq
;
680 static void init_get_clock(void)
684 ret
= QueryPerformanceFrequency(&freq
);
686 fprintf(stderr
, "Could not calibrate ticks\n");
689 clock_freq
= freq
.QuadPart
;
692 static int64_t get_clock(void)
695 QueryPerformanceCounter(&ti
);
696 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
701 static int use_rt_clock
;
703 static void init_get_clock(void)
706 #if defined(__linux__)
709 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
716 static int64_t get_clock(void)
718 #if defined(__linux__)
721 clock_gettime(CLOCK_MONOTONIC
, &ts
);
722 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
726 /* XXX: using gettimeofday leads to problems if the date
727 changes, so it should be avoided. */
729 gettimeofday(&tv
, NULL
);
730 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
736 /***********************************************************/
737 /* guest cycle counter */
739 static int64_t cpu_ticks_prev
;
740 static int64_t cpu_ticks_offset
;
741 static int64_t cpu_clock_offset
;
742 static int cpu_ticks_enabled
;
744 /* return the host CPU cycle counter and handle stop/restart */
745 int64_t cpu_get_ticks(void)
747 if (!cpu_ticks_enabled
) {
748 return cpu_ticks_offset
;
751 ticks
= cpu_get_real_ticks();
752 if (cpu_ticks_prev
> ticks
) {
753 /* Note: non increasing ticks may happen if the host uses
755 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
757 cpu_ticks_prev
= ticks
;
758 return ticks
+ cpu_ticks_offset
;
762 /* return the host CPU monotonic timer and handle stop/restart */
763 static int64_t cpu_get_clock(void)
766 if (!cpu_ticks_enabled
) {
767 return cpu_clock_offset
;
770 return ti
+ cpu_clock_offset
;
774 /* enable cpu_get_ticks() */
775 void cpu_enable_ticks(void)
777 if (!cpu_ticks_enabled
) {
778 cpu_ticks_offset
-= cpu_get_real_ticks();
779 cpu_clock_offset
-= get_clock();
780 cpu_ticks_enabled
= 1;
784 /* disable cpu_get_ticks() : the clock is stopped. You must not call
785 cpu_get_ticks() after that. */
786 void cpu_disable_ticks(void)
788 if (cpu_ticks_enabled
) {
789 cpu_ticks_offset
= cpu_get_ticks();
790 cpu_clock_offset
= cpu_get_clock();
791 cpu_ticks_enabled
= 0;
795 /***********************************************************/
798 #define QEMU_TIMER_REALTIME 0
799 #define QEMU_TIMER_VIRTUAL 1
803 /* XXX: add frequency */
811 struct QEMUTimer
*next
;
814 struct qemu_alarm_timer
{
818 int (*start
)(struct qemu_alarm_timer
*t
);
819 void (*stop
)(struct qemu_alarm_timer
*t
);
820 void (*rearm
)(struct qemu_alarm_timer
*t
);
824 #define ALARM_FLAG_DYNTICKS 0x1
825 #define ALARM_FLAG_MODIFIED 0x2
827 static inline int alarm_has_dynticks(struct qemu_alarm_timer
*t
)
829 return t
->flags
& ALARM_FLAG_DYNTICKS
;
832 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer
*t
)
834 if (!alarm_has_dynticks(t
))
837 if (!(t
->flags
& ALARM_FLAG_MODIFIED
))
840 t
->flags
&= ~(ALARM_FLAG_MODIFIED
);
845 /* TODO: MIN_TIMER_REARM_US should be optimized */
846 #define MIN_TIMER_REARM_US 250
848 static struct qemu_alarm_timer
*alarm_timer
;
852 struct qemu_alarm_win32
{
856 } alarm_win32_data
= {0, NULL
, -1};
858 static int win32_start_timer(struct qemu_alarm_timer
*t
);
859 static void win32_stop_timer(struct qemu_alarm_timer
*t
);
860 static void win32_rearm_timer(struct qemu_alarm_timer
*t
);
864 static int unix_start_timer(struct qemu_alarm_timer
*t
);
865 static void unix_stop_timer(struct qemu_alarm_timer
*t
);
869 static int dynticks_start_timer(struct qemu_alarm_timer
*t
);
870 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
);
871 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
);
873 static int hpet_start_timer(struct qemu_alarm_timer
*t
);
874 static void hpet_stop_timer(struct qemu_alarm_timer
*t
);
876 static int rtc_start_timer(struct qemu_alarm_timer
*t
);
877 static void rtc_stop_timer(struct qemu_alarm_timer
*t
);
879 #endif /* __linux__ */
883 static struct qemu_alarm_timer alarm_timers
[] = {
886 {"dynticks", ALARM_FLAG_DYNTICKS
, dynticks_start_timer
,
887 dynticks_stop_timer
, dynticks_rearm_timer
, NULL
},
888 /* HPET - if available - is preferred */
889 {"hpet", 0, hpet_start_timer
, hpet_stop_timer
, NULL
, NULL
},
890 /* ...otherwise try RTC */
891 {"rtc", 0, rtc_start_timer
, rtc_stop_timer
, NULL
, NULL
},
893 {"unix", 0, unix_start_timer
, unix_stop_timer
, NULL
, NULL
},
895 {"dynticks", ALARM_FLAG_DYNTICKS
, win32_start_timer
,
896 win32_stop_timer
, win32_rearm_timer
, &alarm_win32_data
},
897 {"win32", 0, win32_start_timer
,
898 win32_stop_timer
, NULL
, &alarm_win32_data
},
903 static void show_available_alarms()
907 printf("Available alarm timers, in order of precedence:\n");
908 for (i
= 0; alarm_timers
[i
].name
; i
++)
909 printf("%s\n", alarm_timers
[i
].name
);
912 static void configure_alarms(char const *opt
)
916 int count
= (sizeof(alarm_timers
) / sizeof(*alarm_timers
)) - 1;
920 if (!strcmp(opt
, "help")) {
921 show_available_alarms();
927 /* Reorder the array */
928 name
= strtok(arg
, ",");
930 struct qemu_alarm_timer tmp
;
932 for (i
= 0; i
< count
&& alarm_timers
[i
].name
; i
++) {
933 if (!strcmp(alarm_timers
[i
].name
, name
))
938 fprintf(stderr
, "Unknown clock %s\n", name
);
947 tmp
= alarm_timers
[i
];
948 alarm_timers
[i
] = alarm_timers
[cur
];
949 alarm_timers
[cur
] = tmp
;
953 name
= strtok(NULL
, ",");
959 /* Disable remaining timers */
960 for (i
= cur
; i
< count
; i
++)
961 alarm_timers
[i
].name
= NULL
;
965 show_available_alarms();
971 static QEMUTimer
*active_timers
[2];
973 static QEMUClock
*qemu_new_clock(int type
)
976 clock
= qemu_mallocz(sizeof(QEMUClock
));
983 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
987 ts
= qemu_mallocz(sizeof(QEMUTimer
));
994 void qemu_free_timer(QEMUTimer
*ts
)
999 /* stop a timer, but do not dealloc it */
1000 void qemu_del_timer(QEMUTimer
*ts
)
1004 alarm_timer
->flags
|= ALARM_FLAG_MODIFIED
;
1006 /* NOTE: this code must be signal safe because
1007 qemu_timer_expired() can be called from a signal. */
1008 pt
= &active_timers
[ts
->clock
->type
];
1021 /* modify the current timer so that it will be fired when current_time
1022 >= expire_time. The corresponding callback will be called. */
1023 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
1029 /* add the timer in the sorted list */
1030 /* NOTE: this code must be signal safe because
1031 qemu_timer_expired() can be called from a signal. */
1032 pt
= &active_timers
[ts
->clock
->type
];
1037 if (t
->expire_time
> expire_time
)
1041 ts
->expire_time
= expire_time
;
1046 int qemu_timer_pending(QEMUTimer
*ts
)
1049 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
1056 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
1060 return (timer_head
->expire_time
<= current_time
);
1063 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
1069 if (!ts
|| ts
->expire_time
> current_time
)
1071 /* remove timer from the list before calling the callback */
1072 *ptimer_head
= ts
->next
;
1075 /* run the callback (the timer list can be modified) */
1080 int64_t qemu_get_clock(QEMUClock
*clock
)
1082 switch(clock
->type
) {
1083 case QEMU_TIMER_REALTIME
:
1084 return get_clock() / 1000000;
1086 case QEMU_TIMER_VIRTUAL
:
1087 return cpu_get_clock();
1091 static void init_timers(void)
1094 ticks_per_sec
= QEMU_TIMER_BASE
;
1095 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
1096 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
1100 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1102 uint64_t expire_time
;
1104 if (qemu_timer_pending(ts
)) {
1105 expire_time
= ts
->expire_time
;
1109 qemu_put_be64(f
, expire_time
);
1112 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
1114 uint64_t expire_time
;
1116 expire_time
= qemu_get_be64(f
);
1117 if (expire_time
!= -1) {
1118 qemu_mod_timer(ts
, expire_time
);
1124 static void timer_save(QEMUFile
*f
, void *opaque
)
1126 if (cpu_ticks_enabled
) {
1127 hw_error("cannot save state if virtual timers are running");
1129 qemu_put_be64(f
, cpu_ticks_offset
);
1130 qemu_put_be64(f
, ticks_per_sec
);
1131 qemu_put_be64(f
, cpu_clock_offset
);
1134 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
1136 if (version_id
!= 1 && version_id
!= 2)
1138 if (cpu_ticks_enabled
) {
1141 cpu_ticks_offset
=qemu_get_be64(f
);
1142 ticks_per_sec
=qemu_get_be64(f
);
1143 if (version_id
== 2) {
1144 cpu_clock_offset
=qemu_get_be64(f
);
1150 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
1151 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
1153 static void host_alarm_handler(int host_signum
)
1157 #define DISP_FREQ 1000
1159 static int64_t delta_min
= INT64_MAX
;
1160 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
1162 ti
= qemu_get_clock(vm_clock
);
1163 if (last_clock
!= 0) {
1164 delta
= ti
- last_clock
;
1165 if (delta
< delta_min
)
1167 if (delta
> delta_max
)
1170 if (++count
== DISP_FREQ
) {
1171 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
1172 muldiv64(delta_min
, 1000000, ticks_per_sec
),
1173 muldiv64(delta_max
, 1000000, ticks_per_sec
),
1174 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
1175 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
1177 delta_min
= INT64_MAX
;
1185 if (alarm_has_dynticks(alarm_timer
) ||
1186 qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
1187 qemu_get_clock(vm_clock
)) ||
1188 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
1189 qemu_get_clock(rt_clock
))) {
1191 struct qemu_alarm_win32
*data
= ((struct qemu_alarm_timer
*)dwUser
)->priv
;
1192 SetEvent(data
->host_alarm
);
1194 CPUState
*env
= next_cpu
;
1197 alarm_timer
->flags
|= ALARM_FLAG_MODIFIED
;
1198 /* stop the currently executing cpu because a timer occured */
1199 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
1201 if (env
->kqemu_enabled
) {
1202 kqemu_cpu_interrupt(env
);
1210 static uint64_t qemu_next_deadline(void)
1212 int64_t nearest_delta_us
= INT64_MAX
;
1215 if (active_timers
[QEMU_TIMER_REALTIME
])
1216 nearest_delta_us
= (active_timers
[QEMU_TIMER_REALTIME
]->expire_time
-
1217 qemu_get_clock(rt_clock
))*1000;
1219 if (active_timers
[QEMU_TIMER_VIRTUAL
]) {
1221 vmdelta_us
= (active_timers
[QEMU_TIMER_VIRTUAL
]->expire_time
-
1222 qemu_get_clock(vm_clock
)+999)/1000;
1223 if (vmdelta_us
< nearest_delta_us
)
1224 nearest_delta_us
= vmdelta_us
;
1227 /* Avoid arming the timer to negative, zero, or too low values */
1228 if (nearest_delta_us
<= MIN_TIMER_REARM_US
)
1229 nearest_delta_us
= MIN_TIMER_REARM_US
;
1231 return nearest_delta_us
;
1236 #if defined(__linux__)
1238 #define RTC_FREQ 1024
1240 static void enable_sigio_timer(int fd
)
1242 struct sigaction act
;
1245 sigfillset(&act
.sa_mask
);
1247 act
.sa_handler
= host_alarm_handler
;
1249 sigaction(SIGIO
, &act
, NULL
);
1250 fcntl(fd
, F_SETFL
, O_ASYNC
);
1251 fcntl(fd
, F_SETOWN
, getpid());
1254 static int hpet_start_timer(struct qemu_alarm_timer
*t
)
1256 struct hpet_info info
;
1259 fd
= open("/dev/hpet", O_RDONLY
);
1264 r
= ioctl(fd
, HPET_IRQFREQ
, RTC_FREQ
);
1266 fprintf(stderr
, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1267 "error, but for better emulation accuracy type:\n"
1268 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1272 /* Check capabilities */
1273 r
= ioctl(fd
, HPET_INFO
, &info
);
1277 /* Enable periodic mode */
1278 r
= ioctl(fd
, HPET_EPI
, 0);
1279 if (info
.hi_flags
&& (r
< 0))
1282 /* Enable interrupt */
1283 r
= ioctl(fd
, HPET_IE_ON
, 0);
1287 enable_sigio_timer(fd
);
1288 t
->priv
= (void *)(long)fd
;
1296 static void hpet_stop_timer(struct qemu_alarm_timer
*t
)
1298 int fd
= (long)t
->priv
;
1303 static int rtc_start_timer(struct qemu_alarm_timer
*t
)
1307 TFR(rtc_fd
= open("/dev/rtc", O_RDONLY
));
1310 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1311 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1312 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1313 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1316 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1322 enable_sigio_timer(rtc_fd
);
1324 t
->priv
= (void *)(long)rtc_fd
;
1329 static void rtc_stop_timer(struct qemu_alarm_timer
*t
)
1331 int rtc_fd
= (long)t
->priv
;
1336 static int dynticks_start_timer(struct qemu_alarm_timer
*t
)
1340 struct sigaction act
;
1342 sigfillset(&act
.sa_mask
);
1344 act
.sa_handler
= host_alarm_handler
;
1346 sigaction(SIGALRM
, &act
, NULL
);
1348 ev
.sigev_value
.sival_int
= 0;
1349 ev
.sigev_notify
= SIGEV_SIGNAL
;
1350 ev
.sigev_signo
= SIGALRM
;
1352 if (timer_create(CLOCK_REALTIME
, &ev
, &host_timer
)) {
1353 perror("timer_create");
1355 /* disable dynticks */
1356 fprintf(stderr
, "Dynamic Ticks disabled\n");
1361 t
->priv
= (void *)host_timer
;
1366 static void dynticks_stop_timer(struct qemu_alarm_timer
*t
)
1368 timer_t host_timer
= (timer_t
)t
->priv
;
1370 timer_delete(host_timer
);
1373 static void dynticks_rearm_timer(struct qemu_alarm_timer
*t
)
1375 timer_t host_timer
= (timer_t
)t
->priv
;
1376 struct itimerspec timeout
;
1377 int64_t nearest_delta_us
= INT64_MAX
;
1380 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1381 !active_timers
[QEMU_TIMER_VIRTUAL
])
1384 nearest_delta_us
= qemu_next_deadline();
1386 /* check whether a timer is already running */
1387 if (timer_gettime(host_timer
, &timeout
)) {
1389 fprintf(stderr
, "Internal timer error: aborting\n");
1392 current_us
= timeout
.it_value
.tv_sec
* 1000000 + timeout
.it_value
.tv_nsec
/1000;
1393 if (current_us
&& current_us
<= nearest_delta_us
)
1396 timeout
.it_interval
.tv_sec
= 0;
1397 timeout
.it_interval
.tv_nsec
= 0; /* 0 for one-shot timer */
1398 timeout
.it_value
.tv_sec
= nearest_delta_us
/ 1000000;
1399 timeout
.it_value
.tv_nsec
= (nearest_delta_us
% 1000000) * 1000;
1400 if (timer_settime(host_timer
, 0 /* RELATIVE */, &timeout
, NULL
)) {
1402 fprintf(stderr
, "Internal timer error: aborting\n");
1407 #endif /* defined(__linux__) */
1409 static int unix_start_timer(struct qemu_alarm_timer
*t
)
1411 struct sigaction act
;
1412 struct itimerval itv
;
1416 sigfillset(&act
.sa_mask
);
1418 act
.sa_handler
= host_alarm_handler
;
1420 sigaction(SIGALRM
, &act
, NULL
);
1422 itv
.it_interval
.tv_sec
= 0;
1423 /* for i386 kernel 2.6 to get 1 ms */
1424 itv
.it_interval
.tv_usec
= 999;
1425 itv
.it_value
.tv_sec
= 0;
1426 itv
.it_value
.tv_usec
= 10 * 1000;
1428 err
= setitimer(ITIMER_REAL
, &itv
, NULL
);
1435 static void unix_stop_timer(struct qemu_alarm_timer
*t
)
1437 struct itimerval itv
;
1439 memset(&itv
, 0, sizeof(itv
));
1440 setitimer(ITIMER_REAL
, &itv
, NULL
);
1443 #endif /* !defined(_WIN32) */
1447 static int win32_start_timer(struct qemu_alarm_timer
*t
)
1450 struct qemu_alarm_win32
*data
= t
->priv
;
1453 data
->host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1454 if (!data
->host_alarm
) {
1455 perror("Failed CreateEvent");
1459 memset(&tc
, 0, sizeof(tc
));
1460 timeGetDevCaps(&tc
, sizeof(tc
));
1462 if (data
->period
< tc
.wPeriodMin
)
1463 data
->period
= tc
.wPeriodMin
;
1465 timeBeginPeriod(data
->period
);
1467 flags
= TIME_CALLBACK_FUNCTION
;
1468 if (alarm_has_dynticks(t
))
1469 flags
|= TIME_ONESHOT
;
1471 flags
|= TIME_PERIODIC
;
1473 data
->timerId
= timeSetEvent(1, // interval (ms)
1474 data
->period
, // resolution
1475 host_alarm_handler
, // function
1476 (DWORD
)t
, // parameter
1479 if (!data
->timerId
) {
1480 perror("Failed to initialize win32 alarm timer");
1482 timeEndPeriod(data
->period
);
1483 CloseHandle(data
->host_alarm
);
1487 qemu_add_wait_object(data
->host_alarm
, NULL
, NULL
);
1492 static void win32_stop_timer(struct qemu_alarm_timer
*t
)
1494 struct qemu_alarm_win32
*data
= t
->priv
;
1496 timeKillEvent(data
->timerId
);
1497 timeEndPeriod(data
->period
);
1499 CloseHandle(data
->host_alarm
);
1502 static void win32_rearm_timer(struct qemu_alarm_timer
*t
)
1504 struct qemu_alarm_win32
*data
= t
->priv
;
1505 uint64_t nearest_delta_us
;
1507 if (!active_timers
[QEMU_TIMER_REALTIME
] &&
1508 !active_timers
[QEMU_TIMER_VIRTUAL
])
1511 nearest_delta_us
= qemu_next_deadline();
1512 nearest_delta_us
/= 1000;
1514 timeKillEvent(data
->timerId
);
1516 data
->timerId
= timeSetEvent(1,
1520 TIME_ONESHOT
| TIME_PERIODIC
);
1522 if (!data
->timerId
) {
1523 perror("Failed to re-arm win32 alarm timer");
1525 timeEndPeriod(data
->period
);
1526 CloseHandle(data
->host_alarm
);
1533 static void init_timer_alarm(void)
1535 struct qemu_alarm_timer
*t
;
1538 for (i
= 0; alarm_timers
[i
].name
; i
++) {
1539 t
= &alarm_timers
[i
];
1547 fprintf(stderr
, "Unable to find any suitable alarm timer.\n");
1548 fprintf(stderr
, "Terminating\n");
1555 static void quit_timers(void)
1557 alarm_timer
->stop(alarm_timer
);
1561 /***********************************************************/
1562 /* character device */
1564 static void qemu_chr_event(CharDriverState
*s
, int event
)
1568 s
->chr_event(s
->handler_opaque
, event
);
1571 static void qemu_chr_reset_bh(void *opaque
)
1573 CharDriverState
*s
= opaque
;
1574 qemu_chr_event(s
, CHR_EVENT_RESET
);
1575 qemu_bh_delete(s
->bh
);
1579 void qemu_chr_reset(CharDriverState
*s
)
1581 if (s
->bh
== NULL
) {
1582 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1583 qemu_bh_schedule(s
->bh
);
1587 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1589 return s
->chr_write(s
, buf
, len
);
1592 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1596 return s
->chr_ioctl(s
, cmd
, arg
);
1599 int qemu_chr_can_read(CharDriverState
*s
)
1601 if (!s
->chr_can_read
)
1603 return s
->chr_can_read(s
->handler_opaque
);
1606 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1608 s
->chr_read(s
->handler_opaque
, buf
, len
);
1611 void qemu_chr_accept_input(CharDriverState
*s
)
1613 if (s
->chr_accept_input
)
1614 s
->chr_accept_input(s
);
1617 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1622 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1623 qemu_chr_write(s
, (uint8_t *)buf
, strlen(buf
));
1627 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1629 if (s
->chr_send_event
)
1630 s
->chr_send_event(s
, event
);
1633 void qemu_chr_add_handlers(CharDriverState
*s
,
1634 IOCanRWHandler
*fd_can_read
,
1635 IOReadHandler
*fd_read
,
1636 IOEventHandler
*fd_event
,
1639 s
->chr_can_read
= fd_can_read
;
1640 s
->chr_read
= fd_read
;
1641 s
->chr_event
= fd_event
;
1642 s
->handler_opaque
= opaque
;
1643 if (s
->chr_update_read_handler
)
1644 s
->chr_update_read_handler(s
);
1647 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1652 static CharDriverState
*qemu_chr_open_null(void)
1654 CharDriverState
*chr
;
1656 chr
= qemu_mallocz(sizeof(CharDriverState
));
1659 chr
->chr_write
= null_chr_write
;
1663 /* MUX driver for serial I/O splitting */
1664 static int term_timestamps
;
1665 static int64_t term_timestamps_start
;
1667 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1668 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1670 IOCanRWHandler
*chr_can_read
[MAX_MUX
];
1671 IOReadHandler
*chr_read
[MAX_MUX
];
1672 IOEventHandler
*chr_event
[MAX_MUX
];
1673 void *ext_opaque
[MAX_MUX
];
1674 CharDriverState
*drv
;
1675 unsigned char buffer
[MUX_BUFFER_SIZE
];
1679 int term_got_escape
;
1684 static int mux_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1686 MuxDriver
*d
= chr
->opaque
;
1688 if (!term_timestamps
) {
1689 ret
= d
->drv
->chr_write(d
->drv
, buf
, len
);
1694 for(i
= 0; i
< len
; i
++) {
1695 ret
+= d
->drv
->chr_write(d
->drv
, buf
+i
, 1);
1696 if (buf
[i
] == '\n') {
1702 if (term_timestamps_start
== -1)
1703 term_timestamps_start
= ti
;
1704 ti
-= term_timestamps_start
;
1705 secs
= ti
/ 1000000000;
1706 snprintf(buf1
, sizeof(buf1
),
1707 "[%02d:%02d:%02d.%03d] ",
1711 (int)((ti
/ 1000000) % 1000));
1712 d
->drv
->chr_write(d
->drv
, (uint8_t *)buf1
, strlen(buf1
));
1719 static char *mux_help
[] = {
1720 "% h print this help\n\r",
1721 "% x exit emulator\n\r",
1722 "% s save disk data back to file (if -snapshot)\n\r",
1723 "% t toggle console timestamps\n\r"
1724 "% b send break (magic sysrq)\n\r",
1725 "% c switch between console and monitor\n\r",
1730 static int term_escape_char
= 0x01; /* ctrl-a is used for escape */
1731 static void mux_print_help(CharDriverState
*chr
)
1734 char ebuf
[15] = "Escape-Char";
1735 char cbuf
[50] = "\n\r";
1737 if (term_escape_char
> 0 && term_escape_char
< 26) {
1738 sprintf(cbuf
,"\n\r");
1739 sprintf(ebuf
,"C-%c", term_escape_char
- 1 + 'a');
1741 sprintf(cbuf
,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1744 chr
->chr_write(chr
, (uint8_t *)cbuf
, strlen(cbuf
));
1745 for (i
= 0; mux_help
[i
] != NULL
; i
++) {
1746 for (j
=0; mux_help
[i
][j
] != '\0'; j
++) {
1747 if (mux_help
[i
][j
] == '%')
1748 chr
->chr_write(chr
, (uint8_t *)ebuf
, strlen(ebuf
));
1750 chr
->chr_write(chr
, (uint8_t *)&mux_help
[i
][j
], 1);
1755 static int mux_proc_byte(CharDriverState
*chr
, MuxDriver
*d
, int ch
)
1757 if (d
->term_got_escape
) {
1758 d
->term_got_escape
= 0;
1759 if (ch
== term_escape_char
)
1764 mux_print_help(chr
);
1768 char *term
= "QEMU: Terminated\n\r";
1769 chr
->chr_write(chr
,(uint8_t *)term
,strlen(term
));
1776 for (i
= 0; i
< nb_drives
; i
++) {
1777 bdrv_commit(drives_table
[i
].bdrv
);
1782 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1785 /* Switch to the next registered device */
1787 if (chr
->focus
>= d
->mux_cnt
)
1791 term_timestamps
= !term_timestamps
;
1792 term_timestamps_start
= -1;
1795 } else if (ch
== term_escape_char
) {
1796 d
->term_got_escape
= 1;
1804 static void mux_chr_accept_input(CharDriverState
*chr
)
1807 MuxDriver
*d
= chr
->opaque
;
1809 while (d
->prod
!= d
->cons
&&
1810 d
->chr_can_read
[m
] &&
1811 d
->chr_can_read
[m
](d
->ext_opaque
[m
])) {
1812 d
->chr_read
[m
](d
->ext_opaque
[m
],
1813 &d
->buffer
[d
->cons
++ & MUX_BUFFER_MASK
], 1);
1817 static int mux_chr_can_read(void *opaque
)
1819 CharDriverState
*chr
= opaque
;
1820 MuxDriver
*d
= chr
->opaque
;
1822 if ((d
->prod
- d
->cons
) < MUX_BUFFER_SIZE
)
1824 if (d
->chr_can_read
[chr
->focus
])
1825 return d
->chr_can_read
[chr
->focus
](d
->ext_opaque
[chr
->focus
]);
1829 static void mux_chr_read(void *opaque
, const uint8_t *buf
, int size
)
1831 CharDriverState
*chr
= opaque
;
1832 MuxDriver
*d
= chr
->opaque
;
1836 mux_chr_accept_input (opaque
);
1838 for(i
= 0; i
< size
; i
++)
1839 if (mux_proc_byte(chr
, d
, buf
[i
])) {
1840 if (d
->prod
== d
->cons
&&
1841 d
->chr_can_read
[m
] &&
1842 d
->chr_can_read
[m
](d
->ext_opaque
[m
]))
1843 d
->chr_read
[m
](d
->ext_opaque
[m
], &buf
[i
], 1);
1845 d
->buffer
[d
->prod
++ & MUX_BUFFER_MASK
] = buf
[i
];
1849 static void mux_chr_event(void *opaque
, int event
)
1851 CharDriverState
*chr
= opaque
;
1852 MuxDriver
*d
= chr
->opaque
;
1855 /* Send the event to all registered listeners */
1856 for (i
= 0; i
< d
->mux_cnt
; i
++)
1857 if (d
->chr_event
[i
])
1858 d
->chr_event
[i
](d
->ext_opaque
[i
], event
);
1861 static void mux_chr_update_read_handler(CharDriverState
*chr
)
1863 MuxDriver
*d
= chr
->opaque
;
1865 if (d
->mux_cnt
>= MAX_MUX
) {
1866 fprintf(stderr
, "Cannot add I/O handlers, MUX array is full\n");
1869 d
->ext_opaque
[d
->mux_cnt
] = chr
->handler_opaque
;
1870 d
->chr_can_read
[d
->mux_cnt
] = chr
->chr_can_read
;
1871 d
->chr_read
[d
->mux_cnt
] = chr
->chr_read
;
1872 d
->chr_event
[d
->mux_cnt
] = chr
->chr_event
;
1873 /* Fix up the real driver with mux routines */
1874 if (d
->mux_cnt
== 0) {
1875 qemu_chr_add_handlers(d
->drv
, mux_chr_can_read
, mux_chr_read
,
1876 mux_chr_event
, chr
);
1878 chr
->focus
= d
->mux_cnt
;
1882 static CharDriverState
*qemu_chr_open_mux(CharDriverState
*drv
)
1884 CharDriverState
*chr
;
1887 chr
= qemu_mallocz(sizeof(CharDriverState
));
1890 d
= qemu_mallocz(sizeof(MuxDriver
));
1899 chr
->chr_write
= mux_chr_write
;
1900 chr
->chr_update_read_handler
= mux_chr_update_read_handler
;
1901 chr
->chr_accept_input
= mux_chr_accept_input
;
1908 static void socket_cleanup(void)
1913 static int socket_init(void)
1918 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1920 err
= WSAGetLastError();
1921 fprintf(stderr
, "WSAStartup: %d\n", err
);
1924 atexit(socket_cleanup
);
1928 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1934 ret
= send(fd
, buf
, len
, 0);
1937 errno
= WSAGetLastError();
1938 if (errno
!= WSAEWOULDBLOCK
) {
1941 } else if (ret
== 0) {
1951 void socket_set_nonblock(int fd
)
1953 unsigned long opt
= 1;
1954 ioctlsocket(fd
, FIONBIO
, &opt
);
1959 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1965 ret
= write(fd
, buf
, len
);
1967 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1969 } else if (ret
== 0) {
1979 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1981 return unix_write(fd
, buf
, len1
);
1984 void socket_set_nonblock(int fd
)
1986 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1988 #endif /* !_WIN32 */
1997 #define STDIO_MAX_CLIENTS 1
1998 static int stdio_nb_clients
= 0;
2000 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2002 FDCharDriver
*s
= chr
->opaque
;
2003 return unix_write(s
->fd_out
, buf
, len
);
2006 static int fd_chr_read_poll(void *opaque
)
2008 CharDriverState
*chr
= opaque
;
2009 FDCharDriver
*s
= chr
->opaque
;
2011 s
->max_size
= qemu_chr_can_read(chr
);
2015 static void fd_chr_read(void *opaque
)
2017 CharDriverState
*chr
= opaque
;
2018 FDCharDriver
*s
= chr
->opaque
;
2023 if (len
> s
->max_size
)
2027 size
= read(s
->fd_in
, buf
, len
);
2029 /* FD has been closed. Remove it from the active list. */
2030 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
2034 qemu_chr_read(chr
, buf
, size
);
2038 static void fd_chr_update_read_handler(CharDriverState
*chr
)
2040 FDCharDriver
*s
= chr
->opaque
;
2042 if (s
->fd_in
>= 0) {
2043 if (nographic
&& s
->fd_in
== 0) {
2045 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
2046 fd_chr_read
, NULL
, chr
);
2051 /* open a character device to a unix fd */
2052 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
2054 CharDriverState
*chr
;
2057 chr
= qemu_mallocz(sizeof(CharDriverState
));
2060 s
= qemu_mallocz(sizeof(FDCharDriver
));
2068 chr
->chr_write
= fd_chr_write
;
2069 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
2071 qemu_chr_reset(chr
);
2076 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
2080 TFR(fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666));
2083 return qemu_chr_open_fd(-1, fd_out
);
2086 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
2089 char filename_in
[256], filename_out
[256];
2091 snprintf(filename_in
, 256, "%s.in", filename
);
2092 snprintf(filename_out
, 256, "%s.out", filename
);
2093 TFR(fd_in
= open(filename_in
, O_RDWR
| O_BINARY
));
2094 TFR(fd_out
= open(filename_out
, O_RDWR
| O_BINARY
));
2095 if (fd_in
< 0 || fd_out
< 0) {
2100 TFR(fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
));
2104 return qemu_chr_open_fd(fd_in
, fd_out
);
2108 /* for STDIO, we handle the case where several clients use it
2111 #define TERM_FIFO_MAX_SIZE 1
2113 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
2114 static int term_fifo_size
;
2116 static int stdio_read_poll(void *opaque
)
2118 CharDriverState
*chr
= opaque
;
2120 /* try to flush the queue if needed */
2121 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
2122 qemu_chr_read(chr
, term_fifo
, 1);
2125 /* see if we can absorb more chars */
2126 if (term_fifo_size
== 0)
2132 static void stdio_read(void *opaque
)
2136 CharDriverState
*chr
= opaque
;
2138 size
= read(0, buf
, 1);
2140 /* stdin has been closed. Remove it from the active list. */
2141 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
2145 if (qemu_chr_can_read(chr
) > 0) {
2146 qemu_chr_read(chr
, buf
, 1);
2147 } else if (term_fifo_size
== 0) {
2148 term_fifo
[term_fifo_size
++] = buf
[0];
2153 /* init terminal so that we can grab keys */
2154 static struct termios oldtty
;
2155 static int old_fd0_flags
;
2157 static void term_exit(void)
2159 tcsetattr (0, TCSANOW
, &oldtty
);
2160 fcntl(0, F_SETFL
, old_fd0_flags
);
2163 static void term_init(void)
2167 tcgetattr (0, &tty
);
2169 old_fd0_flags
= fcntl(0, F_GETFL
);
2171 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2172 |INLCR
|IGNCR
|ICRNL
|IXON
);
2173 tty
.c_oflag
|= OPOST
;
2174 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
2175 /* if graphical mode, we allow Ctrl-C handling */
2177 tty
.c_lflag
&= ~ISIG
;
2178 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
2181 tty
.c_cc
[VTIME
] = 0;
2183 tcsetattr (0, TCSANOW
, &tty
);
2187 fcntl(0, F_SETFL
, O_NONBLOCK
);
2190 static CharDriverState
*qemu_chr_open_stdio(void)
2192 CharDriverState
*chr
;
2194 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
2196 chr
= qemu_chr_open_fd(0, 1);
2197 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, chr
);
2204 #if defined(__linux__) || defined(__sun__)
2205 static CharDriverState
*qemu_chr_open_pty(void)
2208 char slave_name
[1024];
2209 int master_fd
, slave_fd
;
2211 #if defined(__linux__)
2212 /* Not satisfying */
2213 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
2218 /* Disabling local echo and line-buffered output */
2219 tcgetattr (master_fd
, &tty
);
2220 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
2222 tty
.c_cc
[VTIME
] = 0;
2223 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
2225 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
2226 return qemu_chr_open_fd(master_fd
, master_fd
);
2229 static void tty_serial_init(int fd
, int speed
,
2230 int parity
, int data_bits
, int stop_bits
)
2236 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2237 speed
, parity
, data_bits
, stop_bits
);
2239 tcgetattr (fd
, &tty
);
2281 cfsetispeed(&tty
, spd
);
2282 cfsetospeed(&tty
, spd
);
2284 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
2285 |INLCR
|IGNCR
|ICRNL
|IXON
);
2286 tty
.c_oflag
|= OPOST
;
2287 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
2288 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
2309 tty
.c_cflag
|= PARENB
;
2312 tty
.c_cflag
|= PARENB
| PARODD
;
2316 tty
.c_cflag
|= CSTOPB
;
2318 tcsetattr (fd
, TCSANOW
, &tty
);
2321 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2323 FDCharDriver
*s
= chr
->opaque
;
2326 case CHR_IOCTL_SERIAL_SET_PARAMS
:
2328 QEMUSerialSetParams
*ssp
= arg
;
2329 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
2330 ssp
->data_bits
, ssp
->stop_bits
);
2333 case CHR_IOCTL_SERIAL_SET_BREAK
:
2335 int enable
= *(int *)arg
;
2337 tcsendbreak(s
->fd_in
, 1);
2346 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
2348 CharDriverState
*chr
;
2351 TFR(fd
= open(filename
, O_RDWR
| O_NONBLOCK
));
2352 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
2353 tty_serial_init(fd
, 115200, 'N', 8, 1);
2354 chr
= qemu_chr_open_fd(fd
, fd
);
2359 chr
->chr_ioctl
= tty_serial_ioctl
;
2360 qemu_chr_reset(chr
);
2363 #else /* ! __linux__ && ! __sun__ */
2364 static CharDriverState
*qemu_chr_open_pty(void)
2368 #endif /* __linux__ || __sun__ */
2370 #if defined(__linux__)
2374 } ParallelCharDriver
;
2376 static int pp_hw_mode(ParallelCharDriver
*s
, uint16_t mode
)
2378 if (s
->mode
!= mode
) {
2380 if (ioctl(s
->fd
, PPSETMODE
, &m
) < 0)
2387 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
2389 ParallelCharDriver
*drv
= chr
->opaque
;
2394 case CHR_IOCTL_PP_READ_DATA
:
2395 if (ioctl(fd
, PPRDATA
, &b
) < 0)
2397 *(uint8_t *)arg
= b
;
2399 case CHR_IOCTL_PP_WRITE_DATA
:
2400 b
= *(uint8_t *)arg
;
2401 if (ioctl(fd
, PPWDATA
, &b
) < 0)
2404 case CHR_IOCTL_PP_READ_CONTROL
:
2405 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
2407 /* Linux gives only the lowest bits, and no way to know data
2408 direction! For better compatibility set the fixed upper
2410 *(uint8_t *)arg
= b
| 0xc0;
2412 case CHR_IOCTL_PP_WRITE_CONTROL
:
2413 b
= *(uint8_t *)arg
;
2414 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
2417 case CHR_IOCTL_PP_READ_STATUS
:
2418 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
2420 *(uint8_t *)arg
= b
;
2422 case CHR_IOCTL_PP_EPP_READ_ADDR
:
2423 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2424 struct ParallelIOArg
*parg
= arg
;
2425 int n
= read(fd
, parg
->buffer
, parg
->count
);
2426 if (n
!= parg
->count
) {
2431 case CHR_IOCTL_PP_EPP_READ
:
2432 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2433 struct ParallelIOArg
*parg
= arg
;
2434 int n
= read(fd
, parg
->buffer
, parg
->count
);
2435 if (n
!= parg
->count
) {
2440 case CHR_IOCTL_PP_EPP_WRITE_ADDR
:
2441 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
|IEEE1284_ADDR
)) {
2442 struct ParallelIOArg
*parg
= arg
;
2443 int n
= write(fd
, parg
->buffer
, parg
->count
);
2444 if (n
!= parg
->count
) {
2449 case CHR_IOCTL_PP_EPP_WRITE
:
2450 if (pp_hw_mode(drv
, IEEE1284_MODE_EPP
)) {
2451 struct ParallelIOArg
*parg
= arg
;
2452 int n
= write(fd
, parg
->buffer
, parg
->count
);
2453 if (n
!= parg
->count
) {
2464 static void pp_close(CharDriverState
*chr
)
2466 ParallelCharDriver
*drv
= chr
->opaque
;
2469 pp_hw_mode(drv
, IEEE1284_MODE_COMPAT
);
2470 ioctl(fd
, PPRELEASE
);
2475 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
2477 CharDriverState
*chr
;
2478 ParallelCharDriver
*drv
;
2481 TFR(fd
= open(filename
, O_RDWR
));
2485 if (ioctl(fd
, PPCLAIM
) < 0) {
2490 drv
= qemu_mallocz(sizeof(ParallelCharDriver
));
2496 drv
->mode
= IEEE1284_MODE_COMPAT
;
2498 chr
= qemu_mallocz(sizeof(CharDriverState
));
2504 chr
->chr_write
= null_chr_write
;
2505 chr
->chr_ioctl
= pp_ioctl
;
2506 chr
->chr_close
= pp_close
;
2509 qemu_chr_reset(chr
);
2513 #endif /* __linux__ */
2519 HANDLE hcom
, hrecv
, hsend
;
2520 OVERLAPPED orecv
, osend
;
2525 #define NSENDBUF 2048
2526 #define NRECVBUF 2048
2527 #define MAXCONNECT 1
2528 #define NTIMEOUT 5000
2530 static int win_chr_poll(void *opaque
);
2531 static int win_chr_pipe_poll(void *opaque
);
2533 static void win_chr_close(CharDriverState
*chr
)
2535 WinCharState
*s
= chr
->opaque
;
2538 CloseHandle(s
->hsend
);
2542 CloseHandle(s
->hrecv
);
2546 CloseHandle(s
->hcom
);
2550 qemu_del_polling_cb(win_chr_pipe_poll
, chr
);
2552 qemu_del_polling_cb(win_chr_poll
, chr
);
2555 static int win_chr_init(CharDriverState
*chr
, const char *filename
)
2557 WinCharState
*s
= chr
->opaque
;
2559 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
2564 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2566 fprintf(stderr
, "Failed CreateEvent\n");
2569 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2571 fprintf(stderr
, "Failed CreateEvent\n");
2575 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
2576 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
2577 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2578 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
2583 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
2584 fprintf(stderr
, "Failed SetupComm\n");
2588 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
2589 size
= sizeof(COMMCONFIG
);
2590 GetDefaultCommConfig(filename
, &comcfg
, &size
);
2591 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
2592 CommConfigDialog(filename
, NULL
, &comcfg
);
2594 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
2595 fprintf(stderr
, "Failed SetCommState\n");
2599 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
2600 fprintf(stderr
, "Failed SetCommMask\n");
2604 cto
.ReadIntervalTimeout
= MAXDWORD
;
2605 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
2606 fprintf(stderr
, "Failed SetCommTimeouts\n");
2610 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
2611 fprintf(stderr
, "Failed ClearCommError\n");
2614 qemu_add_polling_cb(win_chr_poll
, chr
);
2622 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
2624 WinCharState
*s
= chr
->opaque
;
2625 DWORD len
, ret
, size
, err
;
2628 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2629 s
->osend
.hEvent
= s
->hsend
;
2632 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2634 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2636 err
= GetLastError();
2637 if (err
== ERROR_IO_PENDING
) {
2638 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2656 static int win_chr_read_poll(CharDriverState
*chr
)
2658 WinCharState
*s
= chr
->opaque
;
2660 s
->max_size
= qemu_chr_can_read(chr
);
2664 static void win_chr_readfile(CharDriverState
*chr
)
2666 WinCharState
*s
= chr
->opaque
;
2671 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2672 s
->orecv
.hEvent
= s
->hrecv
;
2673 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2675 err
= GetLastError();
2676 if (err
== ERROR_IO_PENDING
) {
2677 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2682 qemu_chr_read(chr
, buf
, size
);
2686 static void win_chr_read(CharDriverState
*chr
)
2688 WinCharState
*s
= chr
->opaque
;
2690 if (s
->len
> s
->max_size
)
2691 s
->len
= s
->max_size
;
2695 win_chr_readfile(chr
);
2698 static int win_chr_poll(void *opaque
)
2700 CharDriverState
*chr
= opaque
;
2701 WinCharState
*s
= chr
->opaque
;
2705 ClearCommError(s
->hcom
, &comerr
, &status
);
2706 if (status
.cbInQue
> 0) {
2707 s
->len
= status
.cbInQue
;
2708 win_chr_read_poll(chr
);
2715 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2717 CharDriverState
*chr
;
2720 chr
= qemu_mallocz(sizeof(CharDriverState
));
2723 s
= qemu_mallocz(sizeof(WinCharState
));
2729 chr
->chr_write
= win_chr_write
;
2730 chr
->chr_close
= win_chr_close
;
2732 if (win_chr_init(chr
, filename
) < 0) {
2737 qemu_chr_reset(chr
);
2741 static int win_chr_pipe_poll(void *opaque
)
2743 CharDriverState
*chr
= opaque
;
2744 WinCharState
*s
= chr
->opaque
;
2747 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2750 win_chr_read_poll(chr
);
2757 static int win_chr_pipe_init(CharDriverState
*chr
, const char *filename
)
2759 WinCharState
*s
= chr
->opaque
;
2767 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2769 fprintf(stderr
, "Failed CreateEvent\n");
2772 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2774 fprintf(stderr
, "Failed CreateEvent\n");
2778 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2779 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2780 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2782 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2783 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2784 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2789 ZeroMemory(&ov
, sizeof(ov
));
2790 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2791 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2793 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2797 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2799 fprintf(stderr
, "Failed GetOverlappedResult\n");
2801 CloseHandle(ov
.hEvent
);
2808 CloseHandle(ov
.hEvent
);
2811 qemu_add_polling_cb(win_chr_pipe_poll
, chr
);
2820 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2822 CharDriverState
*chr
;
2825 chr
= qemu_mallocz(sizeof(CharDriverState
));
2828 s
= qemu_mallocz(sizeof(WinCharState
));
2834 chr
->chr_write
= win_chr_write
;
2835 chr
->chr_close
= win_chr_close
;
2837 if (win_chr_pipe_init(chr
, filename
) < 0) {
2842 qemu_chr_reset(chr
);
2846 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2848 CharDriverState
*chr
;
2851 chr
= qemu_mallocz(sizeof(CharDriverState
));
2854 s
= qemu_mallocz(sizeof(WinCharState
));
2861 chr
->chr_write
= win_chr_write
;
2862 qemu_chr_reset(chr
);
2866 static CharDriverState
*qemu_chr_open_win_con(const char *filename
)
2868 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE
));
2871 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2875 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2876 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2877 if (fd_out
== INVALID_HANDLE_VALUE
)
2880 return qemu_chr_open_win_file(fd_out
);
2882 #endif /* !_WIN32 */
2884 /***********************************************************/
2885 /* UDP Net console */
2889 struct sockaddr_in daddr
;
2896 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2898 NetCharDriver
*s
= chr
->opaque
;
2900 return sendto(s
->fd
, buf
, len
, 0,
2901 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2904 static int udp_chr_read_poll(void *opaque
)
2906 CharDriverState
*chr
= opaque
;
2907 NetCharDriver
*s
= chr
->opaque
;
2909 s
->max_size
= qemu_chr_can_read(chr
);
2911 /* If there were any stray characters in the queue process them
2914 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2915 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2917 s
->max_size
= qemu_chr_can_read(chr
);
2922 static void udp_chr_read(void *opaque
)
2924 CharDriverState
*chr
= opaque
;
2925 NetCharDriver
*s
= chr
->opaque
;
2927 if (s
->max_size
== 0)
2929 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2930 s
->bufptr
= s
->bufcnt
;
2935 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2936 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2938 s
->max_size
= qemu_chr_can_read(chr
);
2942 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2944 NetCharDriver
*s
= chr
->opaque
;
2947 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2948 udp_chr_read
, NULL
, chr
);
2952 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
);
2954 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2956 int parse_host_src_port(struct sockaddr_in
*haddr
,
2957 struct sockaddr_in
*saddr
,
2960 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2962 CharDriverState
*chr
= NULL
;
2963 NetCharDriver
*s
= NULL
;
2965 struct sockaddr_in saddr
;
2967 chr
= qemu_mallocz(sizeof(CharDriverState
));
2970 s
= qemu_mallocz(sizeof(NetCharDriver
));
2974 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2976 perror("socket(PF_INET, SOCK_DGRAM)");
2980 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2981 printf("Could not parse: %s\n", def
);
2985 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2995 chr
->chr_write
= udp_chr_write
;
2996 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
3009 /***********************************************************/
3010 /* TCP Net console */
3021 static void tcp_chr_accept(void *opaque
);
3023 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
3025 TCPCharDriver
*s
= chr
->opaque
;
3027 return send_all(s
->fd
, buf
, len
);
3029 /* XXX: indicate an error ? */
3034 static int tcp_chr_read_poll(void *opaque
)
3036 CharDriverState
*chr
= opaque
;
3037 TCPCharDriver
*s
= chr
->opaque
;
3040 s
->max_size
= qemu_chr_can_read(chr
);
3045 #define IAC_BREAK 243
3046 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
3048 uint8_t *buf
, int *size
)
3050 /* Handle any telnet client's basic IAC options to satisfy char by
3051 * char mode with no echo. All IAC options will be removed from
3052 * the buf and the do_telnetopt variable will be used to track the
3053 * state of the width of the IAC information.
3055 * IAC commands come in sets of 3 bytes with the exception of the
3056 * "IAC BREAK" command and the double IAC.
3062 for (i
= 0; i
< *size
; i
++) {
3063 if (s
->do_telnetopt
> 1) {
3064 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
3065 /* Double IAC means send an IAC */
3069 s
->do_telnetopt
= 1;
3071 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
3072 /* Handle IAC break commands by sending a serial break */
3073 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
3078 if (s
->do_telnetopt
>= 4) {
3079 s
->do_telnetopt
= 1;
3082 if ((unsigned char)buf
[i
] == IAC
) {
3083 s
->do_telnetopt
= 2;
3094 static void tcp_chr_read(void *opaque
)
3096 CharDriverState
*chr
= opaque
;
3097 TCPCharDriver
*s
= chr
->opaque
;
3101 if (!s
->connected
|| s
->max_size
<= 0)
3104 if (len
> s
->max_size
)
3106 size
= recv(s
->fd
, buf
, len
, 0);
3108 /* connection closed */
3110 if (s
->listen_fd
>= 0) {
3111 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3113 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3116 } else if (size
> 0) {
3117 if (s
->do_telnetopt
)
3118 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
3120 qemu_chr_read(chr
, buf
, size
);
3124 static void tcp_chr_connect(void *opaque
)
3126 CharDriverState
*chr
= opaque
;
3127 TCPCharDriver
*s
= chr
->opaque
;
3130 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
3131 tcp_chr_read
, NULL
, chr
);
3132 qemu_chr_reset(chr
);
3135 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3136 static void tcp_chr_telnet_init(int fd
)
3139 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3140 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3141 send(fd
, (char *)buf
, 3, 0);
3142 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3143 send(fd
, (char *)buf
, 3, 0);
3144 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3145 send(fd
, (char *)buf
, 3, 0);
3146 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3147 send(fd
, (char *)buf
, 3, 0);
3150 static void socket_set_nodelay(int fd
)
3153 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
3156 static void tcp_chr_accept(void *opaque
)
3158 CharDriverState
*chr
= opaque
;
3159 TCPCharDriver
*s
= chr
->opaque
;
3160 struct sockaddr_in saddr
;
3162 struct sockaddr_un uaddr
;
3164 struct sockaddr
*addr
;
3171 len
= sizeof(uaddr
);
3172 addr
= (struct sockaddr
*)&uaddr
;
3176 len
= sizeof(saddr
);
3177 addr
= (struct sockaddr
*)&saddr
;
3179 fd
= accept(s
->listen_fd
, addr
, &len
);
3180 if (fd
< 0 && errno
!= EINTR
) {
3182 } else if (fd
>= 0) {
3183 if (s
->do_telnetopt
)
3184 tcp_chr_telnet_init(fd
);
3188 socket_set_nonblock(fd
);
3190 socket_set_nodelay(fd
);
3192 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
3193 tcp_chr_connect(chr
);
3196 static void tcp_chr_close(CharDriverState
*chr
)
3198 TCPCharDriver
*s
= chr
->opaque
;
3201 if (s
->listen_fd
>= 0)
3202 closesocket(s
->listen_fd
);
3206 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
3210 CharDriverState
*chr
= NULL
;
3211 TCPCharDriver
*s
= NULL
;
3212 int fd
= -1, ret
, err
, val
;
3214 int is_waitconnect
= 1;
3217 struct sockaddr_in saddr
;
3219 struct sockaddr_un uaddr
;
3221 struct sockaddr
*addr
;
3226 addr
= (struct sockaddr
*)&uaddr
;
3227 addrlen
= sizeof(uaddr
);
3228 if (parse_unix_path(&uaddr
, host_str
) < 0)
3233 addr
= (struct sockaddr
*)&saddr
;
3234 addrlen
= sizeof(saddr
);
3235 if (parse_host_port(&saddr
, host_str
) < 0)
3240 while((ptr
= strchr(ptr
,','))) {
3242 if (!strncmp(ptr
,"server",6)) {
3244 } else if (!strncmp(ptr
,"nowait",6)) {
3246 } else if (!strncmp(ptr
,"nodelay",6)) {
3249 printf("Unknown option: %s\n", ptr
);
3256 chr
= qemu_mallocz(sizeof(CharDriverState
));
3259 s
= qemu_mallocz(sizeof(TCPCharDriver
));
3265 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
3268 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3273 if (!is_waitconnect
)
3274 socket_set_nonblock(fd
);
3279 s
->is_unix
= is_unix
;
3280 s
->do_nodelay
= do_nodelay
&& !is_unix
;
3283 chr
->chr_write
= tcp_chr_write
;
3284 chr
->chr_close
= tcp_chr_close
;
3287 /* allow fast reuse */
3291 strncpy(path
, uaddr
.sun_path
, 108);
3298 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3301 ret
= bind(fd
, addr
, addrlen
);
3305 ret
= listen(fd
, 0);
3310 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
3312 s
->do_telnetopt
= 1;
3315 ret
= connect(fd
, addr
, addrlen
);
3317 err
= socket_error();
3318 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3319 } else if (err
== EINPROGRESS
) {
3322 } else if (err
== WSAEALREADY
) {
3334 socket_set_nodelay(fd
);
3336 tcp_chr_connect(chr
);
3338 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
3341 if (is_listen
&& is_waitconnect
) {
3342 printf("QEMU waiting for connection on: %s\n", host_str
);
3343 tcp_chr_accept(chr
);
3344 socket_set_nonblock(s
->listen_fd
);
3356 CharDriverState
*qemu_chr_open(const char *filename
)
3360 if (!strcmp(filename
, "vc")) {
3361 return text_console_init(&display_state
, 0);
3362 } else if (strstart(filename
, "vc:", &p
)) {
3363 return text_console_init(&display_state
, p
);
3364 } else if (!strcmp(filename
, "null")) {
3365 return qemu_chr_open_null();
3367 if (strstart(filename
, "tcp:", &p
)) {
3368 return qemu_chr_open_tcp(p
, 0, 0);
3370 if (strstart(filename
, "telnet:", &p
)) {
3371 return qemu_chr_open_tcp(p
, 1, 0);
3373 if (strstart(filename
, "udp:", &p
)) {
3374 return qemu_chr_open_udp(p
);
3376 if (strstart(filename
, "mon:", &p
)) {
3377 CharDriverState
*drv
= qemu_chr_open(p
);
3379 drv
= qemu_chr_open_mux(drv
);
3380 monitor_init(drv
, !nographic
);
3383 printf("Unable to open driver: %s\n", p
);
3387 if (strstart(filename
, "unix:", &p
)) {
3388 return qemu_chr_open_tcp(p
, 0, 1);
3389 } else if (strstart(filename
, "file:", &p
)) {
3390 return qemu_chr_open_file_out(p
);
3391 } else if (strstart(filename
, "pipe:", &p
)) {
3392 return qemu_chr_open_pipe(p
);
3393 } else if (!strcmp(filename
, "pty")) {
3394 return qemu_chr_open_pty();
3395 } else if (!strcmp(filename
, "stdio")) {
3396 return qemu_chr_open_stdio();
3398 #if defined(__linux__)
3399 if (strstart(filename
, "/dev/parport", NULL
)) {
3400 return qemu_chr_open_pp(filename
);
3403 #if defined(__linux__) || defined(__sun__)
3404 if (strstart(filename
, "/dev/", NULL
)) {
3405 return qemu_chr_open_tty(filename
);
3409 if (strstart(filename
, "COM", NULL
)) {
3410 return qemu_chr_open_win(filename
);
3412 if (strstart(filename
, "pipe:", &p
)) {
3413 return qemu_chr_open_win_pipe(p
);
3415 if (strstart(filename
, "con:", NULL
)) {
3416 return qemu_chr_open_win_con(filename
);
3418 if (strstart(filename
, "file:", &p
)) {
3419 return qemu_chr_open_win_file_out(p
);
3427 void qemu_chr_close(CharDriverState
*chr
)
3430 chr
->chr_close(chr
);
3433 /***********************************************************/
3434 /* network device redirectors */
3436 __attribute__ (( unused
))
3437 static void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
3441 for(i
=0;i
<size
;i
+=16) {
3445 fprintf(f
, "%08x ", i
);
3448 fprintf(f
, " %02x", buf
[i
+j
]);
3453 for(j
=0;j
<len
;j
++) {
3455 if (c
< ' ' || c
> '~')
3457 fprintf(f
, "%c", c
);
3463 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
3470 offset
= strtol(p
, &last_char
, 0);
3471 if (0 == errno
&& '\0' == *last_char
&&
3472 offset
>= 0 && offset
<= 0xFFFFFF) {
3473 macaddr
[3] = (offset
& 0xFF0000) >> 16;
3474 macaddr
[4] = (offset
& 0xFF00) >> 8;
3475 macaddr
[5] = offset
& 0xFF;
3478 for(i
= 0; i
< 6; i
++) {
3479 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
3484 if (*p
!= ':' && *p
!= '-')
3495 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
3500 p1
= strchr(p
, sep
);
3506 if (len
> buf_size
- 1)
3508 memcpy(buf
, p
, len
);
3515 int parse_host_src_port(struct sockaddr_in
*haddr
,
3516 struct sockaddr_in
*saddr
,
3517 const char *input_str
)
3519 char *str
= strdup(input_str
);
3520 char *host_str
= str
;
3525 * Chop off any extra arguments at the end of the string which
3526 * would start with a comma, then fill in the src port information
3527 * if it was provided else use the "any address" and "any port".
3529 if ((ptr
= strchr(str
,',')))
3532 if ((src_str
= strchr(input_str
,'@'))) {
3537 if (parse_host_port(haddr
, host_str
) < 0)
3540 if (!src_str
|| *src_str
== '\0')
3543 if (parse_host_port(saddr
, src_str
) < 0)
3554 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
3562 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3564 saddr
->sin_family
= AF_INET
;
3565 if (buf
[0] == '\0') {
3566 saddr
->sin_addr
.s_addr
= 0;
3568 if (isdigit(buf
[0])) {
3569 if (!inet_aton(buf
, &saddr
->sin_addr
))
3572 if ((he
= gethostbyname(buf
)) == NULL
)
3574 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
3577 port
= strtol(p
, (char **)&r
, 0);
3580 saddr
->sin_port
= htons(port
);
3585 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
3590 len
= MIN(108, strlen(str
));
3591 p
= strchr(str
, ',');
3593 len
= MIN(len
, p
- str
);
3595 memset(uaddr
, 0, sizeof(*uaddr
));
3597 uaddr
->sun_family
= AF_UNIX
;
3598 memcpy(uaddr
->sun_path
, str
, len
);
3604 /* find or alloc a new VLAN */
3605 VLANState
*qemu_find_vlan(int id
)
3607 VLANState
**pvlan
, *vlan
;
3608 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3612 vlan
= qemu_mallocz(sizeof(VLANState
));
3617 pvlan
= &first_vlan
;
3618 while (*pvlan
!= NULL
)
3619 pvlan
= &(*pvlan
)->next
;
3624 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
3625 IOReadHandler
*fd_read
,
3626 IOCanRWHandler
*fd_can_read
,
3629 VLANClientState
*vc
, **pvc
;
3630 vc
= qemu_mallocz(sizeof(VLANClientState
));
3633 vc
->fd_read
= fd_read
;
3634 vc
->fd_can_read
= fd_can_read
;
3635 vc
->opaque
= opaque
;
3639 pvc
= &vlan
->first_client
;
3640 while (*pvc
!= NULL
)
3641 pvc
= &(*pvc
)->next
;
3646 int qemu_can_send_packet(VLANClientState
*vc1
)
3648 VLANState
*vlan
= vc1
->vlan
;
3649 VLANClientState
*vc
;
3651 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3653 if (vc
->fd_can_read
&& vc
->fd_can_read(vc
->opaque
))
3660 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
3662 VLANState
*vlan
= vc1
->vlan
;
3663 VLANClientState
*vc
;
3666 printf("vlan %d send:\n", vlan
->id
);
3667 hex_dump(stdout
, buf
, size
);
3669 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
3671 vc
->fd_read(vc
->opaque
, buf
, size
);
3676 #if defined(CONFIG_SLIRP)
3678 /* slirp network adapter */
3680 static int slirp_inited
;
3681 static VLANClientState
*slirp_vc
;
3683 int slirp_can_output(void)
3685 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3688 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3691 printf("slirp output:\n");
3692 hex_dump(stdout
, pkt
, pkt_len
);
3696 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3699 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3702 printf("slirp input:\n");
3703 hex_dump(stdout
, buf
, size
);
3705 slirp_input(buf
, size
);
3708 static int net_slirp_init(VLANState
*vlan
)
3710 if (!slirp_inited
) {
3714 slirp_vc
= qemu_new_vlan_client(vlan
,
3715 slirp_receive
, NULL
, NULL
);
3716 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3720 static void net_slirp_redir(const char *redir_str
)
3725 struct in_addr guest_addr
;
3726 int host_port
, guest_port
;
3728 if (!slirp_inited
) {
3734 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3736 if (!strcmp(buf
, "tcp")) {
3738 } else if (!strcmp(buf
, "udp")) {
3744 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3746 host_port
= strtol(buf
, &r
, 0);
3750 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3752 if (buf
[0] == '\0') {
3753 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3755 if (!inet_aton(buf
, &guest_addr
))
3758 guest_port
= strtol(p
, &r
, 0);
3762 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3763 fprintf(stderr
, "qemu: could not set up redirection\n");
3768 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3776 static void smb_exit(void)
3780 char filename
[1024];
3782 /* erase all the files in the directory */
3783 d
= opendir(smb_dir
);
3788 if (strcmp(de
->d_name
, ".") != 0 &&
3789 strcmp(de
->d_name
, "..") != 0) {
3790 snprintf(filename
, sizeof(filename
), "%s/%s",
3791 smb_dir
, de
->d_name
);
3799 /* automatic user mode samba server configuration */
3800 static void net_slirp_smb(const char *exported_dir
)
3802 char smb_conf
[1024];
3803 char smb_cmdline
[1024];
3806 if (!slirp_inited
) {
3811 /* XXX: better tmp dir construction */
3812 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3813 if (mkdir(smb_dir
, 0700) < 0) {
3814 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3817 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3819 f
= fopen(smb_conf
, "w");
3821 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3828 "socket address=127.0.0.1\n"
3829 "pid directory=%s\n"
3830 "lock directory=%s\n"
3831 "log file=%s/log.smbd\n"
3832 "smb passwd file=%s/smbpasswd\n"
3833 "security = share\n"
3848 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3849 SMBD_COMMAND
, smb_conf
);
3851 slirp_add_exec(0, smb_cmdline
, 4, 139);
3854 #endif /* !defined(_WIN32) */
3855 void do_info_slirp(void)
3860 #endif /* CONFIG_SLIRP */
3862 #if !defined(_WIN32)
3864 typedef struct TAPState
{
3865 VLANClientState
*vc
;
3867 char down_script
[1024];
3870 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3872 TAPState
*s
= opaque
;
3875 ret
= write(s
->fd
, buf
, size
);
3876 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3883 static void tap_send(void *opaque
)
3885 TAPState
*s
= opaque
;
3892 sbuf
.maxlen
= sizeof(buf
);
3894 size
= getmsg(s
->fd
, NULL
, &sbuf
, &f
) >=0 ? sbuf
.len
: -1;
3896 size
= read(s
->fd
, buf
, sizeof(buf
));
3899 qemu_send_packet(s
->vc
, buf
, size
);
3905 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3909 s
= qemu_mallocz(sizeof(TAPState
));
3913 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3914 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3915 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3919 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3920 static int tap_open(char *ifname
, int ifname_size
)
3926 TFR(fd
= open("/dev/tap", O_RDWR
));
3928 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3933 dev
= devname(s
.st_rdev
, S_IFCHR
);
3934 pstrcpy(ifname
, ifname_size
, dev
);
3936 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3939 #elif defined(__sun__)
3940 #define TUNNEWPPA (('T'<<16) | 0x0001)
3942 * Allocate TAP device, returns opened fd.
3943 * Stores dev name in the first arg(must be large enough).
3945 int tap_alloc(char *dev
)
3947 int tap_fd
, if_fd
, ppa
= -1;
3948 static int ip_fd
= 0;
3951 static int arp_fd
= 0;
3952 int ip_muxid
, arp_muxid
;
3953 struct strioctl strioc_if
, strioc_ppa
;
3954 int link_type
= I_PLINK
;;
3956 char actual_name
[32] = "";
3958 memset(&ifr
, 0x0, sizeof(ifr
));
3962 while( *ptr
&& !isdigit((int)*ptr
) ) ptr
++;
3966 /* Check if IP device was opened */
3970 TFR(ip_fd
= open("/dev/udp", O_RDWR
, 0));
3972 syslog(LOG_ERR
, "Can't open /dev/ip (actually /dev/udp)");
3976 TFR(tap_fd
= open("/dev/tap", O_RDWR
, 0));
3978 syslog(LOG_ERR
, "Can't open /dev/tap");
3982 /* Assign a new PPA and get its unit number. */
3983 strioc_ppa
.ic_cmd
= TUNNEWPPA
;
3984 strioc_ppa
.ic_timout
= 0;
3985 strioc_ppa
.ic_len
= sizeof(ppa
);
3986 strioc_ppa
.ic_dp
= (char *)&ppa
;
3987 if ((ppa
= ioctl (tap_fd
, I_STR
, &strioc_ppa
)) < 0)
3988 syslog (LOG_ERR
, "Can't assign new interface");
3990 TFR(if_fd
= open("/dev/tap", O_RDWR
, 0));
3992 syslog(LOG_ERR
, "Can't open /dev/tap (2)");
3995 if(ioctl(if_fd
, I_PUSH
, "ip") < 0){
3996 syslog(LOG_ERR
, "Can't push IP module");
4000 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) < 0)
4001 syslog(LOG_ERR
, "Can't get flags\n");
4003 snprintf (actual_name
, 32, "tap%d", ppa
);
4004 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4007 /* Assign ppa according to the unit number returned by tun device */
4009 if (ioctl (if_fd
, SIOCSLIFNAME
, &ifr
) < 0)
4010 syslog (LOG_ERR
, "Can't set PPA %d", ppa
);
4011 if (ioctl(if_fd
, SIOCGLIFFLAGS
, &ifr
) <0)
4012 syslog (LOG_ERR
, "Can't get flags\n");
4013 /* Push arp module to if_fd */
4014 if (ioctl (if_fd
, I_PUSH
, "arp") < 0)
4015 syslog (LOG_ERR
, "Can't push ARP module (2)");
4017 /* Push arp module to ip_fd */
4018 if (ioctl (ip_fd
, I_POP
, NULL
) < 0)
4019 syslog (LOG_ERR
, "I_POP failed\n");
4020 if (ioctl (ip_fd
, I_PUSH
, "arp") < 0)
4021 syslog (LOG_ERR
, "Can't push ARP module (3)\n");
4023 TFR(arp_fd
= open ("/dev/tap", O_RDWR
, 0));
4025 syslog (LOG_ERR
, "Can't open %s\n", "/dev/tap");
4027 /* Set ifname to arp */
4028 strioc_if
.ic_cmd
= SIOCSLIFNAME
;
4029 strioc_if
.ic_timout
= 0;
4030 strioc_if
.ic_len
= sizeof(ifr
);
4031 strioc_if
.ic_dp
= (char *)&ifr
;
4032 if (ioctl(arp_fd
, I_STR
, &strioc_if
) < 0){
4033 syslog (LOG_ERR
, "Can't set ifname to arp\n");
4036 if((ip_muxid
= ioctl(ip_fd
, I_LINK
, if_fd
)) < 0){
4037 syslog(LOG_ERR
, "Can't link TAP device to IP");
4041 if ((arp_muxid
= ioctl (ip_fd
, link_type
, arp_fd
)) < 0)
4042 syslog (LOG_ERR
, "Can't link TAP device to ARP");
4046 memset(&ifr
, 0x0, sizeof(ifr
));
4047 strncpy (ifr
.lifr_name
, actual_name
, sizeof (ifr
.lifr_name
));
4048 ifr
.lifr_ip_muxid
= ip_muxid
;
4049 ifr
.lifr_arp_muxid
= arp_muxid
;
4051 if (ioctl (ip_fd
, SIOCSLIFMUXID
, &ifr
) < 0)
4053 ioctl (ip_fd
, I_PUNLINK
, arp_muxid
);
4054 ioctl (ip_fd
, I_PUNLINK
, ip_muxid
);
4055 syslog (LOG_ERR
, "Can't set multiplexor id");
4058 sprintf(dev
, "tap%d", ppa
);
4062 static int tap_open(char *ifname
, int ifname_size
)
4066 if( (fd
= tap_alloc(dev
)) < 0 ){
4067 fprintf(stderr
, "Cannot allocate TAP device\n");
4070 pstrcpy(ifname
, ifname_size
, dev
);
4071 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4075 static int tap_open(char *ifname
, int ifname_size
)
4080 TFR(fd
= open("/dev/net/tun", O_RDWR
));
4082 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4085 memset(&ifr
, 0, sizeof(ifr
));
4086 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
4087 if (ifname
[0] != '\0')
4088 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
4090 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
4091 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
4093 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4097 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
4098 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
4103 static int launch_script(const char *setup_script
, const char *ifname
, int fd
)
4109 /* try to launch network script */
4113 int open_max
= sysconf (_SC_OPEN_MAX
), i
;
4114 for (i
= 0; i
< open_max
; i
++)
4115 if (i
!= STDIN_FILENO
&&
4116 i
!= STDOUT_FILENO
&&
4117 i
!= STDERR_FILENO
&&
4122 *parg
++ = (char *)setup_script
;
4123 *parg
++ = (char *)ifname
;
4125 execv(setup_script
, args
);
4128 while (waitpid(pid
, &status
, 0) != pid
);
4129 if (!WIFEXITED(status
) ||
4130 WEXITSTATUS(status
) != 0) {
4131 fprintf(stderr
, "%s: could not launch network script\n",
4139 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
4140 const char *setup_script
, const char *down_script
)
4146 if (ifname1
!= NULL
)
4147 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
4150 TFR(fd
= tap_open(ifname
, sizeof(ifname
)));
4154 if (!setup_script
|| !strcmp(setup_script
, "no"))
4156 if (setup_script
[0] != '\0') {
4157 if (launch_script(setup_script
, ifname
, fd
))
4160 s
= net_tap_fd_init(vlan
, fd
);
4163 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4164 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
4165 if (down_script
&& strcmp(down_script
, "no"))
4166 snprintf(s
->down_script
, sizeof(s
->down_script
), "%s", down_script
);
4170 #endif /* !_WIN32 */
4172 /* network connection */
4173 typedef struct NetSocketState
{
4174 VLANClientState
*vc
;
4176 int state
; /* 0 = getting length, 1 = getting data */
4180 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4183 typedef struct NetSocketListenState
{
4186 } NetSocketListenState
;
4188 /* XXX: we consider we can send the whole packet without blocking */
4189 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
4191 NetSocketState
*s
= opaque
;
4195 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
4196 send_all(s
->fd
, buf
, size
);
4199 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
4201 NetSocketState
*s
= opaque
;
4202 sendto(s
->fd
, buf
, size
, 0,
4203 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
4206 static void net_socket_send(void *opaque
)
4208 NetSocketState
*s
= opaque
;
4213 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
4215 err
= socket_error();
4216 if (err
!= EWOULDBLOCK
)
4218 } else if (size
== 0) {
4219 /* end of connection */
4221 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4227 /* reassemble a packet from the network */
4233 memcpy(s
->buf
+ s
->index
, buf
, l
);
4237 if (s
->index
== 4) {
4239 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
4245 l
= s
->packet_len
- s
->index
;
4248 memcpy(s
->buf
+ s
->index
, buf
, l
);
4252 if (s
->index
>= s
->packet_len
) {
4253 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
4262 static void net_socket_send_dgram(void *opaque
)
4264 NetSocketState
*s
= opaque
;
4267 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
4271 /* end of connection */
4272 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
4275 qemu_send_packet(s
->vc
, s
->buf
, size
);
4278 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
4283 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
4284 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4285 inet_ntoa(mcastaddr
->sin_addr
),
4286 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
4290 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
4292 perror("socket(PF_INET, SOCK_DGRAM)");
4297 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
4298 (const char *)&val
, sizeof(val
));
4300 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4304 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
4310 /* Add host to multicast group */
4311 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
4312 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
4314 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
4315 (const char *)&imr
, sizeof(struct ip_mreq
));
4317 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4321 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4323 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
4324 (const char *)&val
, sizeof(val
));
4326 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4330 socket_set_nonblock(fd
);
4338 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
4341 struct sockaddr_in saddr
;
4343 socklen_t saddr_len
;
4346 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4347 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4348 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4352 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
4354 if (saddr
.sin_addr
.s_addr
==0) {
4355 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4359 /* clone dgram socket */
4360 newfd
= net_socket_mcast_create(&saddr
);
4362 /* error already reported by net_socket_mcast_create() */
4366 /* clone newfd to fd, close newfd */
4371 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4372 fd
, strerror(errno
));
4377 s
= qemu_mallocz(sizeof(NetSocketState
));
4382 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
4383 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
4385 /* mcast: save bound address as dst */
4386 if (is_connected
) s
->dgram_dst
=saddr
;
4388 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4389 "socket: fd=%d (%s mcast=%s:%d)",
4390 fd
, is_connected
? "cloned" : "",
4391 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4395 static void net_socket_connect(void *opaque
)
4397 NetSocketState
*s
= opaque
;
4398 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
4401 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
4405 s
= qemu_mallocz(sizeof(NetSocketState
));
4409 s
->vc
= qemu_new_vlan_client(vlan
,
4410 net_socket_receive
, NULL
, s
);
4411 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4412 "socket: fd=%d", fd
);
4414 net_socket_connect(s
);
4416 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
4421 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
4424 int so_type
=-1, optlen
=sizeof(so_type
);
4426 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
,
4427 (socklen_t
*)&optlen
)< 0) {
4428 fprintf(stderr
, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd
);
4433 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
4435 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4437 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4438 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
4439 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
4444 static void net_socket_accept(void *opaque
)
4446 NetSocketListenState
*s
= opaque
;
4448 struct sockaddr_in saddr
;
4453 len
= sizeof(saddr
);
4454 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
4455 if (fd
< 0 && errno
!= EINTR
) {
4457 } else if (fd
>= 0) {
4461 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
4465 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
4466 "socket: connection from %s:%d",
4467 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4471 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
4473 NetSocketListenState
*s
;
4475 struct sockaddr_in saddr
;
4477 if (parse_host_port(&saddr
, host_str
) < 0)
4480 s
= qemu_mallocz(sizeof(NetSocketListenState
));
4484 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4489 socket_set_nonblock(fd
);
4491 /* allow fast reuse */
4493 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
4495 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4500 ret
= listen(fd
, 0);
4507 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
4511 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
4514 int fd
, connected
, ret
, err
;
4515 struct sockaddr_in saddr
;
4517 if (parse_host_port(&saddr
, host_str
) < 0)
4520 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
4525 socket_set_nonblock(fd
);
4529 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
4531 err
= socket_error();
4532 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
4533 } else if (err
== EINPROGRESS
) {
4536 } else if (err
== WSAEALREADY
) {
4549 s
= net_socket_fd_init(vlan
, fd
, connected
);
4552 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4553 "socket: connect to %s:%d",
4554 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4558 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
4562 struct sockaddr_in saddr
;
4564 if (parse_host_port(&saddr
, host_str
) < 0)
4568 fd
= net_socket_mcast_create(&saddr
);
4572 s
= net_socket_fd_init(vlan
, fd
, 0);
4576 s
->dgram_dst
= saddr
;
4578 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
4579 "socket: mcast=%s:%d",
4580 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
4585 static const char *get_word(char *buf
, int buf_size
, const char *p
)
4592 while (*p
!= '\0') {
4597 } else if (*p
== '\"') {
4598 substring
= !substring
;
4601 } else if (!substring
&& (*p
== ',' || *p
== '='))
4603 if (q
&& (q
- buf
) < buf_size
- 1)
4613 static int get_param_value(char *buf
, int buf_size
,
4614 const char *tag
, const char *str
)
4621 p
= get_word(option
, sizeof(option
), p
);
4625 if (!strcmp(tag
, option
)) {
4626 (void)get_word(buf
, buf_size
, p
);
4629 p
= get_word(NULL
, 0, p
);
4638 static int check_params(char *buf
, int buf_size
,
4639 char **params
, const char *str
)
4646 p
= get_word(buf
, buf_size
, p
);
4650 for(i
= 0; params
[i
] != NULL
; i
++)
4651 if (!strcmp(params
[i
], buf
))
4653 if (params
[i
] == NULL
)
4655 p
= get_word(NULL
, 0, p
);
4664 static int net_client_init(const char *str
)
4675 while (*p
!= '\0' && *p
!= ',') {
4676 if ((q
- device
) < sizeof(device
) - 1)
4684 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
4685 vlan_id
= strtol(buf
, NULL
, 0);
4687 vlan
= qemu_find_vlan(vlan_id
);
4689 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
4692 if (!strcmp(device
, "nic")) {
4696 if (nb_nics
>= MAX_NICS
) {
4697 fprintf(stderr
, "Too Many NICs\n");
4700 nd
= &nd_table
[nb_nics
];
4701 macaddr
= nd
->macaddr
;
4707 macaddr
[5] = 0x56 + nb_nics
;
4709 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
4710 if (parse_macaddr(macaddr
, buf
) < 0) {
4711 fprintf(stderr
, "invalid syntax for ethernet address\n");
4715 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
4716 nd
->model
= strdup(buf
);
4720 vlan
->nb_guest_devs
++;
4723 if (!strcmp(device
, "none")) {
4724 /* does nothing. It is needed to signal that no network cards
4729 if (!strcmp(device
, "user")) {
4730 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
4731 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
4733 vlan
->nb_host_devs
++;
4734 ret
= net_slirp_init(vlan
);
4738 if (!strcmp(device
, "tap")) {
4740 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4741 fprintf(stderr
, "tap: no interface name\n");
4744 vlan
->nb_host_devs
++;
4745 ret
= tap_win32_init(vlan
, ifname
);
4748 if (!strcmp(device
, "tap")) {
4750 char setup_script
[1024], down_script
[1024];
4752 vlan
->nb_host_devs
++;
4753 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4754 fd
= strtol(buf
, NULL
, 0);
4756 if (net_tap_fd_init(vlan
, fd
))
4759 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
4762 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
4763 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
4765 if (get_param_value(down_script
, sizeof(down_script
), "downscript", p
) == 0) {
4766 pstrcpy(down_script
, sizeof(down_script
), DEFAULT_NETWORK_DOWN_SCRIPT
);
4768 ret
= net_tap_init(vlan
, ifname
, setup_script
, down_script
);
4772 if (!strcmp(device
, "socket")) {
4773 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
4775 fd
= strtol(buf
, NULL
, 0);
4777 if (net_socket_fd_init(vlan
, fd
, 1))
4779 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
4780 ret
= net_socket_listen_init(vlan
, buf
);
4781 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
4782 ret
= net_socket_connect_init(vlan
, buf
);
4783 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
4784 ret
= net_socket_mcast_init(vlan
, buf
);
4786 fprintf(stderr
, "Unknown socket options: %s\n", p
);
4789 vlan
->nb_host_devs
++;
4792 fprintf(stderr
, "Unknown network device: %s\n", device
);
4796 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
4802 void do_info_network(void)
4805 VLANClientState
*vc
;
4807 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
4808 term_printf("VLAN %d devices:\n", vlan
->id
);
4809 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
4810 term_printf(" %s\n", vc
->info_str
);
4814 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4816 #define CDROM_ALIAS "index=1,media=cdrom"
4818 #define CDROM_ALIAS "index=2,media=cdrom"
4820 #define FD_ALIAS "index=%d,if=floppy"
4821 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4822 #define MTD_ALIAS "file=\"%s\",if=mtd"
4823 #define SD_ALIAS "index=0,if=sd"
4825 static int drive_add(const char *fmt
, ...)
4829 if (nb_drives_opt
>= MAX_DRIVES
) {
4830 fprintf(stderr
, "qemu: too many drives\n");
4835 vsnprintf(drives_opt
[nb_drives_opt
], sizeof(drives_opt
[0]), fmt
, ap
);
4838 return nb_drives_opt
++;
4841 int drive_get_index(BlockInterfaceType type
, int bus
, int unit
)
4845 /* seek interface, bus and unit */
4847 for (index
= 0; index
< nb_drives
; index
++)
4848 if (drives_table
[index
].type
== type
&&
4849 drives_table
[index
].bus
== bus
&&
4850 drives_table
[index
].unit
== unit
)
4856 int drive_get_max_bus(BlockInterfaceType type
)
4862 for (index
= 0; index
< nb_drives
; index
++) {
4863 if(drives_table
[index
].type
== type
&&
4864 drives_table
[index
].bus
> max_bus
)
4865 max_bus
= drives_table
[index
].bus
;
4870 static int drive_init(const char *str
, int snapshot
, QEMUMachine
*machine
)
4875 const char *mediastr
= "";
4876 BlockInterfaceType type
;
4877 enum { MEDIA_DISK
, MEDIA_CDROM
} media
;
4878 int bus_id
, unit_id
;
4879 int cyls
, heads
, secs
, translation
;
4880 BlockDriverState
*bdrv
;
4883 char *params
[] = { "bus", "unit", "if", "index", "cyls", "heads",
4884 "secs", "trans", "media", "snapshot", "file", NULL
};
4886 if (check_params(buf
, sizeof(buf
), params
, str
) < 0) {
4887 fprintf(stderr
, "qemu: unknowm parameter '%s' in '%s'\n",
4893 cyls
= heads
= secs
= 0;
4896 translation
= BIOS_ATA_TRANSLATION_AUTO
;
4899 if (!strcmp(machine
->name
, "realview") ||
4900 !strcmp(machine
->name
, "SS-5") ||
4901 !strcmp(machine
->name
, "SS-10") ||
4902 !strcmp(machine
->name
, "SS-600MP") ||
4903 !strcmp(machine
->name
, "versatilepb") ||
4904 !strcmp(machine
->name
, "versatileab")) {
4906 max_devs
= MAX_SCSI_DEVS
;
4907 strcpy(devname
, "scsi");
4910 max_devs
= MAX_IDE_DEVS
;
4911 strcpy(devname
, "ide");
4915 /* extract parameters */
4917 if (get_param_value(buf
, sizeof(buf
), "bus", str
)) {
4918 bus_id
= strtol(buf
, NULL
, 0);
4920 fprintf(stderr
, "qemu: '%s' invalid bus id\n", str
);
4925 if (get_param_value(buf
, sizeof(buf
), "unit", str
)) {
4926 unit_id
= strtol(buf
, NULL
, 0);
4928 fprintf(stderr
, "qemu: '%s' invalid unit id\n", str
);
4933 if (get_param_value(buf
, sizeof(buf
), "if", str
)) {
4934 strncpy(devname
, buf
, sizeof(devname
));
4935 if (!strcmp(buf
, "ide")) {
4937 max_devs
= MAX_IDE_DEVS
;
4938 } else if (!strcmp(buf
, "scsi")) {
4940 max_devs
= MAX_SCSI_DEVS
;
4941 } else if (!strcmp(buf
, "floppy")) {
4944 } else if (!strcmp(buf
, "pflash")) {
4947 } else if (!strcmp(buf
, "mtd")) {
4950 } else if (!strcmp(buf
, "sd")) {
4954 fprintf(stderr
, "qemu: '%s' unsupported bus type '%s'\n", str
, buf
);
4959 if (get_param_value(buf
, sizeof(buf
), "index", str
)) {
4960 index
= strtol(buf
, NULL
, 0);
4962 fprintf(stderr
, "qemu: '%s' invalid index\n", str
);
4967 if (get_param_value(buf
, sizeof(buf
), "cyls", str
)) {
4968 cyls
= strtol(buf
, NULL
, 0);
4971 if (get_param_value(buf
, sizeof(buf
), "heads", str
)) {
4972 heads
= strtol(buf
, NULL
, 0);
4975 if (get_param_value(buf
, sizeof(buf
), "secs", str
)) {
4976 secs
= strtol(buf
, NULL
, 0);
4979 if (cyls
|| heads
|| secs
) {
4980 if (cyls
< 1 || cyls
> 16383) {
4981 fprintf(stderr
, "qemu: '%s' invalid physical cyls number\n", str
);
4984 if (heads
< 1 || heads
> 16) {
4985 fprintf(stderr
, "qemu: '%s' invalid physical heads number\n", str
);
4988 if (secs
< 1 || secs
> 63) {
4989 fprintf(stderr
, "qemu: '%s' invalid physical secs number\n", str
);
4994 if (get_param_value(buf
, sizeof(buf
), "trans", str
)) {
4997 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5001 if (!strcmp(buf
, "none"))
5002 translation
= BIOS_ATA_TRANSLATION_NONE
;
5003 else if (!strcmp(buf
, "lba"))
5004 translation
= BIOS_ATA_TRANSLATION_LBA
;
5005 else if (!strcmp(buf
, "auto"))
5006 translation
= BIOS_ATA_TRANSLATION_AUTO
;
5008 fprintf(stderr
, "qemu: '%s' invalid translation type\n", str
);
5013 if (get_param_value(buf
, sizeof(buf
), "media", str
)) {
5014 if (!strcmp(buf
, "disk")) {
5016 } else if (!strcmp(buf
, "cdrom")) {
5017 if (cyls
|| secs
|| heads
) {
5019 "qemu: '%s' invalid physical CHS format\n", str
);
5022 media
= MEDIA_CDROM
;
5024 fprintf(stderr
, "qemu: '%s' invalid media\n", str
);
5029 if (get_param_value(buf
, sizeof(buf
), "snapshot", str
)) {
5030 if (!strcmp(buf
, "on"))
5032 else if (!strcmp(buf
, "off"))
5035 fprintf(stderr
, "qemu: '%s' invalid snapshot option\n", str
);
5040 get_param_value(file
, sizeof(file
), "file", str
);
5042 /* compute bus and unit according index */
5045 if (bus_id
!= 0 || unit_id
!= -1) {
5047 "qemu: '%s' index cannot be used with bus and unit\n", str
);
5055 unit_id
= index
% max_devs
;
5056 bus_id
= index
/ max_devs
;
5060 /* if user doesn't specify a unit_id,
5061 * try to find the first free
5064 if (unit_id
== -1) {
5066 while (drive_get_index(type
, bus_id
, unit_id
) != -1) {
5068 if (max_devs
&& unit_id
>= max_devs
) {
5069 unit_id
-= max_devs
;
5077 if (max_devs
&& unit_id
>= max_devs
) {
5078 fprintf(stderr
, "qemu: '%s' unit %d too big (max is %d)\n",
5079 str
, unit_id
, max_devs
- 1);
5084 * ignore multiple definitions
5087 if (drive_get_index(type
, bus_id
, unit_id
) != -1)
5092 if (type
== IF_IDE
|| type
== IF_SCSI
)
5093 mediastr
= (media
== MEDIA_CDROM
) ? "-cd" : "-hd";
5094 snprintf(buf
, sizeof(buf
), max_devs
? "%1$s%4$i%2$s%3$i" : "%s%s%i",
5095 devname
, mediastr
, unit_id
, bus_id
);
5096 bdrv
= bdrv_new(buf
);
5097 drives_table
[nb_drives
].bdrv
= bdrv
;
5098 drives_table
[nb_drives
].type
= type
;
5099 drives_table
[nb_drives
].bus
= bus_id
;
5100 drives_table
[nb_drives
].unit
= unit_id
;
5109 bdrv_set_geometry_hint(bdrv
, cyls
, heads
, secs
);
5110 bdrv_set_translation_hint(bdrv
, translation
);
5114 bdrv_set_type_hint(bdrv
, BDRV_TYPE_CDROM
);
5119 /* FIXME: This isn't really a floppy, but it's a reasonable
5122 bdrv_set_type_hint(bdrv
, BDRV_TYPE_FLOPPY
);
5130 if (bdrv_open(bdrv
, file
, snapshot
? BDRV_O_SNAPSHOT
: 0) < 0 ||
5131 qemu_key_check(bdrv
, file
)) {
5132 fprintf(stderr
, "qemu: could not open disk image %s\n",
5139 /***********************************************************/
5142 static USBPort
*used_usb_ports
;
5143 static USBPort
*free_usb_ports
;
5145 /* ??? Maybe change this to register a hub to keep track of the topology. */
5146 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
5147 usb_attachfn attach
)
5149 port
->opaque
= opaque
;
5150 port
->index
= index
;
5151 port
->attach
= attach
;
5152 port
->next
= free_usb_ports
;
5153 free_usb_ports
= port
;
5156 static int usb_device_add(const char *devname
)
5162 if (!free_usb_ports
)
5165 if (strstart(devname
, "host:", &p
)) {
5166 dev
= usb_host_device_open(p
);
5167 } else if (!strcmp(devname
, "mouse")) {
5168 dev
= usb_mouse_init();
5169 } else if (!strcmp(devname
, "tablet")) {
5170 dev
= usb_tablet_init();
5171 } else if (!strcmp(devname
, "keyboard")) {
5172 dev
= usb_keyboard_init();
5173 } else if (strstart(devname
, "disk:", &p
)) {
5174 dev
= usb_msd_init(p
);
5175 } else if (!strcmp(devname
, "wacom-tablet")) {
5176 dev
= usb_wacom_init();
5183 /* Find a USB port to add the device to. */
5184 port
= free_usb_ports
;
5188 /* Create a new hub and chain it on. */
5189 free_usb_ports
= NULL
;
5190 port
->next
= used_usb_ports
;
5191 used_usb_ports
= port
;
5193 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
5194 usb_attach(port
, hub
);
5195 port
= free_usb_ports
;
5198 free_usb_ports
= port
->next
;
5199 port
->next
= used_usb_ports
;
5200 used_usb_ports
= port
;
5201 usb_attach(port
, dev
);
5205 static int usb_device_del(const char *devname
)
5213 if (!used_usb_ports
)
5216 p
= strchr(devname
, '.');
5219 bus_num
= strtoul(devname
, NULL
, 0);
5220 addr
= strtoul(p
+ 1, NULL
, 0);
5224 lastp
= &used_usb_ports
;
5225 port
= used_usb_ports
;
5226 while (port
&& port
->dev
->addr
!= addr
) {
5227 lastp
= &port
->next
;
5235 *lastp
= port
->next
;
5236 usb_attach(port
, NULL
);
5237 dev
->handle_destroy(dev
);
5238 port
->next
= free_usb_ports
;
5239 free_usb_ports
= port
;
5243 void do_usb_add(const char *devname
)
5246 ret
= usb_device_add(devname
);
5248 term_printf("Could not add USB device '%s'\n", devname
);
5251 void do_usb_del(const char *devname
)
5254 ret
= usb_device_del(devname
);
5256 term_printf("Could not remove USB device '%s'\n", devname
);
5263 const char *speed_str
;
5266 term_printf("USB support not enabled\n");
5270 for (port
= used_usb_ports
; port
; port
= port
->next
) {
5274 switch(dev
->speed
) {
5278 case USB_SPEED_FULL
:
5281 case USB_SPEED_HIGH
:
5288 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5289 0, dev
->addr
, speed_str
, dev
->devname
);
5293 /***********************************************************/
5294 /* PCMCIA/Cardbus */
5296 static struct pcmcia_socket_entry_s
{
5297 struct pcmcia_socket_s
*socket
;
5298 struct pcmcia_socket_entry_s
*next
;
5299 } *pcmcia_sockets
= 0;
5301 void pcmcia_socket_register(struct pcmcia_socket_s
*socket
)
5303 struct pcmcia_socket_entry_s
*entry
;
5305 entry
= qemu_malloc(sizeof(struct pcmcia_socket_entry_s
));
5306 entry
->socket
= socket
;
5307 entry
->next
= pcmcia_sockets
;
5308 pcmcia_sockets
= entry
;
5311 void pcmcia_socket_unregister(struct pcmcia_socket_s
*socket
)
5313 struct pcmcia_socket_entry_s
*entry
, **ptr
;
5315 ptr
= &pcmcia_sockets
;
5316 for (entry
= *ptr
; entry
; ptr
= &entry
->next
, entry
= *ptr
)
5317 if (entry
->socket
== socket
) {
5323 void pcmcia_info(void)
5325 struct pcmcia_socket_entry_s
*iter
;
5326 if (!pcmcia_sockets
)
5327 term_printf("No PCMCIA sockets\n");
5329 for (iter
= pcmcia_sockets
; iter
; iter
= iter
->next
)
5330 term_printf("%s: %s\n", iter
->socket
->slot_string
,
5331 iter
->socket
->attached
? iter
->socket
->card_string
:
5335 /***********************************************************/
5338 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
5342 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
5346 static void dumb_refresh(DisplayState
*ds
)
5348 #if defined(CONFIG_SDL)
5353 static void dumb_display_init(DisplayState
*ds
)
5358 ds
->dpy_update
= dumb_update
;
5359 ds
->dpy_resize
= dumb_resize
;
5360 ds
->dpy_refresh
= dumb_refresh
;
5363 /***********************************************************/
5366 #define MAX_IO_HANDLERS 64
5368 typedef struct IOHandlerRecord
{
5370 IOCanRWHandler
*fd_read_poll
;
5372 IOHandler
*fd_write
;
5375 /* temporary data */
5377 struct IOHandlerRecord
*next
;
5380 static IOHandlerRecord
*first_io_handler
;
5382 /* XXX: fd_read_poll should be suppressed, but an API change is
5383 necessary in the character devices to suppress fd_can_read(). */
5384 int qemu_set_fd_handler2(int fd
,
5385 IOCanRWHandler
*fd_read_poll
,
5387 IOHandler
*fd_write
,
5390 IOHandlerRecord
**pioh
, *ioh
;
5392 if (!fd_read
&& !fd_write
) {
5393 pioh
= &first_io_handler
;
5398 if (ioh
->fd
== fd
) {
5405 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
5409 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
5412 ioh
->next
= first_io_handler
;
5413 first_io_handler
= ioh
;
5416 ioh
->fd_read_poll
= fd_read_poll
;
5417 ioh
->fd_read
= fd_read
;
5418 ioh
->fd_write
= fd_write
;
5419 ioh
->opaque
= opaque
;
5425 int qemu_set_fd_handler(int fd
,
5427 IOHandler
*fd_write
,
5430 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
5433 /***********************************************************/
5434 /* Polling handling */
5436 typedef struct PollingEntry
{
5439 struct PollingEntry
*next
;
5442 static PollingEntry
*first_polling_entry
;
5444 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
5446 PollingEntry
**ppe
, *pe
;
5447 pe
= qemu_mallocz(sizeof(PollingEntry
));
5451 pe
->opaque
= opaque
;
5452 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
5457 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
5459 PollingEntry
**ppe
, *pe
;
5460 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
5462 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
5471 /***********************************************************/
5472 /* Wait objects support */
5473 typedef struct WaitObjects
{
5475 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
5476 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
5477 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
5480 static WaitObjects wait_objects
= {0};
5482 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5484 WaitObjects
*w
= &wait_objects
;
5486 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
5488 w
->events
[w
->num
] = handle
;
5489 w
->func
[w
->num
] = func
;
5490 w
->opaque
[w
->num
] = opaque
;
5495 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
5498 WaitObjects
*w
= &wait_objects
;
5501 for (i
= 0; i
< w
->num
; i
++) {
5502 if (w
->events
[i
] == handle
)
5505 w
->events
[i
] = w
->events
[i
+ 1];
5506 w
->func
[i
] = w
->func
[i
+ 1];
5507 w
->opaque
[i
] = w
->opaque
[i
+ 1];
5515 /***********************************************************/
5516 /* savevm/loadvm support */
5518 #define IO_BUF_SIZE 32768
5522 BlockDriverState
*bs
;
5525 int64_t base_offset
;
5526 int64_t buf_offset
; /* start of buffer when writing, end of buffer
5529 int buf_size
; /* 0 when writing */
5530 uint8_t buf
[IO_BUF_SIZE
];
5533 QEMUFile
*qemu_fopen(const char *filename
, const char *mode
)
5537 f
= qemu_mallocz(sizeof(QEMUFile
));
5540 if (!strcmp(mode
, "wb")) {
5542 } else if (!strcmp(mode
, "rb")) {
5547 f
->outfile
= fopen(filename
, mode
);
5559 static QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
5563 f
= qemu_mallocz(sizeof(QEMUFile
));
5568 f
->is_writable
= is_writable
;
5569 f
->base_offset
= offset
;
5573 void qemu_fflush(QEMUFile
*f
)
5575 if (!f
->is_writable
)
5577 if (f
->buf_index
> 0) {
5579 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
5580 fwrite(f
->buf
, 1, f
->buf_index
, f
->outfile
);
5582 bdrv_pwrite(f
->bs
, f
->base_offset
+ f
->buf_offset
,
5583 f
->buf
, f
->buf_index
);
5585 f
->buf_offset
+= f
->buf_index
;
5590 static void qemu_fill_buffer(QEMUFile
*f
)
5597 fseek(f
->outfile
, f
->buf_offset
, SEEK_SET
);
5598 len
= fread(f
->buf
, 1, IO_BUF_SIZE
, f
->outfile
);
5602 len
= bdrv_pread(f
->bs
, f
->base_offset
+ f
->buf_offset
,
5603 f
->buf
, IO_BUF_SIZE
);
5609 f
->buf_offset
+= len
;
5612 void qemu_fclose(QEMUFile
*f
)
5622 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
5626 l
= IO_BUF_SIZE
- f
->buf_index
;
5629 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
5633 if (f
->buf_index
>= IO_BUF_SIZE
)
5638 void qemu_put_byte(QEMUFile
*f
, int v
)
5640 f
->buf
[f
->buf_index
++] = v
;
5641 if (f
->buf_index
>= IO_BUF_SIZE
)
5645 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
5651 l
= f
->buf_size
- f
->buf_index
;
5653 qemu_fill_buffer(f
);
5654 l
= f
->buf_size
- f
->buf_index
;
5660 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
5665 return size1
- size
;
5668 int qemu_get_byte(QEMUFile
*f
)
5670 if (f
->buf_index
>= f
->buf_size
) {
5671 qemu_fill_buffer(f
);
5672 if (f
->buf_index
>= f
->buf_size
)
5675 return f
->buf
[f
->buf_index
++];
5678 int64_t qemu_ftell(QEMUFile
*f
)
5680 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
5683 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
5685 if (whence
== SEEK_SET
) {
5687 } else if (whence
== SEEK_CUR
) {
5688 pos
+= qemu_ftell(f
);
5690 /* SEEK_END not supported */
5693 if (f
->is_writable
) {
5695 f
->buf_offset
= pos
;
5697 f
->buf_offset
= pos
;
5704 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
5706 qemu_put_byte(f
, v
>> 8);
5707 qemu_put_byte(f
, v
);
5710 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
5712 qemu_put_byte(f
, v
>> 24);
5713 qemu_put_byte(f
, v
>> 16);
5714 qemu_put_byte(f
, v
>> 8);
5715 qemu_put_byte(f
, v
);
5718 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
5720 qemu_put_be32(f
, v
>> 32);
5721 qemu_put_be32(f
, v
);
5724 unsigned int qemu_get_be16(QEMUFile
*f
)
5727 v
= qemu_get_byte(f
) << 8;
5728 v
|= qemu_get_byte(f
);
5732 unsigned int qemu_get_be32(QEMUFile
*f
)
5735 v
= qemu_get_byte(f
) << 24;
5736 v
|= qemu_get_byte(f
) << 16;
5737 v
|= qemu_get_byte(f
) << 8;
5738 v
|= qemu_get_byte(f
);
5742 uint64_t qemu_get_be64(QEMUFile
*f
)
5745 v
= (uint64_t)qemu_get_be32(f
) << 32;
5746 v
|= qemu_get_be32(f
);
5750 typedef struct SaveStateEntry
{
5754 SaveStateHandler
*save_state
;
5755 LoadStateHandler
*load_state
;
5757 struct SaveStateEntry
*next
;
5760 static SaveStateEntry
*first_se
;
5762 int register_savevm(const char *idstr
,
5765 SaveStateHandler
*save_state
,
5766 LoadStateHandler
*load_state
,
5769 SaveStateEntry
*se
, **pse
;
5771 se
= qemu_malloc(sizeof(SaveStateEntry
));
5774 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
5775 se
->instance_id
= instance_id
;
5776 se
->version_id
= version_id
;
5777 se
->save_state
= save_state
;
5778 se
->load_state
= load_state
;
5779 se
->opaque
= opaque
;
5782 /* add at the end of list */
5784 while (*pse
!= NULL
)
5785 pse
= &(*pse
)->next
;
5790 #define QEMU_VM_FILE_MAGIC 0x5145564d
5791 #define QEMU_VM_FILE_VERSION 0x00000002
5793 static int qemu_savevm_state(QEMUFile
*f
)
5797 int64_t cur_pos
, len_pos
, total_len_pos
;
5799 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
5800 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
5801 total_len_pos
= qemu_ftell(f
);
5802 qemu_put_be64(f
, 0); /* total size */
5804 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
5806 len
= strlen(se
->idstr
);
5807 qemu_put_byte(f
, len
);
5808 qemu_put_buffer(f
, (uint8_t *)se
->idstr
, len
);
5810 qemu_put_be32(f
, se
->instance_id
);
5811 qemu_put_be32(f
, se
->version_id
);
5813 /* record size: filled later */
5814 len_pos
= qemu_ftell(f
);
5815 qemu_put_be32(f
, 0);
5816 se
->save_state(f
, se
->opaque
);
5818 /* fill record size */
5819 cur_pos
= qemu_ftell(f
);
5820 len
= cur_pos
- len_pos
- 4;
5821 qemu_fseek(f
, len_pos
, SEEK_SET
);
5822 qemu_put_be32(f
, len
);
5823 qemu_fseek(f
, cur_pos
, SEEK_SET
);
5825 cur_pos
= qemu_ftell(f
);
5826 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
5827 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
5828 qemu_fseek(f
, cur_pos
, SEEK_SET
);
5834 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
5838 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
5839 if (!strcmp(se
->idstr
, idstr
) &&
5840 instance_id
== se
->instance_id
)
5846 static int qemu_loadvm_state(QEMUFile
*f
)
5849 int len
, ret
, instance_id
, record_len
, version_id
;
5850 int64_t total_len
, end_pos
, cur_pos
;
5854 v
= qemu_get_be32(f
);
5855 if (v
!= QEMU_VM_FILE_MAGIC
)
5857 v
= qemu_get_be32(f
);
5858 if (v
!= QEMU_VM_FILE_VERSION
) {
5863 total_len
= qemu_get_be64(f
);
5864 end_pos
= total_len
+ qemu_ftell(f
);
5866 if (qemu_ftell(f
) >= end_pos
)
5868 len
= qemu_get_byte(f
);
5869 qemu_get_buffer(f
, (uint8_t *)idstr
, len
);
5871 instance_id
= qemu_get_be32(f
);
5872 version_id
= qemu_get_be32(f
);
5873 record_len
= qemu_get_be32(f
);
5875 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5876 idstr
, instance_id
, version_id
, record_len
);
5878 cur_pos
= qemu_ftell(f
);
5879 se
= find_se(idstr
, instance_id
);
5881 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5882 instance_id
, idstr
);
5884 ret
= se
->load_state(f
, se
->opaque
, version_id
);
5886 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5887 instance_id
, idstr
);
5890 /* always seek to exact end of record */
5891 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
5898 /* device can contain snapshots */
5899 static int bdrv_can_snapshot(BlockDriverState
*bs
)
5902 !bdrv_is_removable(bs
) &&
5903 !bdrv_is_read_only(bs
));
5906 /* device must be snapshots in order to have a reliable snapshot */
5907 static int bdrv_has_snapshot(BlockDriverState
*bs
)
5910 !bdrv_is_removable(bs
) &&
5911 !bdrv_is_read_only(bs
));
5914 static BlockDriverState
*get_bs_snapshots(void)
5916 BlockDriverState
*bs
;
5920 return bs_snapshots
;
5921 for(i
= 0; i
<= nb_drives
; i
++) {
5922 bs
= drives_table
[i
].bdrv
;
5923 if (bdrv_can_snapshot(bs
))
5932 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
5935 QEMUSnapshotInfo
*sn_tab
, *sn
;
5939 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5942 for(i
= 0; i
< nb_sns
; i
++) {
5944 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
5954 void do_savevm(const char *name
)
5956 BlockDriverState
*bs
, *bs1
;
5957 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
5958 int must_delete
, ret
, i
;
5959 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5961 int saved_vm_running
;
5968 bs
= get_bs_snapshots();
5970 term_printf("No block device can accept snapshots\n");
5974 /* ??? Should this occur after vm_stop? */
5977 saved_vm_running
= vm_running
;
5982 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
5987 memset(sn
, 0, sizeof(*sn
));
5989 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
5990 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
5993 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
5996 /* fill auxiliary fields */
5999 sn
->date_sec
= tb
.time
;
6000 sn
->date_nsec
= tb
.millitm
* 1000000;
6002 gettimeofday(&tv
, NULL
);
6003 sn
->date_sec
= tv
.tv_sec
;
6004 sn
->date_nsec
= tv
.tv_usec
* 1000;
6006 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
6008 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6009 term_printf("Device %s does not support VM state snapshots\n",
6010 bdrv_get_device_name(bs
));
6014 /* save the VM state */
6015 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
6017 term_printf("Could not open VM state file\n");
6020 ret
= qemu_savevm_state(f
);
6021 sn
->vm_state_size
= qemu_ftell(f
);
6024 term_printf("Error %d while writing VM\n", ret
);
6028 /* create the snapshots */
6030 for(i
= 0; i
< nb_drives
; i
++) {
6031 bs1
= drives_table
[i
].bdrv
;
6032 if (bdrv_has_snapshot(bs1
)) {
6034 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
6036 term_printf("Error while deleting snapshot on '%s'\n",
6037 bdrv_get_device_name(bs1
));
6040 ret
= bdrv_snapshot_create(bs1
, sn
);
6042 term_printf("Error while creating snapshot on '%s'\n",
6043 bdrv_get_device_name(bs1
));
6049 if (saved_vm_running
)
6053 void do_loadvm(const char *name
)
6055 BlockDriverState
*bs
, *bs1
;
6056 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
6059 int saved_vm_running
;
6061 bs
= get_bs_snapshots();
6063 term_printf("No block device supports snapshots\n");
6067 /* Flush all IO requests so they don't interfere with the new state. */
6070 saved_vm_running
= vm_running
;
6073 for(i
= 0; i
<= nb_drives
; i
++) {
6074 bs1
= drives_table
[i
].bdrv
;
6075 if (bdrv_has_snapshot(bs1
)) {
6076 ret
= bdrv_snapshot_goto(bs1
, name
);
6079 term_printf("Warning: ");
6082 term_printf("Snapshots not supported on device '%s'\n",
6083 bdrv_get_device_name(bs1
));
6086 term_printf("Could not find snapshot '%s' on device '%s'\n",
6087 name
, bdrv_get_device_name(bs1
));
6090 term_printf("Error %d while activating snapshot on '%s'\n",
6091 ret
, bdrv_get_device_name(bs1
));
6094 /* fatal on snapshot block device */
6101 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
6102 term_printf("Device %s does not support VM state snapshots\n",
6103 bdrv_get_device_name(bs
));
6107 /* restore the VM state */
6108 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
6110 term_printf("Could not open VM state file\n");
6113 ret
= qemu_loadvm_state(f
);
6116 term_printf("Error %d while loading VM state\n", ret
);
6119 if (saved_vm_running
)
6123 void do_delvm(const char *name
)
6125 BlockDriverState
*bs
, *bs1
;
6128 bs
= get_bs_snapshots();
6130 term_printf("No block device supports snapshots\n");
6134 for(i
= 0; i
<= nb_drives
; i
++) {
6135 bs1
= drives_table
[i
].bdrv
;
6136 if (bdrv_has_snapshot(bs1
)) {
6137 ret
= bdrv_snapshot_delete(bs1
, name
);
6139 if (ret
== -ENOTSUP
)
6140 term_printf("Snapshots not supported on device '%s'\n",
6141 bdrv_get_device_name(bs1
));
6143 term_printf("Error %d while deleting snapshot on '%s'\n",
6144 ret
, bdrv_get_device_name(bs1
));
6150 void do_info_snapshots(void)
6152 BlockDriverState
*bs
, *bs1
;
6153 QEMUSnapshotInfo
*sn_tab
, *sn
;
6157 bs
= get_bs_snapshots();
6159 term_printf("No available block device supports snapshots\n");
6162 term_printf("Snapshot devices:");
6163 for(i
= 0; i
<= nb_drives
; i
++) {
6164 bs1
= drives_table
[i
].bdrv
;
6165 if (bdrv_has_snapshot(bs1
)) {
6167 term_printf(" %s", bdrv_get_device_name(bs1
));
6172 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
6174 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
6177 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
6178 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
6179 for(i
= 0; i
< nb_sns
; i
++) {
6181 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
6186 /***********************************************************/
6187 /* cpu save/restore */
6189 #if defined(TARGET_I386)
6191 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
6193 qemu_put_be32(f
, dt
->selector
);
6194 qemu_put_betl(f
, dt
->base
);
6195 qemu_put_be32(f
, dt
->limit
);
6196 qemu_put_be32(f
, dt
->flags
);
6199 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
6201 dt
->selector
= qemu_get_be32(f
);
6202 dt
->base
= qemu_get_betl(f
);
6203 dt
->limit
= qemu_get_be32(f
);
6204 dt
->flags
= qemu_get_be32(f
);
6207 void cpu_save(QEMUFile
*f
, void *opaque
)
6209 CPUState
*env
= opaque
;
6210 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
6214 for(i
= 0; i
< CPU_NB_REGS
; i
++)
6215 qemu_put_betls(f
, &env
->regs
[i
]);
6216 qemu_put_betls(f
, &env
->eip
);
6217 qemu_put_betls(f
, &env
->eflags
);
6218 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
6219 qemu_put_be32s(f
, &hflags
);
6223 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
6225 for(i
= 0; i
< 8; i
++) {
6226 fptag
|= ((!env
->fptags
[i
]) << i
);
6229 qemu_put_be16s(f
, &fpuc
);
6230 qemu_put_be16s(f
, &fpus
);
6231 qemu_put_be16s(f
, &fptag
);
6233 #ifdef USE_X86LDOUBLE
6238 qemu_put_be16s(f
, &fpregs_format
);
6240 for(i
= 0; i
< 8; i
++) {
6241 #ifdef USE_X86LDOUBLE
6245 /* we save the real CPU data (in case of MMX usage only 'mant'
6246 contains the MMX register */
6247 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
6248 qemu_put_be64(f
, mant
);
6249 qemu_put_be16(f
, exp
);
6252 /* if we use doubles for float emulation, we save the doubles to
6253 avoid losing information in case of MMX usage. It can give
6254 problems if the image is restored on a CPU where long
6255 doubles are used instead. */
6256 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
6260 for(i
= 0; i
< 6; i
++)
6261 cpu_put_seg(f
, &env
->segs
[i
]);
6262 cpu_put_seg(f
, &env
->ldt
);
6263 cpu_put_seg(f
, &env
->tr
);
6264 cpu_put_seg(f
, &env
->gdt
);
6265 cpu_put_seg(f
, &env
->idt
);
6267 qemu_put_be32s(f
, &env
->sysenter_cs
);
6268 qemu_put_be32s(f
, &env
->sysenter_esp
);
6269 qemu_put_be32s(f
, &env
->sysenter_eip
);
6271 qemu_put_betls(f
, &env
->cr
[0]);
6272 qemu_put_betls(f
, &env
->cr
[2]);
6273 qemu_put_betls(f
, &env
->cr
[3]);
6274 qemu_put_betls(f
, &env
->cr
[4]);
6276 for(i
= 0; i
< 8; i
++)
6277 qemu_put_betls(f
, &env
->dr
[i
]);
6280 qemu_put_be32s(f
, &env
->a20_mask
);
6283 qemu_put_be32s(f
, &env
->mxcsr
);
6284 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
6285 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
6286 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
6289 #ifdef TARGET_X86_64
6290 qemu_put_be64s(f
, &env
->efer
);
6291 qemu_put_be64s(f
, &env
->star
);
6292 qemu_put_be64s(f
, &env
->lstar
);
6293 qemu_put_be64s(f
, &env
->cstar
);
6294 qemu_put_be64s(f
, &env
->fmask
);
6295 qemu_put_be64s(f
, &env
->kernelgsbase
);
6297 qemu_put_be32s(f
, &env
->smbase
);
6300 #ifdef USE_X86LDOUBLE
6301 /* XXX: add that in a FPU generic layer */
6302 union x86_longdouble
{
6307 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6308 #define EXPBIAS1 1023
6309 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6310 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6312 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
6316 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
6317 /* exponent + sign */
6318 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
6319 e
|= SIGND1(temp
) >> 16;
6324 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6326 CPUState
*env
= opaque
;
6329 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
6331 if (version_id
!= 3 && version_id
!= 4)
6333 for(i
= 0; i
< CPU_NB_REGS
; i
++)
6334 qemu_get_betls(f
, &env
->regs
[i
]);
6335 qemu_get_betls(f
, &env
->eip
);
6336 qemu_get_betls(f
, &env
->eflags
);
6337 qemu_get_be32s(f
, &hflags
);
6339 qemu_get_be16s(f
, &fpuc
);
6340 qemu_get_be16s(f
, &fpus
);
6341 qemu_get_be16s(f
, &fptag
);
6342 qemu_get_be16s(f
, &fpregs_format
);
6344 /* NOTE: we cannot always restore the FPU state if the image come
6345 from a host with a different 'USE_X86LDOUBLE' define. We guess
6346 if we are in an MMX state to restore correctly in that case. */
6347 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
6348 for(i
= 0; i
< 8; i
++) {
6352 switch(fpregs_format
) {
6354 mant
= qemu_get_be64(f
);
6355 exp
= qemu_get_be16(f
);
6356 #ifdef USE_X86LDOUBLE
6357 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
6359 /* difficult case */
6361 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
6363 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
6367 mant
= qemu_get_be64(f
);
6368 #ifdef USE_X86LDOUBLE
6370 union x86_longdouble
*p
;
6371 /* difficult case */
6372 p
= (void *)&env
->fpregs
[i
];
6377 fp64_to_fp80(p
, mant
);
6381 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
6390 /* XXX: restore FPU round state */
6391 env
->fpstt
= (fpus
>> 11) & 7;
6392 env
->fpus
= fpus
& ~0x3800;
6394 for(i
= 0; i
< 8; i
++) {
6395 env
->fptags
[i
] = (fptag
>> i
) & 1;
6398 for(i
= 0; i
< 6; i
++)
6399 cpu_get_seg(f
, &env
->segs
[i
]);
6400 cpu_get_seg(f
, &env
->ldt
);
6401 cpu_get_seg(f
, &env
->tr
);
6402 cpu_get_seg(f
, &env
->gdt
);
6403 cpu_get_seg(f
, &env
->idt
);
6405 qemu_get_be32s(f
, &env
->sysenter_cs
);
6406 qemu_get_be32s(f
, &env
->sysenter_esp
);
6407 qemu_get_be32s(f
, &env
->sysenter_eip
);
6409 qemu_get_betls(f
, &env
->cr
[0]);
6410 qemu_get_betls(f
, &env
->cr
[2]);
6411 qemu_get_betls(f
, &env
->cr
[3]);
6412 qemu_get_betls(f
, &env
->cr
[4]);
6414 for(i
= 0; i
< 8; i
++)
6415 qemu_get_betls(f
, &env
->dr
[i
]);
6418 qemu_get_be32s(f
, &env
->a20_mask
);
6420 qemu_get_be32s(f
, &env
->mxcsr
);
6421 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
6422 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
6423 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
6426 #ifdef TARGET_X86_64
6427 qemu_get_be64s(f
, &env
->efer
);
6428 qemu_get_be64s(f
, &env
->star
);
6429 qemu_get_be64s(f
, &env
->lstar
);
6430 qemu_get_be64s(f
, &env
->cstar
);
6431 qemu_get_be64s(f
, &env
->fmask
);
6432 qemu_get_be64s(f
, &env
->kernelgsbase
);
6434 if (version_id
>= 4)
6435 qemu_get_be32s(f
, &env
->smbase
);
6437 /* XXX: compute hflags from scratch, except for CPL and IIF */
6438 env
->hflags
= hflags
;
6443 #elif defined(TARGET_PPC)
6444 void cpu_save(QEMUFile
*f
, void *opaque
)
6448 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6453 #elif defined(TARGET_MIPS)
6454 void cpu_save(QEMUFile
*f
, void *opaque
)
6458 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6463 #elif defined(TARGET_SPARC)
6464 void cpu_save(QEMUFile
*f
, void *opaque
)
6466 CPUState
*env
= opaque
;
6470 for(i
= 0; i
< 8; i
++)
6471 qemu_put_betls(f
, &env
->gregs
[i
]);
6472 for(i
= 0; i
< NWINDOWS
* 16; i
++)
6473 qemu_put_betls(f
, &env
->regbase
[i
]);
6476 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
6482 qemu_put_be32(f
, u
.i
);
6485 qemu_put_betls(f
, &env
->pc
);
6486 qemu_put_betls(f
, &env
->npc
);
6487 qemu_put_betls(f
, &env
->y
);
6489 qemu_put_be32(f
, tmp
);
6490 qemu_put_betls(f
, &env
->fsr
);
6491 qemu_put_betls(f
, &env
->tbr
);
6492 #ifndef TARGET_SPARC64
6493 qemu_put_be32s(f
, &env
->wim
);
6495 for(i
= 0; i
< 16; i
++)
6496 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
6500 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6502 CPUState
*env
= opaque
;
6506 for(i
= 0; i
< 8; i
++)
6507 qemu_get_betls(f
, &env
->gregs
[i
]);
6508 for(i
= 0; i
< NWINDOWS
* 16; i
++)
6509 qemu_get_betls(f
, &env
->regbase
[i
]);
6512 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
6517 u
.i
= qemu_get_be32(f
);
6521 qemu_get_betls(f
, &env
->pc
);
6522 qemu_get_betls(f
, &env
->npc
);
6523 qemu_get_betls(f
, &env
->y
);
6524 tmp
= qemu_get_be32(f
);
6525 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
6526 correctly updated */
6528 qemu_get_betls(f
, &env
->fsr
);
6529 qemu_get_betls(f
, &env
->tbr
);
6530 #ifndef TARGET_SPARC64
6531 qemu_get_be32s(f
, &env
->wim
);
6533 for(i
= 0; i
< 16; i
++)
6534 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
6540 #elif defined(TARGET_ARM)
6542 void cpu_save(QEMUFile
*f
, void *opaque
)
6545 CPUARMState
*env
= (CPUARMState
*)opaque
;
6547 for (i
= 0; i
< 16; i
++) {
6548 qemu_put_be32(f
, env
->regs
[i
]);
6550 qemu_put_be32(f
, cpsr_read(env
));
6551 qemu_put_be32(f
, env
->spsr
);
6552 for (i
= 0; i
< 6; i
++) {
6553 qemu_put_be32(f
, env
->banked_spsr
[i
]);
6554 qemu_put_be32(f
, env
->banked_r13
[i
]);
6555 qemu_put_be32(f
, env
->banked_r14
[i
]);
6557 for (i
= 0; i
< 5; i
++) {
6558 qemu_put_be32(f
, env
->usr_regs
[i
]);
6559 qemu_put_be32(f
, env
->fiq_regs
[i
]);
6561 qemu_put_be32(f
, env
->cp15
.c0_cpuid
);
6562 qemu_put_be32(f
, env
->cp15
.c0_cachetype
);
6563 qemu_put_be32(f
, env
->cp15
.c1_sys
);
6564 qemu_put_be32(f
, env
->cp15
.c1_coproc
);
6565 qemu_put_be32(f
, env
->cp15
.c1_xscaleauxcr
);
6566 qemu_put_be32(f
, env
->cp15
.c2_base0
);
6567 qemu_put_be32(f
, env
->cp15
.c2_base1
);
6568 qemu_put_be32(f
, env
->cp15
.c2_mask
);
6569 qemu_put_be32(f
, env
->cp15
.c2_data
);
6570 qemu_put_be32(f
, env
->cp15
.c2_insn
);
6571 qemu_put_be32(f
, env
->cp15
.c3
);
6572 qemu_put_be32(f
, env
->cp15
.c5_insn
);
6573 qemu_put_be32(f
, env
->cp15
.c5_data
);
6574 for (i
= 0; i
< 8; i
++) {
6575 qemu_put_be32(f
, env
->cp15
.c6_region
[i
]);
6577 qemu_put_be32(f
, env
->cp15
.c6_insn
);
6578 qemu_put_be32(f
, env
->cp15
.c6_data
);
6579 qemu_put_be32(f
, env
->cp15
.c9_insn
);
6580 qemu_put_be32(f
, env
->cp15
.c9_data
);
6581 qemu_put_be32(f
, env
->cp15
.c13_fcse
);
6582 qemu_put_be32(f
, env
->cp15
.c13_context
);
6583 qemu_put_be32(f
, env
->cp15
.c13_tls1
);
6584 qemu_put_be32(f
, env
->cp15
.c13_tls2
);
6585 qemu_put_be32(f
, env
->cp15
.c13_tls3
);
6586 qemu_put_be32(f
, env
->cp15
.c15_cpar
);
6588 qemu_put_be32(f
, env
->features
);
6590 if (arm_feature(env
, ARM_FEATURE_VFP
)) {
6591 for (i
= 0; i
< 16; i
++) {
6593 u
.d
= env
->vfp
.regs
[i
];
6594 qemu_put_be32(f
, u
.l
.upper
);
6595 qemu_put_be32(f
, u
.l
.lower
);
6597 for (i
= 0; i
< 16; i
++) {
6598 qemu_put_be32(f
, env
->vfp
.xregs
[i
]);
6601 /* TODO: Should use proper FPSCR access functions. */
6602 qemu_put_be32(f
, env
->vfp
.vec_len
);
6603 qemu_put_be32(f
, env
->vfp
.vec_stride
);
6605 if (arm_feature(env
, ARM_FEATURE_VFP3
)) {
6606 for (i
= 16; i
< 32; i
++) {
6608 u
.d
= env
->vfp
.regs
[i
];
6609 qemu_put_be32(f
, u
.l
.upper
);
6610 qemu_put_be32(f
, u
.l
.lower
);
6615 if (arm_feature(env
, ARM_FEATURE_IWMMXT
)) {
6616 for (i
= 0; i
< 16; i
++) {
6617 qemu_put_be64(f
, env
->iwmmxt
.regs
[i
]);
6619 for (i
= 0; i
< 16; i
++) {
6620 qemu_put_be32(f
, env
->iwmmxt
.cregs
[i
]);
6624 if (arm_feature(env
, ARM_FEATURE_M
)) {
6625 qemu_put_be32(f
, env
->v7m
.other_sp
);
6626 qemu_put_be32(f
, env
->v7m
.vecbase
);
6627 qemu_put_be32(f
, env
->v7m
.basepri
);
6628 qemu_put_be32(f
, env
->v7m
.control
);
6629 qemu_put_be32(f
, env
->v7m
.current_sp
);
6630 qemu_put_be32(f
, env
->v7m
.exception
);
6634 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
6636 CPUARMState
*env
= (CPUARMState
*)opaque
;
6639 if (version_id
!= ARM_CPU_SAVE_VERSION
)
6642 for (i
= 0; i
< 16; i
++) {
6643 env
->regs
[i
] = qemu_get_be32(f
);
6645 cpsr_write(env
, qemu_get_be32(f
), 0xffffffff);
6646 env
->spsr
= qemu_get_be32(f
);
6647 for (i
= 0; i
< 6; i
++) {
6648 env
->banked_spsr
[i
] = qemu_get_be32(f
);
6649 env
->banked_r13
[i
] = qemu_get_be32(f
);
6650 env
->banked_r14
[i
] = qemu_get_be32(f
);
6652 for (i
= 0; i
< 5; i
++) {
6653 env
->usr_regs
[i
] = qemu_get_be32(f
);
6654 env
->fiq_regs
[i
] = qemu_get_be32(f
);
6656 env
->cp15
.c0_cpuid
= qemu_get_be32(f
);
6657 env
->cp15
.c0_cachetype
= qemu_get_be32(f
);
6658 env
->cp15
.c1_sys
= qemu_get_be32(f
);
6659 env
->cp15
.c1_coproc
= qemu_get_be32(f
);
6660 env
->cp15
.c1_xscaleauxcr
= qemu_get_be32(f
);
6661 env
->cp15
.c2_base0
= qemu_get_be32(f
);
6662 env
->cp15
.c2_base1
= qemu_get_be32(f
);
6663 env
->cp15
.c2_mask
= qemu_get_be32(f
);
6664 env
->cp15
.c2_data
= qemu_get_be32(f
);
6665 env
->cp15
.c2_insn
= qemu_get_be32(f
);
6666 env
->cp15
.c3
= qemu_get_be32(f
);
6667 env
->cp15
.c5_insn
= qemu_get_be32(f
);
6668 env
->cp15
.c5_data
= qemu_get_be32(f
);
6669 for (i
= 0; i
< 8; i
++) {
6670 env
->cp15
.c6_region
[i
] = qemu_get_be32(f
);
6672 env
->cp15
.c6_insn
= qemu_get_be32(f
);
6673 env
->cp15
.c6_data
= qemu_get_be32(f
);
6674 env
->cp15
.c9_insn
= qemu_get_be32(f
);
6675 env
->cp15
.c9_data
= qemu_get_be32(f
);
6676 env
->cp15
.c13_fcse
= qemu_get_be32(f
);
6677 env
->cp15
.c13_context
= qemu_get_be32(f
);
6678 env
->cp15
.c13_tls1
= qemu_get_be32(f
);
6679 env
->cp15
.c13_tls2
= qemu_get_be32(f
);
6680 env
->cp15
.c13_tls3
= qemu_get_be32(f
);
6681 env
->cp15
.c15_cpar
= qemu_get_be32(f
);
6683 env
->features
= qemu_get_be32(f
);
6685 if (arm_feature(env
, ARM_FEATURE_VFP
)) {
6686 for (i
= 0; i
< 16; i
++) {
6688 u
.l
.upper
= qemu_get_be32(f
);
6689 u
.l
.lower
= qemu_get_be32(f
);
6690 env
->vfp
.regs
[i
] = u
.d
;
6692 for (i
= 0; i
< 16; i
++) {
6693 env
->vfp
.xregs
[i
] = qemu_get_be32(f
);
6696 /* TODO: Should use proper FPSCR access functions. */
6697 env
->vfp
.vec_len
= qemu_get_be32(f
);
6698 env
->vfp
.vec_stride
= qemu_get_be32(f
);
6700 if (arm_feature(env
, ARM_FEATURE_VFP3
)) {
6701 for (i
= 0; i
< 16; i
++) {
6703 u
.l
.upper
= qemu_get_be32(f
);
6704 u
.l
.lower
= qemu_get_be32(f
);
6705 env
->vfp
.regs
[i
] = u
.d
;
6710 if (arm_feature(env
, ARM_FEATURE_IWMMXT
)) {
6711 for (i
= 0; i
< 16; i
++) {
6712 env
->iwmmxt
.regs
[i
] = qemu_get_be64(f
);
6714 for (i
= 0; i
< 16; i
++) {
6715 env
->iwmmxt
.cregs
[i
] = qemu_get_be32(f
);
6719 if (arm_feature(env
, ARM_FEATURE_M
)) {
6720 env
->v7m
.other_sp
= qemu_get_be32(f
);
6721 env
->v7m
.vecbase
= qemu_get_be32(f
);
6722 env
->v7m
.basepri
= qemu_get_be32(f
);
6723 env
->v7m
.control
= qemu_get_be32(f
);
6724 env
->v7m
.current_sp
= qemu_get_be32(f
);
6725 env
->v7m
.exception
= qemu_get_be32(f
);
6733 //#warning No CPU save/restore functions
6737 /***********************************************************/
6738 /* ram save/restore */
6740 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
6744 v
= qemu_get_byte(f
);
6747 if (qemu_get_buffer(f
, buf
, len
) != len
)
6751 v
= qemu_get_byte(f
);
6752 memset(buf
, v
, len
);
6760 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
6764 if (qemu_get_be32(f
) != phys_ram_size
)
6766 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
6767 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
6774 #define BDRV_HASH_BLOCK_SIZE 1024
6775 #define IOBUF_SIZE 4096
6776 #define RAM_CBLOCK_MAGIC 0xfabe
6778 typedef struct RamCompressState
{
6781 uint8_t buf
[IOBUF_SIZE
];
6784 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
6787 memset(s
, 0, sizeof(*s
));
6789 ret
= deflateInit2(&s
->zstream
, 1,
6791 9, Z_DEFAULT_STRATEGY
);
6794 s
->zstream
.avail_out
= IOBUF_SIZE
;
6795 s
->zstream
.next_out
= s
->buf
;
6799 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
6801 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
6802 qemu_put_be16(s
->f
, len
);
6803 qemu_put_buffer(s
->f
, buf
, len
);
6806 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
6810 s
->zstream
.avail_in
= len
;
6811 s
->zstream
.next_in
= (uint8_t *)buf
;
6812 while (s
->zstream
.avail_in
> 0) {
6813 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
6816 if (s
->zstream
.avail_out
== 0) {
6817 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
6818 s
->zstream
.avail_out
= IOBUF_SIZE
;
6819 s
->zstream
.next_out
= s
->buf
;
6825 static void ram_compress_close(RamCompressState
*s
)
6829 /* compress last bytes */
6831 ret
= deflate(&s
->zstream
, Z_FINISH
);
6832 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
6833 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
6835 ram_put_cblock(s
, s
->buf
, len
);
6837 s
->zstream
.avail_out
= IOBUF_SIZE
;
6838 s
->zstream
.next_out
= s
->buf
;
6839 if (ret
== Z_STREAM_END
)
6846 deflateEnd(&s
->zstream
);
6849 typedef struct RamDecompressState
{
6852 uint8_t buf
[IOBUF_SIZE
];
6853 } RamDecompressState
;
6855 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
6858 memset(s
, 0, sizeof(*s
));
6860 ret
= inflateInit(&s
->zstream
);
6866 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
6870 s
->zstream
.avail_out
= len
;
6871 s
->zstream
.next_out
= buf
;
6872 while (s
->zstream
.avail_out
> 0) {
6873 if (s
->zstream
.avail_in
== 0) {
6874 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
6876 clen
= qemu_get_be16(s
->f
);
6877 if (clen
> IOBUF_SIZE
)
6879 qemu_get_buffer(s
->f
, s
->buf
, clen
);
6880 s
->zstream
.avail_in
= clen
;
6881 s
->zstream
.next_in
= s
->buf
;
6883 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
6884 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
6891 static void ram_decompress_close(RamDecompressState
*s
)
6893 inflateEnd(&s
->zstream
);
6896 static void ram_save(QEMUFile
*f
, void *opaque
)
6899 RamCompressState s1
, *s
= &s1
;
6902 qemu_put_be32(f
, phys_ram_size
);
6903 if (ram_compress_open(s
, f
) < 0)
6905 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6907 if (tight_savevm_enabled
) {
6911 /* find if the memory block is available on a virtual
6914 for(j
= 0; j
< nb_drives
; j
++) {
6915 sector_num
= bdrv_hash_find(drives_table
[j
].bdrv
,
6917 BDRV_HASH_BLOCK_SIZE
);
6918 if (sector_num
>= 0)
6922 goto normal_compress
;
6925 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
6926 ram_compress_buf(s
, buf
, 10);
6932 ram_compress_buf(s
, buf
, 1);
6933 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
6936 ram_compress_close(s
);
6939 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
6941 RamDecompressState s1
, *s
= &s1
;
6945 if (version_id
== 1)
6946 return ram_load_v1(f
, opaque
);
6947 if (version_id
!= 2)
6949 if (qemu_get_be32(f
) != phys_ram_size
)
6951 if (ram_decompress_open(s
, f
) < 0)
6953 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
6954 if (ram_decompress_buf(s
, buf
, 1) < 0) {
6955 fprintf(stderr
, "Error while reading ram block header\n");
6959 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
6960 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
6969 ram_decompress_buf(s
, buf
+ 1, 9);
6971 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
6972 if (bs_index
>= nb_drives
) {
6973 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
6976 if (bdrv_read(drives_table
[bs_index
].bdrv
, sector_num
,
6978 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
6979 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
6980 bs_index
, sector_num
);
6987 printf("Error block header\n");
6991 ram_decompress_close(s
);
6995 /***********************************************************/
6996 /* bottom halves (can be seen as timers which expire ASAP) */
7005 static QEMUBH
*first_bh
= NULL
;
7007 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
7010 bh
= qemu_mallocz(sizeof(QEMUBH
));
7014 bh
->opaque
= opaque
;
7018 int qemu_bh_poll(void)
7037 void qemu_bh_schedule(QEMUBH
*bh
)
7039 CPUState
*env
= cpu_single_env
;
7043 bh
->next
= first_bh
;
7046 /* stop the currently executing CPU to execute the BH ASAP */
7048 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
7052 void qemu_bh_cancel(QEMUBH
*bh
)
7055 if (bh
->scheduled
) {
7058 pbh
= &(*pbh
)->next
;
7064 void qemu_bh_delete(QEMUBH
*bh
)
7070 /***********************************************************/
7071 /* machine registration */
7073 QEMUMachine
*first_machine
= NULL
;
7075 int qemu_register_machine(QEMUMachine
*m
)
7078 pm
= &first_machine
;
7086 static QEMUMachine
*find_machine(const char *name
)
7090 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7091 if (!strcmp(m
->name
, name
))
7097 /***********************************************************/
7098 /* main execution loop */
7100 static void gui_update(void *opaque
)
7102 DisplayState
*ds
= opaque
;
7103 ds
->dpy_refresh(ds
);
7104 qemu_mod_timer(ds
->gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
7107 struct vm_change_state_entry
{
7108 VMChangeStateHandler
*cb
;
7110 LIST_ENTRY (vm_change_state_entry
) entries
;
7113 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
7115 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
7118 VMChangeStateEntry
*e
;
7120 e
= qemu_mallocz(sizeof (*e
));
7126 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
7130 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
7132 LIST_REMOVE (e
, entries
);
7136 static void vm_state_notify(int running
)
7138 VMChangeStateEntry
*e
;
7140 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
7141 e
->cb(e
->opaque
, running
);
7145 /* XXX: support several handlers */
7146 static VMStopHandler
*vm_stop_cb
;
7147 static void *vm_stop_opaque
;
7149 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7152 vm_stop_opaque
= opaque
;
7156 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
7167 qemu_rearm_alarm_timer(alarm_timer
);
7171 void vm_stop(int reason
)
7174 cpu_disable_ticks();
7178 vm_stop_cb(vm_stop_opaque
, reason
);
7185 /* reset/shutdown handler */
7187 typedef struct QEMUResetEntry
{
7188 QEMUResetHandler
*func
;
7190 struct QEMUResetEntry
*next
;
7193 static QEMUResetEntry
*first_reset_entry
;
7194 static int reset_requested
;
7195 static int shutdown_requested
;
7196 static int powerdown_requested
;
7198 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
7200 QEMUResetEntry
**pre
, *re
;
7202 pre
= &first_reset_entry
;
7203 while (*pre
!= NULL
)
7204 pre
= &(*pre
)->next
;
7205 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
7207 re
->opaque
= opaque
;
7212 static void qemu_system_reset(void)
7216 /* reset all devices */
7217 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
7218 re
->func(re
->opaque
);
7222 void qemu_system_reset_request(void)
7225 shutdown_requested
= 1;
7227 reset_requested
= 1;
7230 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7233 void qemu_system_shutdown_request(void)
7235 shutdown_requested
= 1;
7237 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7240 void qemu_system_powerdown_request(void)
7242 powerdown_requested
= 1;
7244 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
7247 void main_loop_wait(int timeout
)
7249 IOHandlerRecord
*ioh
;
7250 fd_set rfds
, wfds
, xfds
;
7259 /* XXX: need to suppress polling by better using win32 events */
7261 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
7262 ret
|= pe
->func(pe
->opaque
);
7267 WaitObjects
*w
= &wait_objects
;
7269 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
7270 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
7271 if (w
->func
[ret
- WAIT_OBJECT_0
])
7272 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
7274 /* Check for additional signaled events */
7275 for(i
= (ret
- WAIT_OBJECT_0
+ 1); i
< w
->num
; i
++) {
7277 /* Check if event is signaled */
7278 ret2
= WaitForSingleObject(w
->events
[i
], 0);
7279 if(ret2
== WAIT_OBJECT_0
) {
7281 w
->func
[i
](w
->opaque
[i
]);
7282 } else if (ret2
== WAIT_TIMEOUT
) {
7284 err
= GetLastError();
7285 fprintf(stderr
, "WaitForSingleObject error %d %d\n", i
, err
);
7288 } else if (ret
== WAIT_TIMEOUT
) {
7290 err
= GetLastError();
7291 fprintf(stderr
, "WaitForMultipleObjects error %d %d\n", ret
, err
);
7295 /* poll any events */
7296 /* XXX: separate device handlers from system ones */
7301 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7305 (!ioh
->fd_read_poll
||
7306 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
7307 FD_SET(ioh
->fd
, &rfds
);
7311 if (ioh
->fd_write
) {
7312 FD_SET(ioh
->fd
, &wfds
);
7322 tv
.tv_usec
= timeout
* 1000;
7324 #if defined(CONFIG_SLIRP)
7326 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
7329 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
7331 IOHandlerRecord
**pioh
;
7333 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
7334 if (!ioh
->deleted
&& ioh
->fd_read
&& FD_ISSET(ioh
->fd
, &rfds
)) {
7335 ioh
->fd_read(ioh
->opaque
);
7337 if (!ioh
->deleted
&& ioh
->fd_write
&& FD_ISSET(ioh
->fd
, &wfds
)) {
7338 ioh
->fd_write(ioh
->opaque
);
7342 /* remove deleted IO handlers */
7343 pioh
= &first_io_handler
;
7353 #if defined(CONFIG_SLIRP)
7360 slirp_select_poll(&rfds
, &wfds
, &xfds
);
7366 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
7367 qemu_get_clock(vm_clock
));
7368 /* run dma transfers, if any */
7372 /* real time timers */
7373 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
7374 qemu_get_clock(rt_clock
));
7376 qemu_rearm_alarm_timer(alarm_timer
);
7378 /* Check bottom-halves last in case any of the earlier events triggered
7384 static int main_loop(void)
7387 #ifdef CONFIG_PROFILER
7392 cur_cpu
= first_cpu
;
7393 next_cpu
= cur_cpu
->next_cpu
?: first_cpu
;
7400 #ifdef CONFIG_PROFILER
7401 ti
= profile_getclock();
7403 ret
= cpu_exec(env
);
7404 #ifdef CONFIG_PROFILER
7405 qemu_time
+= profile_getclock() - ti
;
7407 next_cpu
= env
->next_cpu
?: first_cpu
;
7408 if (event_pending
) {
7409 ret
= EXCP_INTERRUPT
;
7413 if (ret
== EXCP_HLT
) {
7414 /* Give the next CPU a chance to run. */
7418 if (ret
!= EXCP_HALTED
)
7420 /* all CPUs are halted ? */
7426 if (shutdown_requested
) {
7427 ret
= EXCP_INTERRUPT
;
7430 if (reset_requested
) {
7431 reset_requested
= 0;
7432 qemu_system_reset();
7433 ret
= EXCP_INTERRUPT
;
7435 if (powerdown_requested
) {
7436 powerdown_requested
= 0;
7437 qemu_system_powerdown();
7438 ret
= EXCP_INTERRUPT
;
7440 if (ret
== EXCP_DEBUG
) {
7441 vm_stop(EXCP_DEBUG
);
7443 /* If all cpus are halted then wait until the next IRQ */
7444 /* XXX: use timeout computed from timers */
7445 if (ret
== EXCP_HALTED
)
7452 #ifdef CONFIG_PROFILER
7453 ti
= profile_getclock();
7455 main_loop_wait(timeout
);
7456 #ifdef CONFIG_PROFILER
7457 dev_time
+= profile_getclock() - ti
;
7460 cpu_disable_ticks();
7464 static void help(int exitcode
)
7466 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
7467 "usage: %s [options] [disk_image]\n"
7469 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7471 "Standard options:\n"
7472 "-M machine select emulated machine (-M ? for list)\n"
7473 "-cpu cpu select CPU (-cpu ? for list)\n"
7474 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7475 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7476 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7477 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7478 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7479 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7480 " use 'file' as a drive image\n"
7481 "-mtdblock file use 'file' as on-board Flash memory image\n"
7482 "-sd file use 'file' as SecureDigital card image\n"
7483 "-pflash file use 'file' as a parallel flash image\n"
7484 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7485 "-snapshot write to temporary files instead of disk image files\n"
7487 "-no-frame open SDL window without a frame and window decorations\n"
7488 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7489 "-no-quit disable SDL window close capability\n"
7492 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7494 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7495 "-smp n set the number of CPUs to 'n' [default=1]\n"
7496 "-nographic disable graphical output and redirect serial I/Os to console\n"
7497 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7499 "-k language use keyboard layout (for example \"fr\" for French)\n"
7502 "-audio-help print list of audio drivers and their options\n"
7503 "-soundhw c1,... enable audio support\n"
7504 " and only specified sound cards (comma separated list)\n"
7505 " use -soundhw ? to get the list of supported cards\n"
7506 " use -soundhw all to enable all of them\n"
7508 "-localtime set the real time clock to local time [default=utc]\n"
7509 "-full-screen start in full screen\n"
7511 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7513 "-usb enable the USB driver (will be the default soon)\n"
7514 "-usbdevice name add the host or guest USB device 'name'\n"
7515 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7516 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7518 "-name string set the name of the guest\n"
7520 "Network options:\n"
7521 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7522 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7524 "-net user[,vlan=n][,hostname=host]\n"
7525 " connect the user mode network stack to VLAN 'n' and send\n"
7526 " hostname 'host' to DHCP clients\n"
7529 "-net tap[,vlan=n],ifname=name\n"
7530 " connect the host TAP network interface to VLAN 'n'\n"
7532 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7533 " connect the host TAP network interface to VLAN 'n' and use the\n"
7534 " network scripts 'file' (default=%s)\n"
7535 " and 'dfile' (default=%s);\n"
7536 " use '[down]script=no' to disable script execution;\n"
7537 " use 'fd=h' to connect to an already opened TAP interface\n"
7539 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7540 " connect the vlan 'n' to another VLAN using a socket connection\n"
7541 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7542 " connect the vlan 'n' to multicast maddr and port\n"
7543 "-net none use it alone to have zero network devices; if no -net option\n"
7544 " is provided, the default is '-net nic -net user'\n"
7547 "-tftp dir allow tftp access to files in dir [-net user]\n"
7548 "-bootp file advertise file in BOOTP replies\n"
7550 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7552 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7553 " redirect TCP or UDP connections from host to guest [-net user]\n"
7556 "Linux boot specific:\n"
7557 "-kernel bzImage use 'bzImage' as kernel image\n"
7558 "-append cmdline use 'cmdline' as kernel command line\n"
7559 "-initrd file use 'file' as initial ram disk\n"
7561 "Debug/Expert options:\n"
7562 "-monitor dev redirect the monitor to char device 'dev'\n"
7563 "-serial dev redirect the serial port to char device 'dev'\n"
7564 "-parallel dev redirect the parallel port to char device 'dev'\n"
7565 "-pidfile file Write PID to 'file'\n"
7566 "-S freeze CPU at startup (use 'c' to start execution)\n"
7567 "-s wait gdb connection to port\n"
7568 "-p port set gdb connection port [default=%s]\n"
7569 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7570 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7571 " translation (t=none or lba) (usually qemu can guess them)\n"
7572 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7574 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7575 "-no-kqemu disable KQEMU kernel module usage\n"
7578 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7579 " (default is CL-GD5446 PCI VGA)\n"
7580 "-no-acpi disable ACPI\n"
7582 "-no-reboot exit instead of rebooting\n"
7583 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7584 "-vnc display start a VNC server on display\n"
7586 "-daemonize daemonize QEMU after initializing\n"
7588 "-option-rom rom load a file, rom, into the option ROM space\n"
7590 "-prom-env variable=value set OpenBIOS nvram variables\n"
7592 "-clock force the use of the given methods for timer alarm.\n"
7593 " To see what timers are available use -clock help\n"
7595 "During emulation, the following keys are useful:\n"
7596 "ctrl-alt-f toggle full screen\n"
7597 "ctrl-alt-n switch to virtual console 'n'\n"
7598 "ctrl-alt toggle mouse and keyboard grab\n"
7600 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7605 DEFAULT_NETWORK_SCRIPT
,
7606 DEFAULT_NETWORK_DOWN_SCRIPT
,
7608 DEFAULT_GDBSTUB_PORT
,
7613 #define HAS_ARG 0x0001
7628 QEMU_OPTION_mtdblock
,
7632 QEMU_OPTION_snapshot
,
7634 QEMU_OPTION_no_fd_bootchk
,
7637 QEMU_OPTION_nographic
,
7638 QEMU_OPTION_portrait
,
7640 QEMU_OPTION_audio_help
,
7641 QEMU_OPTION_soundhw
,
7661 QEMU_OPTION_no_code_copy
,
7663 QEMU_OPTION_localtime
,
7664 QEMU_OPTION_cirrusvga
,
7667 QEMU_OPTION_std_vga
,
7669 QEMU_OPTION_monitor
,
7671 QEMU_OPTION_parallel
,
7673 QEMU_OPTION_full_screen
,
7674 QEMU_OPTION_no_frame
,
7675 QEMU_OPTION_alt_grab
,
7676 QEMU_OPTION_no_quit
,
7677 QEMU_OPTION_pidfile
,
7678 QEMU_OPTION_no_kqemu
,
7679 QEMU_OPTION_kernel_kqemu
,
7680 QEMU_OPTION_win2k_hack
,
7682 QEMU_OPTION_usbdevice
,
7685 QEMU_OPTION_no_acpi
,
7686 QEMU_OPTION_no_reboot
,
7687 QEMU_OPTION_show_cursor
,
7688 QEMU_OPTION_daemonize
,
7689 QEMU_OPTION_option_rom
,
7690 QEMU_OPTION_semihosting
,
7692 QEMU_OPTION_prom_env
,
7693 QEMU_OPTION_old_param
,
7695 QEMU_OPTION_startdate
,
7698 typedef struct QEMUOption
{
7704 const QEMUOption qemu_options
[] = {
7705 { "h", 0, QEMU_OPTION_h
},
7706 { "help", 0, QEMU_OPTION_h
},
7708 { "M", HAS_ARG
, QEMU_OPTION_M
},
7709 { "cpu", HAS_ARG
, QEMU_OPTION_cpu
},
7710 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
7711 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
7712 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
7713 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
7714 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
7715 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
7716 { "drive", HAS_ARG
, QEMU_OPTION_drive
},
7717 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
7718 { "mtdblock", HAS_ARG
, QEMU_OPTION_mtdblock
},
7719 { "sd", HAS_ARG
, QEMU_OPTION_sd
},
7720 { "pflash", HAS_ARG
, QEMU_OPTION_pflash
},
7721 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
7722 { "snapshot", 0, QEMU_OPTION_snapshot
},
7724 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
7726 { "m", HAS_ARG
, QEMU_OPTION_m
},
7727 { "nographic", 0, QEMU_OPTION_nographic
},
7728 { "portrait", 0, QEMU_OPTION_portrait
},
7729 { "k", HAS_ARG
, QEMU_OPTION_k
},
7731 { "audio-help", 0, QEMU_OPTION_audio_help
},
7732 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
7735 { "net", HAS_ARG
, QEMU_OPTION_net
},
7737 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
7738 { "bootp", HAS_ARG
, QEMU_OPTION_bootp
},
7740 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
7742 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
7745 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
7746 { "append", HAS_ARG
, QEMU_OPTION_append
},
7747 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
7749 { "S", 0, QEMU_OPTION_S
},
7750 { "s", 0, QEMU_OPTION_s
},
7751 { "p", HAS_ARG
, QEMU_OPTION_p
},
7752 { "d", HAS_ARG
, QEMU_OPTION_d
},
7753 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
7754 { "L", HAS_ARG
, QEMU_OPTION_L
},
7755 { "bios", HAS_ARG
, QEMU_OPTION_bios
},
7756 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
7758 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
7759 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
7761 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7762 { "g", 1, QEMU_OPTION_g
},
7764 { "localtime", 0, QEMU_OPTION_localtime
},
7765 { "std-vga", 0, QEMU_OPTION_std_vga
},
7766 { "echr", HAS_ARG
, QEMU_OPTION_echr
},
7767 { "monitor", HAS_ARG
, QEMU_OPTION_monitor
},
7768 { "serial", HAS_ARG
, QEMU_OPTION_serial
},
7769 { "parallel", HAS_ARG
, QEMU_OPTION_parallel
},
7770 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
7771 { "full-screen", 0, QEMU_OPTION_full_screen
},
7773 { "no-frame", 0, QEMU_OPTION_no_frame
},
7774 { "alt-grab", 0, QEMU_OPTION_alt_grab
},
7775 { "no-quit", 0, QEMU_OPTION_no_quit
},
7777 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
7778 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
7779 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
7780 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
7781 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
7783 /* temporary options */
7784 { "usb", 0, QEMU_OPTION_usb
},
7785 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
7786 { "vmwarevga", 0, QEMU_OPTION_vmsvga
},
7787 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
7788 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
7789 { "show-cursor", 0, QEMU_OPTION_show_cursor
},
7790 { "daemonize", 0, QEMU_OPTION_daemonize
},
7791 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
7792 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7793 { "semihosting", 0, QEMU_OPTION_semihosting
},
7795 { "name", HAS_ARG
, QEMU_OPTION_name
},
7796 #if defined(TARGET_SPARC)
7797 { "prom-env", HAS_ARG
, QEMU_OPTION_prom_env
},
7799 #if defined(TARGET_ARM)
7800 { "old-param", 0, QEMU_OPTION_old_param
},
7802 { "clock", HAS_ARG
, QEMU_OPTION_clock
},
7803 { "startdate", HAS_ARG
, QEMU_OPTION_startdate
},
7807 /* password input */
7809 int qemu_key_check(BlockDriverState
*bs
, const char *name
)
7814 if (!bdrv_is_encrypted(bs
))
7817 term_printf("%s is encrypted.\n", name
);
7818 for(i
= 0; i
< 3; i
++) {
7819 monitor_readline("Password: ", 1, password
, sizeof(password
));
7820 if (bdrv_set_key(bs
, password
) == 0)
7822 term_printf("invalid password\n");
7827 static BlockDriverState
*get_bdrv(int index
)
7829 if (index
> nb_drives
)
7831 return drives_table
[index
].bdrv
;
7834 static void read_passwords(void)
7836 BlockDriverState
*bs
;
7839 for(i
= 0; i
< 6; i
++) {
7842 qemu_key_check(bs
, bdrv_get_device_name(bs
));
7846 /* XXX: currently we cannot use simultaneously different CPUs */
7847 static void register_machines(void)
7849 #if defined(TARGET_I386)
7850 qemu_register_machine(&pc_machine
);
7851 qemu_register_machine(&isapc_machine
);
7852 #elif defined(TARGET_PPC)
7853 qemu_register_machine(&heathrow_machine
);
7854 qemu_register_machine(&core99_machine
);
7855 qemu_register_machine(&prep_machine
);
7856 qemu_register_machine(&ref405ep_machine
);
7857 qemu_register_machine(&taihu_machine
);
7858 #elif defined(TARGET_MIPS)
7859 qemu_register_machine(&mips_machine
);
7860 qemu_register_machine(&mips_malta_machine
);
7861 qemu_register_machine(&mips_pica61_machine
);
7862 qemu_register_machine(&mips_mipssim_machine
);
7863 #elif defined(TARGET_SPARC)
7864 #ifdef TARGET_SPARC64
7865 qemu_register_machine(&sun4u_machine
);
7867 qemu_register_machine(&ss5_machine
);
7868 qemu_register_machine(&ss10_machine
);
7869 qemu_register_machine(&ss600mp_machine
);
7870 qemu_register_machine(&ss20_machine
);
7872 #elif defined(TARGET_ARM)
7873 qemu_register_machine(&integratorcp_machine
);
7874 qemu_register_machine(&versatilepb_machine
);
7875 qemu_register_machine(&versatileab_machine
);
7876 qemu_register_machine(&realview_machine
);
7877 qemu_register_machine(&akitapda_machine
);
7878 qemu_register_machine(&spitzpda_machine
);
7879 qemu_register_machine(&borzoipda_machine
);
7880 qemu_register_machine(&terrierpda_machine
);
7881 qemu_register_machine(&palmte_machine
);
7882 qemu_register_machine(&lm3s811evb_machine
);
7883 qemu_register_machine(&lm3s6965evb_machine
);
7884 qemu_register_machine(&connex_machine
);
7885 qemu_register_machine(&verdex_machine
);
7886 qemu_register_machine(&mainstone2_machine
);
7887 #elif defined(TARGET_SH4)
7888 qemu_register_machine(&shix_machine
);
7889 qemu_register_machine(&r2d_machine
);
7890 #elif defined(TARGET_ALPHA)
7892 #elif defined(TARGET_M68K)
7893 qemu_register_machine(&mcf5208evb_machine
);
7894 qemu_register_machine(&an5206_machine
);
7895 qemu_register_machine(&dummy_m68k_machine
);
7896 #elif defined(TARGET_CRIS)
7897 qemu_register_machine(&bareetraxfs_machine
);
7899 #error unsupported CPU
7904 struct soundhw soundhw
[] = {
7905 #ifdef HAS_AUDIO_CHOICE
7912 { .init_isa
= pcspk_audio_init
}
7917 "Creative Sound Blaster 16",
7920 { .init_isa
= SB16_init
}
7927 "Yamaha YMF262 (OPL3)",
7929 "Yamaha YM3812 (OPL2)",
7933 { .init_isa
= Adlib_init
}
7940 "Gravis Ultrasound GF1",
7943 { .init_isa
= GUS_init
}
7949 "ENSONIQ AudioPCI ES1370",
7952 { .init_pci
= es1370_init
}
7956 { NULL
, NULL
, 0, 0, { NULL
} }
7959 static void select_soundhw (const char *optarg
)
7963 if (*optarg
== '?') {
7966 printf ("Valid sound card names (comma separated):\n");
7967 for (c
= soundhw
; c
->name
; ++c
) {
7968 printf ("%-11s %s\n", c
->name
, c
->descr
);
7970 printf ("\n-soundhw all will enable all of the above\n");
7971 exit (*optarg
!= '?');
7979 if (!strcmp (optarg
, "all")) {
7980 for (c
= soundhw
; c
->name
; ++c
) {
7988 e
= strchr (p
, ',');
7989 l
= !e
? strlen (p
) : (size_t) (e
- p
);
7991 for (c
= soundhw
; c
->name
; ++c
) {
7992 if (!strncmp (c
->name
, p
, l
)) {
8001 "Unknown sound card name (too big to show)\n");
8004 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
8009 p
+= l
+ (e
!= NULL
);
8013 goto show_valid_cards
;
8019 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
8021 exit(STATUS_CONTROL_C_EXIT
);
8026 #define MAX_NET_CLIENTS 32
8028 int main(int argc
, char **argv
)
8030 #ifdef CONFIG_GDBSTUB
8032 const char *gdbstub_port
;
8034 uint32_t boot_devices_bitmap
= 0;
8036 int snapshot
, linux_boot
, net_boot
;
8037 const char *initrd_filename
;
8038 const char *kernel_filename
, *kernel_cmdline
;
8039 const char *boot_devices
= "";
8040 DisplayState
*ds
= &display_state
;
8041 int cyls
, heads
, secs
, translation
;
8042 char net_clients
[MAX_NET_CLIENTS
][256];
8046 const char *r
, *optarg
;
8047 CharDriverState
*monitor_hd
;
8048 char monitor_device
[128];
8049 char serial_devices
[MAX_SERIAL_PORTS
][128];
8050 int serial_device_index
;
8051 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
8052 int parallel_device_index
;
8053 const char *loadvm
= NULL
;
8054 QEMUMachine
*machine
;
8055 const char *cpu_model
;
8056 char usb_devices
[MAX_USB_CMDLINE
][128];
8057 int usb_devices_index
;
8059 const char *pid_file
= NULL
;
8062 LIST_INIT (&vm_change_state_head
);
8065 struct sigaction act
;
8066 sigfillset(&act
.sa_mask
);
8068 act
.sa_handler
= SIG_IGN
;
8069 sigaction(SIGPIPE
, &act
, NULL
);
8072 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
8073 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8074 QEMU to run on a single CPU */
8079 h
= GetCurrentProcess();
8080 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
8081 for(i
= 0; i
< 32; i
++) {
8082 if (mask
& (1 << i
))
8087 SetProcessAffinityMask(h
, mask
);
8093 register_machines();
8094 machine
= first_machine
;
8096 initrd_filename
= NULL
;
8097 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
8098 vga_ram_size
= VGA_RAM_SIZE
;
8099 #ifdef CONFIG_GDBSTUB
8101 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
8105 kernel_filename
= NULL
;
8106 kernel_cmdline
= "";
8107 cyls
= heads
= secs
= 0;
8108 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8109 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
8111 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
8112 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
8113 serial_devices
[i
][0] = '\0';
8114 serial_device_index
= 0;
8116 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
8117 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
8118 parallel_devices
[i
][0] = '\0';
8119 parallel_device_index
= 0;
8121 usb_devices_index
= 0;
8129 /* default mac address of the first network interface */
8137 hda_index
= drive_add(HD_ALIAS
, argv
[optind
++], 0);
8139 const QEMUOption
*popt
;
8142 /* Treat --foo the same as -foo. */
8145 popt
= qemu_options
;
8148 fprintf(stderr
, "%s: invalid option -- '%s'\n",
8152 if (!strcmp(popt
->name
, r
+ 1))
8156 if (popt
->flags
& HAS_ARG
) {
8157 if (optind
>= argc
) {
8158 fprintf(stderr
, "%s: option '%s' requires an argument\n",
8162 optarg
= argv
[optind
++];
8167 switch(popt
->index
) {
8169 machine
= find_machine(optarg
);
8172 printf("Supported machines are:\n");
8173 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
8174 printf("%-10s %s%s\n",
8176 m
== first_machine
? " (default)" : "");
8178 exit(*optarg
!= '?');
8181 case QEMU_OPTION_cpu
:
8182 /* hw initialization will check this */
8183 if (*optarg
== '?') {
8184 /* XXX: implement xxx_cpu_list for targets that still miss it */
8185 #if defined(cpu_list)
8186 cpu_list(stdout
, &fprintf
);
8193 case QEMU_OPTION_initrd
:
8194 initrd_filename
= optarg
;
8196 case QEMU_OPTION_hda
:
8198 hda_index
= drive_add(HD_ALIAS
, optarg
, 0);
8200 hda_index
= drive_add(HD_ALIAS
8201 ",cyls=%d,heads=%d,secs=%d%s",
8202 optarg
, 0, cyls
, heads
, secs
,
8203 translation
== BIOS_ATA_TRANSLATION_LBA
?
8205 translation
== BIOS_ATA_TRANSLATION_NONE
?
8206 ",trans=none" : "");
8208 case QEMU_OPTION_hdb
:
8209 case QEMU_OPTION_hdc
:
8210 case QEMU_OPTION_hdd
:
8211 drive_add(HD_ALIAS
, optarg
, popt
->index
- QEMU_OPTION_hda
);
8213 case QEMU_OPTION_drive
:
8214 drive_add("%s", optarg
);
8216 case QEMU_OPTION_mtdblock
:
8217 drive_add(MTD_ALIAS
, optarg
);
8219 case QEMU_OPTION_sd
:
8220 drive_add("file=\"%s\"," SD_ALIAS
, optarg
);
8222 case QEMU_OPTION_pflash
:
8223 drive_add(PFLASH_ALIAS
, optarg
);
8225 case QEMU_OPTION_snapshot
:
8228 case QEMU_OPTION_hdachs
:
8232 cyls
= strtol(p
, (char **)&p
, 0);
8233 if (cyls
< 1 || cyls
> 16383)
8238 heads
= strtol(p
, (char **)&p
, 0);
8239 if (heads
< 1 || heads
> 16)
8244 secs
= strtol(p
, (char **)&p
, 0);
8245 if (secs
< 1 || secs
> 63)
8249 if (!strcmp(p
, "none"))
8250 translation
= BIOS_ATA_TRANSLATION_NONE
;
8251 else if (!strcmp(p
, "lba"))
8252 translation
= BIOS_ATA_TRANSLATION_LBA
;
8253 else if (!strcmp(p
, "auto"))
8254 translation
= BIOS_ATA_TRANSLATION_AUTO
;
8257 } else if (*p
!= '\0') {
8259 fprintf(stderr
, "qemu: invalid physical CHS format\n");
8262 if (hda_index
!= -1)
8263 snprintf(drives_opt
[hda_index
] +
8264 strlen(drives_opt
[hda_index
]),
8265 sizeof(drives_opt
[0]) -
8266 strlen(drives_opt
[hda_index
]),
8267 ",cyls=%d,heads=%d,secs=%d%s",
8269 translation
== BIOS_ATA_TRANSLATION_LBA
?
8271 translation
== BIOS_ATA_TRANSLATION_NONE
?
8272 ",trans=none" : "");
8275 case QEMU_OPTION_nographic
:
8276 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
8277 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "null");
8278 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
8281 case QEMU_OPTION_portrait
:
8284 case QEMU_OPTION_kernel
:
8285 kernel_filename
= optarg
;
8287 case QEMU_OPTION_append
:
8288 kernel_cmdline
= optarg
;
8290 case QEMU_OPTION_cdrom
:
8291 drive_add("file=\"%s\"," CDROM_ALIAS
, optarg
);
8293 case QEMU_OPTION_boot
:
8294 boot_devices
= optarg
;
8295 /* We just do some generic consistency checks */
8297 /* Could easily be extended to 64 devices if needed */
8300 boot_devices_bitmap
= 0;
8301 for (p
= boot_devices
; *p
!= '\0'; p
++) {
8302 /* Allowed boot devices are:
8303 * a b : floppy disk drives
8304 * c ... f : IDE disk drives
8305 * g ... m : machine implementation dependant drives
8306 * n ... p : network devices
8307 * It's up to each machine implementation to check
8308 * if the given boot devices match the actual hardware
8309 * implementation and firmware features.
8311 if (*p
< 'a' || *p
> 'q') {
8312 fprintf(stderr
, "Invalid boot device '%c'\n", *p
);
8315 if (boot_devices_bitmap
& (1 << (*p
- 'a'))) {
8317 "Boot device '%c' was given twice\n",*p
);
8320 boot_devices_bitmap
|= 1 << (*p
- 'a');
8324 case QEMU_OPTION_fda
:
8325 case QEMU_OPTION_fdb
:
8326 drive_add("file=\"%s\"," FD_ALIAS
, optarg
,
8327 popt
->index
- QEMU_OPTION_fda
);
8330 case QEMU_OPTION_no_fd_bootchk
:
8334 case QEMU_OPTION_no_code_copy
:
8335 code_copy_enabled
= 0;
8337 case QEMU_OPTION_net
:
8338 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
8339 fprintf(stderr
, "qemu: too many network clients\n");
8342 pstrcpy(net_clients
[nb_net_clients
],
8343 sizeof(net_clients
[0]),
8348 case QEMU_OPTION_tftp
:
8349 tftp_prefix
= optarg
;
8351 case QEMU_OPTION_bootp
:
8352 bootp_filename
= optarg
;
8355 case QEMU_OPTION_smb
:
8356 net_slirp_smb(optarg
);
8359 case QEMU_OPTION_redir
:
8360 net_slirp_redir(optarg
);
8364 case QEMU_OPTION_audio_help
:
8368 case QEMU_OPTION_soundhw
:
8369 select_soundhw (optarg
);
8376 ram_size
= atoi(optarg
) * 1024 * 1024;
8379 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
8380 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
8381 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
8390 mask
= cpu_str_to_log_mask(optarg
);
8392 printf("Log items (comma separated):\n");
8393 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
8394 printf("%-10s %s\n", item
->name
, item
->help
);
8401 #ifdef CONFIG_GDBSTUB
8406 gdbstub_port
= optarg
;
8412 case QEMU_OPTION_bios
:
8419 keyboard_layout
= optarg
;
8421 case QEMU_OPTION_localtime
:
8424 case QEMU_OPTION_cirrusvga
:
8425 cirrus_vga_enabled
= 1;
8428 case QEMU_OPTION_vmsvga
:
8429 cirrus_vga_enabled
= 0;
8432 case QEMU_OPTION_std_vga
:
8433 cirrus_vga_enabled
= 0;
8441 w
= strtol(p
, (char **)&p
, 10);
8444 fprintf(stderr
, "qemu: invalid resolution or depth\n");
8450 h
= strtol(p
, (char **)&p
, 10);
8455 depth
= strtol(p
, (char **)&p
, 10);
8456 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
8457 depth
!= 24 && depth
!= 32)
8459 } else if (*p
== '\0') {
8460 depth
= graphic_depth
;
8467 graphic_depth
= depth
;
8470 case QEMU_OPTION_echr
:
8473 term_escape_char
= strtol(optarg
, &r
, 0);
8475 printf("Bad argument to echr\n");
8478 case QEMU_OPTION_monitor
:
8479 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
8481 case QEMU_OPTION_serial
:
8482 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
8483 fprintf(stderr
, "qemu: too many serial ports\n");
8486 pstrcpy(serial_devices
[serial_device_index
],
8487 sizeof(serial_devices
[0]), optarg
);
8488 serial_device_index
++;
8490 case QEMU_OPTION_parallel
:
8491 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
8492 fprintf(stderr
, "qemu: too many parallel ports\n");
8495 pstrcpy(parallel_devices
[parallel_device_index
],
8496 sizeof(parallel_devices
[0]), optarg
);
8497 parallel_device_index
++;
8499 case QEMU_OPTION_loadvm
:
8502 case QEMU_OPTION_full_screen
:
8506 case QEMU_OPTION_no_frame
:
8509 case QEMU_OPTION_alt_grab
:
8512 case QEMU_OPTION_no_quit
:
8516 case QEMU_OPTION_pidfile
:
8520 case QEMU_OPTION_win2k_hack
:
8521 win2k_install_hack
= 1;
8525 case QEMU_OPTION_no_kqemu
:
8528 case QEMU_OPTION_kernel_kqemu
:
8532 case QEMU_OPTION_usb
:
8535 case QEMU_OPTION_usbdevice
:
8537 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
8538 fprintf(stderr
, "Too many USB devices\n");
8541 pstrcpy(usb_devices
[usb_devices_index
],
8542 sizeof(usb_devices
[usb_devices_index
]),
8544 usb_devices_index
++;
8546 case QEMU_OPTION_smp
:
8547 smp_cpus
= atoi(optarg
);
8548 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
8549 fprintf(stderr
, "Invalid number of CPUs\n");
8553 case QEMU_OPTION_vnc
:
8554 vnc_display
= optarg
;
8556 case QEMU_OPTION_no_acpi
:
8559 case QEMU_OPTION_no_reboot
:
8562 case QEMU_OPTION_show_cursor
:
8565 case QEMU_OPTION_daemonize
:
8568 case QEMU_OPTION_option_rom
:
8569 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8570 fprintf(stderr
, "Too many option ROMs\n");
8573 option_rom
[nb_option_roms
] = optarg
;
8576 case QEMU_OPTION_semihosting
:
8577 semihosting_enabled
= 1;
8579 case QEMU_OPTION_name
:
8583 case QEMU_OPTION_prom_env
:
8584 if (nb_prom_envs
>= MAX_PROM_ENVS
) {
8585 fprintf(stderr
, "Too many prom variables\n");
8588 prom_envs
[nb_prom_envs
] = optarg
;
8593 case QEMU_OPTION_old_param
:
8596 case QEMU_OPTION_clock
:
8597 configure_alarms(optarg
);
8599 case QEMU_OPTION_startdate
:
8602 if (!strcmp(optarg
, "now")) {
8603 rtc_start_date
= -1;
8605 if (sscanf(optarg
, "%d-%d-%dT%d:%d:%d",
8613 } else if (sscanf(optarg
, "%d-%d-%d",
8616 &tm
.tm_mday
) == 3) {
8625 rtc_start_date
= mktimegm(&tm
);
8626 if (rtc_start_date
== -1) {
8628 fprintf(stderr
, "Invalid date format. Valid format are:\n"
8629 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8640 if (daemonize
&& !nographic
&& vnc_display
== NULL
) {
8641 fprintf(stderr
, "Can only daemonize if using -nographic or -vnc\n");
8648 if (pipe(fds
) == -1)
8659 len
= read(fds
[0], &status
, 1);
8660 if (len
== -1 && (errno
== EINTR
))
8665 else if (status
== 1) {
8666 fprintf(stderr
, "Could not acquire pidfile\n");
8684 signal(SIGTSTP
, SIG_IGN
);
8685 signal(SIGTTOU
, SIG_IGN
);
8686 signal(SIGTTIN
, SIG_IGN
);
8690 if (pid_file
&& qemu_create_pidfile(pid_file
) != 0) {
8693 write(fds
[1], &status
, 1);
8695 fprintf(stderr
, "Could not acquire pid file\n");
8703 linux_boot
= (kernel_filename
!= NULL
);
8704 net_boot
= (boot_devices_bitmap
>> ('n' - 'a')) & 0xF;
8706 /* XXX: this should not be: some embedded targets just have flash */
8707 if (!linux_boot
&& net_boot
== 0 &&
8711 /* boot to floppy or the default cd if no hard disk defined yet */
8712 if (!boot_devices
[0]) {
8713 boot_devices
= "cad";
8715 setvbuf(stdout
, NULL
, _IOLBF
, 0);
8725 /* init network clients */
8726 if (nb_net_clients
== 0) {
8727 /* if no clients, we use a default config */
8728 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
8730 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
8735 for(i
= 0;i
< nb_net_clients
; i
++) {
8736 if (net_client_init(net_clients
[i
]) < 0)
8739 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8740 if (vlan
->nb_guest_devs
== 0 && vlan
->nb_host_devs
== 0)
8742 if (vlan
->nb_guest_devs
== 0) {
8743 fprintf(stderr
, "Invalid vlan (%d) with no nics\n", vlan
->id
);
8746 if (vlan
->nb_host_devs
== 0)
8748 "Warning: vlan %d is not connected to host network\n",
8753 /* XXX: this should be moved in the PC machine instantiation code */
8754 if (net_boot
!= 0) {
8756 for (i
= 0; i
< nb_nics
&& i
< 4; i
++) {
8757 const char *model
= nd_table
[i
].model
;
8759 if (net_boot
& (1 << i
)) {
8762 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
8763 if (get_image_size(buf
) > 0) {
8764 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
8765 fprintf(stderr
, "Too many option ROMs\n");
8768 option_rom
[nb_option_roms
] = strdup(buf
);
8775 fprintf(stderr
, "No valid PXE rom found for network device\n");
8781 /* init the memory */
8782 phys_ram_size
= ram_size
+ vga_ram_size
+ MAX_BIOS_SIZE
;
8784 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
8785 if (!phys_ram_base
) {
8786 fprintf(stderr
, "Could not allocate physical memory\n");
8792 /* we always create the cdrom drive, even if no disk is there */
8794 if (nb_drives_opt
< MAX_DRIVES
)
8795 drive_add(CDROM_ALIAS
);
8797 /* we always create at least one floppy */
8799 if (nb_drives_opt
< MAX_DRIVES
)
8800 drive_add(FD_ALIAS
, 0);
8802 /* we always create one sd slot, even if no card is in it */
8804 if (nb_drives_opt
< MAX_DRIVES
)
8805 drive_add(SD_ALIAS
);
8807 /* open the virtual block devices */
8809 for(i
= 0; i
< nb_drives_opt
; i
++)
8810 if (drive_init(drives_opt
[i
], snapshot
, machine
) == -1)
8813 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
8814 register_savevm("ram", 0, 2, ram_save
, ram_load
, NULL
);
8819 memset(&display_state
, 0, sizeof(display_state
));
8821 /* nearly nothing to do */
8822 dumb_display_init(ds
);
8823 } else if (vnc_display
!= NULL
) {
8824 vnc_display_init(ds
);
8825 if (vnc_display_open(ds
, vnc_display
) < 0)
8828 #if defined(CONFIG_SDL)
8829 sdl_display_init(ds
, full_screen
, no_frame
);
8830 #elif defined(CONFIG_COCOA)
8831 cocoa_display_init(ds
, full_screen
);
8833 dumb_display_init(ds
);
8837 /* Maintain compatibility with multiple stdio monitors */
8838 if (!strcmp(monitor_device
,"stdio")) {
8839 for (i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
8840 if (!strcmp(serial_devices
[i
],"mon:stdio")) {
8841 monitor_device
[0] = '\0';
8843 } else if (!strcmp(serial_devices
[i
],"stdio")) {
8844 monitor_device
[0] = '\0';
8845 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "mon:stdio");
8850 if (monitor_device
[0] != '\0') {
8851 monitor_hd
= qemu_chr_open(monitor_device
);
8853 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
8856 monitor_init(monitor_hd
, !nographic
);
8859 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
8860 const char *devname
= serial_devices
[i
];
8861 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
8862 serial_hds
[i
] = qemu_chr_open(devname
);
8863 if (!serial_hds
[i
]) {
8864 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
8868 if (strstart(devname
, "vc", 0))
8869 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
8873 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
8874 const char *devname
= parallel_devices
[i
];
8875 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
8876 parallel_hds
[i
] = qemu_chr_open(devname
);
8877 if (!parallel_hds
[i
]) {
8878 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
8882 if (strstart(devname
, "vc", 0))
8883 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
8887 machine
->init(ram_size
, vga_ram_size
, boot_devices
, ds
,
8888 kernel_filename
, kernel_cmdline
, initrd_filename
, cpu_model
);
8890 /* init USB devices */
8892 for(i
= 0; i
< usb_devices_index
; i
++) {
8893 if (usb_device_add(usb_devices
[i
]) < 0) {
8894 fprintf(stderr
, "Warning: could not add USB device %s\n",
8900 if (display_state
.dpy_refresh
) {
8901 display_state
.gui_timer
= qemu_new_timer(rt_clock
, gui_update
, &display_state
);
8902 qemu_mod_timer(display_state
.gui_timer
, qemu_get_clock(rt_clock
));
8905 #ifdef CONFIG_GDBSTUB
8907 /* XXX: use standard host:port notation and modify options
8909 if (gdbserver_start(gdbstub_port
) < 0) {
8910 fprintf(stderr
, "qemu: could not open gdbstub device on port '%s'\n",
8921 /* XXX: simplify init */
8934 len
= write(fds
[1], &status
, 1);
8935 if (len
== -1 && (errno
== EINTR
))
8941 TFR(fd
= open("/dev/null", O_RDWR
));
8955 #if !defined(_WIN32)
8956 /* close network clients */
8957 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
8958 VLANClientState
*vc
;
8960 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
8961 if (vc
->fd_read
== tap_receive
) {
8963 TAPState
*s
= vc
->opaque
;
8965 if (sscanf(vc
->info_str
, "tap: ifname=%63s ", ifname
) == 1 &&
8967 launch_script(s
->down_script
, ifname
, s
->fd
);