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
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
62 #if defined(CONFIG_SLIRP)
68 #include <sys/timeb.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
74 #include "qemu_socket.h"
80 #endif /* CONFIG_SDL */
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
95 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
97 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
99 #define SMBD_COMMAND "/usr/sbin/smbd"
102 //#define DEBUG_UNUSED_IOPORT
103 //#define DEBUG_IOPORT
105 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
108 #define DEFAULT_RAM_SIZE 144
110 #define DEFAULT_RAM_SIZE 128
113 #define GUI_REFRESH_INTERVAL 30
115 /* Max number of USB devices that can be specified on the commandline. */
116 #define MAX_USB_CMDLINE 8
118 /* XXX: use a two level table to limit memory usage */
119 #define MAX_IOPORTS 65536
121 const char *bios_dir
= CONFIG_QEMU_SHAREDIR
;
122 char phys_ram_file
[1024];
123 void *ioport_opaque
[MAX_IOPORTS
];
124 IOPortReadFunc
*ioport_read_table
[3][MAX_IOPORTS
];
125 IOPortWriteFunc
*ioport_write_table
[3][MAX_IOPORTS
];
126 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
127 to store the VM snapshots */
128 BlockDriverState
*bs_table
[MAX_DISKS
+ 1], *fd_table
[MAX_FD
];
129 /* point to the block driver where the snapshots are managed */
130 BlockDriverState
*bs_snapshots
;
133 static DisplayState display_state
;
135 const char* keyboard_layout
= NULL
;
136 int64_t ticks_per_sec
;
137 int boot_device
= 'c';
139 int pit_min_timer_count
= 0;
141 NICInfo nd_table
[MAX_NICS
];
142 QEMUTimer
*gui_timer
;
145 int cirrus_vga_enabled
= 1;
147 int graphic_width
= 1024;
148 int graphic_height
= 768;
150 int graphic_width
= 800;
151 int graphic_height
= 600;
153 int graphic_depth
= 15;
156 CharDriverState
*vmchannel_hds
[MAX_VMCHANNEL_DEVICES
];
157 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
158 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
160 int win2k_install_hack
= 0;
163 static VLANState
*first_vlan
;
165 const char *vnc_display
;
166 #if defined(TARGET_SPARC)
168 #elif defined(TARGET_I386)
173 int acpi_enabled
= 1;
177 const char *incoming
;
178 const char *option_rom
[MAX_OPTION_ROMS
];
180 int semihosting_enabled
= 0;
183 /***********************************************************/
184 /* x86 ISA bus support */
186 target_phys_addr_t isa_mem_base
= 0;
189 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr
, "inb: port=0x%04x\n", address
);
197 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
199 #ifdef DEBUG_UNUSED_IOPORT
200 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
204 /* default is to make two byte accesses */
205 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
208 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
209 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
210 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
214 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
216 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
217 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
218 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
221 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr
, "inl: port=0x%04x\n", address
);
229 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
231 #ifdef DEBUG_UNUSED_IOPORT
232 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
236 void init_ioports(void)
240 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
241 ioport_read_table
[0][i
] = default_ioport_readb
;
242 ioport_write_table
[0][i
] = default_ioport_writeb
;
243 ioport_read_table
[1][i
] = default_ioport_readw
;
244 ioport_write_table
[1][i
] = default_ioport_writew
;
245 ioport_read_table
[2][i
] = default_ioport_readl
;
246 ioport_write_table
[2][i
] = default_ioport_writel
;
250 /* size is the word size in byte */
251 int register_ioport_read(int start
, int length
, int size
,
252 IOPortReadFunc
*func
, void *opaque
)
258 } else if (size
== 2) {
260 } else if (size
== 4) {
263 hw_error("register_ioport_read: invalid size");
266 for(i
= start
; i
< start
+ length
; i
+= size
) {
267 ioport_read_table
[bsize
][i
] = func
;
268 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
269 hw_error("register_ioport_read: invalid opaque");
270 ioport_opaque
[i
] = opaque
;
275 /* size is the word size in byte */
276 int register_ioport_write(int start
, int length
, int size
,
277 IOPortWriteFunc
*func
, void *opaque
)
283 } else if (size
== 2) {
285 } else if (size
== 4) {
288 hw_error("register_ioport_write: invalid size");
291 for(i
= start
; i
< start
+ length
; i
+= size
) {
292 ioport_write_table
[bsize
][i
] = func
;
293 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
294 hw_error("register_ioport_write: invalid opaque");
295 ioport_opaque
[i
] = opaque
;
300 void isa_unassign_ioport(int start
, int length
)
304 for(i
= start
; i
< start
+ length
; i
++) {
305 ioport_read_table
[0][i
] = default_ioport_readb
;
306 ioport_read_table
[1][i
] = default_ioport_readw
;
307 ioport_read_table
[2][i
] = default_ioport_readl
;
309 ioport_write_table
[0][i
] = default_ioport_writeb
;
310 ioport_write_table
[1][i
] = default_ioport_writew
;
311 ioport_write_table
[2][i
] = default_ioport_writel
;
315 /***********************************************************/
317 void cpu_outb(CPUState
*env
, int addr
, int val
)
320 if (loglevel
& CPU_LOG_IOPORT
)
321 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
323 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
326 env
->last_io_time
= cpu_get_time_fast();
330 void cpu_outw(CPUState
*env
, int addr
, int val
)
333 if (loglevel
& CPU_LOG_IOPORT
)
334 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
336 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
339 env
->last_io_time
= cpu_get_time_fast();
343 void cpu_outl(CPUState
*env
, int addr
, int val
)
346 if (loglevel
& CPU_LOG_IOPORT
)
347 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
349 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
352 env
->last_io_time
= cpu_get_time_fast();
356 int cpu_inb(CPUState
*env
, int addr
)
359 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
361 if (loglevel
& CPU_LOG_IOPORT
)
362 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
366 env
->last_io_time
= cpu_get_time_fast();
371 int cpu_inw(CPUState
*env
, int addr
)
374 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
376 if (loglevel
& CPU_LOG_IOPORT
)
377 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
381 env
->last_io_time
= cpu_get_time_fast();
386 int cpu_inl(CPUState
*env
, int addr
)
389 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
391 if (loglevel
& CPU_LOG_IOPORT
)
392 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
396 env
->last_io_time
= cpu_get_time_fast();
401 /***********************************************************/
402 void hw_error(const char *fmt
, ...)
408 fprintf(stderr
, "qemu: hardware error: ");
409 vfprintf(stderr
, fmt
, ap
);
410 fprintf(stderr
, "\n");
411 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
412 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
414 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
416 cpu_dump_state(env
, stderr
, fprintf
, 0);
423 /***********************************************************/
426 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
427 static void *qemu_put_kbd_event_opaque
;
428 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
429 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
431 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
433 qemu_put_kbd_event_opaque
= opaque
;
434 qemu_put_kbd_event
= func
;
437 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
438 void *opaque
, int absolute
,
441 QEMUPutMouseEntry
*s
, *cursor
;
443 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
447 s
->qemu_put_mouse_event
= func
;
448 s
->qemu_put_mouse_event_opaque
= opaque
;
449 s
->qemu_put_mouse_event_absolute
= absolute
;
450 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
453 if (!qemu_put_mouse_event_head
) {
454 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
458 cursor
= qemu_put_mouse_event_head
;
459 while (cursor
->next
!= NULL
)
460 cursor
= cursor
->next
;
463 qemu_put_mouse_event_current
= s
;
468 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
470 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
472 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
475 cursor
= qemu_put_mouse_event_head
;
476 while (cursor
!= NULL
&& cursor
!= entry
) {
478 cursor
= cursor
->next
;
481 if (cursor
== NULL
) // does not exist or list empty
483 else if (prev
== NULL
) { // entry is head
484 qemu_put_mouse_event_head
= cursor
->next
;
485 if (qemu_put_mouse_event_current
== entry
)
486 qemu_put_mouse_event_current
= cursor
->next
;
487 qemu_free(entry
->qemu_put_mouse_event_name
);
492 prev
->next
= entry
->next
;
494 if (qemu_put_mouse_event_current
== entry
)
495 qemu_put_mouse_event_current
= prev
;
497 qemu_free(entry
->qemu_put_mouse_event_name
);
501 void kbd_put_keycode(int keycode
)
503 if (qemu_put_kbd_event
) {
504 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
508 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
510 QEMUPutMouseEvent
*mouse_event
;
511 void *mouse_event_opaque
;
513 if (!qemu_put_mouse_event_current
) {
518 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
520 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
523 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
527 int kbd_mouse_is_absolute(void)
529 if (!qemu_put_mouse_event_current
)
532 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
535 void do_info_mice(void)
537 QEMUPutMouseEntry
*cursor
;
540 if (!qemu_put_mouse_event_head
) {
541 term_printf("No mouse devices connected\n");
545 term_printf("Mouse devices available:\n");
546 cursor
= qemu_put_mouse_event_head
;
547 while (cursor
!= NULL
) {
548 term_printf("%c Mouse #%d: %s\n",
549 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
550 index
, cursor
->qemu_put_mouse_event_name
);
552 cursor
= cursor
->next
;
556 void do_mouse_set(int index
)
558 QEMUPutMouseEntry
*cursor
;
561 if (!qemu_put_mouse_event_head
) {
562 term_printf("No mouse devices connected\n");
566 cursor
= qemu_put_mouse_event_head
;
567 while (cursor
!= NULL
&& index
!= i
) {
569 cursor
= cursor
->next
;
573 qemu_put_mouse_event_current
= cursor
;
575 term_printf("Mouse at given index not found\n");
578 /* compute with 96 bit intermediate result: (a*b)/c */
579 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
584 #ifdef WORDS_BIGENDIAN
594 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
595 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
598 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
602 /***********************************************************/
603 /* real time host monotonic timer */
605 #define QEMU_TIMER_BASE 1000000000LL
609 static int64_t clock_freq
;
611 static void init_get_clock(void)
615 ret
= QueryPerformanceFrequency(&freq
);
617 fprintf(stderr
, "Could not calibrate ticks\n");
620 clock_freq
= freq
.QuadPart
;
623 static int64_t get_clock(void)
626 QueryPerformanceCounter(&ti
);
627 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
632 static int use_rt_clock
;
634 static void init_get_clock(void)
637 #if defined(__linux__)
640 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
647 static int64_t get_clock(void)
649 #if defined(__linux__)
652 clock_gettime(CLOCK_MONOTONIC
, &ts
);
653 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
657 /* XXX: using gettimeofday leads to problems if the date
658 changes, so it should be avoided. */
660 gettimeofday(&tv
, NULL
);
661 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
667 /***********************************************************/
668 /* guest cycle counter */
670 static int64_t cpu_ticks_prev
;
671 static int64_t cpu_ticks_offset
;
672 static int64_t cpu_clock_offset
;
673 static int cpu_ticks_enabled
;
675 /* return the host CPU cycle counter and handle stop/restart */
676 int64_t cpu_get_ticks(void)
678 if (!cpu_ticks_enabled
) {
679 return cpu_ticks_offset
;
682 ticks
= cpu_get_real_ticks();
683 if (cpu_ticks_prev
> ticks
) {
684 /* Note: non increasing ticks may happen if the host uses
686 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
688 cpu_ticks_prev
= ticks
;
689 return ticks
+ cpu_ticks_offset
;
693 /* return the host CPU monotonic timer and handle stop/restart */
694 static int64_t cpu_get_clock(void)
697 if (!cpu_ticks_enabled
) {
698 return cpu_clock_offset
;
701 return ti
+ cpu_clock_offset
;
705 /* enable cpu_get_ticks() */
706 void cpu_enable_ticks(void)
708 if (!cpu_ticks_enabled
) {
709 cpu_ticks_offset
-= cpu_get_real_ticks();
710 cpu_clock_offset
-= get_clock();
711 cpu_ticks_enabled
= 1;
715 /* disable cpu_get_ticks() : the clock is stopped. You must not call
716 cpu_get_ticks() after that. */
717 void cpu_disable_ticks(void)
719 if (cpu_ticks_enabled
) {
720 cpu_ticks_offset
= cpu_get_ticks();
721 cpu_clock_offset
= cpu_get_clock();
722 cpu_ticks_enabled
= 0;
726 /***********************************************************/
729 #define QEMU_TIMER_REALTIME 0
730 #define QEMU_TIMER_VIRTUAL 1
734 /* XXX: add frequency */
742 struct QEMUTimer
*next
;
748 static QEMUTimer
*active_timers
[2];
750 static MMRESULT timerID
;
751 static HANDLE host_alarm
= NULL
;
752 static unsigned int period
= 1;
754 /* frequency of the times() clock tick */
755 static int timer_freq
;
758 QEMUClock
*qemu_new_clock(int type
)
761 clock
= qemu_mallocz(sizeof(QEMUClock
));
768 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
772 ts
= qemu_mallocz(sizeof(QEMUTimer
));
779 void qemu_free_timer(QEMUTimer
*ts
)
784 /* stop a timer, but do not dealloc it */
785 void qemu_del_timer(QEMUTimer
*ts
)
789 /* NOTE: this code must be signal safe because
790 qemu_timer_expired() can be called from a signal. */
791 pt
= &active_timers
[ts
->clock
->type
];
804 /* modify the current timer so that it will be fired when current_time
805 >= expire_time. The corresponding callback will be called. */
806 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
812 /* add the timer in the sorted list */
813 /* NOTE: this code must be signal safe because
814 qemu_timer_expired() can be called from a signal. */
815 pt
= &active_timers
[ts
->clock
->type
];
820 if (t
->expire_time
> expire_time
)
824 ts
->expire_time
= expire_time
;
829 int qemu_timer_pending(QEMUTimer
*ts
)
832 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
839 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
843 return (timer_head
->expire_time
<= current_time
);
846 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
852 if (!ts
|| ts
->expire_time
> current_time
)
854 /* remove timer from the list before calling the callback */
855 *ptimer_head
= ts
->next
;
858 /* run the callback (the timer list can be modified) */
863 int64_t qemu_get_clock(QEMUClock
*clock
)
865 switch(clock
->type
) {
866 case QEMU_TIMER_REALTIME
:
867 return get_clock() / 1000000;
869 case QEMU_TIMER_VIRTUAL
:
870 return cpu_get_clock();
874 static void init_timers(void)
877 ticks_per_sec
= QEMU_TIMER_BASE
;
878 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
879 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
883 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
885 uint64_t expire_time
;
887 if (qemu_timer_pending(ts
)) {
888 expire_time
= ts
->expire_time
;
892 qemu_put_be64(f
, expire_time
);
895 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
897 uint64_t expire_time
;
899 expire_time
= qemu_get_be64(f
);
900 if (expire_time
!= -1) {
901 qemu_mod_timer(ts
, expire_time
);
907 static void timer_save(QEMUFile
*f
, void *opaque
)
909 if (cpu_ticks_enabled
) {
910 hw_error("cannot save state if virtual timers are running");
912 qemu_put_be64s(f
, &cpu_ticks_offset
);
913 qemu_put_be64s(f
, &ticks_per_sec
);
914 qemu_put_be64s(f
, &cpu_clock_offset
);
917 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
919 if (version_id
!= 1 && version_id
!= 2)
921 if (cpu_ticks_enabled
) {
924 qemu_get_be64s(f
, &cpu_ticks_offset
);
925 qemu_get_be64s(f
, &ticks_per_sec
);
926 if (version_id
== 2) {
927 qemu_get_be64s(f
, &cpu_clock_offset
);
933 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
934 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
936 static void host_alarm_handler(int host_signum
)
940 #define DISP_FREQ 1000
942 static int64_t delta_min
= INT64_MAX
;
943 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
945 ti
= qemu_get_clock(vm_clock
);
946 if (last_clock
!= 0) {
947 delta
= ti
- last_clock
;
948 if (delta
< delta_min
)
950 if (delta
> delta_max
)
953 if (++count
== DISP_FREQ
) {
954 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
955 muldiv64(delta_min
, 1000000, ticks_per_sec
),
956 muldiv64(delta_max
, 1000000, ticks_per_sec
),
957 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
958 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
960 delta_min
= INT64_MAX
;
968 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
969 qemu_get_clock(vm_clock
)) ||
970 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
971 qemu_get_clock(rt_clock
))) {
973 SetEvent(host_alarm
);
975 CPUState
*env
= cpu_single_env
;
977 /* stop the currently executing cpu because a timer occured */
978 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
980 if (env
->kqemu_enabled
) {
981 kqemu_cpu_interrupt(env
);
990 #if defined(__linux__)
992 #define RTC_FREQ 1024
996 static int start_rtc_timer(void)
998 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1001 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1002 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1003 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1004 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1007 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1012 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1018 static int start_rtc_timer(void)
1023 #endif /* !defined(__linux__) */
1025 #endif /* !defined(_WIN32) */
1027 static void init_timer_alarm(void)
1034 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1035 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1036 if (period
< tc
.wPeriodMin
)
1037 period
= tc
.wPeriodMin
;
1038 timeBeginPeriod(period
);
1039 timerID
= timeSetEvent(1, // interval (ms)
1040 period
, // resolution
1041 host_alarm_handler
, // function
1042 (DWORD
)&count
, // user parameter
1043 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1045 perror("failed timer alarm");
1048 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1050 perror("failed CreateEvent");
1053 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1055 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1058 struct sigaction act
;
1059 struct itimerval itv
;
1061 /* get times() syscall frequency */
1062 timer_freq
= sysconf(_SC_CLK_TCK
);
1065 sigfillset(&act
.sa_mask
);
1067 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1068 act
.sa_flags
|= SA_ONSTACK
;
1070 act
.sa_handler
= host_alarm_handler
;
1071 sigaction(SIGALRM
, &act
, NULL
);
1073 itv
.it_interval
.tv_sec
= 0;
1074 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1075 itv
.it_value
.tv_sec
= 0;
1076 itv
.it_value
.tv_usec
= 10 * 1000;
1077 setitimer(ITIMER_REAL
, &itv
, NULL
);
1078 /* we probe the tick duration of the kernel to inform the user if
1079 the emulated kernel requested a too high timer frequency */
1080 getitimer(ITIMER_REAL
, &itv
);
1082 #if defined(__linux__)
1083 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1084 have timers with 1 ms resolution. The correct solution will
1085 be to use the POSIX real time timers available in recent
1087 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1088 /* try to use /dev/rtc to have a faster timer */
1089 if (start_rtc_timer() < 0)
1091 /* disable itimer */
1092 itv
.it_interval
.tv_sec
= 0;
1093 itv
.it_interval
.tv_usec
= 0;
1094 itv
.it_value
.tv_sec
= 0;
1095 itv
.it_value
.tv_usec
= 0;
1096 setitimer(ITIMER_REAL
, &itv
, NULL
);
1099 sigaction(SIGIO
, &act
, NULL
);
1100 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1101 fcntl(rtc_fd
, F_SETOWN
, getpid());
1103 #endif /* defined(__linux__) */
1106 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1107 PIT_FREQ
) / 1000000;
1113 void quit_timers(void)
1116 timeKillEvent(timerID
);
1117 timeEndPeriod(period
);
1119 CloseHandle(host_alarm
);
1125 /***********************************************************/
1126 /* character device */
1128 static void qemu_chr_event(CharDriverState
*s
, int event
)
1132 s
->chr_event(s
->handler_opaque
, event
);
1135 static void qemu_chr_reset_bh(void *opaque
)
1137 CharDriverState
*s
= opaque
;
1138 qemu_chr_event(s
, CHR_EVENT_RESET
);
1139 qemu_bh_delete(s
->bh
);
1143 void qemu_chr_reset(CharDriverState
*s
)
1145 if (s
->bh
== NULL
) {
1146 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1147 qemu_bh_schedule(s
->bh
);
1151 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1153 return s
->chr_write(s
, buf
, len
);
1156 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1160 return s
->chr_ioctl(s
, cmd
, arg
);
1163 int qemu_chr_can_read(CharDriverState
*s
)
1165 if (!s
->chr_can_read
)
1167 return s
->chr_can_read(s
->handler_opaque
);
1170 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1172 s
->chr_read(s
->handler_opaque
, buf
, len
);
1176 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1181 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1182 qemu_chr_write(s
, buf
, strlen(buf
));
1186 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1188 if (s
->chr_send_event
)
1189 s
->chr_send_event(s
, event
);
1192 void qemu_chr_add_handlers(CharDriverState
*s
,
1193 IOCanRWHandler
*fd_can_read
,
1194 IOReadHandler
*fd_read
,
1195 IOEventHandler
*fd_event
,
1198 s
->chr_can_read
= fd_can_read
;
1199 s
->chr_read
= fd_read
;
1200 s
->chr_event
= fd_event
;
1201 s
->handler_opaque
= opaque
;
1202 if (s
->chr_update_read_handler
)
1203 s
->chr_update_read_handler(s
);
1206 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1211 static CharDriverState
*qemu_chr_open_null(void)
1213 CharDriverState
*chr
;
1215 chr
= qemu_mallocz(sizeof(CharDriverState
));
1218 chr
->chr_write
= null_chr_write
;
1224 static void socket_cleanup(void)
1229 static int socket_init(void)
1234 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1236 err
= WSAGetLastError();
1237 fprintf(stderr
, "WSAStartup: %d\n", err
);
1240 atexit(socket_cleanup
);
1244 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1250 ret
= send(fd
, buf
, len
, 0);
1253 errno
= WSAGetLastError();
1254 if (errno
!= WSAEWOULDBLOCK
) {
1257 } else if (ret
== 0) {
1267 void socket_set_nonblock(int fd
)
1269 unsigned long opt
= 1;
1270 ioctlsocket(fd
, FIONBIO
, &opt
);
1275 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1281 ret
= write(fd
, buf
, len
);
1283 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1285 } else if (ret
== 0) {
1295 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1297 return unix_write(fd
, buf
, len1
);
1300 void socket_set_nonblock(int fd
)
1302 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1304 #endif /* !_WIN32 */
1313 #define STDIO_MAX_CLIENTS 2
1315 static int stdio_nb_clients
;
1316 static CharDriverState
*stdio_clients
[STDIO_MAX_CLIENTS
];
1318 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1320 FDCharDriver
*s
= chr
->opaque
;
1321 return unix_write(s
->fd_out
, buf
, len
);
1324 static int fd_chr_read_poll(void *opaque
)
1326 CharDriverState
*chr
= opaque
;
1327 FDCharDriver
*s
= chr
->opaque
;
1329 s
->max_size
= qemu_chr_can_read(chr
);
1333 static void fd_chr_read(void *opaque
)
1335 CharDriverState
*chr
= opaque
;
1336 FDCharDriver
*s
= chr
->opaque
;
1341 if (len
> s
->max_size
)
1345 size
= read(s
->fd_in
, buf
, len
);
1347 /* FD has been closed. Remove it from the active list. */
1348 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1352 qemu_chr_read(chr
, buf
, size
);
1356 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1358 FDCharDriver
*s
= chr
->opaque
;
1360 if (s
->fd_in
>= 0) {
1361 if (nographic
&& s
->fd_in
== 0) {
1363 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1364 fd_chr_read
, NULL
, chr
);
1369 /* open a character device to a unix fd */
1370 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1372 CharDriverState
*chr
;
1375 chr
= qemu_mallocz(sizeof(CharDriverState
));
1378 s
= qemu_mallocz(sizeof(FDCharDriver
));
1386 chr
->chr_write
= fd_chr_write
;
1387 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1389 qemu_chr_reset(chr
);
1394 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1398 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1401 return qemu_chr_open_fd(-1, fd_out
);
1404 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1407 char filename_in
[256], filename_out
[256];
1409 snprintf(filename_in
, 256, "%s.in", filename
);
1410 snprintf(filename_out
, 256, "%s.out", filename
);
1411 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1412 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1413 if (fd_in
< 0 || fd_out
< 0) {
1418 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1422 return qemu_chr_open_fd(fd_in
, fd_out
);
1426 /* for STDIO, we handle the case where several clients use it
1429 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1431 #define TERM_FIFO_MAX_SIZE 1
1433 static int term_got_escape
, client_index
;
1434 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1435 static int term_fifo_size
;
1436 static int term_timestamps
;
1437 static int64_t term_timestamps_start
;
1439 void term_print_help(void)
1442 "C-a h print this help\n"
1443 "C-a x exit emulator\n"
1444 "C-a s save disk data back to file (if -snapshot)\n"
1445 "C-a b send break (magic sysrq)\n"
1446 "C-a t toggle console timestamps\n"
1447 "C-a c switch between console and monitor\n"
1448 "C-a C-a send C-a\n"
1452 /* called when a char is received */
1453 static void stdio_received_byte(int ch
)
1455 if (term_got_escape
) {
1456 term_got_escape
= 0;
1467 for (i
= 0; i
< MAX_DISKS
; i
++) {
1469 bdrv_commit(bs_table
[i
]);
1474 if (client_index
< stdio_nb_clients
) {
1475 CharDriverState
*chr
;
1478 chr
= stdio_clients
[client_index
];
1480 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1485 if (client_index
>= stdio_nb_clients
)
1487 if (client_index
== 0) {
1488 /* send a new line in the monitor to get the prompt */
1494 term_timestamps
= !term_timestamps
;
1495 term_timestamps_start
= -1;
1500 } else if (ch
== TERM_ESCAPE
) {
1501 term_got_escape
= 1;
1504 if (client_index
< stdio_nb_clients
) {
1506 CharDriverState
*chr
;
1508 chr
= stdio_clients
[client_index
];
1509 if (qemu_chr_can_read(chr
) > 0) {
1511 qemu_chr_read(chr
, buf
, 1);
1512 } else if (term_fifo_size
== 0) {
1513 term_fifo
[term_fifo_size
++] = ch
;
1519 static int stdio_read_poll(void *opaque
)
1521 CharDriverState
*chr
;
1523 if (client_index
< stdio_nb_clients
) {
1524 chr
= stdio_clients
[client_index
];
1525 /* try to flush the queue if needed */
1526 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1527 qemu_chr_read(chr
, term_fifo
, 1);
1530 /* see if we can absorb more chars */
1531 if (term_fifo_size
== 0)
1540 static void stdio_read(void *opaque
)
1545 size
= read(0, buf
, 1);
1547 /* stdin has been closed. Remove it from the active list. */
1548 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1552 stdio_received_byte(buf
[0]);
1555 static int stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1557 FDCharDriver
*s
= chr
->opaque
;
1558 if (!term_timestamps
) {
1559 return unix_write(s
->fd_out
, buf
, len
);
1564 for(i
= 0; i
< len
; i
++) {
1565 unix_write(s
->fd_out
, buf
+ i
, 1);
1566 if (buf
[i
] == '\n') {
1571 if (term_timestamps_start
== -1)
1572 term_timestamps_start
= ti
;
1573 ti
-= term_timestamps_start
;
1574 secs
= ti
/ 1000000000;
1575 snprintf(buf1
, sizeof(buf1
),
1576 "[%02d:%02d:%02d.%03d] ",
1580 (int)((ti
/ 1000000) % 1000));
1581 unix_write(s
->fd_out
, buf1
, strlen(buf1
));
1588 /* init terminal so that we can grab keys */
1589 static struct termios oldtty
;
1590 static int old_fd0_flags
;
1592 static void term_exit(void)
1594 tcsetattr (0, TCSANOW
, &oldtty
);
1595 fcntl(0, F_SETFL
, old_fd0_flags
);
1598 static void term_init(void)
1602 tcgetattr (0, &tty
);
1604 old_fd0_flags
= fcntl(0, F_GETFL
);
1606 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1607 |INLCR
|IGNCR
|ICRNL
|IXON
);
1608 tty
.c_oflag
|= OPOST
;
1609 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1610 /* if graphical mode, we allow Ctrl-C handling */
1612 tty
.c_lflag
&= ~ISIG
;
1613 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1616 tty
.c_cc
[VTIME
] = 0;
1618 tcsetattr (0, TCSANOW
, &tty
);
1622 fcntl(0, F_SETFL
, O_NONBLOCK
);
1625 static CharDriverState
*qemu_chr_open_stdio(void)
1627 CharDriverState
*chr
;
1630 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1632 chr
= qemu_chr_open_fd(0, 1);
1633 chr
->chr_write
= stdio_write
;
1634 if (stdio_nb_clients
== 0)
1635 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, NULL
);
1636 client_index
= stdio_nb_clients
;
1638 if (stdio_nb_clients
!= 0)
1640 chr
= qemu_chr_open_fd(0, 1);
1642 stdio_clients
[stdio_nb_clients
++] = chr
;
1643 if (stdio_nb_clients
== 1) {
1644 /* set the terminal in raw mode */
1650 #if defined(__linux__)
1651 static CharDriverState
*qemu_chr_open_pty(void)
1654 char slave_name
[1024];
1655 int master_fd
, slave_fd
;
1657 /* Not satisfying */
1658 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1662 /* Disabling local echo and line-buffered output */
1663 tcgetattr (master_fd
, &tty
);
1664 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1666 tty
.c_cc
[VTIME
] = 0;
1667 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1669 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1670 return qemu_chr_open_fd(master_fd
, master_fd
);
1673 static void tty_serial_init(int fd
, int speed
,
1674 int parity
, int data_bits
, int stop_bits
)
1680 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1681 speed
, parity
, data_bits
, stop_bits
);
1683 tcgetattr (fd
, &tty
);
1725 cfsetispeed(&tty
, spd
);
1726 cfsetospeed(&tty
, spd
);
1728 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1729 |INLCR
|IGNCR
|ICRNL
|IXON
);
1730 tty
.c_oflag
|= OPOST
;
1731 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1732 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1753 tty
.c_cflag
|= PARENB
;
1756 tty
.c_cflag
|= PARENB
| PARODD
;
1760 tty
.c_cflag
|= CSTOPB
;
1762 tcsetattr (fd
, TCSANOW
, &tty
);
1765 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1767 FDCharDriver
*s
= chr
->opaque
;
1770 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1772 QEMUSerialSetParams
*ssp
= arg
;
1773 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1774 ssp
->data_bits
, ssp
->stop_bits
);
1777 case CHR_IOCTL_SERIAL_SET_BREAK
:
1779 int enable
= *(int *)arg
;
1781 tcsendbreak(s
->fd_in
, 1);
1790 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1792 CharDriverState
*chr
;
1795 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1798 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1799 tty_serial_init(fd
, 115200, 'N', 8, 1);
1800 chr
= qemu_chr_open_fd(fd
, fd
);
1803 chr
->chr_ioctl
= tty_serial_ioctl
;
1804 qemu_chr_reset(chr
);
1808 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1810 int fd
= (int)chr
->opaque
;
1814 case CHR_IOCTL_PP_READ_DATA
:
1815 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1817 *(uint8_t *)arg
= b
;
1819 case CHR_IOCTL_PP_WRITE_DATA
:
1820 b
= *(uint8_t *)arg
;
1821 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1824 case CHR_IOCTL_PP_READ_CONTROL
:
1825 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1827 *(uint8_t *)arg
= b
;
1829 case CHR_IOCTL_PP_WRITE_CONTROL
:
1830 b
= *(uint8_t *)arg
;
1831 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1834 case CHR_IOCTL_PP_READ_STATUS
:
1835 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1837 *(uint8_t *)arg
= b
;
1845 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
1847 CharDriverState
*chr
;
1850 fd
= open(filename
, O_RDWR
);
1854 if (ioctl(fd
, PPCLAIM
) < 0) {
1859 chr
= qemu_mallocz(sizeof(CharDriverState
));
1864 chr
->opaque
= (void *)fd
;
1865 chr
->chr_write
= null_chr_write
;
1866 chr
->chr_ioctl
= pp_ioctl
;
1868 qemu_chr_reset(chr
);
1874 static CharDriverState
*qemu_chr_open_pty(void)
1880 #endif /* !defined(_WIN32) */
1884 CharDriverState
*chr
;
1886 HANDLE hcom
, hrecv
, hsend
;
1887 OVERLAPPED orecv
, osend
;
1892 #define NSENDBUF 2048
1893 #define NRECVBUF 2048
1894 #define MAXCONNECT 1
1895 #define NTIMEOUT 5000
1897 static int win_chr_poll(void *opaque
);
1898 static int win_chr_pipe_poll(void *opaque
);
1900 static void win_chr_close2(WinCharState
*s
)
1903 CloseHandle(s
->hsend
);
1907 CloseHandle(s
->hrecv
);
1911 CloseHandle(s
->hcom
);
1915 qemu_del_polling_cb(win_chr_pipe_poll
, s
);
1917 qemu_del_polling_cb(win_chr_poll
, s
);
1920 static void win_chr_close(CharDriverState
*chr
)
1922 WinCharState
*s
= chr
->opaque
;
1926 static int win_chr_init(WinCharState
*s
, CharDriverState
*chr
, const char *filename
)
1929 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1934 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1936 fprintf(stderr
, "Failed CreateEvent\n");
1939 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1941 fprintf(stderr
, "Failed CreateEvent\n");
1945 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1946 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1947 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1948 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1953 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1954 fprintf(stderr
, "Failed SetupComm\n");
1958 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1959 size
= sizeof(COMMCONFIG
);
1960 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1961 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1962 CommConfigDialog(filename
, NULL
, &comcfg
);
1964 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1965 fprintf(stderr
, "Failed SetCommState\n");
1969 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1970 fprintf(stderr
, "Failed SetCommMask\n");
1974 cto
.ReadIntervalTimeout
= MAXDWORD
;
1975 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1976 fprintf(stderr
, "Failed SetCommTimeouts\n");
1980 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1981 fprintf(stderr
, "Failed ClearCommError\n");
1985 qemu_add_polling_cb(win_chr_poll
, s
);
1993 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
1995 WinCharState
*s
= chr
->opaque
;
1996 DWORD len
, ret
, size
, err
;
1999 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2000 s
->osend
.hEvent
= s
->hsend
;
2003 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2005 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2007 err
= GetLastError();
2008 if (err
== ERROR_IO_PENDING
) {
2009 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2027 static int win_chr_read_poll(WinCharState
*s
)
2029 s
->max_size
= qemu_chr_can_read(s
->chr
);
2033 static void win_chr_readfile(WinCharState
*s
)
2039 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2040 s
->orecv
.hEvent
= s
->hrecv
;
2041 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2043 err
= GetLastError();
2044 if (err
== ERROR_IO_PENDING
) {
2045 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2050 qemu_chr_read(s
->chr
, buf
, size
);
2054 static void win_chr_read(WinCharState
*s
)
2056 if (s
->len
> s
->max_size
)
2057 s
->len
= s
->max_size
;
2061 win_chr_readfile(s
);
2064 static int win_chr_poll(void *opaque
)
2066 WinCharState
*s
= opaque
;
2070 ClearCommError(s
->hcom
, &comerr
, &status
);
2071 if (status
.cbInQue
> 0) {
2072 s
->len
= status
.cbInQue
;
2073 win_chr_read_poll(s
);
2080 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2082 CharDriverState
*chr
;
2085 chr
= qemu_mallocz(sizeof(CharDriverState
));
2088 s
= qemu_mallocz(sizeof(WinCharState
));
2094 chr
->chr_write
= win_chr_write
;
2095 chr
->chr_close
= win_chr_close
;
2097 if (win_chr_init(s
, chr
, filename
) < 0) {
2102 qemu_chr_reset(chr
);
2106 static int win_chr_pipe_poll(void *opaque
)
2108 WinCharState
*s
= opaque
;
2111 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2114 win_chr_read_poll(s
);
2121 static int win_chr_pipe_init(WinCharState
*s
, const char *filename
)
2130 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2132 fprintf(stderr
, "Failed CreateEvent\n");
2135 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2137 fprintf(stderr
, "Failed CreateEvent\n");
2141 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2142 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2143 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2145 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2146 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2147 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2152 ZeroMemory(&ov
, sizeof(ov
));
2153 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2154 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2156 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2160 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2162 fprintf(stderr
, "Failed GetOverlappedResult\n");
2164 CloseHandle(ov
.hEvent
);
2171 CloseHandle(ov
.hEvent
);
2174 qemu_add_polling_cb(win_chr_pipe_poll
, s
);
2183 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2185 CharDriverState
*chr
;
2188 chr
= qemu_mallocz(sizeof(CharDriverState
));
2191 s
= qemu_mallocz(sizeof(WinCharState
));
2197 chr
->chr_write
= win_chr_write
;
2198 chr
->chr_close
= win_chr_close
;
2200 if (win_chr_pipe_init(s
, filename
) < 0) {
2205 qemu_chr_reset(chr
);
2209 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2211 CharDriverState
*chr
;
2214 chr
= qemu_mallocz(sizeof(CharDriverState
));
2217 s
= qemu_mallocz(sizeof(WinCharState
));
2224 chr
->chr_write
= win_chr_write
;
2225 qemu_chr_reset(chr
);
2229 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2233 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2234 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2235 if (fd_out
== INVALID_HANDLE_VALUE
)
2238 return qemu_chr_open_win_file(fd_out
);
2242 /***********************************************************/
2243 /* UDP Net console */
2247 struct sockaddr_in daddr
;
2254 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2256 NetCharDriver
*s
= chr
->opaque
;
2258 return sendto(s
->fd
, buf
, len
, 0,
2259 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2262 static int udp_chr_read_poll(void *opaque
)
2264 CharDriverState
*chr
= opaque
;
2265 NetCharDriver
*s
= chr
->opaque
;
2267 s
->max_size
= qemu_chr_can_read(chr
);
2269 /* If there were any stray characters in the queue process them
2272 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2273 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2275 s
->max_size
= qemu_chr_can_read(chr
);
2280 static void udp_chr_read(void *opaque
)
2282 CharDriverState
*chr
= opaque
;
2283 NetCharDriver
*s
= chr
->opaque
;
2285 if (s
->max_size
== 0)
2287 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2288 s
->bufptr
= s
->bufcnt
;
2293 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2294 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2296 s
->max_size
= qemu_chr_can_read(chr
);
2300 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2302 NetCharDriver
*s
= chr
->opaque
;
2305 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2306 udp_chr_read
, NULL
, chr
);
2311 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2313 int parse_host_src_port(struct sockaddr_in
*haddr
,
2314 struct sockaddr_in
*saddr
,
2317 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2319 CharDriverState
*chr
= NULL
;
2320 NetCharDriver
*s
= NULL
;
2322 struct sockaddr_in saddr
;
2324 chr
= qemu_mallocz(sizeof(CharDriverState
));
2327 s
= qemu_mallocz(sizeof(NetCharDriver
));
2331 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2333 perror("socket(PF_INET, SOCK_DGRAM)");
2337 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2338 printf("Could not parse: %s\n", def
);
2342 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2352 chr
->chr_write
= udp_chr_write
;
2353 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2366 /***********************************************************/
2367 /* TCP Net console */
2378 static void tcp_chr_accept(void *opaque
);
2380 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2382 TCPCharDriver
*s
= chr
->opaque
;
2384 return send_all(s
->fd
, buf
, len
);
2386 /* XXX: indicate an error ? */
2391 static int tcp_chr_read_poll(void *opaque
)
2393 CharDriverState
*chr
= opaque
;
2394 TCPCharDriver
*s
= chr
->opaque
;
2397 s
->max_size
= qemu_chr_can_read(chr
);
2402 #define IAC_BREAK 243
2403 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2405 char *buf
, int *size
)
2407 /* Handle any telnet client's basic IAC options to satisfy char by
2408 * char mode with no echo. All IAC options will be removed from
2409 * the buf and the do_telnetopt variable will be used to track the
2410 * state of the width of the IAC information.
2412 * IAC commands come in sets of 3 bytes with the exception of the
2413 * "IAC BREAK" command and the double IAC.
2419 for (i
= 0; i
< *size
; i
++) {
2420 if (s
->do_telnetopt
> 1) {
2421 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2422 /* Double IAC means send an IAC */
2426 s
->do_telnetopt
= 1;
2428 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2429 /* Handle IAC break commands by sending a serial break */
2430 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2435 if (s
->do_telnetopt
>= 4) {
2436 s
->do_telnetopt
= 1;
2439 if ((unsigned char)buf
[i
] == IAC
) {
2440 s
->do_telnetopt
= 2;
2451 static void tcp_chr_read(void *opaque
)
2453 CharDriverState
*chr
= opaque
;
2454 TCPCharDriver
*s
= chr
->opaque
;
2458 if (!s
->connected
|| s
->max_size
<= 0)
2461 if (len
> s
->max_size
)
2463 size
= recv(s
->fd
, buf
, len
, 0);
2465 /* connection closed */
2467 if (s
->listen_fd
>= 0) {
2468 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2470 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2473 } else if (size
> 0) {
2474 if (s
->do_telnetopt
)
2475 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2477 qemu_chr_read(chr
, buf
, size
);
2481 static void tcp_chr_connect(void *opaque
)
2483 CharDriverState
*chr
= opaque
;
2484 TCPCharDriver
*s
= chr
->opaque
;
2487 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2488 tcp_chr_read
, NULL
, chr
);
2489 qemu_chr_reset(chr
);
2492 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2493 static void tcp_chr_telnet_init(int fd
)
2496 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2497 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2498 send(fd
, (char *)buf
, 3, 0);
2499 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2500 send(fd
, (char *)buf
, 3, 0);
2501 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2502 send(fd
, (char *)buf
, 3, 0);
2503 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2504 send(fd
, (char *)buf
, 3, 0);
2507 static void socket_set_nodelay(int fd
)
2510 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2513 static void tcp_chr_accept(void *opaque
)
2515 CharDriverState
*chr
= opaque
;
2516 TCPCharDriver
*s
= chr
->opaque
;
2517 struct sockaddr_in saddr
;
2519 struct sockaddr_un uaddr
;
2521 struct sockaddr
*addr
;
2528 len
= sizeof(uaddr
);
2529 addr
= (struct sockaddr
*)&uaddr
;
2533 len
= sizeof(saddr
);
2534 addr
= (struct sockaddr
*)&saddr
;
2536 fd
= accept(s
->listen_fd
, addr
, &len
);
2537 if (fd
< 0 && errno
!= EINTR
) {
2539 } else if (fd
>= 0) {
2540 if (s
->do_telnetopt
)
2541 tcp_chr_telnet_init(fd
);
2545 socket_set_nonblock(fd
);
2547 socket_set_nodelay(fd
);
2549 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2550 tcp_chr_connect(chr
);
2553 static void tcp_chr_close(CharDriverState
*chr
)
2555 TCPCharDriver
*s
= chr
->opaque
;
2558 if (s
->listen_fd
>= 0)
2559 closesocket(s
->listen_fd
);
2563 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2567 CharDriverState
*chr
= NULL
;
2568 TCPCharDriver
*s
= NULL
;
2569 int fd
= -1, ret
, err
, val
;
2571 int is_waitconnect
= 1;
2574 struct sockaddr_in saddr
;
2576 struct sockaddr_un uaddr
;
2578 struct sockaddr
*addr
;
2583 addr
= (struct sockaddr
*)&uaddr
;
2584 addrlen
= sizeof(uaddr
);
2585 if (parse_unix_path(&uaddr
, host_str
) < 0)
2590 addr
= (struct sockaddr
*)&saddr
;
2591 addrlen
= sizeof(saddr
);
2592 if (parse_host_port(&saddr
, host_str
) < 0)
2597 while((ptr
= strchr(ptr
,','))) {
2599 if (!strncmp(ptr
,"server",6)) {
2601 } else if (!strncmp(ptr
,"nowait",6)) {
2603 } else if (!strncmp(ptr
,"nodelay",6)) {
2606 printf("Unknown option: %s\n", ptr
);
2613 chr
= qemu_mallocz(sizeof(CharDriverState
));
2616 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2622 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2625 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2630 if (!is_waitconnect
)
2631 socket_set_nonblock(fd
);
2636 s
->is_unix
= is_unix
;
2637 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2640 chr
->chr_write
= tcp_chr_write
;
2641 chr
->chr_close
= tcp_chr_close
;
2644 /* allow fast reuse */
2648 strncpy(path
, uaddr
.sun_path
, 108);
2655 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2658 ret
= bind(fd
, addr
, addrlen
);
2662 ret
= listen(fd
, 0);
2667 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2669 s
->do_telnetopt
= 1;
2672 ret
= connect(fd
, addr
, addrlen
);
2674 err
= socket_error();
2675 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2676 } else if (err
== EINPROGRESS
) {
2687 socket_set_nodelay(fd
);
2689 tcp_chr_connect(chr
);
2691 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2694 if (is_listen
&& is_waitconnect
) {
2695 printf("QEMU waiting for connection on: %s\n", host_str
);
2696 tcp_chr_accept(chr
);
2697 socket_set_nonblock(s
->listen_fd
);
2709 CharDriverState
*qemu_chr_open(const char *filename
)
2713 if (!strcmp(filename
, "vc")) {
2714 return text_console_init(&display_state
);
2715 } else if (!strcmp(filename
, "null")) {
2716 return qemu_chr_open_null();
2718 if (strstart(filename
, "tcp:", &p
)) {
2719 return qemu_chr_open_tcp(p
, 0, 0);
2721 if (strstart(filename
, "telnet:", &p
)) {
2722 return qemu_chr_open_tcp(p
, 1, 0);
2724 if (strstart(filename
, "udp:", &p
)) {
2725 return qemu_chr_open_udp(p
);
2728 if (strstart(filename
, "unix:", &p
)) {
2729 return qemu_chr_open_tcp(p
, 0, 1);
2730 } else if (strstart(filename
, "file:", &p
)) {
2731 return qemu_chr_open_file_out(p
);
2732 } else if (strstart(filename
, "pipe:", &p
)) {
2733 return qemu_chr_open_pipe(p
);
2734 } else if (!strcmp(filename
, "pty")) {
2735 return qemu_chr_open_pty();
2736 } else if (!strcmp(filename
, "stdio")) {
2737 return qemu_chr_open_stdio();
2740 #if defined(__linux__)
2741 if (strstart(filename
, "/dev/parport", NULL
)) {
2742 return qemu_chr_open_pp(filename
);
2744 if (strstart(filename
, "/dev/", NULL
)) {
2745 return qemu_chr_open_tty(filename
);
2749 if (strstart(filename
, "COM", NULL
)) {
2750 return qemu_chr_open_win(filename
);
2752 if (strstart(filename
, "pipe:", &p
)) {
2753 return qemu_chr_open_win_pipe(p
);
2755 if (strstart(filename
, "file:", &p
)) {
2756 return qemu_chr_open_win_file_out(p
);
2764 void qemu_chr_close(CharDriverState
*chr
)
2767 chr
->chr_close(chr
);
2770 /***********************************************************/
2771 /* network device redirectors */
2773 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2777 for(i
=0;i
<size
;i
+=16) {
2781 fprintf(f
, "%08x ", i
);
2784 fprintf(f
, " %02x", buf
[i
+j
]);
2789 for(j
=0;j
<len
;j
++) {
2791 if (c
< ' ' || c
> '~')
2793 fprintf(f
, "%c", c
);
2799 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2802 for(i
= 0; i
< 6; i
++) {
2803 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
2816 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
2821 p1
= strchr(p
, sep
);
2827 if (len
> buf_size
- 1)
2829 memcpy(buf
, p
, len
);
2836 int parse_host_src_port(struct sockaddr_in
*haddr
,
2837 struct sockaddr_in
*saddr
,
2838 const char *input_str
)
2840 char *str
= strdup(input_str
);
2841 char *host_str
= str
;
2846 * Chop off any extra arguments at the end of the string which
2847 * would start with a comma, then fill in the src port information
2848 * if it was provided else use the "any address" and "any port".
2850 if ((ptr
= strchr(str
,',')))
2853 if ((src_str
= strchr(input_str
,'@'))) {
2858 if (parse_host_port(haddr
, host_str
) < 0)
2861 if (!src_str
|| *src_str
== '\0')
2864 if (parse_host_port(saddr
, src_str
) < 0)
2875 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
2883 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2885 saddr
->sin_family
= AF_INET
;
2886 if (buf
[0] == '\0') {
2887 saddr
->sin_addr
.s_addr
= 0;
2889 if (isdigit(buf
[0])) {
2890 if (!inet_aton(buf
, &saddr
->sin_addr
))
2893 if ((he
= gethostbyname(buf
)) == NULL
)
2895 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
2898 port
= strtol(p
, (char **)&r
, 0);
2901 saddr
->sin_port
= htons(port
);
2906 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
2911 len
= MIN(108, strlen(str
));
2912 p
= strchr(str
, ',');
2914 len
= MIN(len
, p
- str
);
2916 memset(uaddr
, 0, sizeof(*uaddr
));
2918 uaddr
->sun_family
= AF_UNIX
;
2919 memcpy(uaddr
->sun_path
, str
, len
);
2925 /* find or alloc a new VLAN */
2926 VLANState
*qemu_find_vlan(int id
)
2928 VLANState
**pvlan
, *vlan
;
2929 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2933 vlan
= qemu_mallocz(sizeof(VLANState
));
2938 pvlan
= &first_vlan
;
2939 while (*pvlan
!= NULL
)
2940 pvlan
= &(*pvlan
)->next
;
2945 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
2946 IOReadHandler
*fd_read
,
2947 IOCanRWHandler
*fd_can_read
,
2950 VLANClientState
*vc
, **pvc
;
2951 vc
= qemu_mallocz(sizeof(VLANClientState
));
2954 vc
->fd_read
= fd_read
;
2955 vc
->fd_can_read
= fd_can_read
;
2956 vc
->opaque
= opaque
;
2960 pvc
= &vlan
->first_client
;
2961 while (*pvc
!= NULL
)
2962 pvc
= &(*pvc
)->next
;
2967 int qemu_can_send_packet(VLANClientState
*vc1
)
2969 VLANState
*vlan
= vc1
->vlan
;
2970 VLANClientState
*vc
;
2972 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2974 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
2981 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
2983 VLANState
*vlan
= vc1
->vlan
;
2984 VLANClientState
*vc
;
2987 printf("vlan %d send:\n", vlan
->id
);
2988 hex_dump(stdout
, buf
, size
);
2990 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2992 vc
->fd_read(vc
->opaque
, buf
, size
);
2997 #if defined(CONFIG_SLIRP)
2999 /* slirp network adapter */
3001 static int slirp_inited
;
3002 static VLANClientState
*slirp_vc
;
3004 int slirp_can_output(void)
3006 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3009 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3012 printf("slirp output:\n");
3013 hex_dump(stdout
, pkt
, pkt_len
);
3017 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3020 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3023 printf("slirp input:\n");
3024 hex_dump(stdout
, buf
, size
);
3026 slirp_input(buf
, size
);
3029 static int net_slirp_init(VLANState
*vlan
)
3031 if (!slirp_inited
) {
3035 slirp_vc
= qemu_new_vlan_client(vlan
,
3036 slirp_receive
, NULL
, NULL
);
3037 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3041 static void net_slirp_redir(const char *redir_str
)
3046 struct in_addr guest_addr
;
3047 int host_port
, guest_port
;
3049 if (!slirp_inited
) {
3055 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3057 if (!strcmp(buf
, "tcp")) {
3059 } else if (!strcmp(buf
, "udp")) {
3065 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3067 host_port
= strtol(buf
, &r
, 0);
3071 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3073 if (buf
[0] == '\0') {
3074 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3076 if (!inet_aton(buf
, &guest_addr
))
3079 guest_port
= strtol(p
, &r
, 0);
3083 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3084 fprintf(stderr
, "qemu: could not set up redirection\n");
3089 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3097 static void smb_exit(void)
3101 char filename
[1024];
3103 /* erase all the files in the directory */
3104 d
= opendir(smb_dir
);
3109 if (strcmp(de
->d_name
, ".") != 0 &&
3110 strcmp(de
->d_name
, "..") != 0) {
3111 snprintf(filename
, sizeof(filename
), "%s/%s",
3112 smb_dir
, de
->d_name
);
3120 /* automatic user mode samba server configuration */
3121 void net_slirp_smb(const char *exported_dir
)
3123 char smb_conf
[1024];
3124 char smb_cmdline
[1024];
3127 if (!slirp_inited
) {
3132 /* XXX: better tmp dir construction */
3133 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3134 if (mkdir(smb_dir
, 0700) < 0) {
3135 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3138 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3140 f
= fopen(smb_conf
, "w");
3142 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3149 "socket address=127.0.0.1\n"
3150 "pid directory=%s\n"
3151 "lock directory=%s\n"
3152 "log file=%s/log.smbd\n"
3153 "smb passwd file=%s/smbpasswd\n"
3154 "security = share\n"
3169 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3170 SMBD_COMMAND
, smb_conf
);
3172 slirp_add_exec(0, smb_cmdline
, 4, 139);
3175 #endif /* !defined(_WIN32) */
3177 #endif /* CONFIG_SLIRP */
3179 #if !defined(_WIN32)
3181 typedef struct TAPState
{
3182 VLANClientState
*vc
;
3186 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3188 TAPState
*s
= opaque
;
3191 ret
= write(s
->fd
, buf
, size
);
3192 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3199 static void tap_send(void *opaque
)
3201 TAPState
*s
= opaque
;
3205 size
= read(s
->fd
, buf
, sizeof(buf
));
3207 qemu_send_packet(s
->vc
, buf
, size
);
3213 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3217 s
= qemu_mallocz(sizeof(TAPState
));
3221 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3222 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3223 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3228 static int tap_open(char *ifname
, int ifname_size
)
3234 fd
= open("/dev/tap", O_RDWR
);
3236 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3241 dev
= devname(s
.st_rdev
, S_IFCHR
);
3242 pstrcpy(ifname
, ifname_size
, dev
);
3244 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3247 #elif defined(__sun__)
3248 static int tap_open(char *ifname
, int ifname_size
)
3250 fprintf(stderr
, "warning: tap_open not yet implemented\n");
3254 static int tap_open(char *ifname
, int ifname_size
)
3259 fd
= open("/dev/net/tun", O_RDWR
);
3261 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3264 memset(&ifr
, 0, sizeof(ifr
));
3265 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3266 if (ifname
[0] != '\0')
3267 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3269 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3270 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3272 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3276 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3277 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3282 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3283 const char *setup_script
)
3286 int pid
, status
, fd
;
3291 if (ifname1
!= NULL
)
3292 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3295 fd
= tap_open(ifname
, sizeof(ifname
));
3299 if (!setup_script
|| !strcmp(setup_script
, "no"))
3301 if (setup_script
[0] != '\0') {
3302 /* try to launch network init script */
3307 *parg
++ = (char *)setup_script
;
3310 execv(setup_script
, args
);
3313 while (waitpid(pid
, &status
, 0) != pid
);
3314 if (!WIFEXITED(status
) ||
3315 WEXITSTATUS(status
) != 0) {
3316 fprintf(stderr
, "%s: could not launch network script\n",
3322 s
= net_tap_fd_init(vlan
, fd
);
3325 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3326 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3330 #endif /* !_WIN32 */
3332 /* network connection */
3333 typedef struct NetSocketState
{
3334 VLANClientState
*vc
;
3336 int state
; /* 0 = getting length, 1 = getting data */
3340 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3343 typedef struct NetSocketListenState
{
3346 } NetSocketListenState
;
3348 /* XXX: we consider we can send the whole packet without blocking */
3349 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3351 NetSocketState
*s
= opaque
;
3355 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3356 send_all(s
->fd
, buf
, size
);
3359 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3361 NetSocketState
*s
= opaque
;
3362 sendto(s
->fd
, buf
, size
, 0,
3363 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3366 static void net_socket_send(void *opaque
)
3368 NetSocketState
*s
= opaque
;
3373 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3375 err
= socket_error();
3376 if (err
!= EWOULDBLOCK
)
3378 } else if (size
== 0) {
3379 /* end of connection */
3381 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3387 /* reassemble a packet from the network */
3393 memcpy(s
->buf
+ s
->index
, buf
, l
);
3397 if (s
->index
== 4) {
3399 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3405 l
= s
->packet_len
- s
->index
;
3408 memcpy(s
->buf
+ s
->index
, buf
, l
);
3412 if (s
->index
>= s
->packet_len
) {
3413 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3422 static void net_socket_send_dgram(void *opaque
)
3424 NetSocketState
*s
= opaque
;
3427 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3431 /* end of connection */
3432 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3435 qemu_send_packet(s
->vc
, s
->buf
, size
);
3438 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3443 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3444 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3445 inet_ntoa(mcastaddr
->sin_addr
),
3446 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3450 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3452 perror("socket(PF_INET, SOCK_DGRAM)");
3457 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3458 (const char *)&val
, sizeof(val
));
3460 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3464 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3470 /* Add host to multicast group */
3471 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3472 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3474 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3475 (const char *)&imr
, sizeof(struct ip_mreq
));
3477 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3481 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3483 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3484 (const char *)&val
, sizeof(val
));
3486 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3490 socket_set_nonblock(fd
);
3498 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3501 struct sockaddr_in saddr
;
3503 socklen_t saddr_len
;
3506 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3507 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3508 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3512 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3514 if (saddr
.sin_addr
.s_addr
==0) {
3515 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3519 /* clone dgram socket */
3520 newfd
= net_socket_mcast_create(&saddr
);
3522 /* error already reported by net_socket_mcast_create() */
3526 /* clone newfd to fd, close newfd */
3531 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3532 fd
, strerror(errno
));
3537 s
= qemu_mallocz(sizeof(NetSocketState
));
3542 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3543 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3545 /* mcast: save bound address as dst */
3546 if (is_connected
) s
->dgram_dst
=saddr
;
3548 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3549 "socket: fd=%d (%s mcast=%s:%d)",
3550 fd
, is_connected
? "cloned" : "",
3551 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3555 static void net_socket_connect(void *opaque
)
3557 NetSocketState
*s
= opaque
;
3558 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3561 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3565 s
= qemu_mallocz(sizeof(NetSocketState
));
3569 s
->vc
= qemu_new_vlan_client(vlan
,
3570 net_socket_receive
, NULL
, s
);
3571 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3572 "socket: fd=%d", fd
);
3574 net_socket_connect(s
);
3576 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3581 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3584 int so_type
=-1, optlen
=sizeof(so_type
);
3586 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3587 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3592 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3594 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3596 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3597 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3598 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3603 static void net_socket_accept(void *opaque
)
3605 NetSocketListenState
*s
= opaque
;
3607 struct sockaddr_in saddr
;
3612 len
= sizeof(saddr
);
3613 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3614 if (fd
< 0 && errno
!= EINTR
) {
3616 } else if (fd
>= 0) {
3620 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3624 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3625 "socket: connection from %s:%d",
3626 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3630 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3632 NetSocketListenState
*s
;
3634 struct sockaddr_in saddr
;
3636 if (parse_host_port(&saddr
, host_str
) < 0)
3639 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3643 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3648 socket_set_nonblock(fd
);
3650 /* allow fast reuse */
3652 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3654 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3659 ret
= listen(fd
, 0);
3666 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3670 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3673 int fd
, connected
, ret
, err
;
3674 struct sockaddr_in saddr
;
3676 if (parse_host_port(&saddr
, host_str
) < 0)
3679 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3684 socket_set_nonblock(fd
);
3688 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3690 err
= socket_error();
3691 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3692 } else if (err
== EINPROGRESS
) {
3704 s
= net_socket_fd_init(vlan
, fd
, connected
);
3707 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3708 "socket: connect to %s:%d",
3709 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3713 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
3717 struct sockaddr_in saddr
;
3719 if (parse_host_port(&saddr
, host_str
) < 0)
3723 fd
= net_socket_mcast_create(&saddr
);
3727 s
= net_socket_fd_init(vlan
, fd
, 0);
3731 s
->dgram_dst
= saddr
;
3733 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3734 "socket: mcast=%s:%d",
3735 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3740 static int get_param_value(char *buf
, int buf_size
,
3741 const char *tag
, const char *str
)
3750 while (*p
!= '\0' && *p
!= '=') {
3751 if ((q
- option
) < sizeof(option
) - 1)
3759 if (!strcmp(tag
, option
)) {
3761 while (*p
!= '\0' && *p
!= ',') {
3762 if ((q
- buf
) < buf_size
- 1)
3769 while (*p
!= '\0' && *p
!= ',') {
3780 static int net_client_init(const char *str
)
3791 while (*p
!= '\0' && *p
!= ',') {
3792 if ((q
- device
) < sizeof(device
) - 1)
3800 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
3801 vlan_id
= strtol(buf
, NULL
, 0);
3803 vlan
= qemu_find_vlan(vlan_id
);
3805 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
3808 if (!strcmp(device
, "nic")) {
3812 if (nb_nics
>= MAX_NICS
) {
3813 fprintf(stderr
, "Too Many NICs\n");
3816 nd
= &nd_table
[nb_nics
];
3817 macaddr
= nd
->macaddr
;
3823 macaddr
[5] = 0x56 + nb_nics
;
3825 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
3826 if (parse_macaddr(macaddr
, buf
) < 0) {
3827 fprintf(stderr
, "invalid syntax for ethernet address\n");
3831 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
3832 nd
->model
= strdup(buf
);
3838 if (!strcmp(device
, "none")) {
3839 /* does nothing. It is needed to signal that no network cards
3844 if (!strcmp(device
, "user")) {
3845 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
3846 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
3848 ret
= net_slirp_init(vlan
);
3852 if (!strcmp(device
, "tap")) {
3854 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3855 fprintf(stderr
, "tap: no interface name\n");
3858 ret
= tap_win32_init(vlan
, ifname
);
3861 if (!strcmp(device
, "tap")) {
3863 char setup_script
[1024];
3865 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3866 fd
= strtol(buf
, NULL
, 0);
3868 if (net_tap_fd_init(vlan
, fd
))
3871 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3874 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
3875 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
3877 ret
= net_tap_init(vlan
, ifname
, setup_script
);
3881 if (!strcmp(device
, "socket")) {
3882 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3884 fd
= strtol(buf
, NULL
, 0);
3886 if (net_socket_fd_init(vlan
, fd
, 1))
3888 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
3889 ret
= net_socket_listen_init(vlan
, buf
);
3890 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
3891 ret
= net_socket_connect_init(vlan
, buf
);
3892 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
3893 ret
= net_socket_mcast_init(vlan
, buf
);
3895 fprintf(stderr
, "Unknown socket options: %s\n", p
);
3900 fprintf(stderr
, "Unknown network device: %s\n", device
);
3904 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
3910 void do_info_network(void)
3913 VLANClientState
*vc
;
3915 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3916 term_printf("VLAN %d devices:\n", vlan
->id
);
3917 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
3918 term_printf(" %s\n", vc
->info_str
);
3922 /***********************************************************/
3925 static USBPort
*used_usb_ports
;
3926 static USBPort
*free_usb_ports
;
3928 /* ??? Maybe change this to register a hub to keep track of the topology. */
3929 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
3930 usb_attachfn attach
)
3932 port
->opaque
= opaque
;
3933 port
->index
= index
;
3934 port
->attach
= attach
;
3935 port
->next
= free_usb_ports
;
3936 free_usb_ports
= port
;
3939 static int usb_device_add(const char *devname
)
3945 if (!free_usb_ports
)
3948 if (strstart(devname
, "host:", &p
)) {
3949 dev
= usb_host_device_open(p
);
3950 } else if (!strcmp(devname
, "mouse")) {
3951 dev
= usb_mouse_init();
3952 } else if (!strcmp(devname
, "tablet")) {
3953 dev
= usb_tablet_init();
3954 } else if (strstart(devname
, "disk:", &p
)) {
3955 dev
= usb_msd_init(p
);
3962 /* Find a USB port to add the device to. */
3963 port
= free_usb_ports
;
3967 /* Create a new hub and chain it on. */
3968 free_usb_ports
= NULL
;
3969 port
->next
= used_usb_ports
;
3970 used_usb_ports
= port
;
3972 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
3973 usb_attach(port
, hub
);
3974 port
= free_usb_ports
;
3977 free_usb_ports
= port
->next
;
3978 port
->next
= used_usb_ports
;
3979 used_usb_ports
= port
;
3980 usb_attach(port
, dev
);
3984 static int usb_device_del(const char *devname
)
3992 if (!used_usb_ports
)
3995 p
= strchr(devname
, '.');
3998 bus_num
= strtoul(devname
, NULL
, 0);
3999 addr
= strtoul(p
+ 1, NULL
, 0);
4003 lastp
= &used_usb_ports
;
4004 port
= used_usb_ports
;
4005 while (port
&& port
->dev
->addr
!= addr
) {
4006 lastp
= &port
->next
;
4014 *lastp
= port
->next
;
4015 usb_attach(port
, NULL
);
4016 dev
->handle_destroy(dev
);
4017 port
->next
= free_usb_ports
;
4018 free_usb_ports
= port
;
4022 void do_usb_add(const char *devname
)
4025 ret
= usb_device_add(devname
);
4027 term_printf("Could not add USB device '%s'\n", devname
);
4030 void do_usb_del(const char *devname
)
4033 ret
= usb_device_del(devname
);
4035 term_printf("Could not remove USB device '%s'\n", devname
);
4042 const char *speed_str
;
4045 term_printf("USB support not enabled\n");
4049 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4053 switch(dev
->speed
) {
4057 case USB_SPEED_FULL
:
4060 case USB_SPEED_HIGH
:
4067 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4068 0, dev
->addr
, speed_str
, dev
->devname
);
4072 /***********************************************************/
4075 static char *pid_filename
;
4077 /* Remove PID file. Called on normal exit */
4079 static void remove_pidfile(void)
4081 unlink (pid_filename
);
4084 static void create_pidfile(const char *filename
)
4086 struct stat pidstat
;
4089 /* Try to write our PID to the named file */
4090 if (stat(filename
, &pidstat
) < 0) {
4091 if (errno
== ENOENT
) {
4092 if ((f
= fopen (filename
, "w")) == NULL
) {
4093 perror("Opening pidfile");
4096 fprintf(f
, "%d\n", getpid());
4098 pid_filename
= qemu_strdup(filename
);
4099 if (!pid_filename
) {
4100 fprintf(stderr
, "Could not save PID filename");
4103 atexit(remove_pidfile
);
4106 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4112 /***********************************************************/
4115 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4119 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4123 static void dumb_refresh(DisplayState
*ds
)
4128 void dumb_display_init(DisplayState
*ds
)
4133 ds
->dpy_update
= dumb_update
;
4134 ds
->dpy_resize
= dumb_resize
;
4135 ds
->dpy_refresh
= dumb_refresh
;
4138 /***********************************************************/
4141 #define MAX_IO_HANDLERS 64
4143 typedef struct IOHandlerRecord
{
4145 IOCanRWHandler
*fd_read_poll
;
4147 IOHandler
*fd_write
;
4149 /* temporary data */
4151 struct IOHandlerRecord
*next
;
4154 static IOHandlerRecord
*first_io_handler
;
4156 /* XXX: fd_read_poll should be suppressed, but an API change is
4157 necessary in the character devices to suppress fd_can_read(). */
4158 int qemu_set_fd_handler2(int fd
,
4159 IOCanRWHandler
*fd_read_poll
,
4161 IOHandler
*fd_write
,
4164 IOHandlerRecord
**pioh
, *ioh
;
4166 if (!fd_read
&& !fd_write
) {
4167 pioh
= &first_io_handler
;
4172 if (ioh
->fd
== fd
) {
4180 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4184 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4187 ioh
->next
= first_io_handler
;
4188 first_io_handler
= ioh
;
4191 ioh
->fd_read_poll
= fd_read_poll
;
4192 ioh
->fd_read
= fd_read
;
4193 ioh
->fd_write
= fd_write
;
4194 ioh
->opaque
= opaque
;
4199 int qemu_set_fd_handler(int fd
,
4201 IOHandler
*fd_write
,
4204 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4207 /***********************************************************/
4208 /* Polling handling */
4210 typedef struct PollingEntry
{
4213 struct PollingEntry
*next
;
4216 static PollingEntry
*first_polling_entry
;
4218 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4220 PollingEntry
**ppe
, *pe
;
4221 pe
= qemu_mallocz(sizeof(PollingEntry
));
4225 pe
->opaque
= opaque
;
4226 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4231 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4233 PollingEntry
**ppe
, *pe
;
4234 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4236 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4245 /***********************************************************/
4246 /* Wait objects support */
4247 typedef struct WaitObjects
{
4249 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4250 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4251 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4254 static WaitObjects wait_objects
= {0};
4256 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4258 WaitObjects
*w
= &wait_objects
;
4260 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4262 w
->events
[w
->num
] = handle
;
4263 w
->func
[w
->num
] = func
;
4264 w
->opaque
[w
->num
] = opaque
;
4269 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4272 WaitObjects
*w
= &wait_objects
;
4275 for (i
= 0; i
< w
->num
; i
++) {
4276 if (w
->events
[i
] == handle
)
4279 w
->events
[i
] = w
->events
[i
+ 1];
4280 w
->func
[i
] = w
->func
[i
+ 1];
4281 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4289 #define SELF_ANNOUNCE_ROUNDS 5
4290 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4291 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4292 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4294 static int announce_self_create(uint8_t *buf
,
4297 uint32_t magic
= EXPERIMENTAL_MAGIC
;
4298 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
4300 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4302 memset(buf
, 0xff, 6); /* h_dst */
4303 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
4304 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
4305 memcpy(buf
+ 14, &magic
, 4); /* magic */
4307 return 18; /* len */
4310 static void qemu_announce_self(void)
4314 VLANClientState
*vc
;
4317 for (i
= 0; i
< nb_nics
; i
++) {
4318 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
4319 vlan
= nd_table
[i
].vlan
;
4320 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4321 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
4322 vc
->fd_read(vc
->opaque
, buf
, len
);
4327 /***********************************************************/
4328 /* savevm/loadvm support */
4330 #define IO_BUF_SIZE 32768
4333 QEMUFilePutBufferFunc
*put_buffer
;
4334 QEMUFileGetBufferFunc
*get_buffer
;
4335 QEMUFileCloseFunc
*close
;
4338 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4341 int buf_size
; /* 0 when writing */
4342 uint8_t buf
[IO_BUF_SIZE
];
4345 typedef struct QEMUFileFD
4350 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4352 QEMUFileFD
*s
= opaque
;
4357 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
4359 if (errno
== EINTR
|| errno
== EAGAIN
)
4366 QEMUFile
*qemu_fopen_fd(int fd
)
4368 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
4370 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
4373 typedef struct QEMUFileUnix
4378 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4380 QEMUFileUnix
*s
= opaque
;
4381 fseek(s
->outfile
, pos
, SEEK_SET
);
4382 fwrite(buf
, 1, size
, s
->outfile
);
4385 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4387 QEMUFileUnix
*s
= opaque
;
4388 fseek(s
->outfile
, pos
, SEEK_SET
);
4389 return fread(buf
, 1, size
, s
->outfile
);
4392 static void file_close(void *opaque
)
4394 QEMUFileUnix
*s
= opaque
;
4399 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
4403 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
4407 s
->outfile
= fopen(filename
, mode
);
4411 if (!strcmp(mode
, "wb"))
4412 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
4413 else if (!strcmp(mode
, "rb"))
4414 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
4423 typedef struct QEMUFileBdrv
4425 BlockDriverState
*bs
;
4426 int64_t base_offset
;
4429 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4431 QEMUFileBdrv
*s
= opaque
;
4432 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4435 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4437 QEMUFileBdrv
*s
= opaque
;
4438 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4441 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4445 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
4450 s
->base_offset
= offset
;
4453 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
4455 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
4458 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
4459 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
4463 f
= qemu_mallocz(sizeof(QEMUFile
));
4468 f
->put_buffer
= put_buffer
;
4469 f
->get_buffer
= get_buffer
;
4475 void qemu_fflush(QEMUFile
*f
)
4480 if (f
->buf_index
> 0) {
4481 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
4482 f
->buf_offset
+= f
->buf_index
;
4487 static void qemu_fill_buffer(QEMUFile
*f
)
4494 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
4500 f
->buf_offset
+= len
;
4503 void qemu_fclose(QEMUFile
*f
)
4507 f
->close(f
->opaque
);
4511 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4515 l
= IO_BUF_SIZE
- f
->buf_index
;
4518 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4522 if (f
->buf_index
>= IO_BUF_SIZE
)
4527 void qemu_put_byte(QEMUFile
*f
, int v
)
4529 f
->buf
[f
->buf_index
++] = v
;
4530 if (f
->buf_index
>= IO_BUF_SIZE
)
4534 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4540 l
= f
->buf_size
- f
->buf_index
;
4542 qemu_fill_buffer(f
);
4543 l
= f
->buf_size
- f
->buf_index
;
4549 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4554 return size1
- size
;
4557 int qemu_get_byte(QEMUFile
*f
)
4559 if (f
->buf_index
>= f
->buf_size
) {
4560 qemu_fill_buffer(f
);
4561 if (f
->buf_index
>= f
->buf_size
)
4564 return f
->buf
[f
->buf_index
++];
4567 int64_t qemu_ftell(QEMUFile
*f
)
4569 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4572 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4574 if (whence
== SEEK_SET
) {
4576 } else if (whence
== SEEK_CUR
) {
4577 pos
+= qemu_ftell(f
);
4579 /* SEEK_END not supported */
4582 if (f
->put_buffer
) {
4584 f
->buf_offset
= pos
;
4586 f
->buf_offset
= pos
;
4593 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4595 qemu_put_byte(f
, v
>> 8);
4596 qemu_put_byte(f
, v
);
4599 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4601 qemu_put_byte(f
, v
>> 24);
4602 qemu_put_byte(f
, v
>> 16);
4603 qemu_put_byte(f
, v
>> 8);
4604 qemu_put_byte(f
, v
);
4607 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4609 qemu_put_be32(f
, v
>> 32);
4610 qemu_put_be32(f
, v
);
4613 unsigned int qemu_get_be16(QEMUFile
*f
)
4616 v
= qemu_get_byte(f
) << 8;
4617 v
|= qemu_get_byte(f
);
4621 unsigned int qemu_get_be32(QEMUFile
*f
)
4624 v
= qemu_get_byte(f
) << 24;
4625 v
|= qemu_get_byte(f
) << 16;
4626 v
|= qemu_get_byte(f
) << 8;
4627 v
|= qemu_get_byte(f
);
4631 uint64_t qemu_get_be64(QEMUFile
*f
)
4634 v
= (uint64_t)qemu_get_be32(f
) << 32;
4635 v
|= qemu_get_be32(f
);
4639 typedef struct SaveStateEntry
{
4643 SaveStateHandler
*save_state
;
4644 LoadStateHandler
*load_state
;
4646 struct SaveStateEntry
*next
;
4649 static SaveStateEntry
*first_se
;
4651 int register_savevm(const char *idstr
,
4654 SaveStateHandler
*save_state
,
4655 LoadStateHandler
*load_state
,
4658 SaveStateEntry
*se
, **pse
;
4660 se
= qemu_malloc(sizeof(SaveStateEntry
));
4663 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4664 se
->instance_id
= instance_id
;
4665 se
->version_id
= version_id
;
4666 se
->save_state
= save_state
;
4667 se
->load_state
= load_state
;
4668 se
->opaque
= opaque
;
4671 /* add at the end of list */
4673 while (*pse
!= NULL
)
4674 pse
= &(*pse
)->next
;
4679 #define QEMU_VM_FILE_MAGIC 0x5145564d
4680 #define QEMU_VM_FILE_VERSION 0x00000002
4682 int qemu_savevm_state(QEMUFile
*f
)
4686 int64_t cur_pos
, len_pos
, total_len_pos
;
4688 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4689 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4690 total_len_pos
= qemu_ftell(f
);
4691 qemu_put_be64(f
, 0); /* total size */
4693 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4695 len
= strlen(se
->idstr
);
4696 qemu_put_byte(f
, len
);
4697 qemu_put_buffer(f
, se
->idstr
, len
);
4699 qemu_put_be32(f
, se
->instance_id
);
4700 qemu_put_be32(f
, se
->version_id
);
4702 /* record size: filled later */
4703 len_pos
= qemu_ftell(f
);
4704 qemu_put_be32(f
, 0);
4706 se
->save_state(f
, se
->opaque
);
4708 /* fill record size */
4709 cur_pos
= qemu_ftell(f
);
4710 len
= cur_pos
- len_pos
- 4;
4711 qemu_fseek(f
, len_pos
, SEEK_SET
);
4712 qemu_put_be32(f
, len
);
4713 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4715 cur_pos
= qemu_ftell(f
);
4716 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4717 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4718 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4724 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4728 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4729 if (!strcmp(se
->idstr
, idstr
) &&
4730 instance_id
== se
->instance_id
)
4736 int qemu_loadvm_state(QEMUFile
*f
)
4739 int len
, ret
, instance_id
, record_len
, version_id
;
4740 int64_t total_len
, end_pos
, cur_pos
;
4744 v
= qemu_get_be32(f
);
4745 if (v
!= QEMU_VM_FILE_MAGIC
)
4747 v
= qemu_get_be32(f
);
4748 if (v
!= QEMU_VM_FILE_VERSION
) {
4753 total_len
= qemu_get_be64(f
);
4754 end_pos
= total_len
+ qemu_ftell(f
);
4756 if (qemu_ftell(f
) >= end_pos
)
4758 len
= qemu_get_byte(f
);
4759 qemu_get_buffer(f
, idstr
, len
);
4761 instance_id
= qemu_get_be32(f
);
4762 version_id
= qemu_get_be32(f
);
4763 record_len
= qemu_get_be32(f
);
4765 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4766 idstr
, instance_id
, version_id
, record_len
);
4768 cur_pos
= qemu_ftell(f
);
4769 se
= find_se(idstr
, instance_id
);
4771 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4772 instance_id
, idstr
);
4774 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4776 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4777 instance_id
, idstr
);
4780 /* always seek to exact end of record */
4781 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4788 int qemu_live_savevm_state(QEMUFile
*f
)
4793 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4794 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4796 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4797 len
= strlen(se
->idstr
);
4799 qemu_put_byte(f
, len
);
4800 qemu_put_buffer(f
, se
->idstr
, len
);
4801 qemu_put_be32(f
, se
->instance_id
);
4802 qemu_put_be32(f
, se
->version_id
);
4804 se
->save_state(f
, se
->opaque
);
4807 qemu_put_byte(f
, 0);
4813 int qemu_live_loadvm_state(QEMUFile
*f
)
4816 int len
, ret
, instance_id
, version_id
;
4820 v
= qemu_get_be32(f
);
4821 if (v
!= QEMU_VM_FILE_MAGIC
)
4823 v
= qemu_get_be32(f
);
4824 if (v
!= QEMU_VM_FILE_VERSION
) {
4831 len
= qemu_get_byte(f
);
4834 qemu_get_buffer(f
, idstr
, len
);
4836 instance_id
= qemu_get_be32(f
);
4837 version_id
= qemu_get_be32(f
);
4838 se
= find_se(idstr
, instance_id
);
4840 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4841 instance_id
, idstr
);
4843 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4845 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4846 instance_id
, idstr
);
4852 qemu_announce_self();
4858 /* device can contain snapshots */
4859 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4862 !bdrv_is_removable(bs
) &&
4863 !bdrv_is_read_only(bs
));
4866 /* device must be snapshots in order to have a reliable snapshot */
4867 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4870 !bdrv_is_removable(bs
) &&
4871 !bdrv_is_read_only(bs
));
4874 static BlockDriverState
*get_bs_snapshots(void)
4876 BlockDriverState
*bs
;
4880 return bs_snapshots
;
4881 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4883 if (bdrv_can_snapshot(bs
))
4892 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
4895 QEMUSnapshotInfo
*sn_tab
, *sn
;
4899 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
4902 for(i
= 0; i
< nb_sns
; i
++) {
4904 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
4914 void do_savevm(const char *name
)
4916 BlockDriverState
*bs
, *bs1
;
4917 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
4918 int must_delete
, ret
, i
;
4919 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
4921 int saved_vm_running
;
4928 bs
= get_bs_snapshots();
4930 term_printf("No block device can accept snapshots\n");
4934 /* ??? Should this occur after vm_stop? */
4937 saved_vm_running
= vm_running
;
4942 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
4947 memset(sn
, 0, sizeof(*sn
));
4949 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
4950 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
4953 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
4956 /* fill auxiliary fields */
4959 sn
->date_sec
= tb
.time
;
4960 sn
->date_nsec
= tb
.millitm
* 1000000;
4962 gettimeofday(&tv
, NULL
);
4963 sn
->date_sec
= tv
.tv_sec
;
4964 sn
->date_nsec
= tv
.tv_usec
* 1000;
4966 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
4968 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
4969 term_printf("Device %s does not support VM state snapshots\n",
4970 bdrv_get_device_name(bs
));
4974 /* save the VM state */
4975 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
4977 term_printf("Could not open VM state file\n");
4980 ret
= qemu_savevm_state(f
);
4981 sn
->vm_state_size
= qemu_ftell(f
);
4984 term_printf("Error %d while writing VM\n", ret
);
4988 /* create the snapshots */
4990 for(i
= 0; i
< MAX_DISKS
; i
++) {
4992 if (bdrv_has_snapshot(bs1
)) {
4994 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
4996 term_printf("Error while deleting snapshot on '%s'\n",
4997 bdrv_get_device_name(bs1
));
5000 ret
= bdrv_snapshot_create(bs1
, sn
);
5002 term_printf("Error while creating snapshot on '%s'\n",
5003 bdrv_get_device_name(bs1
));
5009 if (saved_vm_running
)
5013 void do_loadvm(const char *name
)
5015 BlockDriverState
*bs
, *bs1
;
5016 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5019 int saved_vm_running
;
5021 bs
= get_bs_snapshots();
5023 term_printf("No block device supports snapshots\n");
5027 /* Flush all IO requests so they don't interfere with the new state. */
5030 saved_vm_running
= vm_running
;
5033 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5035 if (bdrv_has_snapshot(bs1
)) {
5036 ret
= bdrv_snapshot_goto(bs1
, name
);
5039 term_printf("Warning: ");
5042 term_printf("Snapshots not supported on device '%s'\n",
5043 bdrv_get_device_name(bs1
));
5046 term_printf("Could not find snapshot '%s' on device '%s'\n",
5047 name
, bdrv_get_device_name(bs1
));
5050 term_printf("Error %d while activating snapshot on '%s'\n",
5051 ret
, bdrv_get_device_name(bs1
));
5054 /* fatal on snapshot block device */
5061 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5062 term_printf("Device %s does not support VM state snapshots\n",
5063 bdrv_get_device_name(bs
));
5067 /* restore the VM state */
5068 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5070 term_printf("Could not open VM state file\n");
5073 ret
= qemu_loadvm_state(f
);
5076 term_printf("Error %d while loading VM state\n", ret
);
5079 if (saved_vm_running
)
5083 void do_delvm(const char *name
)
5085 BlockDriverState
*bs
, *bs1
;
5088 bs
= get_bs_snapshots();
5090 term_printf("No block device supports snapshots\n");
5094 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5096 if (bdrv_has_snapshot(bs1
)) {
5097 ret
= bdrv_snapshot_delete(bs1
, name
);
5099 if (ret
== -ENOTSUP
)
5100 term_printf("Snapshots not supported on device '%s'\n",
5101 bdrv_get_device_name(bs1
));
5103 term_printf("Error %d while deleting snapshot on '%s'\n",
5104 ret
, bdrv_get_device_name(bs1
));
5110 void do_info_snapshots(void)
5112 BlockDriverState
*bs
, *bs1
;
5113 QEMUSnapshotInfo
*sn_tab
, *sn
;
5117 bs
= get_bs_snapshots();
5119 term_printf("No available block device supports snapshots\n");
5122 term_printf("Snapshot devices:");
5123 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5125 if (bdrv_has_snapshot(bs1
)) {
5127 term_printf(" %s", bdrv_get_device_name(bs1
));
5132 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5134 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5137 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5138 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5139 for(i
= 0; i
< nb_sns
; i
++) {
5141 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5146 /***********************************************************/
5147 /* cpu save/restore */
5149 #if defined(TARGET_I386)
5151 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5153 qemu_put_be32(f
, dt
->selector
);
5154 qemu_put_betl(f
, dt
->base
);
5155 qemu_put_be32(f
, dt
->limit
);
5156 qemu_put_be32(f
, dt
->flags
);
5159 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5161 dt
->selector
= qemu_get_be32(f
);
5162 dt
->base
= qemu_get_betl(f
);
5163 dt
->limit
= qemu_get_be32(f
);
5164 dt
->flags
= qemu_get_be32(f
);
5167 void cpu_save(QEMUFile
*f
, void *opaque
)
5169 CPUState
*env
= opaque
;
5170 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5176 kvm_save_registers(env
);
5179 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5180 qemu_put_betls(f
, &env
->regs
[i
]);
5181 qemu_put_betls(f
, &env
->eip
);
5182 qemu_put_betls(f
, &env
->eflags
);
5183 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5184 qemu_put_be32s(f
, &hflags
);
5188 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5190 for(i
= 0; i
< 8; i
++) {
5191 fptag
|= ((!env
->fptags
[i
]) << i
);
5194 qemu_put_be16s(f
, &fpuc
);
5195 qemu_put_be16s(f
, &fpus
);
5196 qemu_put_be16s(f
, &fptag
);
5198 #ifdef USE_X86LDOUBLE
5203 qemu_put_be16s(f
, &fpregs_format
);
5205 for(i
= 0; i
< 8; i
++) {
5206 #ifdef USE_X86LDOUBLE
5210 /* we save the real CPU data (in case of MMX usage only 'mant'
5211 contains the MMX register */
5212 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5213 qemu_put_be64(f
, mant
);
5214 qemu_put_be16(f
, exp
);
5217 /* if we use doubles for float emulation, we save the doubles to
5218 avoid losing information in case of MMX usage. It can give
5219 problems if the image is restored on a CPU where long
5220 doubles are used instead. */
5221 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5225 for(i
= 0; i
< 6; i
++)
5226 cpu_put_seg(f
, &env
->segs
[i
]);
5227 cpu_put_seg(f
, &env
->ldt
);
5228 cpu_put_seg(f
, &env
->tr
);
5229 cpu_put_seg(f
, &env
->gdt
);
5230 cpu_put_seg(f
, &env
->idt
);
5232 qemu_put_be32s(f
, &env
->sysenter_cs
);
5233 qemu_put_be32s(f
, &env
->sysenter_esp
);
5234 qemu_put_be32s(f
, &env
->sysenter_eip
);
5236 qemu_put_betls(f
, &env
->cr
[0]);
5237 qemu_put_betls(f
, &env
->cr
[2]);
5238 qemu_put_betls(f
, &env
->cr
[3]);
5239 qemu_put_betls(f
, &env
->cr
[4]);
5241 for(i
= 0; i
< 8; i
++)
5242 qemu_put_betls(f
, &env
->dr
[i
]);
5245 qemu_put_be32s(f
, &env
->a20_mask
);
5248 qemu_put_be32s(f
, &env
->mxcsr
);
5249 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5250 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5251 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5254 #ifdef TARGET_X86_64
5255 qemu_put_be64s(f
, &env
->efer
);
5256 qemu_put_be64s(f
, &env
->star
);
5257 qemu_put_be64s(f
, &env
->lstar
);
5258 qemu_put_be64s(f
, &env
->cstar
);
5259 qemu_put_be64s(f
, &env
->fmask
);
5260 qemu_put_be64s(f
, &env
->kernelgsbase
);
5262 qemu_put_be32s(f
, &env
->smbase
);
5266 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5267 qemu_put_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
5269 qemu_put_be64s(f
, &env
->tsc
);
5275 #ifdef USE_X86LDOUBLE
5276 /* XXX: add that in a FPU generic layer */
5277 union x86_longdouble
{
5282 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5283 #define EXPBIAS1 1023
5284 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5285 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5287 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5291 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5292 /* exponent + sign */
5293 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5294 e
|= SIGND1(temp
) >> 16;
5299 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5301 CPUState
*env
= opaque
;
5304 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5306 if (version_id
!= 3 && version_id
!= 4)
5308 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5309 qemu_get_betls(f
, &env
->regs
[i
]);
5310 qemu_get_betls(f
, &env
->eip
);
5311 qemu_get_betls(f
, &env
->eflags
);
5312 qemu_get_be32s(f
, &hflags
);
5314 qemu_get_be16s(f
, &fpuc
);
5315 qemu_get_be16s(f
, &fpus
);
5316 qemu_get_be16s(f
, &fptag
);
5317 qemu_get_be16s(f
, &fpregs_format
);
5319 /* NOTE: we cannot always restore the FPU state if the image come
5320 from a host with a different 'USE_X86LDOUBLE' define. We guess
5321 if we are in an MMX state to restore correctly in that case. */
5322 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5323 for(i
= 0; i
< 8; i
++) {
5327 switch(fpregs_format
) {
5329 mant
= qemu_get_be64(f
);
5330 exp
= qemu_get_be16(f
);
5331 #ifdef USE_X86LDOUBLE
5332 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5334 /* difficult case */
5336 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5338 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5342 mant
= qemu_get_be64(f
);
5343 #ifdef USE_X86LDOUBLE
5345 union x86_longdouble
*p
;
5346 /* difficult case */
5347 p
= (void *)&env
->fpregs
[i
];
5352 fp64_to_fp80(p
, mant
);
5356 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5365 /* XXX: restore FPU round state */
5366 env
->fpstt
= (fpus
>> 11) & 7;
5367 env
->fpus
= fpus
& ~0x3800;
5369 for(i
= 0; i
< 8; i
++) {
5370 env
->fptags
[i
] = (fptag
>> i
) & 1;
5373 for(i
= 0; i
< 6; i
++)
5374 cpu_get_seg(f
, &env
->segs
[i
]);
5375 cpu_get_seg(f
, &env
->ldt
);
5376 cpu_get_seg(f
, &env
->tr
);
5377 cpu_get_seg(f
, &env
->gdt
);
5378 cpu_get_seg(f
, &env
->idt
);
5380 qemu_get_be32s(f
, &env
->sysenter_cs
);
5381 qemu_get_be32s(f
, &env
->sysenter_esp
);
5382 qemu_get_be32s(f
, &env
->sysenter_eip
);
5384 qemu_get_betls(f
, &env
->cr
[0]);
5385 qemu_get_betls(f
, &env
->cr
[2]);
5386 qemu_get_betls(f
, &env
->cr
[3]);
5387 qemu_get_betls(f
, &env
->cr
[4]);
5389 for(i
= 0; i
< 8; i
++)
5390 qemu_get_betls(f
, &env
->dr
[i
]);
5393 qemu_get_be32s(f
, &env
->a20_mask
);
5395 qemu_get_be32s(f
, &env
->mxcsr
);
5396 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5397 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5398 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5401 #ifdef TARGET_X86_64
5402 qemu_get_be64s(f
, &env
->efer
);
5403 qemu_get_be64s(f
, &env
->star
);
5404 qemu_get_be64s(f
, &env
->lstar
);
5405 qemu_get_be64s(f
, &env
->cstar
);
5406 qemu_get_be64s(f
, &env
->fmask
);
5407 qemu_get_be64s(f
, &env
->kernelgsbase
);
5409 if (version_id
>= 4)
5410 qemu_get_be32s(f
, &env
->smbase
);
5412 /* XXX: compute hflags from scratch, except for CPL and IIF */
5413 env
->hflags
= hflags
;
5417 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5418 qemu_get_betls(f
, &env
->kvm_interrupt_bitmap
[i
]);
5420 qemu_get_be64s(f
, &env
->tsc
);
5421 kvm_load_registers(env
);
5427 #elif defined(TARGET_PPC)
5428 void cpu_save(QEMUFile
*f
, void *opaque
)
5432 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5437 #elif defined(TARGET_MIPS)
5438 void cpu_save(QEMUFile
*f
, void *opaque
)
5442 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5447 #elif defined(TARGET_SPARC)
5448 void cpu_save(QEMUFile
*f
, void *opaque
)
5450 CPUState
*env
= opaque
;
5454 for(i
= 0; i
< 8; i
++)
5455 qemu_put_betls(f
, &env
->gregs
[i
]);
5456 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5457 qemu_put_betls(f
, &env
->regbase
[i
]);
5460 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5466 qemu_put_be32(f
, u
.i
);
5469 qemu_put_betls(f
, &env
->pc
);
5470 qemu_put_betls(f
, &env
->npc
);
5471 qemu_put_betls(f
, &env
->y
);
5473 qemu_put_be32(f
, tmp
);
5474 qemu_put_betls(f
, &env
->fsr
);
5475 qemu_put_betls(f
, &env
->tbr
);
5476 #ifndef TARGET_SPARC64
5477 qemu_put_be32s(f
, &env
->wim
);
5479 for(i
= 0; i
< 16; i
++)
5480 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5484 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5486 CPUState
*env
= opaque
;
5490 for(i
= 0; i
< 8; i
++)
5491 qemu_get_betls(f
, &env
->gregs
[i
]);
5492 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5493 qemu_get_betls(f
, &env
->regbase
[i
]);
5496 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5501 u
.i
= qemu_get_be32(f
);
5505 qemu_get_betls(f
, &env
->pc
);
5506 qemu_get_betls(f
, &env
->npc
);
5507 qemu_get_betls(f
, &env
->y
);
5508 tmp
= qemu_get_be32(f
);
5509 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5510 correctly updated */
5512 qemu_get_betls(f
, &env
->fsr
);
5513 qemu_get_betls(f
, &env
->tbr
);
5514 #ifndef TARGET_SPARC64
5515 qemu_get_be32s(f
, &env
->wim
);
5517 for(i
= 0; i
< 16; i
++)
5518 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5524 #elif defined(TARGET_ARM)
5526 /* ??? Need to implement these. */
5527 void cpu_save(QEMUFile
*f
, void *opaque
)
5531 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5538 #warning No CPU save/restore functions
5542 /***********************************************************/
5543 /* ram save/restore */
5545 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5549 v
= qemu_get_byte(f
);
5552 if (qemu_get_buffer(f
, buf
, len
) != len
)
5556 v
= qemu_get_byte(f
);
5557 memset(buf
, v
, len
);
5565 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5569 if (qemu_get_be32(f
) != phys_ram_size
)
5571 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5573 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5576 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5583 #define BDRV_HASH_BLOCK_SIZE 1024
5584 #define IOBUF_SIZE 4096
5585 #define RAM_CBLOCK_MAGIC 0xfabe
5587 typedef struct RamCompressState
{
5590 uint8_t buf
[IOBUF_SIZE
];
5593 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5596 memset(s
, 0, sizeof(*s
));
5598 ret
= deflateInit2(&s
->zstream
, 1,
5600 9, Z_DEFAULT_STRATEGY
);
5603 s
->zstream
.avail_out
= IOBUF_SIZE
;
5604 s
->zstream
.next_out
= s
->buf
;
5608 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5610 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5611 qemu_put_be16(s
->f
, len
);
5612 qemu_put_buffer(s
->f
, buf
, len
);
5615 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5619 s
->zstream
.avail_in
= len
;
5620 s
->zstream
.next_in
= (uint8_t *)buf
;
5621 while (s
->zstream
.avail_in
> 0) {
5622 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5625 if (s
->zstream
.avail_out
== 0) {
5626 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5627 s
->zstream
.avail_out
= IOBUF_SIZE
;
5628 s
->zstream
.next_out
= s
->buf
;
5634 static void ram_compress_close(RamCompressState
*s
)
5638 /* compress last bytes */
5640 ret
= deflate(&s
->zstream
, Z_FINISH
);
5641 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5642 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5644 ram_put_cblock(s
, s
->buf
, len
);
5646 s
->zstream
.avail_out
= IOBUF_SIZE
;
5647 s
->zstream
.next_out
= s
->buf
;
5648 if (ret
== Z_STREAM_END
)
5655 deflateEnd(&s
->zstream
);
5658 typedef struct RamDecompressState
{
5661 uint8_t buf
[IOBUF_SIZE
];
5662 } RamDecompressState
;
5664 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5667 memset(s
, 0, sizeof(*s
));
5669 ret
= inflateInit(&s
->zstream
);
5675 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5679 s
->zstream
.avail_out
= len
;
5680 s
->zstream
.next_out
= buf
;
5681 while (s
->zstream
.avail_out
> 0) {
5682 if (s
->zstream
.avail_in
== 0) {
5683 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5685 clen
= qemu_get_be16(s
->f
);
5686 if (clen
> IOBUF_SIZE
)
5688 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5689 s
->zstream
.avail_in
= clen
;
5690 s
->zstream
.next_in
= s
->buf
;
5692 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5693 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5700 static void ram_decompress_close(RamDecompressState
*s
)
5702 inflateEnd(&s
->zstream
);
5705 static void ram_save_live(QEMUFile
*f
, void *opaque
)
5709 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
5711 if (kvm_allowed
&& (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
5714 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
5715 qemu_put_be32(f
, addr
);
5716 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5719 qemu_put_be32(f
, 1);
5722 static void ram_save_static(QEMUFile
*f
, void *opaque
)
5725 RamCompressState s1
, *s
= &s1
;
5728 qemu_put_be32(f
, phys_ram_size
);
5729 if (ram_compress_open(s
, f
) < 0)
5731 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5733 if (tight_savevm_enabled
) {
5737 /* find if the memory block is available on a virtual
5740 for(j
= 0; j
< MAX_DISKS
; j
++) {
5742 sector_num
= bdrv_hash_find(bs_table
[j
],
5743 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5744 if (sector_num
>= 0)
5749 goto normal_compress
;
5752 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5753 ram_compress_buf(s
, buf
, 10);
5759 ram_compress_buf(s
, buf
, 1);
5760 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5763 ram_compress_close(s
);
5766 static void ram_save(QEMUFile
*f
, void *opaque
)
5768 int in_migration
= cpu_physical_memory_get_dirty_tracking();
5770 qemu_put_byte(f
, in_migration
);
5773 ram_save_live(f
, opaque
);
5775 ram_save_static(f
, opaque
);
5778 static int ram_load_live(QEMUFile
*f
, void *opaque
)
5783 addr
= qemu_get_be32(f
);
5787 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5793 static int ram_load_static(QEMUFile
*f
, void *opaque
)
5795 RamDecompressState s1
, *s
= &s1
;
5799 if (qemu_get_be32(f
) != phys_ram_size
)
5801 if (ram_decompress_open(s
, f
) < 0)
5803 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5804 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5805 fprintf(stderr
, "Error while reading ram block header\n");
5809 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5810 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5819 ram_decompress_buf(s
, buf
+ 1, 9);
5821 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5822 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5823 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5826 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5827 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5828 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5829 bs_index
, sector_num
);
5836 printf("Error block header\n");
5840 ram_decompress_close(s
);
5844 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5848 switch (version_id
) {
5850 ret
= ram_load_v1(f
, opaque
);
5853 if (qemu_get_byte(f
)) {
5854 ret
= ram_load_live(f
, opaque
);
5858 ret
= ram_load_static(f
, opaque
);
5868 /***********************************************************/
5869 /* bottom halves (can be seen as timers which expire ASAP) */
5878 static QEMUBH
*first_bh
= NULL
;
5880 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5883 bh
= qemu_mallocz(sizeof(QEMUBH
));
5887 bh
->opaque
= opaque
;
5891 int qemu_bh_poll(void)
5910 void qemu_bh_schedule(QEMUBH
*bh
)
5912 CPUState
*env
= cpu_single_env
;
5916 bh
->next
= first_bh
;
5919 /* stop the currently executing CPU to execute the BH ASAP */
5921 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5925 void qemu_bh_cancel(QEMUBH
*bh
)
5928 if (bh
->scheduled
) {
5931 pbh
= &(*pbh
)->next
;
5937 void qemu_bh_delete(QEMUBH
*bh
)
5943 /***********************************************************/
5944 /* machine registration */
5946 QEMUMachine
*first_machine
= NULL
;
5948 int qemu_register_machine(QEMUMachine
*m
)
5951 pm
= &first_machine
;
5959 QEMUMachine
*find_machine(const char *name
)
5963 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5964 if (!strcmp(m
->name
, name
))
5970 /***********************************************************/
5971 /* main execution loop */
5973 void gui_update(void *opaque
)
5975 display_state
.dpy_refresh(&display_state
);
5976 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
5979 struct vm_change_state_entry
{
5980 VMChangeStateHandler
*cb
;
5982 LIST_ENTRY (vm_change_state_entry
) entries
;
5985 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
5987 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
5990 VMChangeStateEntry
*e
;
5992 e
= qemu_mallocz(sizeof (*e
));
5998 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6002 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6004 LIST_REMOVE (e
, entries
);
6008 static void vm_state_notify(int running
)
6010 VMChangeStateEntry
*e
;
6012 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6013 e
->cb(e
->opaque
, running
);
6017 /* XXX: support several handlers */
6018 static VMStopHandler
*vm_stop_cb
;
6019 static void *vm_stop_opaque
;
6021 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6024 vm_stop_opaque
= opaque
;
6028 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6042 void vm_stop(int reason
)
6045 cpu_disable_ticks();
6049 vm_stop_cb(vm_stop_opaque
, reason
);
6056 /* reset/shutdown handler */
6058 typedef struct QEMUResetEntry
{
6059 QEMUResetHandler
*func
;
6061 struct QEMUResetEntry
*next
;
6064 static QEMUResetEntry
*first_reset_entry
;
6065 static int reset_requested
;
6066 static int shutdown_requested
;
6067 static int powerdown_requested
;
6069 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6071 QEMUResetEntry
**pre
, *re
;
6073 pre
= &first_reset_entry
;
6074 while (*pre
!= NULL
)
6075 pre
= &(*pre
)->next
;
6076 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6078 re
->opaque
= opaque
;
6083 static void qemu_system_reset(void)
6087 /* reset all devices */
6088 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6089 re
->func(re
->opaque
);
6093 void qemu_system_reset_request(void)
6096 shutdown_requested
= 1;
6098 reset_requested
= 1;
6101 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6104 void qemu_system_shutdown_request(void)
6106 shutdown_requested
= 1;
6108 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6111 void qemu_system_powerdown_request(void)
6113 powerdown_requested
= 1;
6115 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6118 void main_loop_wait(int timeout
)
6120 IOHandlerRecord
*ioh
, *ioh_next
;
6121 fd_set rfds
, wfds
, xfds
;
6127 /* XXX: need to suppress polling by better using win32 events */
6129 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6130 ret
|= pe
->func(pe
->opaque
);
6133 if (ret
== 0 && timeout
> 0) {
6135 WaitObjects
*w
= &wait_objects
;
6137 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6138 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6139 if (w
->func
[ret
- WAIT_OBJECT_0
])
6140 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6141 } else if (ret
== WAIT_TIMEOUT
) {
6143 err
= GetLastError();
6144 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6148 /* poll any events */
6149 /* XXX: separate device handlers from system ones */
6154 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6156 (!ioh
->fd_read_poll
||
6157 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6158 FD_SET(ioh
->fd
, &rfds
);
6162 if (ioh
->fd_write
) {
6163 FD_SET(ioh
->fd
, &wfds
);
6173 tv
.tv_usec
= timeout
* 1000;
6175 #if defined(CONFIG_SLIRP)
6177 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6180 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6182 /* XXX: better handling of removal */
6183 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh_next
) {
6184 ioh_next
= ioh
->next
;
6185 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6186 ioh
->fd_read(ioh
->opaque
);
6188 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6189 ioh
->fd_write(ioh
->opaque
);
6193 #if defined(CONFIG_SLIRP)
6200 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6207 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6208 qemu_get_clock(vm_clock
));
6209 /* run dma transfers, if any */
6213 /* real time timers */
6214 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6215 qemu_get_clock(rt_clock
));
6218 static CPUState
*cur_cpu
;
6223 #ifdef CONFIG_PROFILER
6228 cur_cpu
= first_cpu
;
6235 env
= env
->next_cpu
;
6238 #ifdef CONFIG_PROFILER
6239 ti
= profile_getclock();
6241 ret
= cpu_exec(env
);
6242 #ifdef CONFIG_PROFILER
6243 qemu_time
+= profile_getclock() - ti
;
6245 if (ret
!= EXCP_HALTED
)
6247 /* all CPUs are halted ? */
6248 if (env
== cur_cpu
) {
6255 if (shutdown_requested
) {
6256 ret
= EXCP_INTERRUPT
;
6259 if (reset_requested
) {
6260 reset_requested
= 0;
6261 qemu_system_reset();
6264 kvm_load_registers(env
);
6266 ret
= EXCP_INTERRUPT
;
6268 if (powerdown_requested
) {
6269 powerdown_requested
= 0;
6270 qemu_system_powerdown();
6271 ret
= EXCP_INTERRUPT
;
6273 if (ret
== EXCP_DEBUG
) {
6274 vm_stop(EXCP_DEBUG
);
6276 /* if hlt instruction, we wait until the next IRQ */
6277 /* XXX: use timeout computed from timers */
6278 if (ret
== EXCP_HLT
)
6285 #ifdef CONFIG_PROFILER
6286 ti
= profile_getclock();
6288 main_loop_wait(timeout
);
6289 #ifdef CONFIG_PROFILER
6290 dev_time
+= profile_getclock() - ti
;
6293 cpu_disable_ticks();
6299 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6300 "usage: %s [options] [disk_image]\n"
6302 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6304 "Standard options:\n"
6305 "-M machine select emulated machine (-M ? for list)\n"
6306 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6307 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6308 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6309 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6310 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6311 "-snapshot write to temporary files instead of disk image files\n"
6313 "-no-quit disable SDL window close capability\n"
6316 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6318 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6319 "-smp n set the number of CPUs to 'n' [default=1]\n"
6320 "-nographic disable graphical output and redirect serial I/Os to console\n"
6322 "-k language use keyboard layout (for example \"fr\" for French)\n"
6325 "-audio-help print list of audio drivers and their options\n"
6326 "-soundhw c1,... enable audio support\n"
6327 " and only specified sound cards (comma separated list)\n"
6328 " use -soundhw ? to get the list of supported cards\n"
6329 " use -soundhw all to enable all of them\n"
6331 "-localtime set the real time clock to local time [default=utc]\n"
6332 "-full-screen start in full screen\n"
6334 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6336 "-usb enable the USB driver (will be the default soon)\n"
6337 "-usbdevice name add the host or guest USB device 'name'\n"
6338 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6339 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6342 "Network options:\n"
6343 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6344 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6346 "-net user[,vlan=n][,hostname=host]\n"
6347 " connect the user mode network stack to VLAN 'n' and send\n"
6348 " hostname 'host' to DHCP clients\n"
6351 "-net tap[,vlan=n],ifname=name\n"
6352 " connect the host TAP network interface to VLAN 'n'\n"
6354 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6355 " connect the host TAP network interface to VLAN 'n' and use\n"
6356 " the network script 'file' (default=%s);\n"
6357 " use 'script=no' to disable script execution;\n"
6358 " use 'fd=h' to connect to an already opened TAP interface\n"
6360 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6361 " connect the vlan 'n' to another VLAN using a socket connection\n"
6362 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6363 " connect the vlan 'n' to multicast maddr and port\n"
6364 "-net none use it alone to have zero network devices; if no -net option\n"
6365 " is provided, the default is '-net nic -net user'\n"
6368 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6370 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6372 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6373 " redirect TCP or UDP connections from host to guest [-net user]\n"
6376 "Linux boot specific:\n"
6377 "-kernel bzImage use 'bzImage' as kernel image\n"
6378 "-append cmdline use 'cmdline' as kernel command line\n"
6379 "-initrd file use 'file' as initial ram disk\n"
6381 "Debug/Expert options:\n"
6382 "-monitor dev redirect the monitor to char device 'dev'\n"
6383 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6384 "-serial dev redirect the serial port to char device 'dev'\n"
6385 "-parallel dev redirect the parallel port to char device 'dev'\n"
6386 "-pidfile file Write PID to 'file'\n"
6387 "-S freeze CPU at startup (use 'c' to start execution)\n"
6388 "-s wait gdb connection to port %d\n"
6389 "-p port change gdb connection port\n"
6390 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6391 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6392 " translation (t=none or lba) (usually qemu can guess them)\n"
6393 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6395 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6396 "-no-kqemu disable KQEMU kernel module usage\n"
6399 "-no-kvm disable KVM hardware virtualization\n"
6401 #ifdef USE_CODE_COPY
6402 "-no-code-copy disable code copy acceleration\n"
6405 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6406 " (default is CL-GD5446 PCI VGA)\n"
6407 "-no-acpi disable ACPI\n"
6409 "-no-reboot exit instead of rebooting\n"
6410 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6411 "-vnc display start a VNC server on display\n"
6413 "-daemonize daemonize QEMU after initializing\n"
6415 "-option-rom rom load a file, rom, into the option ROM space\n"
6417 "During emulation, the following keys are useful:\n"
6418 "ctrl-alt-f toggle full screen\n"
6419 "ctrl-alt-n switch to virtual console 'n'\n"
6420 "ctrl-alt toggle mouse and keyboard grab\n"
6422 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6427 DEFAULT_NETWORK_SCRIPT
,
6429 DEFAULT_GDBSTUB_PORT
,
6434 #define HAS_ARG 0x0001
6448 QEMU_OPTION_snapshot
,
6450 QEMU_OPTION_no_fd_bootchk
,
6453 QEMU_OPTION_nographic
,
6455 QEMU_OPTION_audio_help
,
6456 QEMU_OPTION_soundhw
,
6474 QEMU_OPTION_no_code_copy
,
6476 QEMU_OPTION_localtime
,
6477 QEMU_OPTION_cirrusvga
,
6479 QEMU_OPTION_std_vga
,
6480 QEMU_OPTION_monitor
,
6481 QEMU_OPTION_vmchannel
,
6483 QEMU_OPTION_parallel
,
6485 QEMU_OPTION_full_screen
,
6486 QEMU_OPTION_no_quit
,
6487 QEMU_OPTION_pidfile
,
6488 QEMU_OPTION_no_kqemu
,
6489 QEMU_OPTION_kernel_kqemu
,
6490 QEMU_OPTION_win2k_hack
,
6492 QEMU_OPTION_usbdevice
,
6495 QEMU_OPTION_no_acpi
,
6497 QEMU_OPTION_no_reboot
,
6498 QEMU_OPTION_daemonize
,
6499 QEMU_OPTION_option_rom
,
6500 QEMU_OPTION_semihosting
,
6501 QEMU_OPTION_incoming
,
6504 typedef struct QEMUOption
{
6510 const QEMUOption qemu_options
[] = {
6511 { "h", 0, QEMU_OPTION_h
},
6512 { "help", 0, QEMU_OPTION_h
},
6514 { "M", HAS_ARG
, QEMU_OPTION_M
},
6515 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6516 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6517 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6518 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6519 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6520 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6521 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6522 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6523 { "snapshot", 0, QEMU_OPTION_snapshot
},
6525 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6527 { "m", HAS_ARG
, QEMU_OPTION_m
},
6528 { "nographic", 0, QEMU_OPTION_nographic
},
6529 { "k", HAS_ARG
, QEMU_OPTION_k
},
6531 { "audio-help", 0, QEMU_OPTION_audio_help
},
6532 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6535 { "net", HAS_ARG
, QEMU_OPTION_net
},
6537 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6539 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6541 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6544 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6545 { "append", HAS_ARG
, QEMU_OPTION_append
},
6546 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6548 { "S", 0, QEMU_OPTION_S
},
6549 { "s", 0, QEMU_OPTION_s
},
6550 { "p", HAS_ARG
, QEMU_OPTION_p
},
6551 { "d", HAS_ARG
, QEMU_OPTION_d
},
6552 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6553 { "L", HAS_ARG
, QEMU_OPTION_L
},
6554 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6556 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6557 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6560 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
6562 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6563 { "g", 1, QEMU_OPTION_g
},
6565 { "localtime", 0, QEMU_OPTION_localtime
},
6566 { "std-vga", 0, QEMU_OPTION_std_vga
},
6567 { "monitor", 1, QEMU_OPTION_monitor
},
6568 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
6569 { "serial", 1, QEMU_OPTION_serial
},
6570 { "parallel", 1, QEMU_OPTION_parallel
},
6571 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6572 { "incoming", 1, QEMU_OPTION_incoming
},
6573 { "full-screen", 0, QEMU_OPTION_full_screen
},
6575 { "no-quit", 0, QEMU_OPTION_no_quit
},
6577 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6578 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6579 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6580 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6581 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6583 /* temporary options */
6584 { "usb", 0, QEMU_OPTION_usb
},
6585 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6586 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6587 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6588 { "daemonize", 0, QEMU_OPTION_daemonize
},
6589 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6590 #if defined(TARGET_ARM)
6591 { "semihosting", 0, QEMU_OPTION_semihosting
},
6596 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6598 /* this stack is only used during signal handling */
6599 #define SIGNAL_STACK_SIZE 32768
6601 static uint8_t *signal_stack
;
6605 /* password input */
6607 static BlockDriverState
*get_bdrv(int index
)
6609 BlockDriverState
*bs
;
6612 bs
= bs_table
[index
];
6613 } else if (index
< 6) {
6614 bs
= fd_table
[index
- 4];
6621 static void read_passwords(void)
6623 BlockDriverState
*bs
;
6627 for(i
= 0; i
< 6; i
++) {
6629 if (bs
&& bdrv_is_encrypted(bs
)) {
6630 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6631 for(j
= 0; j
< 3; j
++) {
6632 monitor_readline("Password: ",
6633 1, password
, sizeof(password
));
6634 if (bdrv_set_key(bs
, password
) == 0)
6636 term_printf("invalid password\n");
6642 /* XXX: currently we cannot use simultaneously different CPUs */
6643 void register_machines(void)
6645 #if defined(TARGET_I386)
6646 qemu_register_machine(&pc_machine
);
6647 qemu_register_machine(&isapc_machine
);
6648 #elif defined(TARGET_PPC)
6649 qemu_register_machine(&heathrow_machine
);
6650 qemu_register_machine(&core99_machine
);
6651 qemu_register_machine(&prep_machine
);
6652 #elif defined(TARGET_MIPS)
6653 qemu_register_machine(&mips_machine
);
6654 qemu_register_machine(&mips_malta_machine
);
6655 #elif defined(TARGET_SPARC)
6656 #ifdef TARGET_SPARC64
6657 qemu_register_machine(&sun4u_machine
);
6659 qemu_register_machine(&sun4m_machine
);
6661 #elif defined(TARGET_ARM)
6662 qemu_register_machine(&integratorcp926_machine
);
6663 qemu_register_machine(&integratorcp1026_machine
);
6664 qemu_register_machine(&versatilepb_machine
);
6665 qemu_register_machine(&versatileab_machine
);
6666 qemu_register_machine(&realview_machine
);
6667 #elif defined(TARGET_SH4)
6668 qemu_register_machine(&shix_machine
);
6670 #error unsupported CPU
6675 struct soundhw soundhw
[] = {
6682 { .init_isa
= pcspk_audio_init
}
6687 "Creative Sound Blaster 16",
6690 { .init_isa
= SB16_init
}
6697 "Yamaha YMF262 (OPL3)",
6699 "Yamaha YM3812 (OPL2)",
6703 { .init_isa
= Adlib_init
}
6710 "Gravis Ultrasound GF1",
6713 { .init_isa
= GUS_init
}
6719 "ENSONIQ AudioPCI ES1370",
6722 { .init_pci
= es1370_init
}
6725 { NULL
, NULL
, 0, 0, { NULL
} }
6728 static void select_soundhw (const char *optarg
)
6732 if (*optarg
== '?') {
6735 printf ("Valid sound card names (comma separated):\n");
6736 for (c
= soundhw
; c
->name
; ++c
) {
6737 printf ("%-11s %s\n", c
->name
, c
->descr
);
6739 printf ("\n-soundhw all will enable all of the above\n");
6740 exit (*optarg
!= '?');
6748 if (!strcmp (optarg
, "all")) {
6749 for (c
= soundhw
; c
->name
; ++c
) {
6757 e
= strchr (p
, ',');
6758 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6760 for (c
= soundhw
; c
->name
; ++c
) {
6761 if (!strncmp (c
->name
, p
, l
)) {
6770 "Unknown sound card name (too big to show)\n");
6773 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6778 p
+= l
+ (e
!= NULL
);
6782 goto show_valid_cards
;
6788 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6790 exit(STATUS_CONTROL_C_EXIT
);
6795 #define MAX_NET_CLIENTS 32
6797 static int saved_argc
;
6798 static char **saved_argv
;
6800 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
6804 *opt_daemonize
= daemonize
;
6805 *opt_incoming
= incoming
;
6808 int main(int argc
, char **argv
)
6810 #ifdef CONFIG_GDBSTUB
6811 int use_gdbstub
, gdbstub_port
;
6814 int snapshot
, linux_boot
;
6815 const char *initrd_filename
;
6816 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6817 const char *kernel_filename
, *kernel_cmdline
;
6818 DisplayState
*ds
= &display_state
;
6819 int cyls
, heads
, secs
, translation
;
6820 char net_clients
[MAX_NET_CLIENTS
][256];
6823 const char *r
, *optarg
;
6824 CharDriverState
*monitor_hd
;
6825 char monitor_device
[128];
6826 char vmchannel_devices
[MAX_VMCHANNEL_DEVICES
][128];
6827 int vmchannel_device_index
;
6828 char serial_devices
[MAX_SERIAL_PORTS
][128];
6829 int serial_device_index
;
6830 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6831 int parallel_device_index
;
6832 const char *loadvm
= NULL
;
6833 QEMUMachine
*machine
;
6834 char usb_devices
[MAX_USB_CMDLINE
][128];
6835 int usb_devices_index
;
6841 LIST_INIT (&vm_change_state_head
);
6844 struct sigaction act
;
6845 sigfillset(&act
.sa_mask
);
6847 act
.sa_handler
= SIG_IGN
;
6848 sigaction(SIGPIPE
, &act
, NULL
);
6851 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6852 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6853 QEMU to run on a single CPU */
6858 h
= GetCurrentProcess();
6859 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6860 for(i
= 0; i
< 32; i
++) {
6861 if (mask
& (1 << i
))
6866 SetProcessAffinityMask(h
, mask
);
6872 register_machines();
6873 machine
= first_machine
;
6874 initrd_filename
= NULL
;
6875 for(i
= 0; i
< MAX_FD
; i
++)
6876 fd_filename
[i
] = NULL
;
6877 for(i
= 0; i
< MAX_DISKS
; i
++)
6878 hd_filename
[i
] = NULL
;
6879 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6880 vga_ram_size
= VGA_RAM_SIZE
;
6881 bios_size
= BIOS_SIZE
;
6882 #ifdef CONFIG_GDBSTUB
6884 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6888 kernel_filename
= NULL
;
6889 kernel_cmdline
= "";
6895 cyls
= heads
= secs
= 0;
6896 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6897 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6899 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++)
6900 vmchannel_devices
[i
][0] = '\0';
6901 vmchannel_device_index
= 0;
6903 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6904 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6905 serial_devices
[i
][0] = '\0';
6906 serial_device_index
= 0;
6908 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6909 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6910 parallel_devices
[i
][0] = '\0';
6911 parallel_device_index
= 0;
6913 usb_devices_index
= 0;
6918 /* default mac address of the first network interface */
6926 hd_filename
[0] = argv
[optind
++];
6928 const QEMUOption
*popt
;
6931 /* Treat --foo the same as -foo. */
6934 popt
= qemu_options
;
6937 fprintf(stderr
, "%s: invalid option -- '%s'\n",
6941 if (!strcmp(popt
->name
, r
+ 1))
6945 if (popt
->flags
& HAS_ARG
) {
6946 if (optind
>= argc
) {
6947 fprintf(stderr
, "%s: option '%s' requires an argument\n",
6951 optarg
= argv
[optind
++];
6956 switch(popt
->index
) {
6958 machine
= find_machine(optarg
);
6961 printf("Supported machines are:\n");
6962 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
6963 printf("%-10s %s%s\n",
6965 m
== first_machine
? " (default)" : "");
6970 case QEMU_OPTION_initrd
:
6971 initrd_filename
= optarg
;
6973 case QEMU_OPTION_hda
:
6974 case QEMU_OPTION_hdb
:
6975 case QEMU_OPTION_hdc
:
6976 case QEMU_OPTION_hdd
:
6979 hd_index
= popt
->index
- QEMU_OPTION_hda
;
6980 hd_filename
[hd_index
] = optarg
;
6981 if (hd_index
== cdrom_index
)
6985 case QEMU_OPTION_snapshot
:
6988 case QEMU_OPTION_hdachs
:
6992 cyls
= strtol(p
, (char **)&p
, 0);
6993 if (cyls
< 1 || cyls
> 16383)
6998 heads
= strtol(p
, (char **)&p
, 0);
6999 if (heads
< 1 || heads
> 16)
7004 secs
= strtol(p
, (char **)&p
, 0);
7005 if (secs
< 1 || secs
> 63)
7009 if (!strcmp(p
, "none"))
7010 translation
= BIOS_ATA_TRANSLATION_NONE
;
7011 else if (!strcmp(p
, "lba"))
7012 translation
= BIOS_ATA_TRANSLATION_LBA
;
7013 else if (!strcmp(p
, "auto"))
7014 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7017 } else if (*p
!= '\0') {
7019 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7024 case QEMU_OPTION_nographic
:
7025 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7026 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7029 case QEMU_OPTION_kernel
:
7030 kernel_filename
= optarg
;
7032 case QEMU_OPTION_append
:
7033 kernel_cmdline
= optarg
;
7035 case QEMU_OPTION_cdrom
:
7036 if (cdrom_index
>= 0) {
7037 hd_filename
[cdrom_index
] = optarg
;
7040 case QEMU_OPTION_boot
:
7041 boot_device
= optarg
[0];
7042 if (boot_device
!= 'a' &&
7043 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7045 boot_device
!= 'n' &&
7047 boot_device
!= 'c' && boot_device
!= 'd') {
7048 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7052 case QEMU_OPTION_fda
:
7053 fd_filename
[0] = optarg
;
7055 case QEMU_OPTION_fdb
:
7056 fd_filename
[1] = optarg
;
7059 case QEMU_OPTION_no_fd_bootchk
:
7063 case QEMU_OPTION_no_code_copy
:
7064 code_copy_enabled
= 0;
7066 case QEMU_OPTION_net
:
7067 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7068 fprintf(stderr
, "qemu: too many network clients\n");
7071 pstrcpy(net_clients
[nb_net_clients
],
7072 sizeof(net_clients
[0]),
7077 case QEMU_OPTION_tftp
:
7078 tftp_prefix
= optarg
;
7081 case QEMU_OPTION_smb
:
7082 net_slirp_smb(optarg
);
7085 case QEMU_OPTION_redir
:
7086 net_slirp_redir(optarg
);
7090 case QEMU_OPTION_audio_help
:
7094 case QEMU_OPTION_soundhw
:
7095 select_soundhw (optarg
);
7102 ram_size
= atoi(optarg
) * 1024 * 1024;
7105 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7106 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7107 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7116 mask
= cpu_str_to_log_mask(optarg
);
7118 printf("Log items (comma separated):\n");
7119 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7120 printf("%-10s %s\n", item
->name
, item
->help
);
7127 #ifdef CONFIG_GDBSTUB
7132 gdbstub_port
= atoi(optarg
);
7142 keyboard_layout
= optarg
;
7144 case QEMU_OPTION_localtime
:
7147 case QEMU_OPTION_cirrusvga
:
7148 cirrus_vga_enabled
= 1;
7150 case QEMU_OPTION_std_vga
:
7151 cirrus_vga_enabled
= 0;
7158 w
= strtol(p
, (char **)&p
, 10);
7161 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7167 h
= strtol(p
, (char **)&p
, 10);
7172 depth
= strtol(p
, (char **)&p
, 10);
7173 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7174 depth
!= 24 && depth
!= 32)
7176 } else if (*p
== '\0') {
7177 depth
= graphic_depth
;
7184 graphic_depth
= depth
;
7187 case QEMU_OPTION_monitor
:
7188 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7190 case QEMU_OPTION_vmchannel
:
7191 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
7192 fprintf(stderr
, "qemu: too many vmchannel devices\n");
7195 pstrcpy(vmchannel_devices
[vmchannel_device_index
],
7196 sizeof(vmchannel_devices
[0]), optarg
);
7197 vmchannel_device_index
++;
7199 case QEMU_OPTION_serial
:
7200 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7201 fprintf(stderr
, "qemu: too many serial ports\n");
7204 pstrcpy(serial_devices
[serial_device_index
],
7205 sizeof(serial_devices
[0]), optarg
);
7206 serial_device_index
++;
7208 case QEMU_OPTION_parallel
:
7209 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7210 fprintf(stderr
, "qemu: too many parallel ports\n");
7213 pstrcpy(parallel_devices
[parallel_device_index
],
7214 sizeof(parallel_devices
[0]), optarg
);
7215 parallel_device_index
++;
7217 case QEMU_OPTION_loadvm
:
7220 case QEMU_OPTION_incoming
:
7223 case QEMU_OPTION_full_screen
:
7227 case QEMU_OPTION_no_quit
:
7231 case QEMU_OPTION_pidfile
:
7232 create_pidfile(optarg
);
7235 case QEMU_OPTION_win2k_hack
:
7236 win2k_install_hack
= 1;
7240 case QEMU_OPTION_no_kqemu
:
7243 case QEMU_OPTION_kernel_kqemu
:
7248 case QEMU_OPTION_no_kvm
:
7252 case QEMU_OPTION_usb
:
7255 case QEMU_OPTION_usbdevice
:
7257 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7258 fprintf(stderr
, "Too many USB devices\n");
7261 pstrcpy(usb_devices
[usb_devices_index
],
7262 sizeof(usb_devices
[usb_devices_index
]),
7264 usb_devices_index
++;
7266 case QEMU_OPTION_smp
:
7267 smp_cpus
= atoi(optarg
);
7268 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7269 fprintf(stderr
, "Invalid number of CPUs\n");
7273 case QEMU_OPTION_vnc
:
7274 vnc_display
= optarg
;
7276 case QEMU_OPTION_no_acpi
:
7279 case QEMU_OPTION_no_reboot
:
7282 case QEMU_OPTION_daemonize
:
7285 case QEMU_OPTION_option_rom
:
7286 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7287 fprintf(stderr
, "Too many option ROMs\n");
7290 option_rom
[nb_option_roms
] = optarg
;
7293 case QEMU_OPTION_semihosting
:
7294 semihosting_enabled
= 1;
7304 if (pipe(fds
) == -1)
7315 len
= read(fds
[0], &status
, 1);
7316 if (len
== -1 && (errno
== EINTR
))
7319 if (len
!= 1 || status
!= 0)
7336 signal(SIGTSTP
, SIG_IGN
);
7337 signal(SIGTTOU
, SIG_IGN
);
7338 signal(SIGTTIN
, SIG_IGN
);
7344 if (kvm_qemu_init() < 0) {
7345 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
7355 linux_boot
= (kernel_filename
!= NULL
);
7358 hd_filename
[0] == '\0' &&
7359 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7360 fd_filename
[0] == '\0')
7363 /* boot to floppy or the default cd if no hard disk defined yet */
7364 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7365 if (fd_filename
[0] != '\0')
7371 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7381 /* init network clients */
7382 if (nb_net_clients
== 0) {
7383 /* if no clients, we use a default config */
7384 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7386 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7391 for(i
= 0;i
< nb_net_clients
; i
++) {
7392 if (net_client_init(net_clients
[i
]) < 0)
7397 if (boot_device
== 'n') {
7398 for (i
= 0; i
< nb_nics
; i
++) {
7399 const char *model
= nd_table
[i
].model
;
7403 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7404 if (get_image_size(buf
) > 0) {
7405 option_rom
[nb_option_roms
] = strdup(buf
);
7411 fprintf(stderr
, "No valid PXE rom found for network device\n");
7414 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7418 /* init the memory */
7419 phys_ram_size
= ram_size
+ vga_ram_size
+ bios_size
;
7422 for (i
= 0; i
< nb_option_roms
; i
++) {
7423 int ret
= get_image_size(option_rom
[i
]);
7425 fprintf(stderr
, "Could not load option rom '%s'\n", option_rom
[i
]);
7428 phys_ram_size
+= ret
;
7432 /* Initialize kvm */
7434 phys_ram_size
+= KVM_EXTRA_PAGES
* 4096;
7435 if (kvm_qemu_create_context() < 0) {
7436 fprintf(stderr
, "Could not create KVM context\n");
7440 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7441 if (!phys_ram_base
) {
7442 fprintf(stderr
, "Could not allocate physical memory\n");
7447 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7448 if (!phys_ram_base
) {
7449 fprintf(stderr
, "Could not allocate physical memory\n");
7454 /* we always create the cdrom drive, even if no disk is there */
7456 if (cdrom_index
>= 0) {
7457 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7458 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7461 /* open the virtual block devices */
7462 for(i
= 0; i
< MAX_DISKS
; i
++) {
7463 if (hd_filename
[i
]) {
7466 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7467 bs_table
[i
] = bdrv_new(buf
);
7469 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7470 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7474 if (i
== 0 && cyls
!= 0) {
7475 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7476 bdrv_set_translation_hint(bs_table
[i
], translation
);
7481 /* we always create at least one floppy disk */
7482 fd_table
[0] = bdrv_new("fda");
7483 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7485 for(i
= 0; i
< MAX_FD
; i
++) {
7486 if (fd_filename
[i
]) {
7489 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7490 fd_table
[i
] = bdrv_new(buf
);
7491 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7493 if (fd_filename
[i
] != '\0') {
7494 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7495 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7496 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7504 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7505 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
7511 dumb_display_init(ds
);
7512 } else if (vnc_display
!= NULL
) {
7513 vnc_display_init(ds
, vnc_display
);
7515 #if defined(CONFIG_SDL)
7516 sdl_display_init(ds
, full_screen
);
7517 #elif defined(CONFIG_COCOA)
7518 cocoa_display_init(ds
, full_screen
);
7520 dumb_display_init(ds
);
7524 monitor_hd
= qemu_chr_open(monitor_device
);
7526 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7529 monitor_init(monitor_hd
, !nographic
);
7531 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++) {
7532 const char *devname
= vmchannel_devices
[i
];
7533 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7537 if (strstart(devname
, "di:", &devname
)) {
7538 devid
= strtol(devname
, &termn
, 16);
7539 devname
= termn
+ 1;
7542 fprintf(stderr
, "qemu: could not find vmchannel device id '%s'\n",
7546 vmchannel_hds
[i
] = qemu_chr_open(devname
);
7547 if (!vmchannel_hds
[i
]) {
7548 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n",
7552 vmchannel_init(vmchannel_hds
[i
], devid
, i
);
7556 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7557 const char *devname
= serial_devices
[i
];
7558 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7559 serial_hds
[i
] = qemu_chr_open(devname
);
7560 if (!serial_hds
[i
]) {
7561 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7565 if (!strcmp(devname
, "vc"))
7566 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7570 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7571 const char *devname
= parallel_devices
[i
];
7572 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7573 parallel_hds
[i
] = qemu_chr_open(devname
);
7574 if (!parallel_hds
[i
]) {
7575 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7579 if (!strcmp(devname
, "vc"))
7580 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7584 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7585 ds
, fd_filename
, snapshot
,
7586 kernel_filename
, kernel_cmdline
, initrd_filename
);
7588 /* init USB devices */
7590 for(i
= 0; i
< usb_devices_index
; i
++) {
7591 if (usb_device_add(usb_devices
[i
]) < 0) {
7592 fprintf(stderr
, "Warning: could not add USB device %s\n",
7598 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7599 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7601 #ifdef CONFIG_GDBSTUB
7603 /* XXX: use standard host:port notation and modify options
7605 if (gdbserver_start_port(gdbstub_port
) < 0) {
7606 fprintf(stderr
, "qemu: could not open gdbstub device on port '%d'\n",
7619 rc
= migrate_incoming(incoming
);
7621 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
7627 /* XXX: simplify init */
7640 len
= write(fds
[1], &status
, 1);
7641 if (len
== -1 && (errno
== EINTR
))
7648 fd
= open("/dev/null", O_RDWR
);