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 int balloon_used
= 0;
157 CharDriverState
*vmchannel_hds
[MAX_VMCHANNEL_DEVICES
];
158 CharDriverState
*serial_hds
[MAX_SERIAL_PORTS
];
159 CharDriverState
*parallel_hds
[MAX_PARALLEL_PORTS
];
161 int win2k_install_hack
= 0;
164 static VLANState
*first_vlan
;
166 const char *vnc_display
;
167 #if defined(TARGET_SPARC)
169 #elif defined(TARGET_I386)
174 int acpi_enabled
= 1;
178 const char *incoming
;
179 const char *option_rom
[MAX_OPTION_ROMS
];
181 int semihosting_enabled
= 0;
183 int time_drift_fix
= 0;
184 const char *cpu_vendor_string
;
186 /***********************************************************/
187 /* x86 ISA bus support */
189 target_phys_addr_t isa_mem_base
= 0;
192 uint32_t default_ioport_readb(void *opaque
, uint32_t address
)
194 #ifdef DEBUG_UNUSED_IOPORT
195 fprintf(stderr
, "inb: port=0x%04x\n", address
);
200 void default_ioport_writeb(void *opaque
, uint32_t address
, uint32_t data
)
202 #ifdef DEBUG_UNUSED_IOPORT
203 fprintf(stderr
, "outb: port=0x%04x data=0x%02x\n", address
, data
);
207 /* default is to make two byte accesses */
208 uint32_t default_ioport_readw(void *opaque
, uint32_t address
)
211 data
= ioport_read_table
[0][address
](ioport_opaque
[address
], address
);
212 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
213 data
|= ioport_read_table
[0][address
](ioport_opaque
[address
], address
) << 8;
217 void default_ioport_writew(void *opaque
, uint32_t address
, uint32_t data
)
219 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, data
& 0xff);
220 address
= (address
+ 1) & (MAX_IOPORTS
- 1);
221 ioport_write_table
[0][address
](ioport_opaque
[address
], address
, (data
>> 8) & 0xff);
224 uint32_t default_ioport_readl(void *opaque
, uint32_t address
)
226 #ifdef DEBUG_UNUSED_IOPORT
227 fprintf(stderr
, "inl: port=0x%04x\n", address
);
232 void default_ioport_writel(void *opaque
, uint32_t address
, uint32_t data
)
234 #ifdef DEBUG_UNUSED_IOPORT
235 fprintf(stderr
, "outl: port=0x%04x data=0x%02x\n", address
, data
);
239 void init_ioports(void)
243 for(i
= 0; i
< MAX_IOPORTS
; i
++) {
244 ioport_read_table
[0][i
] = default_ioport_readb
;
245 ioport_write_table
[0][i
] = default_ioport_writeb
;
246 ioport_read_table
[1][i
] = default_ioport_readw
;
247 ioport_write_table
[1][i
] = default_ioport_writew
;
248 ioport_read_table
[2][i
] = default_ioport_readl
;
249 ioport_write_table
[2][i
] = default_ioport_writel
;
253 /* size is the word size in byte */
254 int register_ioport_read(int start
, int length
, int size
,
255 IOPortReadFunc
*func
, void *opaque
)
261 } else if (size
== 2) {
263 } else if (size
== 4) {
266 hw_error("register_ioport_read: invalid size");
269 for(i
= start
; i
< start
+ length
; i
+= size
) {
270 ioport_read_table
[bsize
][i
] = func
;
271 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
272 hw_error("register_ioport_read: invalid opaque");
273 ioport_opaque
[i
] = opaque
;
278 /* size is the word size in byte */
279 int register_ioport_write(int start
, int length
, int size
,
280 IOPortWriteFunc
*func
, void *opaque
)
286 } else if (size
== 2) {
288 } else if (size
== 4) {
291 hw_error("register_ioport_write: invalid size");
294 for(i
= start
; i
< start
+ length
; i
+= size
) {
295 ioport_write_table
[bsize
][i
] = func
;
296 if (ioport_opaque
[i
] != NULL
&& ioport_opaque
[i
] != opaque
)
297 hw_error("register_ioport_write: invalid opaque");
298 ioport_opaque
[i
] = opaque
;
303 void isa_unassign_ioport(int start
, int length
)
307 for(i
= start
; i
< start
+ length
; i
++) {
308 ioport_read_table
[0][i
] = default_ioport_readb
;
309 ioport_read_table
[1][i
] = default_ioport_readw
;
310 ioport_read_table
[2][i
] = default_ioport_readl
;
312 ioport_write_table
[0][i
] = default_ioport_writeb
;
313 ioport_write_table
[1][i
] = default_ioport_writew
;
314 ioport_write_table
[2][i
] = default_ioport_writel
;
318 /***********************************************************/
320 void cpu_outb(CPUState
*env
, int addr
, int val
)
323 if (loglevel
& CPU_LOG_IOPORT
)
324 fprintf(logfile
, "outb: %04x %02x\n", addr
, val
);
326 ioport_write_table
[0][addr
](ioport_opaque
[addr
], addr
, val
);
329 env
->last_io_time
= cpu_get_time_fast();
333 void cpu_outw(CPUState
*env
, int addr
, int val
)
336 if (loglevel
& CPU_LOG_IOPORT
)
337 fprintf(logfile
, "outw: %04x %04x\n", addr
, val
);
339 ioport_write_table
[1][addr
](ioport_opaque
[addr
], addr
, val
);
342 env
->last_io_time
= cpu_get_time_fast();
346 void cpu_outl(CPUState
*env
, int addr
, int val
)
349 if (loglevel
& CPU_LOG_IOPORT
)
350 fprintf(logfile
, "outl: %04x %08x\n", addr
, val
);
352 ioport_write_table
[2][addr
](ioport_opaque
[addr
], addr
, val
);
355 env
->last_io_time
= cpu_get_time_fast();
359 int cpu_inb(CPUState
*env
, int addr
)
362 val
= ioport_read_table
[0][addr
](ioport_opaque
[addr
], addr
);
364 if (loglevel
& CPU_LOG_IOPORT
)
365 fprintf(logfile
, "inb : %04x %02x\n", addr
, val
);
369 env
->last_io_time
= cpu_get_time_fast();
374 int cpu_inw(CPUState
*env
, int addr
)
377 val
= ioport_read_table
[1][addr
](ioport_opaque
[addr
], addr
);
379 if (loglevel
& CPU_LOG_IOPORT
)
380 fprintf(logfile
, "inw : %04x %04x\n", addr
, val
);
384 env
->last_io_time
= cpu_get_time_fast();
389 int cpu_inl(CPUState
*env
, int addr
)
392 val
= ioport_read_table
[2][addr
](ioport_opaque
[addr
], addr
);
394 if (loglevel
& CPU_LOG_IOPORT
)
395 fprintf(logfile
, "inl : %04x %08x\n", addr
, val
);
399 env
->last_io_time
= cpu_get_time_fast();
404 /***********************************************************/
405 void hw_error(const char *fmt
, ...)
411 fprintf(stderr
, "qemu: hardware error: ");
412 vfprintf(stderr
, fmt
, ap
);
413 fprintf(stderr
, "\n");
414 for(env
= first_cpu
; env
!= NULL
; env
= env
->next_cpu
) {
415 fprintf(stderr
, "CPU #%d:\n", env
->cpu_index
);
417 cpu_dump_state(env
, stderr
, fprintf
, X86_DUMP_FPU
);
419 cpu_dump_state(env
, stderr
, fprintf
, 0);
426 /***********************************************************/
429 static QEMUPutKBDEvent
*qemu_put_kbd_event
;
430 static void *qemu_put_kbd_event_opaque
;
431 static QEMUPutMouseEntry
*qemu_put_mouse_event_head
;
432 static QEMUPutMouseEntry
*qemu_put_mouse_event_current
;
434 void qemu_add_kbd_event_handler(QEMUPutKBDEvent
*func
, void *opaque
)
436 qemu_put_kbd_event_opaque
= opaque
;
437 qemu_put_kbd_event
= func
;
440 QEMUPutMouseEntry
*qemu_add_mouse_event_handler(QEMUPutMouseEvent
*func
,
441 void *opaque
, int absolute
,
444 QEMUPutMouseEntry
*s
, *cursor
;
446 s
= qemu_mallocz(sizeof(QEMUPutMouseEntry
));
450 s
->qemu_put_mouse_event
= func
;
451 s
->qemu_put_mouse_event_opaque
= opaque
;
452 s
->qemu_put_mouse_event_absolute
= absolute
;
453 s
->qemu_put_mouse_event_name
= qemu_strdup(name
);
456 if (!qemu_put_mouse_event_head
) {
457 qemu_put_mouse_event_head
= qemu_put_mouse_event_current
= s
;
461 cursor
= qemu_put_mouse_event_head
;
462 while (cursor
->next
!= NULL
)
463 cursor
= cursor
->next
;
466 qemu_put_mouse_event_current
= s
;
471 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry
*entry
)
473 QEMUPutMouseEntry
*prev
= NULL
, *cursor
;
475 if (!qemu_put_mouse_event_head
|| entry
== NULL
)
478 cursor
= qemu_put_mouse_event_head
;
479 while (cursor
!= NULL
&& cursor
!= entry
) {
481 cursor
= cursor
->next
;
484 if (cursor
== NULL
) // does not exist or list empty
486 else if (prev
== NULL
) { // entry is head
487 qemu_put_mouse_event_head
= cursor
->next
;
488 if (qemu_put_mouse_event_current
== entry
)
489 qemu_put_mouse_event_current
= cursor
->next
;
490 qemu_free(entry
->qemu_put_mouse_event_name
);
495 prev
->next
= entry
->next
;
497 if (qemu_put_mouse_event_current
== entry
)
498 qemu_put_mouse_event_current
= prev
;
500 qemu_free(entry
->qemu_put_mouse_event_name
);
504 void kbd_put_keycode(int keycode
)
506 if (qemu_put_kbd_event
) {
507 qemu_put_kbd_event(qemu_put_kbd_event_opaque
, keycode
);
511 void kbd_mouse_event(int dx
, int dy
, int dz
, int buttons_state
)
513 QEMUPutMouseEvent
*mouse_event
;
514 void *mouse_event_opaque
;
516 if (!qemu_put_mouse_event_current
) {
521 qemu_put_mouse_event_current
->qemu_put_mouse_event
;
523 qemu_put_mouse_event_current
->qemu_put_mouse_event_opaque
;
526 mouse_event(mouse_event_opaque
, dx
, dy
, dz
, buttons_state
);
530 int kbd_mouse_is_absolute(void)
532 if (!qemu_put_mouse_event_current
)
535 return qemu_put_mouse_event_current
->qemu_put_mouse_event_absolute
;
538 void do_info_mice(void)
540 QEMUPutMouseEntry
*cursor
;
543 if (!qemu_put_mouse_event_head
) {
544 term_printf("No mouse devices connected\n");
548 term_printf("Mouse devices available:\n");
549 cursor
= qemu_put_mouse_event_head
;
550 while (cursor
!= NULL
) {
551 term_printf("%c Mouse #%d: %s\n",
552 (cursor
== qemu_put_mouse_event_current
? '*' : ' '),
553 index
, cursor
->qemu_put_mouse_event_name
);
555 cursor
= cursor
->next
;
559 void do_mouse_set(int index
)
561 QEMUPutMouseEntry
*cursor
;
564 if (!qemu_put_mouse_event_head
) {
565 term_printf("No mouse devices connected\n");
569 cursor
= qemu_put_mouse_event_head
;
570 while (cursor
!= NULL
&& index
!= i
) {
572 cursor
= cursor
->next
;
576 qemu_put_mouse_event_current
= cursor
;
578 term_printf("Mouse at given index not found\n");
581 /* compute with 96 bit intermediate result: (a*b)/c */
582 uint64_t muldiv64(uint64_t a
, uint32_t b
, uint32_t c
)
587 #ifdef WORDS_BIGENDIAN
597 rl
= (uint64_t)u
.l
.low
* (uint64_t)b
;
598 rh
= (uint64_t)u
.l
.high
* (uint64_t)b
;
601 res
.l
.low
= (((rh
% c
) << 32) + (rl
& 0xffffffff)) / c
;
605 /***********************************************************/
606 /* real time host monotonic timer */
608 #define QEMU_TIMER_BASE 1000000000LL
612 static int64_t clock_freq
;
614 static void init_get_clock(void)
618 ret
= QueryPerformanceFrequency(&freq
);
620 fprintf(stderr
, "Could not calibrate ticks\n");
623 clock_freq
= freq
.QuadPart
;
626 static int64_t get_clock(void)
629 QueryPerformanceCounter(&ti
);
630 return muldiv64(ti
.QuadPart
, QEMU_TIMER_BASE
, clock_freq
);
635 static int use_rt_clock
;
637 static void init_get_clock(void)
640 #if defined(__linux__)
643 if (clock_gettime(CLOCK_MONOTONIC
, &ts
) == 0) {
650 static int64_t get_clock(void)
652 #if defined(__linux__)
655 clock_gettime(CLOCK_MONOTONIC
, &ts
);
656 return ts
.tv_sec
* 1000000000LL + ts
.tv_nsec
;
660 /* XXX: using gettimeofday leads to problems if the date
661 changes, so it should be avoided. */
663 gettimeofday(&tv
, NULL
);
664 return tv
.tv_sec
* 1000000000LL + (tv
.tv_usec
* 1000);
670 /***********************************************************/
671 /* guest cycle counter */
673 static int64_t cpu_ticks_prev
;
674 static int64_t cpu_ticks_offset
;
675 static int64_t cpu_clock_offset
;
676 static int cpu_ticks_enabled
;
678 /* return the host CPU cycle counter and handle stop/restart */
679 int64_t cpu_get_ticks(void)
681 if (!cpu_ticks_enabled
) {
682 return cpu_ticks_offset
;
685 ticks
= cpu_get_real_ticks();
686 if (cpu_ticks_prev
> ticks
) {
687 /* Note: non increasing ticks may happen if the host uses
689 cpu_ticks_offset
+= cpu_ticks_prev
- ticks
;
691 cpu_ticks_prev
= ticks
;
692 return ticks
+ cpu_ticks_offset
;
696 /* return the host CPU monotonic timer and handle stop/restart */
697 static int64_t cpu_get_clock(void)
700 if (!cpu_ticks_enabled
) {
701 return cpu_clock_offset
;
704 return ti
+ cpu_clock_offset
;
708 /* enable cpu_get_ticks() */
709 void cpu_enable_ticks(void)
711 if (!cpu_ticks_enabled
) {
712 cpu_ticks_offset
-= cpu_get_real_ticks();
713 cpu_clock_offset
-= get_clock();
714 cpu_ticks_enabled
= 1;
718 /* disable cpu_get_ticks() : the clock is stopped. You must not call
719 cpu_get_ticks() after that. */
720 void cpu_disable_ticks(void)
722 if (cpu_ticks_enabled
) {
723 cpu_ticks_offset
= cpu_get_ticks();
724 cpu_clock_offset
= cpu_get_clock();
725 cpu_ticks_enabled
= 0;
729 /***********************************************************/
732 #define QEMU_TIMER_REALTIME 0
733 #define QEMU_TIMER_VIRTUAL 1
737 /* XXX: add frequency */
745 struct QEMUTimer
*next
;
751 static QEMUTimer
*active_timers
[2];
753 static MMRESULT timerID
;
754 static HANDLE host_alarm
= NULL
;
755 static unsigned int period
= 1;
757 /* frequency of the times() clock tick */
758 static int timer_freq
;
761 QEMUClock
*qemu_new_clock(int type
)
764 clock
= qemu_mallocz(sizeof(QEMUClock
));
771 QEMUTimer
*qemu_new_timer(QEMUClock
*clock
, QEMUTimerCB
*cb
, void *opaque
)
775 ts
= qemu_mallocz(sizeof(QEMUTimer
));
782 void qemu_free_timer(QEMUTimer
*ts
)
787 /* stop a timer, but do not dealloc it */
788 void qemu_del_timer(QEMUTimer
*ts
)
792 /* NOTE: this code must be signal safe because
793 qemu_timer_expired() can be called from a signal. */
794 pt
= &active_timers
[ts
->clock
->type
];
807 /* modify the current timer so that it will be fired when current_time
808 >= expire_time. The corresponding callback will be called. */
809 void qemu_mod_timer(QEMUTimer
*ts
, int64_t expire_time
)
815 /* add the timer in the sorted list */
816 /* NOTE: this code must be signal safe because
817 qemu_timer_expired() can be called from a signal. */
818 pt
= &active_timers
[ts
->clock
->type
];
823 if (t
->expire_time
> expire_time
)
827 ts
->expire_time
= expire_time
;
832 int qemu_timer_pending(QEMUTimer
*ts
)
835 for(t
= active_timers
[ts
->clock
->type
]; t
!= NULL
; t
= t
->next
) {
842 static inline int qemu_timer_expired(QEMUTimer
*timer_head
, int64_t current_time
)
846 return (timer_head
->expire_time
<= current_time
);
849 static void qemu_run_timers(QEMUTimer
**ptimer_head
, int64_t current_time
)
855 if (!ts
|| ts
->expire_time
> current_time
)
857 /* remove timer from the list before calling the callback */
858 *ptimer_head
= ts
->next
;
861 /* run the callback (the timer list can be modified) */
866 int64_t qemu_get_clock(QEMUClock
*clock
)
868 switch(clock
->type
) {
869 case QEMU_TIMER_REALTIME
:
870 return get_clock() / 1000000;
872 case QEMU_TIMER_VIRTUAL
:
873 return cpu_get_clock();
877 static void init_timers(void)
880 ticks_per_sec
= QEMU_TIMER_BASE
;
881 rt_clock
= qemu_new_clock(QEMU_TIMER_REALTIME
);
882 vm_clock
= qemu_new_clock(QEMU_TIMER_VIRTUAL
);
886 void qemu_put_timer(QEMUFile
*f
, QEMUTimer
*ts
)
888 uint64_t expire_time
;
890 if (qemu_timer_pending(ts
)) {
891 expire_time
= ts
->expire_time
;
895 qemu_put_be64(f
, expire_time
);
898 void qemu_get_timer(QEMUFile
*f
, QEMUTimer
*ts
)
900 uint64_t expire_time
;
902 expire_time
= qemu_get_be64(f
);
903 if (expire_time
!= -1) {
904 qemu_mod_timer(ts
, expire_time
);
910 static void timer_save(QEMUFile
*f
, void *opaque
)
912 if (cpu_ticks_enabled
) {
913 hw_error("cannot save state if virtual timers are running");
915 qemu_put_be64s(f
, &cpu_ticks_offset
);
916 qemu_put_be64s(f
, &ticks_per_sec
);
917 qemu_put_be64s(f
, &cpu_clock_offset
);
920 static int timer_load(QEMUFile
*f
, void *opaque
, int version_id
)
922 if (version_id
!= 1 && version_id
!= 2)
924 if (cpu_ticks_enabled
) {
927 qemu_get_be64s(f
, &cpu_ticks_offset
);
928 qemu_get_be64s(f
, &ticks_per_sec
);
929 if (version_id
== 2) {
930 qemu_get_be64s(f
, &cpu_clock_offset
);
936 void CALLBACK
host_alarm_handler(UINT uTimerID
, UINT uMsg
,
937 DWORD_PTR dwUser
, DWORD_PTR dw1
, DWORD_PTR dw2
)
939 static void host_alarm_handler(int host_signum
)
943 #define DISP_FREQ 1000
945 static int64_t delta_min
= INT64_MAX
;
946 static int64_t delta_max
, delta_cum
, last_clock
, delta
, ti
;
948 ti
= qemu_get_clock(vm_clock
);
949 if (last_clock
!= 0) {
950 delta
= ti
- last_clock
;
951 if (delta
< delta_min
)
953 if (delta
> delta_max
)
956 if (++count
== DISP_FREQ
) {
957 printf("timer: min=%" PRId64
" us max=%" PRId64
" us avg=%" PRId64
" us avg_freq=%0.3f Hz\n",
958 muldiv64(delta_min
, 1000000, ticks_per_sec
),
959 muldiv64(delta_max
, 1000000, ticks_per_sec
),
960 muldiv64(delta_cum
, 1000000 / DISP_FREQ
, ticks_per_sec
),
961 (double)ticks_per_sec
/ ((double)delta_cum
/ DISP_FREQ
));
963 delta_min
= INT64_MAX
;
971 if (qemu_timer_expired(active_timers
[QEMU_TIMER_VIRTUAL
],
972 qemu_get_clock(vm_clock
)) ||
973 qemu_timer_expired(active_timers
[QEMU_TIMER_REALTIME
],
974 qemu_get_clock(rt_clock
))) {
976 SetEvent(host_alarm
);
978 CPUState
*env
= cpu_single_env
;
980 /* stop the currently executing cpu because a timer occured */
981 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
983 if (env
->kqemu_enabled
) {
984 kqemu_cpu_interrupt(env
);
993 #if defined(__linux__)
995 #define RTC_FREQ 1024
997 static int use_rtc
= 1;
1000 static int start_rtc_timer(void)
1002 rtc_fd
= open("/dev/rtc", O_RDONLY
);
1005 if (ioctl(rtc_fd
, RTC_IRQP_SET
, RTC_FREQ
) < 0) {
1006 fprintf(stderr
, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1007 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1008 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1011 if (ioctl(rtc_fd
, RTC_PIE_ON
, 0) < 0) {
1016 pit_min_timer_count
= PIT_FREQ
/ RTC_FREQ
;
1022 static int start_rtc_timer(void)
1027 #endif /* !defined(__linux__) */
1029 #endif /* !defined(_WIN32) */
1031 static void init_timer_alarm(void)
1038 ZeroMemory(&tc
, sizeof(TIMECAPS
));
1039 timeGetDevCaps(&tc
, sizeof(TIMECAPS
));
1040 if (period
< tc
.wPeriodMin
)
1041 period
= tc
.wPeriodMin
;
1042 timeBeginPeriod(period
);
1043 timerID
= timeSetEvent(1, // interval (ms)
1044 period
, // resolution
1045 host_alarm_handler
, // function
1046 (DWORD
)&count
, // user parameter
1047 TIME_PERIODIC
| TIME_CALLBACK_FUNCTION
);
1049 perror("failed timer alarm");
1052 host_alarm
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
1054 perror("failed CreateEvent");
1057 qemu_add_wait_object(host_alarm
, NULL
, NULL
);
1059 pit_min_timer_count
= ((uint64_t)10000 * PIT_FREQ
) / 1000000;
1062 struct sigaction act
;
1063 struct itimerval itv
;
1065 /* get times() syscall frequency */
1066 timer_freq
= sysconf(_SC_CLK_TCK
);
1069 sigfillset(&act
.sa_mask
);
1071 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1072 act
.sa_flags
|= SA_ONSTACK
;
1074 act
.sa_handler
= host_alarm_handler
;
1075 sigaction(SIGALRM
, &act
, NULL
);
1077 itv
.it_interval
.tv_sec
= 0;
1078 itv
.it_interval
.tv_usec
= 999; /* for i386 kernel 2.6 to get 1 ms */
1079 itv
.it_value
.tv_sec
= 0;
1080 itv
.it_value
.tv_usec
= 10 * 1000;
1081 setitimer(ITIMER_REAL
, &itv
, NULL
);
1082 /* we probe the tick duration of the kernel to inform the user if
1083 the emulated kernel requested a too high timer frequency */
1084 getitimer(ITIMER_REAL
, &itv
);
1086 #if defined(__linux__)
1087 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1088 have timers with 1 ms resolution. The correct solution will
1089 be to use the POSIX real time timers available in recent
1091 if (itv
.it_interval
.tv_usec
> 1000 || 1) {
1092 /* try to use /dev/rtc to have a faster timer */
1093 if (!use_rtc
|| (start_rtc_timer() < 0))
1095 /* disable itimer */
1096 itv
.it_interval
.tv_sec
= 0;
1097 itv
.it_interval
.tv_usec
= 0;
1098 itv
.it_value
.tv_sec
= 0;
1099 itv
.it_value
.tv_usec
= 0;
1100 setitimer(ITIMER_REAL
, &itv
, NULL
);
1103 sigaction(SIGIO
, &act
, NULL
);
1104 fcntl(rtc_fd
, F_SETFL
, O_ASYNC
);
1105 fcntl(rtc_fd
, F_SETOWN
, getpid());
1107 #endif /* defined(__linux__) */
1110 pit_min_timer_count
= ((uint64_t)itv
.it_interval
.tv_usec
*
1111 PIT_FREQ
) / 1000000;
1117 void quit_timers(void)
1120 timeKillEvent(timerID
);
1121 timeEndPeriod(period
);
1123 CloseHandle(host_alarm
);
1129 /***********************************************************/
1130 /* character device */
1132 static void qemu_chr_event(CharDriverState
*s
, int event
)
1136 s
->chr_event(s
->handler_opaque
, event
);
1139 static void qemu_chr_reset_bh(void *opaque
)
1141 CharDriverState
*s
= opaque
;
1142 qemu_chr_event(s
, CHR_EVENT_RESET
);
1143 qemu_bh_delete(s
->bh
);
1147 void qemu_chr_reset(CharDriverState
*s
)
1149 if (s
->bh
== NULL
) {
1150 s
->bh
= qemu_bh_new(qemu_chr_reset_bh
, s
);
1151 qemu_bh_schedule(s
->bh
);
1155 int qemu_chr_write(CharDriverState
*s
, const uint8_t *buf
, int len
)
1157 return s
->chr_write(s
, buf
, len
);
1160 int qemu_chr_ioctl(CharDriverState
*s
, int cmd
, void *arg
)
1164 return s
->chr_ioctl(s
, cmd
, arg
);
1167 int qemu_chr_can_read(CharDriverState
*s
)
1169 if (!s
->chr_can_read
)
1171 return s
->chr_can_read(s
->handler_opaque
);
1174 void qemu_chr_read(CharDriverState
*s
, uint8_t *buf
, int len
)
1176 s
->chr_read(s
->handler_opaque
, buf
, len
);
1180 void qemu_chr_printf(CharDriverState
*s
, const char *fmt
, ...)
1185 vsnprintf(buf
, sizeof(buf
), fmt
, ap
);
1186 qemu_chr_write(s
, buf
, strlen(buf
));
1190 void qemu_chr_send_event(CharDriverState
*s
, int event
)
1192 if (s
->chr_send_event
)
1193 s
->chr_send_event(s
, event
);
1196 void qemu_chr_add_handlers(CharDriverState
*s
,
1197 IOCanRWHandler
*fd_can_read
,
1198 IOReadHandler
*fd_read
,
1199 IOEventHandler
*fd_event
,
1202 s
->chr_can_read
= fd_can_read
;
1203 s
->chr_read
= fd_read
;
1204 s
->chr_event
= fd_event
;
1205 s
->handler_opaque
= opaque
;
1206 if (s
->chr_update_read_handler
)
1207 s
->chr_update_read_handler(s
);
1210 static int null_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1215 static CharDriverState
*qemu_chr_open_null(void)
1217 CharDriverState
*chr
;
1219 chr
= qemu_mallocz(sizeof(CharDriverState
));
1222 chr
->chr_write
= null_chr_write
;
1228 static void socket_cleanup(void)
1233 static int socket_init(void)
1238 ret
= WSAStartup(MAKEWORD(2,2), &Data
);
1240 err
= WSAGetLastError();
1241 fprintf(stderr
, "WSAStartup: %d\n", err
);
1244 atexit(socket_cleanup
);
1248 static int send_all(int fd
, const uint8_t *buf
, int len1
)
1254 ret
= send(fd
, buf
, len
, 0);
1257 errno
= WSAGetLastError();
1258 if (errno
!= WSAEWOULDBLOCK
) {
1261 } else if (ret
== 0) {
1271 void socket_set_nonblock(int fd
)
1273 unsigned long opt
= 1;
1274 ioctlsocket(fd
, FIONBIO
, &opt
);
1279 static int unix_write(int fd
, const uint8_t *buf
, int len1
)
1285 ret
= write(fd
, buf
, len
);
1287 if (errno
!= EINTR
&& errno
!= EAGAIN
)
1289 } else if (ret
== 0) {
1299 static inline int send_all(int fd
, const uint8_t *buf
, int len1
)
1301 return unix_write(fd
, buf
, len1
);
1304 void socket_set_nonblock(int fd
)
1306 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1308 #endif /* !_WIN32 */
1317 #define STDIO_MAX_CLIENTS 2
1319 static int stdio_nb_clients
;
1320 static CharDriverState
*stdio_clients
[STDIO_MAX_CLIENTS
];
1322 static int fd_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1324 FDCharDriver
*s
= chr
->opaque
;
1325 return unix_write(s
->fd_out
, buf
, len
);
1328 static int fd_chr_read_poll(void *opaque
)
1330 CharDriverState
*chr
= opaque
;
1331 FDCharDriver
*s
= chr
->opaque
;
1333 s
->max_size
= qemu_chr_can_read(chr
);
1337 static void fd_chr_read(void *opaque
)
1339 CharDriverState
*chr
= opaque
;
1340 FDCharDriver
*s
= chr
->opaque
;
1345 if (len
> s
->max_size
)
1349 size
= read(s
->fd_in
, buf
, len
);
1351 /* FD has been closed. Remove it from the active list. */
1352 qemu_set_fd_handler2(s
->fd_in
, NULL
, NULL
, NULL
, NULL
);
1356 qemu_chr_read(chr
, buf
, size
);
1360 static void fd_chr_update_read_handler(CharDriverState
*chr
)
1362 FDCharDriver
*s
= chr
->opaque
;
1364 if (s
->fd_in
>= 0) {
1365 if (nographic
&& s
->fd_in
== 0) {
1367 qemu_set_fd_handler2(s
->fd_in
, fd_chr_read_poll
,
1368 fd_chr_read
, NULL
, chr
);
1373 /* open a character device to a unix fd */
1374 static CharDriverState
*qemu_chr_open_fd(int fd_in
, int fd_out
)
1376 CharDriverState
*chr
;
1379 chr
= qemu_mallocz(sizeof(CharDriverState
));
1382 s
= qemu_mallocz(sizeof(FDCharDriver
));
1390 chr
->chr_write
= fd_chr_write
;
1391 chr
->chr_update_read_handler
= fd_chr_update_read_handler
;
1393 qemu_chr_reset(chr
);
1398 static CharDriverState
*qemu_chr_open_file_out(const char *file_out
)
1402 fd_out
= open(file_out
, O_WRONLY
| O_TRUNC
| O_CREAT
| O_BINARY
, 0666);
1405 return qemu_chr_open_fd(-1, fd_out
);
1408 static CharDriverState
*qemu_chr_open_pipe(const char *filename
)
1411 char filename_in
[256], filename_out
[256];
1413 snprintf(filename_in
, 256, "%s.in", filename
);
1414 snprintf(filename_out
, 256, "%s.out", filename
);
1415 fd_in
= open(filename_in
, O_RDWR
| O_BINARY
);
1416 fd_out
= open(filename_out
, O_RDWR
| O_BINARY
);
1417 if (fd_in
< 0 || fd_out
< 0) {
1422 fd_in
= fd_out
= open(filename
, O_RDWR
| O_BINARY
);
1426 return qemu_chr_open_fd(fd_in
, fd_out
);
1430 /* for STDIO, we handle the case where several clients use it
1433 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1435 #define TERM_FIFO_MAX_SIZE 1
1437 static int term_got_escape
, client_index
;
1438 static uint8_t term_fifo
[TERM_FIFO_MAX_SIZE
];
1439 static int term_fifo_size
;
1440 static int term_timestamps
;
1441 static int64_t term_timestamps_start
;
1443 void term_print_help(void)
1446 "C-a h print this help\n"
1447 "C-a x exit emulator\n"
1448 "C-a s save disk data back to file (if -snapshot)\n"
1449 "C-a b send break (magic sysrq)\n"
1450 "C-a t toggle console timestamps\n"
1451 "C-a c switch between console and monitor\n"
1452 "C-a C-a send C-a\n"
1456 /* called when a char is received */
1457 static void stdio_received_byte(int ch
)
1459 if (term_got_escape
) {
1460 term_got_escape
= 0;
1471 for (i
= 0; i
< MAX_DISKS
; i
++) {
1473 bdrv_commit(bs_table
[i
]);
1478 if (client_index
< stdio_nb_clients
) {
1479 CharDriverState
*chr
;
1482 chr
= stdio_clients
[client_index
];
1484 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
1489 if (client_index
>= stdio_nb_clients
)
1491 if (client_index
== 0) {
1492 /* send a new line in the monitor to get the prompt */
1498 term_timestamps
= !term_timestamps
;
1499 term_timestamps_start
= -1;
1504 } else if (ch
== TERM_ESCAPE
) {
1505 term_got_escape
= 1;
1508 if (client_index
< stdio_nb_clients
) {
1510 CharDriverState
*chr
;
1512 chr
= stdio_clients
[client_index
];
1513 if (qemu_chr_can_read(chr
) > 0) {
1515 qemu_chr_read(chr
, buf
, 1);
1516 } else if (term_fifo_size
== 0) {
1517 term_fifo
[term_fifo_size
++] = ch
;
1523 static int stdio_read_poll(void *opaque
)
1525 CharDriverState
*chr
;
1527 if (client_index
< stdio_nb_clients
) {
1528 chr
= stdio_clients
[client_index
];
1529 /* try to flush the queue if needed */
1530 if (term_fifo_size
!= 0 && qemu_chr_can_read(chr
) > 0) {
1531 qemu_chr_read(chr
, term_fifo
, 1);
1534 /* see if we can absorb more chars */
1535 if (term_fifo_size
== 0)
1544 static void stdio_read(void *opaque
)
1549 size
= read(0, buf
, 1);
1551 /* stdin has been closed. Remove it from the active list. */
1552 qemu_set_fd_handler2(0, NULL
, NULL
, NULL
, NULL
);
1556 stdio_received_byte(buf
[0]);
1559 static int stdio_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
1561 FDCharDriver
*s
= chr
->opaque
;
1562 if (!term_timestamps
) {
1563 return unix_write(s
->fd_out
, buf
, len
);
1568 for(i
= 0; i
< len
; i
++) {
1569 unix_write(s
->fd_out
, buf
+ i
, 1);
1570 if (buf
[i
] == '\n') {
1575 if (term_timestamps_start
== -1)
1576 term_timestamps_start
= ti
;
1577 ti
-= term_timestamps_start
;
1578 secs
= ti
/ 1000000000;
1579 snprintf(buf1
, sizeof(buf1
),
1580 "[%02d:%02d:%02d.%03d] ",
1584 (int)((ti
/ 1000000) % 1000));
1585 unix_write(s
->fd_out
, buf1
, strlen(buf1
));
1592 /* init terminal so that we can grab keys */
1593 static struct termios oldtty
;
1594 static int old_fd0_flags
;
1596 static void term_exit(void)
1598 tcsetattr (0, TCSANOW
, &oldtty
);
1599 fcntl(0, F_SETFL
, old_fd0_flags
);
1602 static void term_init(void)
1606 tcgetattr (0, &tty
);
1608 old_fd0_flags
= fcntl(0, F_GETFL
);
1610 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1611 |INLCR
|IGNCR
|ICRNL
|IXON
);
1612 tty
.c_oflag
|= OPOST
;
1613 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
);
1614 /* if graphical mode, we allow Ctrl-C handling */
1616 tty
.c_lflag
&= ~ISIG
;
1617 tty
.c_cflag
&= ~(CSIZE
|PARENB
);
1620 tty
.c_cc
[VTIME
] = 0;
1622 tcsetattr (0, TCSANOW
, &tty
);
1626 fcntl(0, F_SETFL
, O_NONBLOCK
);
1629 static CharDriverState
*qemu_chr_open_stdio(void)
1631 CharDriverState
*chr
;
1634 if (stdio_nb_clients
>= STDIO_MAX_CLIENTS
)
1636 chr
= qemu_chr_open_fd(0, 1);
1637 chr
->chr_write
= stdio_write
;
1638 if (stdio_nb_clients
== 0)
1639 qemu_set_fd_handler2(0, stdio_read_poll
, stdio_read
, NULL
, NULL
);
1640 client_index
= stdio_nb_clients
;
1642 if (stdio_nb_clients
!= 0)
1644 chr
= qemu_chr_open_fd(0, 1);
1646 stdio_clients
[stdio_nb_clients
++] = chr
;
1647 if (stdio_nb_clients
== 1) {
1648 /* set the terminal in raw mode */
1654 #if defined(__linux__)
1655 static CharDriverState
*qemu_chr_open_pty(void)
1658 char slave_name
[1024];
1659 int master_fd
, slave_fd
;
1661 /* Not satisfying */
1662 if (openpty(&master_fd
, &slave_fd
, slave_name
, NULL
, NULL
) < 0) {
1666 /* Disabling local echo and line-buffered output */
1667 tcgetattr (master_fd
, &tty
);
1668 tty
.c_lflag
&= ~(ECHO
|ICANON
|ISIG
);
1670 tty
.c_cc
[VTIME
] = 0;
1671 tcsetattr (master_fd
, TCSAFLUSH
, &tty
);
1673 fprintf(stderr
, "char device redirected to %s\n", slave_name
);
1674 return qemu_chr_open_fd(master_fd
, master_fd
);
1677 static void tty_serial_init(int fd
, int speed
,
1678 int parity
, int data_bits
, int stop_bits
)
1684 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1685 speed
, parity
, data_bits
, stop_bits
);
1687 tcgetattr (fd
, &tty
);
1729 cfsetispeed(&tty
, spd
);
1730 cfsetospeed(&tty
, spd
);
1732 tty
.c_iflag
&= ~(IGNBRK
|BRKINT
|PARMRK
|ISTRIP
1733 |INLCR
|IGNCR
|ICRNL
|IXON
);
1734 tty
.c_oflag
|= OPOST
;
1735 tty
.c_lflag
&= ~(ECHO
|ECHONL
|ICANON
|IEXTEN
|ISIG
);
1736 tty
.c_cflag
&= ~(CSIZE
|PARENB
|PARODD
|CRTSCTS
|CSTOPB
);
1757 tty
.c_cflag
|= PARENB
;
1760 tty
.c_cflag
|= PARENB
| PARODD
;
1764 tty
.c_cflag
|= CSTOPB
;
1766 tcsetattr (fd
, TCSANOW
, &tty
);
1769 static int tty_serial_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1771 FDCharDriver
*s
= chr
->opaque
;
1774 case CHR_IOCTL_SERIAL_SET_PARAMS
:
1776 QEMUSerialSetParams
*ssp
= arg
;
1777 tty_serial_init(s
->fd_in
, ssp
->speed
, ssp
->parity
,
1778 ssp
->data_bits
, ssp
->stop_bits
);
1781 case CHR_IOCTL_SERIAL_SET_BREAK
:
1783 int enable
= *(int *)arg
;
1785 tcsendbreak(s
->fd_in
, 1);
1794 static CharDriverState
*qemu_chr_open_tty(const char *filename
)
1796 CharDriverState
*chr
;
1799 fd
= open(filename
, O_RDWR
| O_NONBLOCK
);
1802 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
1803 tty_serial_init(fd
, 115200, 'N', 8, 1);
1804 chr
= qemu_chr_open_fd(fd
, fd
);
1807 chr
->chr_ioctl
= tty_serial_ioctl
;
1808 qemu_chr_reset(chr
);
1812 static int pp_ioctl(CharDriverState
*chr
, int cmd
, void *arg
)
1814 int fd
= (int)chr
->opaque
;
1818 case CHR_IOCTL_PP_READ_DATA
:
1819 if (ioctl(fd
, PPRDATA
, &b
) < 0)
1821 *(uint8_t *)arg
= b
;
1823 case CHR_IOCTL_PP_WRITE_DATA
:
1824 b
= *(uint8_t *)arg
;
1825 if (ioctl(fd
, PPWDATA
, &b
) < 0)
1828 case CHR_IOCTL_PP_READ_CONTROL
:
1829 if (ioctl(fd
, PPRCONTROL
, &b
) < 0)
1831 *(uint8_t *)arg
= b
;
1833 case CHR_IOCTL_PP_WRITE_CONTROL
:
1834 b
= *(uint8_t *)arg
;
1835 if (ioctl(fd
, PPWCONTROL
, &b
) < 0)
1838 case CHR_IOCTL_PP_READ_STATUS
:
1839 if (ioctl(fd
, PPRSTATUS
, &b
) < 0)
1841 *(uint8_t *)arg
= b
;
1849 static CharDriverState
*qemu_chr_open_pp(const char *filename
)
1851 CharDriverState
*chr
;
1854 fd
= open(filename
, O_RDWR
);
1858 if (ioctl(fd
, PPCLAIM
) < 0) {
1863 chr
= qemu_mallocz(sizeof(CharDriverState
));
1868 chr
->opaque
= (void *)fd
;
1869 chr
->chr_write
= null_chr_write
;
1870 chr
->chr_ioctl
= pp_ioctl
;
1872 qemu_chr_reset(chr
);
1878 static CharDriverState
*qemu_chr_open_pty(void)
1884 #endif /* !defined(_WIN32) */
1888 CharDriverState
*chr
;
1890 HANDLE hcom
, hrecv
, hsend
;
1891 OVERLAPPED orecv
, osend
;
1896 #define NSENDBUF 2048
1897 #define NRECVBUF 2048
1898 #define MAXCONNECT 1
1899 #define NTIMEOUT 5000
1901 static int win_chr_poll(void *opaque
);
1902 static int win_chr_pipe_poll(void *opaque
);
1904 static void win_chr_close2(WinCharState
*s
)
1907 CloseHandle(s
->hsend
);
1911 CloseHandle(s
->hrecv
);
1915 CloseHandle(s
->hcom
);
1919 qemu_del_polling_cb(win_chr_pipe_poll
, s
);
1921 qemu_del_polling_cb(win_chr_poll
, s
);
1924 static void win_chr_close(CharDriverState
*chr
)
1926 WinCharState
*s
= chr
->opaque
;
1930 static int win_chr_init(WinCharState
*s
, CharDriverState
*chr
, const char *filename
)
1933 COMMTIMEOUTS cto
= { 0, 0, 0, 0, 0};
1938 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1940 fprintf(stderr
, "Failed CreateEvent\n");
1943 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
1945 fprintf(stderr
, "Failed CreateEvent\n");
1949 s
->hcom
= CreateFile(filename
, GENERIC_READ
|GENERIC_WRITE
, 0, NULL
,
1950 OPEN_EXISTING
, FILE_FLAG_OVERLAPPED
, 0);
1951 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
1952 fprintf(stderr
, "Failed CreateFile (%lu)\n", GetLastError());
1957 if (!SetupComm(s
->hcom
, NRECVBUF
, NSENDBUF
)) {
1958 fprintf(stderr
, "Failed SetupComm\n");
1962 ZeroMemory(&comcfg
, sizeof(COMMCONFIG
));
1963 size
= sizeof(COMMCONFIG
);
1964 GetDefaultCommConfig(filename
, &comcfg
, &size
);
1965 comcfg
.dcb
.DCBlength
= sizeof(DCB
);
1966 CommConfigDialog(filename
, NULL
, &comcfg
);
1968 if (!SetCommState(s
->hcom
, &comcfg
.dcb
)) {
1969 fprintf(stderr
, "Failed SetCommState\n");
1973 if (!SetCommMask(s
->hcom
, EV_ERR
)) {
1974 fprintf(stderr
, "Failed SetCommMask\n");
1978 cto
.ReadIntervalTimeout
= MAXDWORD
;
1979 if (!SetCommTimeouts(s
->hcom
, &cto
)) {
1980 fprintf(stderr
, "Failed SetCommTimeouts\n");
1984 if (!ClearCommError(s
->hcom
, &err
, &comstat
)) {
1985 fprintf(stderr
, "Failed ClearCommError\n");
1989 qemu_add_polling_cb(win_chr_poll
, s
);
1997 static int win_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len1
)
1999 WinCharState
*s
= chr
->opaque
;
2000 DWORD len
, ret
, size
, err
;
2003 ZeroMemory(&s
->osend
, sizeof(s
->osend
));
2004 s
->osend
.hEvent
= s
->hsend
;
2007 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, &s
->osend
);
2009 ret
= WriteFile(s
->hcom
, buf
, len
, &size
, NULL
);
2011 err
= GetLastError();
2012 if (err
== ERROR_IO_PENDING
) {
2013 ret
= GetOverlappedResult(s
->hcom
, &s
->osend
, &size
, TRUE
);
2031 static int win_chr_read_poll(WinCharState
*s
)
2033 s
->max_size
= qemu_chr_can_read(s
->chr
);
2037 static void win_chr_readfile(WinCharState
*s
)
2043 ZeroMemory(&s
->orecv
, sizeof(s
->orecv
));
2044 s
->orecv
.hEvent
= s
->hrecv
;
2045 ret
= ReadFile(s
->hcom
, buf
, s
->len
, &size
, &s
->orecv
);
2047 err
= GetLastError();
2048 if (err
== ERROR_IO_PENDING
) {
2049 ret
= GetOverlappedResult(s
->hcom
, &s
->orecv
, &size
, TRUE
);
2054 qemu_chr_read(s
->chr
, buf
, size
);
2058 static void win_chr_read(WinCharState
*s
)
2060 if (s
->len
> s
->max_size
)
2061 s
->len
= s
->max_size
;
2065 win_chr_readfile(s
);
2068 static int win_chr_poll(void *opaque
)
2070 WinCharState
*s
= opaque
;
2074 ClearCommError(s
->hcom
, &comerr
, &status
);
2075 if (status
.cbInQue
> 0) {
2076 s
->len
= status
.cbInQue
;
2077 win_chr_read_poll(s
);
2084 static CharDriverState
*qemu_chr_open_win(const char *filename
)
2086 CharDriverState
*chr
;
2089 chr
= qemu_mallocz(sizeof(CharDriverState
));
2092 s
= qemu_mallocz(sizeof(WinCharState
));
2098 chr
->chr_write
= win_chr_write
;
2099 chr
->chr_close
= win_chr_close
;
2101 if (win_chr_init(s
, chr
, filename
) < 0) {
2106 qemu_chr_reset(chr
);
2110 static int win_chr_pipe_poll(void *opaque
)
2112 WinCharState
*s
= opaque
;
2115 PeekNamedPipe(s
->hcom
, NULL
, 0, NULL
, &size
, NULL
);
2118 win_chr_read_poll(s
);
2125 static int win_chr_pipe_init(WinCharState
*s
, const char *filename
)
2134 s
->hsend
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2136 fprintf(stderr
, "Failed CreateEvent\n");
2139 s
->hrecv
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2141 fprintf(stderr
, "Failed CreateEvent\n");
2145 snprintf(openname
, sizeof(openname
), "\\\\.\\pipe\\%s", filename
);
2146 s
->hcom
= CreateNamedPipe(openname
, PIPE_ACCESS_DUPLEX
| FILE_FLAG_OVERLAPPED
,
2147 PIPE_TYPE_BYTE
| PIPE_READMODE_BYTE
|
2149 MAXCONNECT
, NSENDBUF
, NRECVBUF
, NTIMEOUT
, NULL
);
2150 if (s
->hcom
== INVALID_HANDLE_VALUE
) {
2151 fprintf(stderr
, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2156 ZeroMemory(&ov
, sizeof(ov
));
2157 ov
.hEvent
= CreateEvent(NULL
, TRUE
, FALSE
, NULL
);
2158 ret
= ConnectNamedPipe(s
->hcom
, &ov
);
2160 fprintf(stderr
, "Failed ConnectNamedPipe\n");
2164 ret
= GetOverlappedResult(s
->hcom
, &ov
, &size
, TRUE
);
2166 fprintf(stderr
, "Failed GetOverlappedResult\n");
2168 CloseHandle(ov
.hEvent
);
2175 CloseHandle(ov
.hEvent
);
2178 qemu_add_polling_cb(win_chr_pipe_poll
, s
);
2187 static CharDriverState
*qemu_chr_open_win_pipe(const char *filename
)
2189 CharDriverState
*chr
;
2192 chr
= qemu_mallocz(sizeof(CharDriverState
));
2195 s
= qemu_mallocz(sizeof(WinCharState
));
2201 chr
->chr_write
= win_chr_write
;
2202 chr
->chr_close
= win_chr_close
;
2204 if (win_chr_pipe_init(s
, filename
) < 0) {
2209 qemu_chr_reset(chr
);
2213 static CharDriverState
*qemu_chr_open_win_file(HANDLE fd_out
)
2215 CharDriverState
*chr
;
2218 chr
= qemu_mallocz(sizeof(CharDriverState
));
2221 s
= qemu_mallocz(sizeof(WinCharState
));
2228 chr
->chr_write
= win_chr_write
;
2229 qemu_chr_reset(chr
);
2233 static CharDriverState
*qemu_chr_open_win_file_out(const char *file_out
)
2237 fd_out
= CreateFile(file_out
, GENERIC_WRITE
, FILE_SHARE_READ
, NULL
,
2238 OPEN_ALWAYS
, FILE_ATTRIBUTE_NORMAL
, NULL
);
2239 if (fd_out
== INVALID_HANDLE_VALUE
)
2242 return qemu_chr_open_win_file(fd_out
);
2246 /***********************************************************/
2247 /* UDP Net console */
2251 struct sockaddr_in daddr
;
2258 static int udp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2260 NetCharDriver
*s
= chr
->opaque
;
2262 return sendto(s
->fd
, buf
, len
, 0,
2263 (struct sockaddr
*)&s
->daddr
, sizeof(struct sockaddr_in
));
2266 static int udp_chr_read_poll(void *opaque
)
2268 CharDriverState
*chr
= opaque
;
2269 NetCharDriver
*s
= chr
->opaque
;
2271 s
->max_size
= qemu_chr_can_read(chr
);
2273 /* If there were any stray characters in the queue process them
2276 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2277 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2279 s
->max_size
= qemu_chr_can_read(chr
);
2284 static void udp_chr_read(void *opaque
)
2286 CharDriverState
*chr
= opaque
;
2287 NetCharDriver
*s
= chr
->opaque
;
2289 if (s
->max_size
== 0)
2291 s
->bufcnt
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
2292 s
->bufptr
= s
->bufcnt
;
2297 while (s
->max_size
> 0 && s
->bufptr
< s
->bufcnt
) {
2298 qemu_chr_read(chr
, &s
->buf
[s
->bufptr
], 1);
2300 s
->max_size
= qemu_chr_can_read(chr
);
2304 static void udp_chr_update_read_handler(CharDriverState
*chr
)
2306 NetCharDriver
*s
= chr
->opaque
;
2309 qemu_set_fd_handler2(s
->fd
, udp_chr_read_poll
,
2310 udp_chr_read
, NULL
, chr
);
2315 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
);
2317 int parse_host_src_port(struct sockaddr_in
*haddr
,
2318 struct sockaddr_in
*saddr
,
2321 static CharDriverState
*qemu_chr_open_udp(const char *def
)
2323 CharDriverState
*chr
= NULL
;
2324 NetCharDriver
*s
= NULL
;
2326 struct sockaddr_in saddr
;
2328 chr
= qemu_mallocz(sizeof(CharDriverState
));
2331 s
= qemu_mallocz(sizeof(NetCharDriver
));
2335 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
2337 perror("socket(PF_INET, SOCK_DGRAM)");
2341 if (parse_host_src_port(&s
->daddr
, &saddr
, def
) < 0) {
2342 printf("Could not parse: %s\n", def
);
2346 if (bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
)) < 0)
2356 chr
->chr_write
= udp_chr_write
;
2357 chr
->chr_update_read_handler
= udp_chr_update_read_handler
;
2370 /***********************************************************/
2371 /* TCP Net console */
2382 static void tcp_chr_accept(void *opaque
);
2384 static int tcp_chr_write(CharDriverState
*chr
, const uint8_t *buf
, int len
)
2386 TCPCharDriver
*s
= chr
->opaque
;
2388 return send_all(s
->fd
, buf
, len
);
2390 /* XXX: indicate an error ? */
2395 static int tcp_chr_read_poll(void *opaque
)
2397 CharDriverState
*chr
= opaque
;
2398 TCPCharDriver
*s
= chr
->opaque
;
2401 s
->max_size
= qemu_chr_can_read(chr
);
2406 #define IAC_BREAK 243
2407 static void tcp_chr_process_IAC_bytes(CharDriverState
*chr
,
2409 char *buf
, int *size
)
2411 /* Handle any telnet client's basic IAC options to satisfy char by
2412 * char mode with no echo. All IAC options will be removed from
2413 * the buf and the do_telnetopt variable will be used to track the
2414 * state of the width of the IAC information.
2416 * IAC commands come in sets of 3 bytes with the exception of the
2417 * "IAC BREAK" command and the double IAC.
2423 for (i
= 0; i
< *size
; i
++) {
2424 if (s
->do_telnetopt
> 1) {
2425 if ((unsigned char)buf
[i
] == IAC
&& s
->do_telnetopt
== 2) {
2426 /* Double IAC means send an IAC */
2430 s
->do_telnetopt
= 1;
2432 if ((unsigned char)buf
[i
] == IAC_BREAK
&& s
->do_telnetopt
== 2) {
2433 /* Handle IAC break commands by sending a serial break */
2434 qemu_chr_event(chr
, CHR_EVENT_BREAK
);
2439 if (s
->do_telnetopt
>= 4) {
2440 s
->do_telnetopt
= 1;
2443 if ((unsigned char)buf
[i
] == IAC
) {
2444 s
->do_telnetopt
= 2;
2455 static void tcp_chr_read(void *opaque
)
2457 CharDriverState
*chr
= opaque
;
2458 TCPCharDriver
*s
= chr
->opaque
;
2462 if (!s
->connected
|| s
->max_size
<= 0)
2465 if (len
> s
->max_size
)
2467 size
= recv(s
->fd
, buf
, len
, 0);
2469 /* connection closed */
2471 if (s
->listen_fd
>= 0) {
2472 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2474 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
2477 } else if (size
> 0) {
2478 if (s
->do_telnetopt
)
2479 tcp_chr_process_IAC_bytes(chr
, s
, buf
, &size
);
2481 qemu_chr_read(chr
, buf
, size
);
2485 static void tcp_chr_connect(void *opaque
)
2487 CharDriverState
*chr
= opaque
;
2488 TCPCharDriver
*s
= chr
->opaque
;
2491 qemu_set_fd_handler2(s
->fd
, tcp_chr_read_poll
,
2492 tcp_chr_read
, NULL
, chr
);
2493 qemu_chr_reset(chr
);
2496 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2497 static void tcp_chr_telnet_init(int fd
)
2500 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2501 IACSET(buf
, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2502 send(fd
, (char *)buf
, 3, 0);
2503 IACSET(buf
, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2504 send(fd
, (char *)buf
, 3, 0);
2505 IACSET(buf
, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2506 send(fd
, (char *)buf
, 3, 0);
2507 IACSET(buf
, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2508 send(fd
, (char *)buf
, 3, 0);
2511 static void socket_set_nodelay(int fd
)
2514 setsockopt(fd
, IPPROTO_TCP
, TCP_NODELAY
, (char *)&val
, sizeof(val
));
2517 static void tcp_chr_accept(void *opaque
)
2519 CharDriverState
*chr
= opaque
;
2520 TCPCharDriver
*s
= chr
->opaque
;
2521 struct sockaddr_in saddr
;
2523 struct sockaddr_un uaddr
;
2525 struct sockaddr
*addr
;
2532 len
= sizeof(uaddr
);
2533 addr
= (struct sockaddr
*)&uaddr
;
2537 len
= sizeof(saddr
);
2538 addr
= (struct sockaddr
*)&saddr
;
2540 fd
= accept(s
->listen_fd
, addr
, &len
);
2541 if (fd
< 0 && errno
!= EINTR
) {
2543 } else if (fd
>= 0) {
2544 if (s
->do_telnetopt
)
2545 tcp_chr_telnet_init(fd
);
2549 socket_set_nonblock(fd
);
2551 socket_set_nodelay(fd
);
2553 qemu_set_fd_handler(s
->listen_fd
, NULL
, NULL
, NULL
);
2554 tcp_chr_connect(chr
);
2557 static void tcp_chr_close(CharDriverState
*chr
)
2559 TCPCharDriver
*s
= chr
->opaque
;
2562 if (s
->listen_fd
>= 0)
2563 closesocket(s
->listen_fd
);
2567 static CharDriverState
*qemu_chr_open_tcp(const char *host_str
,
2571 CharDriverState
*chr
= NULL
;
2572 TCPCharDriver
*s
= NULL
;
2573 int fd
= -1, ret
, err
, val
;
2575 int is_waitconnect
= 1;
2578 struct sockaddr_in saddr
;
2580 struct sockaddr_un uaddr
;
2582 struct sockaddr
*addr
;
2587 addr
= (struct sockaddr
*)&uaddr
;
2588 addrlen
= sizeof(uaddr
);
2589 if (parse_unix_path(&uaddr
, host_str
) < 0)
2594 addr
= (struct sockaddr
*)&saddr
;
2595 addrlen
= sizeof(saddr
);
2596 if (parse_host_port(&saddr
, host_str
) < 0)
2601 while((ptr
= strchr(ptr
,','))) {
2603 if (!strncmp(ptr
,"server",6)) {
2605 } else if (!strncmp(ptr
,"nowait",6)) {
2607 } else if (!strncmp(ptr
,"nodelay",6)) {
2610 printf("Unknown option: %s\n", ptr
);
2617 chr
= qemu_mallocz(sizeof(CharDriverState
));
2620 s
= qemu_mallocz(sizeof(TCPCharDriver
));
2626 fd
= socket(PF_UNIX
, SOCK_STREAM
, 0);
2629 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
2634 if (!is_waitconnect
)
2635 socket_set_nonblock(fd
);
2640 s
->is_unix
= is_unix
;
2641 s
->do_nodelay
= do_nodelay
&& !is_unix
;
2644 chr
->chr_write
= tcp_chr_write
;
2645 chr
->chr_close
= tcp_chr_close
;
2648 /* allow fast reuse */
2652 strncpy(path
, uaddr
.sun_path
, 108);
2659 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
2662 ret
= bind(fd
, addr
, addrlen
);
2666 ret
= listen(fd
, 0);
2671 qemu_set_fd_handler(s
->listen_fd
, tcp_chr_accept
, NULL
, chr
);
2673 s
->do_telnetopt
= 1;
2676 ret
= connect(fd
, addr
, addrlen
);
2678 err
= socket_error();
2679 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
2680 } else if (err
== EINPROGRESS
) {
2691 socket_set_nodelay(fd
);
2693 tcp_chr_connect(chr
);
2695 qemu_set_fd_handler(s
->fd
, NULL
, tcp_chr_connect
, chr
);
2698 if (is_listen
&& is_waitconnect
) {
2699 printf("QEMU waiting for connection on: %s\n", host_str
);
2700 tcp_chr_accept(chr
);
2701 socket_set_nonblock(s
->listen_fd
);
2713 CharDriverState
*qemu_chr_open(const char *filename
)
2717 if (!strcmp(filename
, "vc")) {
2718 return text_console_init(&display_state
);
2719 } else if (!strcmp(filename
, "null")) {
2720 return qemu_chr_open_null();
2722 if (strstart(filename
, "tcp:", &p
)) {
2723 return qemu_chr_open_tcp(p
, 0, 0);
2725 if (strstart(filename
, "telnet:", &p
)) {
2726 return qemu_chr_open_tcp(p
, 1, 0);
2728 if (strstart(filename
, "udp:", &p
)) {
2729 return qemu_chr_open_udp(p
);
2732 if (strstart(filename
, "unix:", &p
)) {
2733 return qemu_chr_open_tcp(p
, 0, 1);
2734 } else if (strstart(filename
, "file:", &p
)) {
2735 return qemu_chr_open_file_out(p
);
2736 } else if (strstart(filename
, "pipe:", &p
)) {
2737 return qemu_chr_open_pipe(p
);
2738 } else if (!strcmp(filename
, "pty")) {
2739 return qemu_chr_open_pty();
2740 } else if (!strcmp(filename
, "stdio")) {
2741 return qemu_chr_open_stdio();
2744 #if defined(__linux__)
2745 if (strstart(filename
, "/dev/parport", NULL
)) {
2746 return qemu_chr_open_pp(filename
);
2748 if (strstart(filename
, "/dev/", NULL
)) {
2749 return qemu_chr_open_tty(filename
);
2753 if (strstart(filename
, "COM", NULL
)) {
2754 return qemu_chr_open_win(filename
);
2756 if (strstart(filename
, "pipe:", &p
)) {
2757 return qemu_chr_open_win_pipe(p
);
2759 if (strstart(filename
, "file:", &p
)) {
2760 return qemu_chr_open_win_file_out(p
);
2768 void qemu_chr_close(CharDriverState
*chr
)
2771 chr
->chr_close(chr
);
2774 /***********************************************************/
2775 /* network device redirectors */
2777 void hex_dump(FILE *f
, const uint8_t *buf
, int size
)
2781 for(i
=0;i
<size
;i
+=16) {
2785 fprintf(f
, "%08x ", i
);
2788 fprintf(f
, " %02x", buf
[i
+j
]);
2793 for(j
=0;j
<len
;j
++) {
2795 if (c
< ' ' || c
> '~')
2797 fprintf(f
, "%c", c
);
2803 static int parse_macaddr(uint8_t *macaddr
, const char *p
)
2806 for(i
= 0; i
< 6; i
++) {
2807 macaddr
[i
] = strtol(p
, (char **)&p
, 16);
2820 static int get_str_sep(char *buf
, int buf_size
, const char **pp
, int sep
)
2825 p1
= strchr(p
, sep
);
2831 if (len
> buf_size
- 1)
2833 memcpy(buf
, p
, len
);
2840 int parse_host_src_port(struct sockaddr_in
*haddr
,
2841 struct sockaddr_in
*saddr
,
2842 const char *input_str
)
2844 char *str
= strdup(input_str
);
2845 char *host_str
= str
;
2850 * Chop off any extra arguments at the end of the string which
2851 * would start with a comma, then fill in the src port information
2852 * if it was provided else use the "any address" and "any port".
2854 if ((ptr
= strchr(str
,',')))
2857 if ((src_str
= strchr(input_str
,'@'))) {
2862 if (parse_host_port(haddr
, host_str
) < 0)
2865 if (!src_str
|| *src_str
== '\0')
2868 if (parse_host_port(saddr
, src_str
) < 0)
2879 int parse_host_port(struct sockaddr_in
*saddr
, const char *str
)
2887 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
2889 saddr
->sin_family
= AF_INET
;
2890 if (buf
[0] == '\0') {
2891 saddr
->sin_addr
.s_addr
= 0;
2893 if (isdigit(buf
[0])) {
2894 if (!inet_aton(buf
, &saddr
->sin_addr
))
2897 if ((he
= gethostbyname(buf
)) == NULL
)
2899 saddr
->sin_addr
= *(struct in_addr
*)he
->h_addr
;
2902 port
= strtol(p
, (char **)&r
, 0);
2905 saddr
->sin_port
= htons(port
);
2910 static int parse_unix_path(struct sockaddr_un
*uaddr
, const char *str
)
2915 len
= MIN(108, strlen(str
));
2916 p
= strchr(str
, ',');
2918 len
= MIN(len
, p
- str
);
2920 memset(uaddr
, 0, sizeof(*uaddr
));
2922 uaddr
->sun_family
= AF_UNIX
;
2923 memcpy(uaddr
->sun_path
, str
, len
);
2929 /* find or alloc a new VLAN */
2930 VLANState
*qemu_find_vlan(int id
)
2932 VLANState
**pvlan
, *vlan
;
2933 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
2937 vlan
= qemu_mallocz(sizeof(VLANState
));
2942 pvlan
= &first_vlan
;
2943 while (*pvlan
!= NULL
)
2944 pvlan
= &(*pvlan
)->next
;
2949 VLANClientState
*qemu_new_vlan_client(VLANState
*vlan
,
2950 IOReadHandler
*fd_read
,
2951 IOCanRWHandler
*fd_can_read
,
2954 VLANClientState
*vc
, **pvc
;
2955 vc
= qemu_mallocz(sizeof(VLANClientState
));
2958 vc
->fd_read
= fd_read
;
2959 vc
->fd_can_read
= fd_can_read
;
2960 vc
->opaque
= opaque
;
2964 pvc
= &vlan
->first_client
;
2965 while (*pvc
!= NULL
)
2966 pvc
= &(*pvc
)->next
;
2971 int qemu_can_send_packet(VLANClientState
*vc1
)
2973 VLANState
*vlan
= vc1
->vlan
;
2974 VLANClientState
*vc
;
2976 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2978 if (vc
->fd_can_read
&& !vc
->fd_can_read(vc
->opaque
))
2985 void qemu_send_packet(VLANClientState
*vc1
, const uint8_t *buf
, int size
)
2987 VLANState
*vlan
= vc1
->vlan
;
2988 VLANClientState
*vc
;
2991 printf("vlan %d send:\n", vlan
->id
);
2992 hex_dump(stdout
, buf
, size
);
2994 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
2996 vc
->fd_read(vc
->opaque
, buf
, size
);
3001 #if defined(CONFIG_SLIRP)
3003 /* slirp network adapter */
3005 static int slirp_inited
;
3006 static VLANClientState
*slirp_vc
;
3008 int slirp_can_output(void)
3010 return !slirp_vc
|| qemu_can_send_packet(slirp_vc
);
3013 void slirp_output(const uint8_t *pkt
, int pkt_len
)
3016 printf("slirp output:\n");
3017 hex_dump(stdout
, pkt
, pkt_len
);
3021 qemu_send_packet(slirp_vc
, pkt
, pkt_len
);
3024 static void slirp_receive(void *opaque
, const uint8_t *buf
, int size
)
3027 printf("slirp input:\n");
3028 hex_dump(stdout
, buf
, size
);
3030 slirp_input(buf
, size
);
3033 static int net_slirp_init(VLANState
*vlan
)
3035 if (!slirp_inited
) {
3039 slirp_vc
= qemu_new_vlan_client(vlan
,
3040 slirp_receive
, NULL
, NULL
);
3041 snprintf(slirp_vc
->info_str
, sizeof(slirp_vc
->info_str
), "user redirector");
3045 static void net_slirp_redir(const char *redir_str
)
3050 struct in_addr guest_addr
;
3051 int host_port
, guest_port
;
3053 if (!slirp_inited
) {
3059 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3061 if (!strcmp(buf
, "tcp")) {
3063 } else if (!strcmp(buf
, "udp")) {
3069 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3071 host_port
= strtol(buf
, &r
, 0);
3075 if (get_str_sep(buf
, sizeof(buf
), &p
, ':') < 0)
3077 if (buf
[0] == '\0') {
3078 pstrcpy(buf
, sizeof(buf
), "10.0.2.15");
3080 if (!inet_aton(buf
, &guest_addr
))
3083 guest_port
= strtol(p
, &r
, 0);
3087 if (slirp_redir(is_udp
, host_port
, guest_addr
, guest_port
) < 0) {
3088 fprintf(stderr
, "qemu: could not set up redirection\n");
3093 fprintf(stderr
, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3101 static void smb_exit(void)
3105 char filename
[1024];
3107 /* erase all the files in the directory */
3108 d
= opendir(smb_dir
);
3113 if (strcmp(de
->d_name
, ".") != 0 &&
3114 strcmp(de
->d_name
, "..") != 0) {
3115 snprintf(filename
, sizeof(filename
), "%s/%s",
3116 smb_dir
, de
->d_name
);
3124 /* automatic user mode samba server configuration */
3125 void net_slirp_smb(const char *exported_dir
)
3127 char smb_conf
[1024];
3128 char smb_cmdline
[1024];
3131 if (!slirp_inited
) {
3136 /* XXX: better tmp dir construction */
3137 snprintf(smb_dir
, sizeof(smb_dir
), "/tmp/qemu-smb.%d", getpid());
3138 if (mkdir(smb_dir
, 0700) < 0) {
3139 fprintf(stderr
, "qemu: could not create samba server dir '%s'\n", smb_dir
);
3142 snprintf(smb_conf
, sizeof(smb_conf
), "%s/%s", smb_dir
, "smb.conf");
3144 f
= fopen(smb_conf
, "w");
3146 fprintf(stderr
, "qemu: could not create samba server configuration file '%s'\n", smb_conf
);
3153 "socket address=127.0.0.1\n"
3154 "pid directory=%s\n"
3155 "lock directory=%s\n"
3156 "log file=%s/log.smbd\n"
3157 "smb passwd file=%s/smbpasswd\n"
3158 "security = share\n"
3173 snprintf(smb_cmdline
, sizeof(smb_cmdline
), "%s -s %s",
3174 SMBD_COMMAND
, smb_conf
);
3176 slirp_add_exec(0, smb_cmdline
, 4, 139);
3179 #endif /* !defined(_WIN32) */
3181 #endif /* CONFIG_SLIRP */
3183 #if !defined(_WIN32)
3185 typedef struct TAPState
{
3186 VLANClientState
*vc
;
3190 static void tap_receive(void *opaque
, const uint8_t *buf
, int size
)
3192 TAPState
*s
= opaque
;
3195 ret
= write(s
->fd
, buf
, size
);
3196 if (ret
< 0 && (errno
== EINTR
|| errno
== EAGAIN
)) {
3203 static void tap_send(void *opaque
)
3205 TAPState
*s
= opaque
;
3209 size
= read(s
->fd
, buf
, sizeof(buf
));
3211 qemu_send_packet(s
->vc
, buf
, size
);
3217 static TAPState
*net_tap_fd_init(VLANState
*vlan
, int fd
)
3221 s
= qemu_mallocz(sizeof(TAPState
));
3225 s
->vc
= qemu_new_vlan_client(vlan
, tap_receive
, NULL
, s
);
3226 qemu_set_fd_handler(s
->fd
, tap_send
, NULL
, s
);
3227 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
), "tap: fd=%d", fd
);
3232 static int tap_open(char *ifname
, int ifname_size
)
3238 fd
= open("/dev/tap", O_RDWR
);
3240 fprintf(stderr
, "warning: could not open /dev/tap: no virtual network emulation\n");
3245 dev
= devname(s
.st_rdev
, S_IFCHR
);
3246 pstrcpy(ifname
, ifname_size
, dev
);
3248 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3251 #elif defined(__sun__)
3252 static int tap_open(char *ifname
, int ifname_size
)
3254 fprintf(stderr
, "warning: tap_open not yet implemented\n");
3258 static int tap_open(char *ifname
, int ifname_size
)
3263 fd
= open("/dev/net/tun", O_RDWR
);
3265 fprintf(stderr
, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3268 memset(&ifr
, 0, sizeof(ifr
));
3269 ifr
.ifr_flags
= IFF_TAP
| IFF_NO_PI
;
3270 if (ifname
[0] != '\0')
3271 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, ifname
);
3273 pstrcpy(ifr
.ifr_name
, IFNAMSIZ
, "tap%d");
3274 ret
= ioctl(fd
, TUNSETIFF
, (void *) &ifr
);
3276 fprintf(stderr
, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3280 pstrcpy(ifname
, ifname_size
, ifr
.ifr_name
);
3281 fcntl(fd
, F_SETFL
, O_NONBLOCK
);
3286 static int net_tap_init(VLANState
*vlan
, const char *ifname1
,
3287 const char *setup_script
)
3290 int pid
, status
, fd
;
3295 if (ifname1
!= NULL
)
3296 pstrcpy(ifname
, sizeof(ifname
), ifname1
);
3299 fd
= tap_open(ifname
, sizeof(ifname
));
3303 if (!setup_script
|| !strcmp(setup_script
, "no"))
3305 if (setup_script
[0] != '\0') {
3306 /* try to launch network init script */
3311 *parg
++ = (char *)setup_script
;
3314 execv(setup_script
, args
);
3317 while (waitpid(pid
, &status
, 0) != pid
);
3318 if (!WIFEXITED(status
) ||
3319 WEXITSTATUS(status
) != 0) {
3320 fprintf(stderr
, "%s: could not launch network script\n",
3326 s
= net_tap_fd_init(vlan
, fd
);
3329 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3330 "tap: ifname=%s setup_script=%s", ifname
, setup_script
);
3334 #endif /* !_WIN32 */
3336 /* network connection */
3337 typedef struct NetSocketState
{
3338 VLANClientState
*vc
;
3340 int state
; /* 0 = getting length, 1 = getting data */
3344 struct sockaddr_in dgram_dst
; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3347 typedef struct NetSocketListenState
{
3350 } NetSocketListenState
;
3352 /* XXX: we consider we can send the whole packet without blocking */
3353 static void net_socket_receive(void *opaque
, const uint8_t *buf
, int size
)
3355 NetSocketState
*s
= opaque
;
3359 send_all(s
->fd
, (const uint8_t *)&len
, sizeof(len
));
3360 send_all(s
->fd
, buf
, size
);
3363 static void net_socket_receive_dgram(void *opaque
, const uint8_t *buf
, int size
)
3365 NetSocketState
*s
= opaque
;
3366 sendto(s
->fd
, buf
, size
, 0,
3367 (struct sockaddr
*)&s
->dgram_dst
, sizeof(s
->dgram_dst
));
3370 static void net_socket_send(void *opaque
)
3372 NetSocketState
*s
= opaque
;
3377 size
= recv(s
->fd
, buf1
, sizeof(buf1
), 0);
3379 err
= socket_error();
3380 if (err
!= EWOULDBLOCK
)
3382 } else if (size
== 0) {
3383 /* end of connection */
3385 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3391 /* reassemble a packet from the network */
3397 memcpy(s
->buf
+ s
->index
, buf
, l
);
3401 if (s
->index
== 4) {
3403 s
->packet_len
= ntohl(*(uint32_t *)s
->buf
);
3409 l
= s
->packet_len
- s
->index
;
3412 memcpy(s
->buf
+ s
->index
, buf
, l
);
3416 if (s
->index
>= s
->packet_len
) {
3417 qemu_send_packet(s
->vc
, s
->buf
, s
->packet_len
);
3426 static void net_socket_send_dgram(void *opaque
)
3428 NetSocketState
*s
= opaque
;
3431 size
= recv(s
->fd
, s
->buf
, sizeof(s
->buf
), 0);
3435 /* end of connection */
3436 qemu_set_fd_handler(s
->fd
, NULL
, NULL
, NULL
);
3439 qemu_send_packet(s
->vc
, s
->buf
, size
);
3442 static int net_socket_mcast_create(struct sockaddr_in
*mcastaddr
)
3447 if (!IN_MULTICAST(ntohl(mcastaddr
->sin_addr
.s_addr
))) {
3448 fprintf(stderr
, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3449 inet_ntoa(mcastaddr
->sin_addr
),
3450 (int)ntohl(mcastaddr
->sin_addr
.s_addr
));
3454 fd
= socket(PF_INET
, SOCK_DGRAM
, 0);
3456 perror("socket(PF_INET, SOCK_DGRAM)");
3461 ret
=setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
,
3462 (const char *)&val
, sizeof(val
));
3464 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3468 ret
= bind(fd
, (struct sockaddr
*)mcastaddr
, sizeof(*mcastaddr
));
3474 /* Add host to multicast group */
3475 imr
.imr_multiaddr
= mcastaddr
->sin_addr
;
3476 imr
.imr_interface
.s_addr
= htonl(INADDR_ANY
);
3478 ret
= setsockopt(fd
, IPPROTO_IP
, IP_ADD_MEMBERSHIP
,
3479 (const char *)&imr
, sizeof(struct ip_mreq
));
3481 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3485 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3487 ret
=setsockopt(fd
, IPPROTO_IP
, IP_MULTICAST_LOOP
,
3488 (const char *)&val
, sizeof(val
));
3490 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3494 socket_set_nonblock(fd
);
3502 static NetSocketState
*net_socket_fd_init_dgram(VLANState
*vlan
, int fd
,
3505 struct sockaddr_in saddr
;
3507 socklen_t saddr_len
;
3510 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3511 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3512 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3516 if (getsockname(fd
, (struct sockaddr
*) &saddr
, &saddr_len
) == 0) {
3518 if (saddr
.sin_addr
.s_addr
==0) {
3519 fprintf(stderr
, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3523 /* clone dgram socket */
3524 newfd
= net_socket_mcast_create(&saddr
);
3526 /* error already reported by net_socket_mcast_create() */
3530 /* clone newfd to fd, close newfd */
3535 fprintf(stderr
, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3536 fd
, strerror(errno
));
3541 s
= qemu_mallocz(sizeof(NetSocketState
));
3546 s
->vc
= qemu_new_vlan_client(vlan
, net_socket_receive_dgram
, NULL
, s
);
3547 qemu_set_fd_handler(s
->fd
, net_socket_send_dgram
, NULL
, s
);
3549 /* mcast: save bound address as dst */
3550 if (is_connected
) s
->dgram_dst
=saddr
;
3552 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3553 "socket: fd=%d (%s mcast=%s:%d)",
3554 fd
, is_connected
? "cloned" : "",
3555 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3559 static void net_socket_connect(void *opaque
)
3561 NetSocketState
*s
= opaque
;
3562 qemu_set_fd_handler(s
->fd
, net_socket_send
, NULL
, s
);
3565 static NetSocketState
*net_socket_fd_init_stream(VLANState
*vlan
, int fd
,
3569 s
= qemu_mallocz(sizeof(NetSocketState
));
3573 s
->vc
= qemu_new_vlan_client(vlan
,
3574 net_socket_receive
, NULL
, s
);
3575 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3576 "socket: fd=%d", fd
);
3578 net_socket_connect(s
);
3580 qemu_set_fd_handler(s
->fd
, NULL
, net_socket_connect
, s
);
3585 static NetSocketState
*net_socket_fd_init(VLANState
*vlan
, int fd
,
3588 int so_type
=-1, optlen
=sizeof(so_type
);
3590 if(getsockopt(fd
, SOL_SOCKET
, SO_TYPE
, (char *)&so_type
, &optlen
)< 0) {
3591 fprintf(stderr
, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd
);
3596 return net_socket_fd_init_dgram(vlan
, fd
, is_connected
);
3598 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3600 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3601 fprintf(stderr
, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type
, fd
);
3602 return net_socket_fd_init_stream(vlan
, fd
, is_connected
);
3607 static void net_socket_accept(void *opaque
)
3609 NetSocketListenState
*s
= opaque
;
3611 struct sockaddr_in saddr
;
3616 len
= sizeof(saddr
);
3617 fd
= accept(s
->fd
, (struct sockaddr
*)&saddr
, &len
);
3618 if (fd
< 0 && errno
!= EINTR
) {
3620 } else if (fd
>= 0) {
3624 s1
= net_socket_fd_init(s
->vlan
, fd
, 1);
3628 snprintf(s1
->vc
->info_str
, sizeof(s1
->vc
->info_str
),
3629 "socket: connection from %s:%d",
3630 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3634 static int net_socket_listen_init(VLANState
*vlan
, const char *host_str
)
3636 NetSocketListenState
*s
;
3638 struct sockaddr_in saddr
;
3640 if (parse_host_port(&saddr
, host_str
) < 0)
3643 s
= qemu_mallocz(sizeof(NetSocketListenState
));
3647 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3652 socket_set_nonblock(fd
);
3654 /* allow fast reuse */
3656 setsockopt(fd
, SOL_SOCKET
, SO_REUSEADDR
, (const char *)&val
, sizeof(val
));
3658 ret
= bind(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3663 ret
= listen(fd
, 0);
3670 qemu_set_fd_handler(fd
, net_socket_accept
, NULL
, s
);
3674 static int net_socket_connect_init(VLANState
*vlan
, const char *host_str
)
3677 int fd
, connected
, ret
, err
;
3678 struct sockaddr_in saddr
;
3680 if (parse_host_port(&saddr
, host_str
) < 0)
3683 fd
= socket(PF_INET
, SOCK_STREAM
, 0);
3688 socket_set_nonblock(fd
);
3692 ret
= connect(fd
, (struct sockaddr
*)&saddr
, sizeof(saddr
));
3694 err
= socket_error();
3695 if (err
== EINTR
|| err
== EWOULDBLOCK
) {
3696 } else if (err
== EINPROGRESS
) {
3708 s
= net_socket_fd_init(vlan
, fd
, connected
);
3711 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3712 "socket: connect to %s:%d",
3713 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3717 static int net_socket_mcast_init(VLANState
*vlan
, const char *host_str
)
3721 struct sockaddr_in saddr
;
3723 if (parse_host_port(&saddr
, host_str
) < 0)
3727 fd
= net_socket_mcast_create(&saddr
);
3731 s
= net_socket_fd_init(vlan
, fd
, 0);
3735 s
->dgram_dst
= saddr
;
3737 snprintf(s
->vc
->info_str
, sizeof(s
->vc
->info_str
),
3738 "socket: mcast=%s:%d",
3739 inet_ntoa(saddr
.sin_addr
), ntohs(saddr
.sin_port
));
3744 static int get_param_value(char *buf
, int buf_size
,
3745 const char *tag
, const char *str
)
3754 while (*p
!= '\0' && *p
!= '=') {
3755 if ((q
- option
) < sizeof(option
) - 1)
3763 if (!strcmp(tag
, option
)) {
3765 while (*p
!= '\0' && *p
!= ',') {
3766 if ((q
- buf
) < buf_size
- 1)
3773 while (*p
!= '\0' && *p
!= ',') {
3784 static int net_client_init(const char *str
)
3795 while (*p
!= '\0' && *p
!= ',') {
3796 if ((q
- device
) < sizeof(device
) - 1)
3804 if (get_param_value(buf
, sizeof(buf
), "vlan", p
)) {
3805 vlan_id
= strtol(buf
, NULL
, 0);
3807 vlan
= qemu_find_vlan(vlan_id
);
3809 fprintf(stderr
, "Could not create vlan %d\n", vlan_id
);
3812 if (!strcmp(device
, "nic")) {
3816 if (nb_nics
>= MAX_NICS
) {
3817 fprintf(stderr
, "Too Many NICs\n");
3820 nd
= &nd_table
[nb_nics
];
3821 macaddr
= nd
->macaddr
;
3827 macaddr
[5] = 0x56 + nb_nics
;
3829 if (get_param_value(buf
, sizeof(buf
), "macaddr", p
)) {
3830 if (parse_macaddr(macaddr
, buf
) < 0) {
3831 fprintf(stderr
, "invalid syntax for ethernet address\n");
3835 if (get_param_value(buf
, sizeof(buf
), "model", p
)) {
3836 nd
->model
= strdup(buf
);
3842 if (!strcmp(device
, "none")) {
3843 /* does nothing. It is needed to signal that no network cards
3848 if (!strcmp(device
, "user")) {
3849 if (get_param_value(buf
, sizeof(buf
), "hostname", p
)) {
3850 pstrcpy(slirp_hostname
, sizeof(slirp_hostname
), buf
);
3852 ret
= net_slirp_init(vlan
);
3856 if (!strcmp(device
, "tap")) {
3858 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3859 fprintf(stderr
, "tap: no interface name\n");
3862 ret
= tap_win32_init(vlan
, ifname
);
3865 if (!strcmp(device
, "tap")) {
3867 char setup_script
[1024];
3869 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3870 fd
= strtol(buf
, NULL
, 0);
3872 if (net_tap_fd_init(vlan
, fd
))
3875 if (get_param_value(ifname
, sizeof(ifname
), "ifname", p
) <= 0) {
3878 if (get_param_value(setup_script
, sizeof(setup_script
), "script", p
) == 0) {
3879 pstrcpy(setup_script
, sizeof(setup_script
), DEFAULT_NETWORK_SCRIPT
);
3881 ret
= net_tap_init(vlan
, ifname
, setup_script
);
3885 if (!strcmp(device
, "socket")) {
3886 if (get_param_value(buf
, sizeof(buf
), "fd", p
) > 0) {
3888 fd
= strtol(buf
, NULL
, 0);
3890 if (net_socket_fd_init(vlan
, fd
, 1))
3892 } else if (get_param_value(buf
, sizeof(buf
), "listen", p
) > 0) {
3893 ret
= net_socket_listen_init(vlan
, buf
);
3894 } else if (get_param_value(buf
, sizeof(buf
), "connect", p
) > 0) {
3895 ret
= net_socket_connect_init(vlan
, buf
);
3896 } else if (get_param_value(buf
, sizeof(buf
), "mcast", p
) > 0) {
3897 ret
= net_socket_mcast_init(vlan
, buf
);
3899 fprintf(stderr
, "Unknown socket options: %s\n", p
);
3904 fprintf(stderr
, "Unknown network device: %s\n", device
);
3908 fprintf(stderr
, "Could not initialize device '%s'\n", device
);
3914 void do_info_network(void)
3917 VLANClientState
*vc
;
3919 for(vlan
= first_vlan
; vlan
!= NULL
; vlan
= vlan
->next
) {
3920 term_printf("VLAN %d devices:\n", vlan
->id
);
3921 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
)
3922 term_printf(" %s\n", vc
->info_str
);
3926 /***********************************************************/
3929 static USBPort
*used_usb_ports
;
3930 static USBPort
*free_usb_ports
;
3932 /* ??? Maybe change this to register a hub to keep track of the topology. */
3933 void qemu_register_usb_port(USBPort
*port
, void *opaque
, int index
,
3934 usb_attachfn attach
)
3936 port
->opaque
= opaque
;
3937 port
->index
= index
;
3938 port
->attach
= attach
;
3939 port
->next
= free_usb_ports
;
3940 free_usb_ports
= port
;
3943 static int usb_device_add(const char *devname
)
3949 if (!free_usb_ports
)
3952 if (strstart(devname
, "host:", &p
)) {
3953 dev
= usb_host_device_open(p
);
3954 } else if (!strcmp(devname
, "mouse")) {
3955 dev
= usb_mouse_init();
3956 } else if (!strcmp(devname
, "tablet")) {
3957 dev
= usb_tablet_init();
3958 } else if (strstart(devname
, "disk:", &p
)) {
3959 dev
= usb_msd_init(p
);
3966 /* Find a USB port to add the device to. */
3967 port
= free_usb_ports
;
3971 /* Create a new hub and chain it on. */
3972 free_usb_ports
= NULL
;
3973 port
->next
= used_usb_ports
;
3974 used_usb_ports
= port
;
3976 hub
= usb_hub_init(VM_USB_HUB_SIZE
);
3977 usb_attach(port
, hub
);
3978 port
= free_usb_ports
;
3981 free_usb_ports
= port
->next
;
3982 port
->next
= used_usb_ports
;
3983 used_usb_ports
= port
;
3984 usb_attach(port
, dev
);
3988 static int usb_device_del(const char *devname
)
3996 if (!used_usb_ports
)
3999 p
= strchr(devname
, '.');
4002 bus_num
= strtoul(devname
, NULL
, 0);
4003 addr
= strtoul(p
+ 1, NULL
, 0);
4007 lastp
= &used_usb_ports
;
4008 port
= used_usb_ports
;
4009 while (port
&& port
->dev
->addr
!= addr
) {
4010 lastp
= &port
->next
;
4018 *lastp
= port
->next
;
4019 usb_attach(port
, NULL
);
4020 dev
->handle_destroy(dev
);
4021 port
->next
= free_usb_ports
;
4022 free_usb_ports
= port
;
4026 void do_usb_add(const char *devname
)
4029 ret
= usb_device_add(devname
);
4031 term_printf("Could not add USB device '%s'\n", devname
);
4034 void do_usb_del(const char *devname
)
4037 ret
= usb_device_del(devname
);
4039 term_printf("Could not remove USB device '%s'\n", devname
);
4046 const char *speed_str
;
4049 term_printf("USB support not enabled\n");
4053 for (port
= used_usb_ports
; port
; port
= port
->next
) {
4057 switch(dev
->speed
) {
4061 case USB_SPEED_FULL
:
4064 case USB_SPEED_HIGH
:
4071 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4072 0, dev
->addr
, speed_str
, dev
->devname
);
4076 /***********************************************************/
4079 static char *pid_filename
;
4081 /* Remove PID file. Called on normal exit */
4083 static void remove_pidfile(void)
4085 unlink (pid_filename
);
4088 static void create_pidfile(const char *filename
)
4090 struct stat pidstat
;
4093 /* Try to write our PID to the named file */
4094 if (stat(filename
, &pidstat
) < 0) {
4095 if (errno
== ENOENT
) {
4096 if ((f
= fopen (filename
, "w")) == NULL
) {
4097 perror("Opening pidfile");
4100 fprintf(f
, "%d\n", getpid());
4102 pid_filename
= qemu_strdup(filename
);
4103 if (!pid_filename
) {
4104 fprintf(stderr
, "Could not save PID filename");
4107 atexit(remove_pidfile
);
4110 fprintf(stderr
, "%s already exists. Remove it and try again.\n",
4116 /***********************************************************/
4119 static void dumb_update(DisplayState
*ds
, int x
, int y
, int w
, int h
)
4123 static void dumb_resize(DisplayState
*ds
, int w
, int h
)
4127 static void dumb_refresh(DisplayState
*ds
)
4132 void dumb_display_init(DisplayState
*ds
)
4137 ds
->dpy_update
= dumb_update
;
4138 ds
->dpy_resize
= dumb_resize
;
4139 ds
->dpy_refresh
= dumb_refresh
;
4142 /***********************************************************/
4145 #define MAX_IO_HANDLERS 64
4147 typedef struct IOHandlerRecord
{
4149 IOCanRWHandler
*fd_read_poll
;
4151 IOHandler
*fd_write
;
4154 /* temporary data */
4156 struct IOHandlerRecord
*next
;
4159 static IOHandlerRecord
*first_io_handler
;
4161 /* XXX: fd_read_poll should be suppressed, but an API change is
4162 necessary in the character devices to suppress fd_can_read(). */
4163 int qemu_set_fd_handler2(int fd
,
4164 IOCanRWHandler
*fd_read_poll
,
4166 IOHandler
*fd_write
,
4169 IOHandlerRecord
**pioh
, *ioh
;
4171 if (!fd_read
&& !fd_write
) {
4172 pioh
= &first_io_handler
;
4177 if (ioh
->fd
== fd
) {
4184 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
4188 ioh
= qemu_mallocz(sizeof(IOHandlerRecord
));
4191 ioh
->next
= first_io_handler
;
4192 first_io_handler
= ioh
;
4195 ioh
->fd_read_poll
= fd_read_poll
;
4196 ioh
->fd_read
= fd_read
;
4197 ioh
->fd_write
= fd_write
;
4198 ioh
->opaque
= opaque
;
4204 int qemu_set_fd_handler(int fd
,
4206 IOHandler
*fd_write
,
4209 return qemu_set_fd_handler2(fd
, NULL
, fd_read
, fd_write
, opaque
);
4212 /***********************************************************/
4213 /* Polling handling */
4215 typedef struct PollingEntry
{
4218 struct PollingEntry
*next
;
4221 static PollingEntry
*first_polling_entry
;
4223 int qemu_add_polling_cb(PollingFunc
*func
, void *opaque
)
4225 PollingEntry
**ppe
, *pe
;
4226 pe
= qemu_mallocz(sizeof(PollingEntry
));
4230 pe
->opaque
= opaque
;
4231 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
);
4236 void qemu_del_polling_cb(PollingFunc
*func
, void *opaque
)
4238 PollingEntry
**ppe
, *pe
;
4239 for(ppe
= &first_polling_entry
; *ppe
!= NULL
; ppe
= &(*ppe
)->next
) {
4241 if (pe
->func
== func
&& pe
->opaque
== opaque
) {
4250 /***********************************************************/
4251 /* Wait objects support */
4252 typedef struct WaitObjects
{
4254 HANDLE events
[MAXIMUM_WAIT_OBJECTS
+ 1];
4255 WaitObjectFunc
*func
[MAXIMUM_WAIT_OBJECTS
+ 1];
4256 void *opaque
[MAXIMUM_WAIT_OBJECTS
+ 1];
4259 static WaitObjects wait_objects
= {0};
4261 int qemu_add_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4263 WaitObjects
*w
= &wait_objects
;
4265 if (w
->num
>= MAXIMUM_WAIT_OBJECTS
)
4267 w
->events
[w
->num
] = handle
;
4268 w
->func
[w
->num
] = func
;
4269 w
->opaque
[w
->num
] = opaque
;
4274 void qemu_del_wait_object(HANDLE handle
, WaitObjectFunc
*func
, void *opaque
)
4277 WaitObjects
*w
= &wait_objects
;
4280 for (i
= 0; i
< w
->num
; i
++) {
4281 if (w
->events
[i
] == handle
)
4284 w
->events
[i
] = w
->events
[i
+ 1];
4285 w
->func
[i
] = w
->func
[i
+ 1];
4286 w
->opaque
[i
] = w
->opaque
[i
+ 1];
4294 #define SELF_ANNOUNCE_ROUNDS 5
4295 #define ETH_P_EXPERIMENTAL 0x01F1 /* just a number */
4296 //#define ETH_P_EXPERIMENTAL 0x0012 /* make it the size of the packet */
4297 #define EXPERIMENTAL_MAGIC 0xf1f23f4f
4299 static int announce_self_create(uint8_t *buf
,
4302 uint32_t magic
= EXPERIMENTAL_MAGIC
;
4303 uint16_t proto
= htons(ETH_P_EXPERIMENTAL
);
4305 /* FIXME: should we send a different packet (arp/rarp/ping)? */
4307 memset(buf
, 0xff, 6); /* h_dst */
4308 memcpy(buf
+ 6, mac_addr
, 6); /* h_src */
4309 memcpy(buf
+ 12, &proto
, 2); /* h_proto */
4310 memcpy(buf
+ 14, &magic
, 4); /* magic */
4312 return 18; /* len */
4315 static void qemu_announce_self(void)
4319 VLANClientState
*vc
;
4322 for (i
= 0; i
< nb_nics
; i
++) {
4323 len
= announce_self_create(buf
, nd_table
[i
].macaddr
);
4324 vlan
= nd_table
[i
].vlan
;
4325 for(vc
= vlan
->first_client
; vc
!= NULL
; vc
= vc
->next
) {
4326 if (vc
->fd_read
== tap_receive
) /* send only if tap */
4327 for (j
=0; j
< SELF_ANNOUNCE_ROUNDS
; j
++)
4328 vc
->fd_read(vc
->opaque
, buf
, len
);
4333 /***********************************************************/
4334 /* savevm/loadvm support */
4336 #define IO_BUF_SIZE 32768
4339 QEMUFilePutBufferFunc
*put_buffer
;
4340 QEMUFileGetBufferFunc
*get_buffer
;
4341 QEMUFileCloseFunc
*close
;
4344 int64_t buf_offset
; /* start of buffer when writing, end of buffer
4347 int buf_size
; /* 0 when writing */
4348 uint8_t buf
[IO_BUF_SIZE
];
4351 typedef struct QEMUFileFD
4356 static int fd_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4358 QEMUFileFD
*s
= opaque
;
4363 len
= read(s
->fd
, buf
+ offset
, size
- offset
);
4365 if (errno
== EINTR
|| errno
== EAGAIN
)
4372 QEMUFile
*qemu_fopen_fd(int fd
)
4374 QEMUFileFD
*s
= qemu_mallocz(sizeof(QEMUFileFD
));
4376 return qemu_fopen(s
, NULL
, fd_get_buffer
, qemu_free
);
4379 typedef struct QEMUFileUnix
4384 static void file_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4386 QEMUFileUnix
*s
= opaque
;
4387 fseek(s
->outfile
, pos
, SEEK_SET
);
4388 fwrite(buf
, 1, size
, s
->outfile
);
4391 static int file_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4393 QEMUFileUnix
*s
= opaque
;
4394 fseek(s
->outfile
, pos
, SEEK_SET
);
4395 return fread(buf
, 1, size
, s
->outfile
);
4398 static void file_close(void *opaque
)
4400 QEMUFileUnix
*s
= opaque
;
4405 QEMUFile
*qemu_fopen_file(const char *filename
, const char *mode
)
4409 s
= qemu_mallocz(sizeof(QEMUFileUnix
));
4413 s
->outfile
= fopen(filename
, mode
);
4417 if (!strcmp(mode
, "wb"))
4418 return qemu_fopen(s
, file_put_buffer
, NULL
, file_close
);
4419 else if (!strcmp(mode
, "rb"))
4420 return qemu_fopen(s
, NULL
, file_get_buffer
, file_close
);
4429 typedef struct QEMUFileBdrv
4431 BlockDriverState
*bs
;
4432 int64_t base_offset
;
4435 static void bdrv_put_buffer(void *opaque
, const uint8_t *buf
, int64_t pos
, int size
)
4437 QEMUFileBdrv
*s
= opaque
;
4438 bdrv_pwrite(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4441 static int bdrv_get_buffer(void *opaque
, uint8_t *buf
, int64_t pos
, int size
)
4443 QEMUFileBdrv
*s
= opaque
;
4444 return bdrv_pread(s
->bs
, s
->base_offset
+ pos
, buf
, size
);
4447 QEMUFile
*qemu_fopen_bdrv(BlockDriverState
*bs
, int64_t offset
, int is_writable
)
4451 s
= qemu_mallocz(sizeof(QEMUFileBdrv
));
4456 s
->base_offset
= offset
;
4459 return qemu_fopen(s
, bdrv_put_buffer
, NULL
, qemu_free
);
4461 return qemu_fopen(s
, NULL
, bdrv_get_buffer
, qemu_free
);
4464 QEMUFile
*qemu_fopen(void *opaque
, QEMUFilePutBufferFunc
*put_buffer
,
4465 QEMUFileGetBufferFunc
*get_buffer
, QEMUFileCloseFunc
*close
)
4469 f
= qemu_mallocz(sizeof(QEMUFile
));
4474 f
->put_buffer
= put_buffer
;
4475 f
->get_buffer
= get_buffer
;
4481 void qemu_fflush(QEMUFile
*f
)
4486 if (f
->buf_index
> 0) {
4487 f
->put_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, f
->buf_index
);
4488 f
->buf_offset
+= f
->buf_index
;
4493 static void qemu_fill_buffer(QEMUFile
*f
)
4500 len
= f
->get_buffer(f
->opaque
, f
->buf
, f
->buf_offset
, IO_BUF_SIZE
);
4506 f
->buf_offset
+= len
;
4509 void qemu_fclose(QEMUFile
*f
)
4513 f
->close(f
->opaque
);
4517 void qemu_put_buffer(QEMUFile
*f
, const uint8_t *buf
, int size
)
4521 l
= IO_BUF_SIZE
- f
->buf_index
;
4524 memcpy(f
->buf
+ f
->buf_index
, buf
, l
);
4528 if (f
->buf_index
>= IO_BUF_SIZE
)
4533 void qemu_put_byte(QEMUFile
*f
, int v
)
4535 f
->buf
[f
->buf_index
++] = v
;
4536 if (f
->buf_index
>= IO_BUF_SIZE
)
4540 int qemu_get_buffer(QEMUFile
*f
, uint8_t *buf
, int size1
)
4546 l
= f
->buf_size
- f
->buf_index
;
4548 qemu_fill_buffer(f
);
4549 l
= f
->buf_size
- f
->buf_index
;
4555 memcpy(buf
, f
->buf
+ f
->buf_index
, l
);
4560 return size1
- size
;
4563 int qemu_get_byte(QEMUFile
*f
)
4565 if (f
->buf_index
>= f
->buf_size
) {
4566 qemu_fill_buffer(f
);
4567 if (f
->buf_index
>= f
->buf_size
)
4570 return f
->buf
[f
->buf_index
++];
4573 int64_t qemu_ftell(QEMUFile
*f
)
4575 return f
->buf_offset
- f
->buf_size
+ f
->buf_index
;
4578 int64_t qemu_fseek(QEMUFile
*f
, int64_t pos
, int whence
)
4580 if (whence
== SEEK_SET
) {
4582 } else if (whence
== SEEK_CUR
) {
4583 pos
+= qemu_ftell(f
);
4585 /* SEEK_END not supported */
4588 if (f
->put_buffer
) {
4590 f
->buf_offset
= pos
;
4592 f
->buf_offset
= pos
;
4599 void qemu_put_be16(QEMUFile
*f
, unsigned int v
)
4601 qemu_put_byte(f
, v
>> 8);
4602 qemu_put_byte(f
, v
);
4605 void qemu_put_be32(QEMUFile
*f
, unsigned int v
)
4607 qemu_put_byte(f
, v
>> 24);
4608 qemu_put_byte(f
, v
>> 16);
4609 qemu_put_byte(f
, v
>> 8);
4610 qemu_put_byte(f
, v
);
4613 void qemu_put_be64(QEMUFile
*f
, uint64_t v
)
4615 qemu_put_be32(f
, v
>> 32);
4616 qemu_put_be32(f
, v
);
4619 unsigned int qemu_get_be16(QEMUFile
*f
)
4622 v
= qemu_get_byte(f
) << 8;
4623 v
|= qemu_get_byte(f
);
4627 unsigned int qemu_get_be32(QEMUFile
*f
)
4630 v
= qemu_get_byte(f
) << 24;
4631 v
|= qemu_get_byte(f
) << 16;
4632 v
|= qemu_get_byte(f
) << 8;
4633 v
|= qemu_get_byte(f
);
4637 uint64_t qemu_get_be64(QEMUFile
*f
)
4640 v
= (uint64_t)qemu_get_be32(f
) << 32;
4641 v
|= qemu_get_be32(f
);
4645 typedef struct SaveStateEntry
{
4649 SaveStateHandler
*save_state
;
4650 LoadStateHandler
*load_state
;
4652 struct SaveStateEntry
*next
;
4655 static SaveStateEntry
*first_se
;
4657 int register_savevm(const char *idstr
,
4660 SaveStateHandler
*save_state
,
4661 LoadStateHandler
*load_state
,
4664 SaveStateEntry
*se
, **pse
;
4666 se
= qemu_malloc(sizeof(SaveStateEntry
));
4669 pstrcpy(se
->idstr
, sizeof(se
->idstr
), idstr
);
4670 se
->instance_id
= instance_id
;
4671 se
->version_id
= version_id
;
4672 se
->save_state
= save_state
;
4673 se
->load_state
= load_state
;
4674 se
->opaque
= opaque
;
4677 /* add at the end of list */
4679 while (*pse
!= NULL
)
4680 pse
= &(*pse
)->next
;
4685 #define QEMU_VM_FILE_MAGIC 0x5145564d
4686 #define QEMU_VM_FILE_VERSION 0x00000002
4688 int qemu_savevm_state(QEMUFile
*f
)
4692 int64_t cur_pos
, len_pos
, total_len_pos
;
4694 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4695 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4696 total_len_pos
= qemu_ftell(f
);
4697 qemu_put_be64(f
, 0); /* total size */
4699 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4701 len
= strlen(se
->idstr
);
4702 qemu_put_byte(f
, len
);
4703 qemu_put_buffer(f
, se
->idstr
, len
);
4705 qemu_put_be32(f
, se
->instance_id
);
4706 qemu_put_be32(f
, se
->version_id
);
4708 /* record size: filled later */
4709 len_pos
= qemu_ftell(f
);
4710 qemu_put_be32(f
, 0);
4712 se
->save_state(f
, se
->opaque
);
4714 /* fill record size */
4715 cur_pos
= qemu_ftell(f
);
4716 len
= cur_pos
- len_pos
- 4;
4717 qemu_fseek(f
, len_pos
, SEEK_SET
);
4718 qemu_put_be32(f
, len
);
4719 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4721 cur_pos
= qemu_ftell(f
);
4722 qemu_fseek(f
, total_len_pos
, SEEK_SET
);
4723 qemu_put_be64(f
, cur_pos
- total_len_pos
- 8);
4724 qemu_fseek(f
, cur_pos
, SEEK_SET
);
4730 static SaveStateEntry
*find_se(const char *idstr
, int instance_id
)
4734 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4735 if (!strcmp(se
->idstr
, idstr
) &&
4736 instance_id
== se
->instance_id
)
4742 int qemu_loadvm_state(QEMUFile
*f
)
4745 int len
, ret
, instance_id
, record_len
, version_id
;
4746 int64_t total_len
, end_pos
, cur_pos
;
4750 v
= qemu_get_be32(f
);
4751 if (v
!= QEMU_VM_FILE_MAGIC
)
4753 v
= qemu_get_be32(f
);
4754 if (v
!= QEMU_VM_FILE_VERSION
) {
4759 total_len
= qemu_get_be64(f
);
4760 end_pos
= total_len
+ qemu_ftell(f
);
4762 if (qemu_ftell(f
) >= end_pos
)
4764 len
= qemu_get_byte(f
);
4765 qemu_get_buffer(f
, idstr
, len
);
4767 instance_id
= qemu_get_be32(f
);
4768 version_id
= qemu_get_be32(f
);
4769 record_len
= qemu_get_be32(f
);
4771 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4772 idstr
, instance_id
, version_id
, record_len
);
4774 cur_pos
= qemu_ftell(f
);
4775 se
= find_se(idstr
, instance_id
);
4777 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4778 instance_id
, idstr
);
4780 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4782 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4783 instance_id
, idstr
);
4787 /* always seek to exact end of record */
4788 qemu_fseek(f
, cur_pos
+ record_len
, SEEK_SET
);
4795 int qemu_live_savevm_state(QEMUFile
*f
)
4800 qemu_put_be32(f
, QEMU_VM_FILE_MAGIC
);
4801 qemu_put_be32(f
, QEMU_VM_FILE_VERSION
);
4803 for(se
= first_se
; se
!= NULL
; se
= se
->next
) {
4804 len
= strlen(se
->idstr
);
4806 qemu_put_byte(f
, len
);
4807 qemu_put_buffer(f
, se
->idstr
, len
);
4808 qemu_put_be32(f
, se
->instance_id
);
4809 qemu_put_be32(f
, se
->version_id
);
4811 se
->save_state(f
, se
->opaque
);
4814 qemu_put_byte(f
, 0);
4820 int qemu_live_loadvm_state(QEMUFile
*f
)
4823 int len
, ret
, instance_id
, version_id
;
4827 v
= qemu_get_be32(f
);
4828 if (v
!= QEMU_VM_FILE_MAGIC
)
4830 v
= qemu_get_be32(f
);
4831 if (v
!= QEMU_VM_FILE_VERSION
) {
4838 len
= qemu_get_byte(f
);
4841 qemu_get_buffer(f
, idstr
, len
);
4843 instance_id
= qemu_get_be32(f
);
4844 version_id
= qemu_get_be32(f
);
4845 se
= find_se(idstr
, instance_id
);
4847 fprintf(stderr
, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4848 instance_id
, idstr
);
4850 if (version_id
> se
->version_id
) { /* src version > dst version */
4851 fprintf(stderr
, "migration:version mismatch:%s:%d(s)>%d(d)\n",
4852 idstr
, version_id
, se
->version_id
);
4856 ret
= se
->load_state(f
, se
->opaque
, version_id
);
4858 fprintf(stderr
, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4859 instance_id
, idstr
);
4866 qemu_announce_self();
4872 /* device can contain snapshots */
4873 static int bdrv_can_snapshot(BlockDriverState
*bs
)
4876 !bdrv_is_removable(bs
) &&
4877 !bdrv_is_read_only(bs
));
4880 /* device must be snapshots in order to have a reliable snapshot */
4881 static int bdrv_has_snapshot(BlockDriverState
*bs
)
4884 !bdrv_is_removable(bs
) &&
4885 !bdrv_is_read_only(bs
));
4888 static BlockDriverState
*get_bs_snapshots(void)
4890 BlockDriverState
*bs
;
4894 return bs_snapshots
;
4895 for(i
= 0; i
<= MAX_DISKS
; i
++) {
4897 if (bdrv_can_snapshot(bs
))
4906 static int bdrv_snapshot_find(BlockDriverState
*bs
, QEMUSnapshotInfo
*sn_info
,
4909 QEMUSnapshotInfo
*sn_tab
, *sn
;
4913 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
4916 for(i
= 0; i
< nb_sns
; i
++) {
4918 if (!strcmp(sn
->id_str
, name
) || !strcmp(sn
->name
, name
)) {
4928 void do_savevm(const char *name
)
4930 BlockDriverState
*bs
, *bs1
;
4931 QEMUSnapshotInfo sn1
, *sn
= &sn1
, old_sn1
, *old_sn
= &old_sn1
;
4932 int must_delete
, ret
, i
;
4933 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
4935 int saved_vm_running
;
4942 bs
= get_bs_snapshots();
4944 term_printf("No block device can accept snapshots\n");
4948 /* ??? Should this occur after vm_stop? */
4951 saved_vm_running
= vm_running
;
4956 ret
= bdrv_snapshot_find(bs
, old_sn
, name
);
4961 memset(sn
, 0, sizeof(*sn
));
4963 pstrcpy(sn
->name
, sizeof(sn
->name
), old_sn
->name
);
4964 pstrcpy(sn
->id_str
, sizeof(sn
->id_str
), old_sn
->id_str
);
4967 pstrcpy(sn
->name
, sizeof(sn
->name
), name
);
4970 /* fill auxiliary fields */
4973 sn
->date_sec
= tb
.time
;
4974 sn
->date_nsec
= tb
.millitm
* 1000000;
4976 gettimeofday(&tv
, NULL
);
4977 sn
->date_sec
= tv
.tv_sec
;
4978 sn
->date_nsec
= tv
.tv_usec
* 1000;
4980 sn
->vm_clock_nsec
= qemu_get_clock(vm_clock
);
4982 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
4983 term_printf("Device %s does not support VM state snapshots\n",
4984 bdrv_get_device_name(bs
));
4988 /* save the VM state */
4989 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 1);
4991 term_printf("Could not open VM state file\n");
4994 ret
= qemu_savevm_state(f
);
4995 sn
->vm_state_size
= qemu_ftell(f
);
4998 term_printf("Error %d while writing VM\n", ret
);
5002 /* create the snapshots */
5004 for(i
= 0; i
< MAX_DISKS
; i
++) {
5006 if (bdrv_has_snapshot(bs1
)) {
5008 ret
= bdrv_snapshot_delete(bs1
, old_sn
->id_str
);
5010 term_printf("Error while deleting snapshot on '%s'\n",
5011 bdrv_get_device_name(bs1
));
5014 ret
= bdrv_snapshot_create(bs1
, sn
);
5016 term_printf("Error while creating snapshot on '%s'\n",
5017 bdrv_get_device_name(bs1
));
5023 if (saved_vm_running
)
5027 void do_loadvm(const char *name
)
5029 BlockDriverState
*bs
, *bs1
;
5030 BlockDriverInfo bdi1
, *bdi
= &bdi1
;
5033 int saved_vm_running
;
5035 bs
= get_bs_snapshots();
5037 term_printf("No block device supports snapshots\n");
5041 /* Flush all IO requests so they don't interfere with the new state. */
5044 saved_vm_running
= vm_running
;
5047 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5049 if (bdrv_has_snapshot(bs1
)) {
5050 ret
= bdrv_snapshot_goto(bs1
, name
);
5053 term_printf("Warning: ");
5056 term_printf("Snapshots not supported on device '%s'\n",
5057 bdrv_get_device_name(bs1
));
5060 term_printf("Could not find snapshot '%s' on device '%s'\n",
5061 name
, bdrv_get_device_name(bs1
));
5064 term_printf("Error %d while activating snapshot on '%s'\n",
5065 ret
, bdrv_get_device_name(bs1
));
5068 /* fatal on snapshot block device */
5075 if (bdrv_get_info(bs
, bdi
) < 0 || bdi
->vm_state_offset
<= 0) {
5076 term_printf("Device %s does not support VM state snapshots\n",
5077 bdrv_get_device_name(bs
));
5081 /* restore the VM state */
5082 f
= qemu_fopen_bdrv(bs
, bdi
->vm_state_offset
, 0);
5084 term_printf("Could not open VM state file\n");
5087 ret
= qemu_loadvm_state(f
);
5090 term_printf("Error %d while loading VM state\n", ret
);
5093 if (saved_vm_running
)
5097 void do_delvm(const char *name
)
5099 BlockDriverState
*bs
, *bs1
;
5102 bs
= get_bs_snapshots();
5104 term_printf("No block device supports snapshots\n");
5108 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5110 if (bdrv_has_snapshot(bs1
)) {
5111 ret
= bdrv_snapshot_delete(bs1
, name
);
5113 if (ret
== -ENOTSUP
)
5114 term_printf("Snapshots not supported on device '%s'\n",
5115 bdrv_get_device_name(bs1
));
5117 term_printf("Error %d while deleting snapshot on '%s'\n",
5118 ret
, bdrv_get_device_name(bs1
));
5124 void do_info_snapshots(void)
5126 BlockDriverState
*bs
, *bs1
;
5127 QEMUSnapshotInfo
*sn_tab
, *sn
;
5131 bs
= get_bs_snapshots();
5133 term_printf("No available block device supports snapshots\n");
5136 term_printf("Snapshot devices:");
5137 for(i
= 0; i
<= MAX_DISKS
; i
++) {
5139 if (bdrv_has_snapshot(bs1
)) {
5141 term_printf(" %s", bdrv_get_device_name(bs1
));
5146 nb_sns
= bdrv_snapshot_list(bs
, &sn_tab
);
5148 term_printf("bdrv_snapshot_list: error %d\n", nb_sns
);
5151 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs
));
5152 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), NULL
));
5153 for(i
= 0; i
< nb_sns
; i
++) {
5155 term_printf("%s\n", bdrv_snapshot_dump(buf
, sizeof(buf
), sn
));
5160 /***********************************************************/
5161 /* cpu save/restore */
5163 #if defined(TARGET_I386)
5165 static void cpu_put_seg(QEMUFile
*f
, SegmentCache
*dt
)
5167 qemu_put_be32(f
, dt
->selector
);
5168 qemu_put_betl(f
, dt
->base
);
5169 qemu_put_be32(f
, dt
->limit
);
5170 qemu_put_be32(f
, dt
->flags
);
5173 static void cpu_get_seg(QEMUFile
*f
, SegmentCache
*dt
)
5175 dt
->selector
= qemu_get_be32(f
);
5176 dt
->base
= qemu_get_betl(f
);
5177 dt
->limit
= qemu_get_be32(f
);
5178 dt
->flags
= qemu_get_be32(f
);
5181 void cpu_save(QEMUFile
*f
, void *opaque
)
5183 CPUState
*env
= opaque
;
5184 uint16_t fptag
, fpus
, fpuc
, fpregs_format
;
5190 kvm_save_registers(env
);
5193 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5194 qemu_put_betls(f
, &env
->regs
[i
]);
5195 qemu_put_betls(f
, &env
->eip
);
5196 qemu_put_betls(f
, &env
->eflags
);
5197 hflags
= env
->hflags
; /* XXX: suppress most of the redundant hflags */
5198 qemu_put_be32s(f
, &hflags
);
5202 fpus
= (env
->fpus
& ~0x3800) | (env
->fpstt
& 0x7) << 11;
5204 for(i
= 0; i
< 8; i
++) {
5205 fptag
|= ((!env
->fptags
[i
]) << i
);
5208 qemu_put_be16s(f
, &fpuc
);
5209 qemu_put_be16s(f
, &fpus
);
5210 qemu_put_be16s(f
, &fptag
);
5212 #ifdef USE_X86LDOUBLE
5217 qemu_put_be16s(f
, &fpregs_format
);
5219 for(i
= 0; i
< 8; i
++) {
5220 #ifdef USE_X86LDOUBLE
5224 /* we save the real CPU data (in case of MMX usage only 'mant'
5225 contains the MMX register */
5226 cpu_get_fp80(&mant
, &exp
, env
->fpregs
[i
].d
);
5227 qemu_put_be64(f
, mant
);
5228 qemu_put_be16(f
, exp
);
5231 /* if we use doubles for float emulation, we save the doubles to
5232 avoid losing information in case of MMX usage. It can give
5233 problems if the image is restored on a CPU where long
5234 doubles are used instead. */
5235 qemu_put_be64(f
, env
->fpregs
[i
].mmx
.MMX_Q(0));
5239 for(i
= 0; i
< 6; i
++)
5240 cpu_put_seg(f
, &env
->segs
[i
]);
5241 cpu_put_seg(f
, &env
->ldt
);
5242 cpu_put_seg(f
, &env
->tr
);
5243 cpu_put_seg(f
, &env
->gdt
);
5244 cpu_put_seg(f
, &env
->idt
);
5246 qemu_put_be32s(f
, &env
->sysenter_cs
);
5247 qemu_put_be32s(f
, &env
->sysenter_esp
);
5248 qemu_put_be32s(f
, &env
->sysenter_eip
);
5250 qemu_put_betls(f
, &env
->cr
[0]);
5251 qemu_put_betls(f
, &env
->cr
[2]);
5252 qemu_put_betls(f
, &env
->cr
[3]);
5253 qemu_put_betls(f
, &env
->cr
[4]);
5255 for(i
= 0; i
< 8; i
++)
5256 qemu_put_betls(f
, &env
->dr
[i
]);
5259 qemu_put_be32s(f
, &env
->a20_mask
);
5262 qemu_put_be32s(f
, &env
->mxcsr
);
5263 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5264 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5265 qemu_put_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5268 #ifdef TARGET_X86_64
5269 qemu_put_be64s(f
, &env
->efer
);
5270 qemu_put_be64s(f
, &env
->star
);
5271 qemu_put_be64s(f
, &env
->lstar
);
5272 qemu_put_be64s(f
, &env
->cstar
);
5273 qemu_put_be64s(f
, &env
->fmask
);
5274 qemu_put_be64s(f
, &env
->kernelgsbase
);
5276 qemu_put_be32s(f
, &env
->smbase
);
5280 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5281 qemu_put_be32s(f
, &env
->kvm_interrupt_bitmap
[i
]);
5283 qemu_put_be64s(f
, &env
->tsc
);
5289 #ifdef USE_X86LDOUBLE
5290 /* XXX: add that in a FPU generic layer */
5291 union x86_longdouble
{
5296 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5297 #define EXPBIAS1 1023
5298 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5299 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5301 static void fp64_to_fp80(union x86_longdouble
*p
, uint64_t temp
)
5305 p
->mant
= (MANTD1(temp
) << 11) | (1LL << 63);
5306 /* exponent + sign */
5307 e
= EXPD1(temp
) - EXPBIAS1
+ 16383;
5308 e
|= SIGND1(temp
) >> 16;
5313 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5315 CPUState
*env
= opaque
;
5318 uint16_t fpus
, fpuc
, fptag
, fpregs_format
;
5320 if (version_id
!= 3 && version_id
!= 4)
5322 for(i
= 0; i
< CPU_NB_REGS
; i
++)
5323 qemu_get_betls(f
, &env
->regs
[i
]);
5324 qemu_get_betls(f
, &env
->eip
);
5325 qemu_get_betls(f
, &env
->eflags
);
5326 qemu_get_be32s(f
, &hflags
);
5328 qemu_get_be16s(f
, &fpuc
);
5329 qemu_get_be16s(f
, &fpus
);
5330 qemu_get_be16s(f
, &fptag
);
5331 qemu_get_be16s(f
, &fpregs_format
);
5333 /* NOTE: we cannot always restore the FPU state if the image come
5334 from a host with a different 'USE_X86LDOUBLE' define. We guess
5335 if we are in an MMX state to restore correctly in that case. */
5336 guess_mmx
= ((fptag
== 0xff) && (fpus
& 0x3800) == 0);
5337 for(i
= 0; i
< 8; i
++) {
5341 switch(fpregs_format
) {
5343 mant
= qemu_get_be64(f
);
5344 exp
= qemu_get_be16(f
);
5345 #ifdef USE_X86LDOUBLE
5346 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5348 /* difficult case */
5350 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5352 env
->fpregs
[i
].d
= cpu_set_fp80(mant
, exp
);
5356 mant
= qemu_get_be64(f
);
5357 #ifdef USE_X86LDOUBLE
5359 union x86_longdouble
*p
;
5360 /* difficult case */
5361 p
= (void *)&env
->fpregs
[i
];
5366 fp64_to_fp80(p
, mant
);
5370 env
->fpregs
[i
].mmx
.MMX_Q(0) = mant
;
5379 /* XXX: restore FPU round state */
5380 env
->fpstt
= (fpus
>> 11) & 7;
5381 env
->fpus
= fpus
& ~0x3800;
5383 for(i
= 0; i
< 8; i
++) {
5384 env
->fptags
[i
] = (fptag
>> i
) & 1;
5387 for(i
= 0; i
< 6; i
++)
5388 cpu_get_seg(f
, &env
->segs
[i
]);
5389 cpu_get_seg(f
, &env
->ldt
);
5390 cpu_get_seg(f
, &env
->tr
);
5391 cpu_get_seg(f
, &env
->gdt
);
5392 cpu_get_seg(f
, &env
->idt
);
5394 qemu_get_be32s(f
, &env
->sysenter_cs
);
5395 qemu_get_be32s(f
, &env
->sysenter_esp
);
5396 qemu_get_be32s(f
, &env
->sysenter_eip
);
5398 qemu_get_betls(f
, &env
->cr
[0]);
5399 qemu_get_betls(f
, &env
->cr
[2]);
5400 qemu_get_betls(f
, &env
->cr
[3]);
5401 qemu_get_betls(f
, &env
->cr
[4]);
5403 for(i
= 0; i
< 8; i
++)
5404 qemu_get_betls(f
, &env
->dr
[i
]);
5407 qemu_get_be32s(f
, &env
->a20_mask
);
5409 qemu_get_be32s(f
, &env
->mxcsr
);
5410 for(i
= 0; i
< CPU_NB_REGS
; i
++) {
5411 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(0));
5412 qemu_get_be64s(f
, &env
->xmm_regs
[i
].XMM_Q(1));
5415 #ifdef TARGET_X86_64
5416 qemu_get_be64s(f
, &env
->efer
);
5417 qemu_get_be64s(f
, &env
->star
);
5418 qemu_get_be64s(f
, &env
->lstar
);
5419 qemu_get_be64s(f
, &env
->cstar
);
5420 qemu_get_be64s(f
, &env
->fmask
);
5421 qemu_get_be64s(f
, &env
->kernelgsbase
);
5423 if (version_id
>= 4)
5424 qemu_get_be32s(f
, &env
->smbase
);
5426 /* XXX: compute hflags from scratch, except for CPL and IIF */
5427 env
->hflags
= hflags
;
5431 for (i
= 0; i
< NR_IRQ_WORDS
; i
++) {
5432 qemu_get_be32s(f
, &env
->kvm_interrupt_bitmap
[i
]);
5434 qemu_get_be64s(f
, &env
->tsc
);
5435 kvm_load_registers(env
);
5441 #elif defined(TARGET_PPC)
5442 void cpu_save(QEMUFile
*f
, void *opaque
)
5446 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5451 #elif defined(TARGET_MIPS)
5452 void cpu_save(QEMUFile
*f
, void *opaque
)
5456 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5461 #elif defined(TARGET_SPARC)
5462 void cpu_save(QEMUFile
*f
, void *opaque
)
5464 CPUState
*env
= opaque
;
5468 for(i
= 0; i
< 8; i
++)
5469 qemu_put_betls(f
, &env
->gregs
[i
]);
5470 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5471 qemu_put_betls(f
, &env
->regbase
[i
]);
5474 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5480 qemu_put_be32(f
, u
.i
);
5483 qemu_put_betls(f
, &env
->pc
);
5484 qemu_put_betls(f
, &env
->npc
);
5485 qemu_put_betls(f
, &env
->y
);
5487 qemu_put_be32(f
, tmp
);
5488 qemu_put_betls(f
, &env
->fsr
);
5489 qemu_put_betls(f
, &env
->tbr
);
5490 #ifndef TARGET_SPARC64
5491 qemu_put_be32s(f
, &env
->wim
);
5493 for(i
= 0; i
< 16; i
++)
5494 qemu_put_be32s(f
, &env
->mmuregs
[i
]);
5498 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5500 CPUState
*env
= opaque
;
5504 for(i
= 0; i
< 8; i
++)
5505 qemu_get_betls(f
, &env
->gregs
[i
]);
5506 for(i
= 0; i
< NWINDOWS
* 16; i
++)
5507 qemu_get_betls(f
, &env
->regbase
[i
]);
5510 for(i
= 0; i
< TARGET_FPREGS
; i
++) {
5515 u
.i
= qemu_get_be32(f
);
5519 qemu_get_betls(f
, &env
->pc
);
5520 qemu_get_betls(f
, &env
->npc
);
5521 qemu_get_betls(f
, &env
->y
);
5522 tmp
= qemu_get_be32(f
);
5523 env
->cwp
= 0; /* needed to ensure that the wrapping registers are
5524 correctly updated */
5526 qemu_get_betls(f
, &env
->fsr
);
5527 qemu_get_betls(f
, &env
->tbr
);
5528 #ifndef TARGET_SPARC64
5529 qemu_get_be32s(f
, &env
->wim
);
5531 for(i
= 0; i
< 16; i
++)
5532 qemu_get_be32s(f
, &env
->mmuregs
[i
]);
5538 #elif defined(TARGET_ARM)
5540 /* ??? Need to implement these. */
5541 void cpu_save(QEMUFile
*f
, void *opaque
)
5545 int cpu_load(QEMUFile
*f
, void *opaque
, int version_id
)
5552 #warning No CPU save/restore functions
5556 /***********************************************************/
5557 /* ram save/restore */
5559 static int ram_get_page(QEMUFile
*f
, uint8_t *buf
, int len
)
5563 v
= qemu_get_byte(f
);
5566 if (qemu_get_buffer(f
, buf
, len
) != len
)
5570 v
= qemu_get_byte(f
);
5571 memset(buf
, v
, len
);
5579 static int ram_load_v1(QEMUFile
*f
, void *opaque
)
5583 if (qemu_get_be32(f
) != phys_ram_size
)
5585 for(i
= 0; i
< phys_ram_size
; i
+= TARGET_PAGE_SIZE
) {
5587 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5590 ret
= ram_get_page(f
, phys_ram_base
+ i
, TARGET_PAGE_SIZE
);
5597 #define BDRV_HASH_BLOCK_SIZE 1024
5598 #define IOBUF_SIZE 4096
5599 #define RAM_CBLOCK_MAGIC 0xfabe
5601 typedef struct RamCompressState
{
5604 uint8_t buf
[IOBUF_SIZE
];
5607 static int ram_compress_open(RamCompressState
*s
, QEMUFile
*f
)
5610 memset(s
, 0, sizeof(*s
));
5612 ret
= deflateInit2(&s
->zstream
, 1,
5614 9, Z_DEFAULT_STRATEGY
);
5617 s
->zstream
.avail_out
= IOBUF_SIZE
;
5618 s
->zstream
.next_out
= s
->buf
;
5622 static void ram_put_cblock(RamCompressState
*s
, const uint8_t *buf
, int len
)
5624 qemu_put_be16(s
->f
, RAM_CBLOCK_MAGIC
);
5625 qemu_put_be16(s
->f
, len
);
5626 qemu_put_buffer(s
->f
, buf
, len
);
5629 static int ram_compress_buf(RamCompressState
*s
, const uint8_t *buf
, int len
)
5633 s
->zstream
.avail_in
= len
;
5634 s
->zstream
.next_in
= (uint8_t *)buf
;
5635 while (s
->zstream
.avail_in
> 0) {
5636 ret
= deflate(&s
->zstream
, Z_NO_FLUSH
);
5639 if (s
->zstream
.avail_out
== 0) {
5640 ram_put_cblock(s
, s
->buf
, IOBUF_SIZE
);
5641 s
->zstream
.avail_out
= IOBUF_SIZE
;
5642 s
->zstream
.next_out
= s
->buf
;
5648 static void ram_compress_close(RamCompressState
*s
)
5652 /* compress last bytes */
5654 ret
= deflate(&s
->zstream
, Z_FINISH
);
5655 if (ret
== Z_OK
|| ret
== Z_STREAM_END
) {
5656 len
= IOBUF_SIZE
- s
->zstream
.avail_out
;
5658 ram_put_cblock(s
, s
->buf
, len
);
5660 s
->zstream
.avail_out
= IOBUF_SIZE
;
5661 s
->zstream
.next_out
= s
->buf
;
5662 if (ret
== Z_STREAM_END
)
5669 deflateEnd(&s
->zstream
);
5672 typedef struct RamDecompressState
{
5675 uint8_t buf
[IOBUF_SIZE
];
5676 } RamDecompressState
;
5678 static int ram_decompress_open(RamDecompressState
*s
, QEMUFile
*f
)
5681 memset(s
, 0, sizeof(*s
));
5683 ret
= inflateInit(&s
->zstream
);
5689 static int ram_decompress_buf(RamDecompressState
*s
, uint8_t *buf
, int len
)
5693 s
->zstream
.avail_out
= len
;
5694 s
->zstream
.next_out
= buf
;
5695 while (s
->zstream
.avail_out
> 0) {
5696 if (s
->zstream
.avail_in
== 0) {
5697 if (qemu_get_be16(s
->f
) != RAM_CBLOCK_MAGIC
)
5699 clen
= qemu_get_be16(s
->f
);
5700 if (clen
> IOBUF_SIZE
)
5702 qemu_get_buffer(s
->f
, s
->buf
, clen
);
5703 s
->zstream
.avail_in
= clen
;
5704 s
->zstream
.next_in
= s
->buf
;
5706 ret
= inflate(&s
->zstream
, Z_PARTIAL_FLUSH
);
5707 if (ret
!= Z_OK
&& ret
!= Z_STREAM_END
) {
5714 static void ram_decompress_close(RamDecompressState
*s
)
5716 inflateEnd(&s
->zstream
);
5719 static void ram_save_live(QEMUFile
*f
, void *opaque
)
5723 for (addr
= 0; addr
< phys_ram_size
; addr
+= TARGET_PAGE_SIZE
) {
5725 if (kvm_allowed
&& (addr
>=0xa0000) && (addr
<0xc0000)) /* do not access video-addresses */
5728 if (cpu_physical_memory_get_dirty(addr
, MIGRATION_DIRTY_FLAG
)) {
5729 qemu_put_be32(f
, addr
);
5730 qemu_put_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5733 qemu_put_be32(f
, 1);
5736 static void ram_save_static(QEMUFile
*f
, void *opaque
)
5739 RamCompressState s1
, *s
= &s1
;
5742 qemu_put_be32(f
, phys_ram_size
);
5743 if (ram_compress_open(s
, f
) < 0)
5745 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5747 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5751 if (tight_savevm_enabled
) {
5755 /* find if the memory block is available on a virtual
5758 for(j
= 0; j
< MAX_DISKS
; j
++) {
5760 sector_num
= bdrv_hash_find(bs_table
[j
],
5761 phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5762 if (sector_num
>= 0)
5767 goto normal_compress
;
5770 cpu_to_be64wu((uint64_t *)(buf
+ 2), sector_num
);
5771 ram_compress_buf(s
, buf
, 10);
5777 ram_compress_buf(s
, buf
, 1);
5778 ram_compress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
);
5781 ram_compress_close(s
);
5784 static void ram_save(QEMUFile
*f
, void *opaque
)
5786 int in_migration
= cpu_physical_memory_get_dirty_tracking();
5788 qemu_put_byte(f
, in_migration
);
5791 ram_save_live(f
, opaque
);
5793 ram_save_static(f
, opaque
);
5796 static int ram_load_live(QEMUFile
*f
, void *opaque
)
5801 addr
= qemu_get_be32(f
);
5805 qemu_get_buffer(f
, phys_ram_base
+ addr
, TARGET_PAGE_SIZE
);
5811 static int ram_load_static(QEMUFile
*f
, void *opaque
)
5813 RamDecompressState s1
, *s
= &s1
;
5817 if (qemu_get_be32(f
) != phys_ram_size
)
5819 if (ram_decompress_open(s
, f
) < 0)
5821 for(i
= 0; i
< phys_ram_size
; i
+= BDRV_HASH_BLOCK_SIZE
) {
5823 if (kvm_allowed
&& (i
>=0xa0000) && (i
<0xc0000)) /* do not access video-addresses */
5826 if (ram_decompress_buf(s
, buf
, 1) < 0) {
5827 fprintf(stderr
, "Error while reading ram block header\n");
5831 if (ram_decompress_buf(s
, phys_ram_base
+ i
, BDRV_HASH_BLOCK_SIZE
) < 0) {
5832 fprintf(stderr
, "Error while reading ram block address=0x%08x", i
);
5841 ram_decompress_buf(s
, buf
+ 1, 9);
5843 sector_num
= be64_to_cpupu((const uint64_t *)(buf
+ 2));
5844 if (bs_index
>= MAX_DISKS
|| bs_table
[bs_index
] == NULL
) {
5845 fprintf(stderr
, "Invalid block device index %d\n", bs_index
);
5848 if (bdrv_read(bs_table
[bs_index
], sector_num
, phys_ram_base
+ i
,
5849 BDRV_HASH_BLOCK_SIZE
/ 512) < 0) {
5850 fprintf(stderr
, "Error while reading sector %d:%" PRId64
"\n",
5851 bs_index
, sector_num
);
5858 printf("Error block header\n");
5862 ram_decompress_close(s
);
5866 static int ram_load(QEMUFile
*f
, void *opaque
, int version_id
)
5870 switch (version_id
) {
5872 ret
= ram_load_v1(f
, opaque
);
5875 if (qemu_get_byte(f
)) {
5876 ret
= ram_load_live(f
, opaque
);
5880 ret
= ram_load_static(f
, opaque
);
5890 /***********************************************************/
5891 /* bottom halves (can be seen as timers which expire ASAP) */
5900 static QEMUBH
*first_bh
= NULL
;
5902 QEMUBH
*qemu_bh_new(QEMUBHFunc
*cb
, void *opaque
)
5905 bh
= qemu_mallocz(sizeof(QEMUBH
));
5909 bh
->opaque
= opaque
;
5913 int qemu_bh_poll(void)
5932 void qemu_bh_schedule(QEMUBH
*bh
)
5934 CPUState
*env
= cpu_single_env
;
5938 bh
->next
= first_bh
;
5941 /* stop the currently executing CPU to execute the BH ASAP */
5943 cpu_interrupt(env
, CPU_INTERRUPT_EXIT
);
5947 void qemu_bh_cancel(QEMUBH
*bh
)
5950 if (bh
->scheduled
) {
5953 pbh
= &(*pbh
)->next
;
5959 void qemu_bh_delete(QEMUBH
*bh
)
5965 /***********************************************************/
5966 /* machine registration */
5968 QEMUMachine
*first_machine
= NULL
;
5970 int qemu_register_machine(QEMUMachine
*m
)
5973 pm
= &first_machine
;
5981 QEMUMachine
*find_machine(const char *name
)
5985 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
5986 if (!strcmp(m
->name
, name
))
5992 /***********************************************************/
5993 /* main execution loop */
5995 void gui_update(void *opaque
)
5997 display_state
.dpy_refresh(&display_state
);
5998 qemu_mod_timer(gui_timer
, GUI_REFRESH_INTERVAL
+ qemu_get_clock(rt_clock
));
6001 struct vm_change_state_entry
{
6002 VMChangeStateHandler
*cb
;
6004 LIST_ENTRY (vm_change_state_entry
) entries
;
6007 static LIST_HEAD(vm_change_state_head
, vm_change_state_entry
) vm_change_state_head
;
6009 VMChangeStateEntry
*qemu_add_vm_change_state_handler(VMChangeStateHandler
*cb
,
6012 VMChangeStateEntry
*e
;
6014 e
= qemu_mallocz(sizeof (*e
));
6020 LIST_INSERT_HEAD(&vm_change_state_head
, e
, entries
);
6024 void qemu_del_vm_change_state_handler(VMChangeStateEntry
*e
)
6026 LIST_REMOVE (e
, entries
);
6030 static void vm_state_notify(int running
)
6032 VMChangeStateEntry
*e
;
6034 for (e
= vm_change_state_head
.lh_first
; e
; e
= e
->entries
.le_next
) {
6035 e
->cb(e
->opaque
, running
);
6039 /* XXX: support several handlers */
6040 static VMStopHandler
*vm_stop_cb
;
6041 static void *vm_stop_opaque
;
6043 int qemu_add_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6046 vm_stop_opaque
= opaque
;
6050 void qemu_del_vm_stop_handler(VMStopHandler
*cb
, void *opaque
)
6064 void vm_stop(int reason
)
6067 cpu_disable_ticks();
6071 vm_stop_cb(vm_stop_opaque
, reason
);
6078 /* reset/shutdown handler */
6080 typedef struct QEMUResetEntry
{
6081 QEMUResetHandler
*func
;
6083 struct QEMUResetEntry
*next
;
6086 static QEMUResetEntry
*first_reset_entry
;
6087 static int reset_requested
;
6088 static int shutdown_requested
;
6089 static int powerdown_requested
;
6091 int qemu_shutdown_requested(void)
6093 int r
= shutdown_requested
;
6094 shutdown_requested
= 0;
6098 int qemu_reset_requested(void)
6100 int r
= reset_requested
;
6101 reset_requested
= 0;
6105 int qemu_powerdown_requested(void)
6107 int r
= powerdown_requested
;
6108 powerdown_requested
= 0;
6112 void qemu_register_reset(QEMUResetHandler
*func
, void *opaque
)
6114 QEMUResetEntry
**pre
, *re
;
6116 pre
= &first_reset_entry
;
6117 while (*pre
!= NULL
)
6118 pre
= &(*pre
)->next
;
6119 re
= qemu_mallocz(sizeof(QEMUResetEntry
));
6121 re
->opaque
= opaque
;
6126 void qemu_system_reset(void)
6130 /* reset all devices */
6131 for(re
= first_reset_entry
; re
!= NULL
; re
= re
->next
) {
6132 re
->func(re
->opaque
);
6136 void qemu_system_reset_request(void)
6139 shutdown_requested
= 1;
6141 reset_requested
= 1;
6144 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6147 void qemu_system_shutdown_request(void)
6149 shutdown_requested
= 1;
6151 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6154 void qemu_system_powerdown_request(void)
6156 powerdown_requested
= 1;
6158 cpu_interrupt(cpu_single_env
, CPU_INTERRUPT_EXIT
);
6161 void main_loop_wait(int timeout
)
6163 IOHandlerRecord
*ioh
;
6164 fd_set rfds
, wfds
, xfds
;
6170 /* XXX: need to suppress polling by better using win32 events */
6172 for(pe
= first_polling_entry
; pe
!= NULL
; pe
= pe
->next
) {
6173 ret
|= pe
->func(pe
->opaque
);
6176 if (ret
== 0 && timeout
> 0) {
6178 WaitObjects
*w
= &wait_objects
;
6180 ret
= WaitForMultipleObjects(w
->num
, w
->events
, FALSE
, timeout
);
6181 if (WAIT_OBJECT_0
+ 0 <= ret
&& ret
<= WAIT_OBJECT_0
+ w
->num
- 1) {
6182 if (w
->func
[ret
- WAIT_OBJECT_0
])
6183 w
->func
[ret
- WAIT_OBJECT_0
](w
->opaque
[ret
- WAIT_OBJECT_0
]);
6184 } else if (ret
== WAIT_TIMEOUT
) {
6186 err
= GetLastError();
6187 fprintf(stderr
, "Wait error %d %d\n", ret
, err
);
6191 /* poll any events */
6192 /* XXX: separate device handlers from system ones */
6197 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6201 (!ioh
->fd_read_poll
||
6202 ioh
->fd_read_poll(ioh
->opaque
) != 0)) {
6203 FD_SET(ioh
->fd
, &rfds
);
6207 if (ioh
->fd_write
) {
6208 FD_SET(ioh
->fd
, &wfds
);
6218 tv
.tv_usec
= timeout
* 1000;
6220 #if defined(CONFIG_SLIRP)
6222 slirp_select_fill(&nfds
, &rfds
, &wfds
, &xfds
);
6225 ret
= select(nfds
+ 1, &rfds
, &wfds
, &xfds
, &tv
);
6227 IOHandlerRecord
**pioh
;
6229 for(ioh
= first_io_handler
; ioh
!= NULL
; ioh
= ioh
->next
) {
6232 if (FD_ISSET(ioh
->fd
, &rfds
)) {
6233 ioh
->fd_read(ioh
->opaque
);
6235 if (FD_ISSET(ioh
->fd
, &wfds
)) {
6236 ioh
->fd_write(ioh
->opaque
);
6240 /* remove deleted IO handlers */
6241 pioh
= &first_io_handler
;
6251 #if defined(CONFIG_SLIRP)
6258 slirp_select_poll(&rfds
, &wfds
, &xfds
);
6265 qemu_run_timers(&active_timers
[QEMU_TIMER_VIRTUAL
],
6266 qemu_get_clock(vm_clock
));
6267 /* run dma transfers, if any */
6271 /* real time timers */
6272 qemu_run_timers(&active_timers
[QEMU_TIMER_REALTIME
],
6273 qemu_get_clock(rt_clock
));
6276 static CPUState
*cur_cpu
;
6281 #ifdef CONFIG_PROFILER
6290 cpu_disable_ticks();
6294 cur_cpu
= first_cpu
;
6301 env
= env
->next_cpu
;
6304 #ifdef CONFIG_PROFILER
6305 ti
= profile_getclock();
6307 ret
= cpu_exec(env
);
6308 #ifdef CONFIG_PROFILER
6309 qemu_time
+= profile_getclock() - ti
;
6311 if (ret
!= EXCP_HALTED
)
6313 /* all CPUs are halted ? */
6314 if (env
== cur_cpu
) {
6321 if (shutdown_requested
) {
6322 ret
= EXCP_INTERRUPT
;
6325 if (reset_requested
) {
6326 reset_requested
= 0;
6327 qemu_system_reset();
6330 kvm_load_registers(env
);
6332 ret
= EXCP_INTERRUPT
;
6334 if (powerdown_requested
) {
6335 powerdown_requested
= 0;
6336 qemu_system_powerdown();
6337 ret
= EXCP_INTERRUPT
;
6339 if (ret
== EXCP_DEBUG
) {
6340 vm_stop(EXCP_DEBUG
);
6342 /* if hlt instruction, we wait until the next IRQ */
6343 /* XXX: use timeout computed from timers */
6344 if (ret
== EXCP_HLT
)
6351 #ifdef CONFIG_PROFILER
6352 ti
= profile_getclock();
6354 main_loop_wait(timeout
);
6355 #ifdef CONFIG_PROFILER
6356 dev_time
+= profile_getclock() - ti
;
6359 cpu_disable_ticks();
6365 printf("QEMU PC emulator version " QEMU_VERSION
", Copyright (c) 2003-2007 Fabrice Bellard\n"
6366 "usage: %s [options] [disk_image]\n"
6368 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6370 "Standard options:\n"
6371 "-M machine select emulated machine (-M ? for list)\n"
6372 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6373 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6374 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6375 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6376 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6377 "-snapshot write to temporary files instead of disk image files\n"
6379 "-no-quit disable SDL window close capability\n"
6382 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6384 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6385 "-smp n set the number of CPUs to 'n' [default=1]\n"
6386 "-nographic disable graphical output and redirect serial I/Os to console\n"
6388 "-k language use keyboard layout (for example \"fr\" for French)\n"
6391 "-audio-help print list of audio drivers and their options\n"
6392 "-soundhw c1,... enable audio support\n"
6393 " and only specified sound cards (comma separated list)\n"
6394 " use -soundhw ? to get the list of supported cards\n"
6395 " use -soundhw all to enable all of them\n"
6397 "-localtime set the real time clock to local time [default=utc]\n"
6398 "-full-screen start in full screen\n"
6400 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6402 "-usb enable the USB driver (will be the default soon)\n"
6403 "-usbdevice name add the host or guest USB device 'name'\n"
6404 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6405 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6408 "Network options:\n"
6409 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6410 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6412 "-net user[,vlan=n][,hostname=host]\n"
6413 " connect the user mode network stack to VLAN 'n' and send\n"
6414 " hostname 'host' to DHCP clients\n"
6417 "-net tap[,vlan=n],ifname=name\n"
6418 " connect the host TAP network interface to VLAN 'n'\n"
6420 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6421 " connect the host TAP network interface to VLAN 'n' and use\n"
6422 " the network script 'file' (default=%s);\n"
6423 " use 'script=no' to disable script execution;\n"
6424 " use 'fd=h' to connect to an already opened TAP interface\n"
6426 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6427 " connect the vlan 'n' to another VLAN using a socket connection\n"
6428 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6429 " connect the vlan 'n' to multicast maddr and port\n"
6430 "-net none use it alone to have zero network devices; if no -net option\n"
6431 " is provided, the default is '-net nic -net user'\n"
6434 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6436 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6438 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6439 " redirect TCP or UDP connections from host to guest [-net user]\n"
6442 "Linux boot specific:\n"
6443 "-kernel bzImage use 'bzImage' as kernel image\n"
6444 "-append cmdline use 'cmdline' as kernel command line\n"
6445 "-initrd file use 'file' as initial ram disk\n"
6447 "Debug/Expert options:\n"
6448 "-monitor dev redirect the monitor to char device 'dev'\n"
6449 "-vmchannel di:DI,dev redirect the hypercall device with device id DI, to char device 'dev'\n"
6450 "-balloon dev redirect the balloon hypercall device to char device 'dev'\n"
6451 "-serial dev redirect the serial port to char device 'dev'\n"
6452 "-parallel dev redirect the parallel port to char device 'dev'\n"
6453 "-pidfile file Write PID to 'file'\n"
6454 "-S freeze CPU at startup (use 'c' to start execution)\n"
6455 "-s wait gdb connection to port %d\n"
6456 "-p port change gdb connection port\n"
6457 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6458 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6459 " translation (t=none or lba) (usually qemu can guess them)\n"
6460 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6462 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6463 "-no-kqemu disable KQEMU kernel module usage\n"
6466 "-no-kvm disable KVM hardware virtualization\n"
6468 #ifdef USE_CODE_COPY
6469 "-no-code-copy disable code copy acceleration\n"
6472 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6473 " (default is CL-GD5446 PCI VGA)\n"
6474 "-no-acpi disable ACPI\n"
6476 "-no-reboot exit instead of rebooting\n"
6477 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6478 "-vnc display start a VNC server on display\n"
6480 "-daemonize daemonize QEMU after initializing\n"
6482 "-no-tdf do not inject timer interrupts that got lost\n"
6483 #if defined(__linux__)
6484 "-no-rtc don't use /dev/rtc for timer alarm (do use gettimeofday)\n"
6486 "-option-rom rom load a file, rom, into the option ROM space\n"
6488 "During emulation, the following keys are useful:\n"
6489 "ctrl-alt-f toggle full screen\n"
6490 "ctrl-alt-n switch to virtual console 'n'\n"
6491 "ctrl-alt toggle mouse and keyboard grab\n"
6493 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6498 DEFAULT_NETWORK_SCRIPT
,
6500 DEFAULT_GDBSTUB_PORT
,
6505 #define HAS_ARG 0x0001
6519 QEMU_OPTION_snapshot
,
6521 QEMU_OPTION_no_fd_bootchk
,
6524 QEMU_OPTION_nographic
,
6526 QEMU_OPTION_audio_help
,
6527 QEMU_OPTION_soundhw
,
6545 QEMU_OPTION_no_code_copy
,
6547 QEMU_OPTION_localtime
,
6548 QEMU_OPTION_cirrusvga
,
6550 QEMU_OPTION_std_vga
,
6551 QEMU_OPTION_monitor
,
6552 QEMU_OPTION_balloon
,
6553 QEMU_OPTION_vmchannel
,
6555 QEMU_OPTION_parallel
,
6557 QEMU_OPTION_full_screen
,
6558 QEMU_OPTION_no_quit
,
6559 QEMU_OPTION_pidfile
,
6560 QEMU_OPTION_no_kqemu
,
6561 QEMU_OPTION_kernel_kqemu
,
6562 QEMU_OPTION_win2k_hack
,
6564 QEMU_OPTION_usbdevice
,
6567 QEMU_OPTION_no_acpi
,
6569 QEMU_OPTION_no_reboot
,
6570 QEMU_OPTION_daemonize
,
6571 QEMU_OPTION_option_rom
,
6572 QEMU_OPTION_semihosting
,
6573 QEMU_OPTION_incoming
,
6575 #if defined(__linux__)
6578 QEMU_OPTION_cpu_vendor
,
6581 typedef struct QEMUOption
{
6587 const QEMUOption qemu_options
[] = {
6588 { "h", 0, QEMU_OPTION_h
},
6589 { "help", 0, QEMU_OPTION_h
},
6591 { "M", HAS_ARG
, QEMU_OPTION_M
},
6592 { "fda", HAS_ARG
, QEMU_OPTION_fda
},
6593 { "fdb", HAS_ARG
, QEMU_OPTION_fdb
},
6594 { "hda", HAS_ARG
, QEMU_OPTION_hda
},
6595 { "hdb", HAS_ARG
, QEMU_OPTION_hdb
},
6596 { "hdc", HAS_ARG
, QEMU_OPTION_hdc
},
6597 { "hdd", HAS_ARG
, QEMU_OPTION_hdd
},
6598 { "cdrom", HAS_ARG
, QEMU_OPTION_cdrom
},
6599 { "boot", HAS_ARG
, QEMU_OPTION_boot
},
6600 { "snapshot", 0, QEMU_OPTION_snapshot
},
6602 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk
},
6604 { "m", HAS_ARG
, QEMU_OPTION_m
},
6605 { "nographic", 0, QEMU_OPTION_nographic
},
6606 { "k", HAS_ARG
, QEMU_OPTION_k
},
6608 { "audio-help", 0, QEMU_OPTION_audio_help
},
6609 { "soundhw", HAS_ARG
, QEMU_OPTION_soundhw
},
6612 { "net", HAS_ARG
, QEMU_OPTION_net
},
6614 { "tftp", HAS_ARG
, QEMU_OPTION_tftp
},
6616 { "smb", HAS_ARG
, QEMU_OPTION_smb
},
6618 { "redir", HAS_ARG
, QEMU_OPTION_redir
},
6621 { "kernel", HAS_ARG
, QEMU_OPTION_kernel
},
6622 { "append", HAS_ARG
, QEMU_OPTION_append
},
6623 { "initrd", HAS_ARG
, QEMU_OPTION_initrd
},
6625 { "S", 0, QEMU_OPTION_S
},
6626 { "s", 0, QEMU_OPTION_s
},
6627 { "p", HAS_ARG
, QEMU_OPTION_p
},
6628 { "d", HAS_ARG
, QEMU_OPTION_d
},
6629 { "hdachs", HAS_ARG
, QEMU_OPTION_hdachs
},
6630 { "L", HAS_ARG
, QEMU_OPTION_L
},
6631 { "no-code-copy", 0, QEMU_OPTION_no_code_copy
},
6633 { "no-kqemu", 0, QEMU_OPTION_no_kqemu
},
6634 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu
},
6637 { "no-kvm", 0, QEMU_OPTION_no_kvm
},
6639 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6640 { "g", 1, QEMU_OPTION_g
},
6642 { "localtime", 0, QEMU_OPTION_localtime
},
6643 { "std-vga", 0, QEMU_OPTION_std_vga
},
6644 { "monitor", 1, QEMU_OPTION_monitor
},
6645 { "balloon", 1, QEMU_OPTION_balloon
},
6646 { "vmchannel", 1, QEMU_OPTION_vmchannel
},
6647 { "serial", 1, QEMU_OPTION_serial
},
6648 { "parallel", 1, QEMU_OPTION_parallel
},
6649 { "loadvm", HAS_ARG
, QEMU_OPTION_loadvm
},
6650 { "incoming", 1, QEMU_OPTION_incoming
},
6651 { "full-screen", 0, QEMU_OPTION_full_screen
},
6653 { "no-quit", 0, QEMU_OPTION_no_quit
},
6655 { "pidfile", HAS_ARG
, QEMU_OPTION_pidfile
},
6656 { "win2k-hack", 0, QEMU_OPTION_win2k_hack
},
6657 { "usbdevice", HAS_ARG
, QEMU_OPTION_usbdevice
},
6658 { "smp", HAS_ARG
, QEMU_OPTION_smp
},
6659 { "vnc", HAS_ARG
, QEMU_OPTION_vnc
},
6661 /* temporary options */
6662 { "usb", 0, QEMU_OPTION_usb
},
6663 { "cirrusvga", 0, QEMU_OPTION_cirrusvga
},
6664 { "no-acpi", 0, QEMU_OPTION_no_acpi
},
6665 { "no-reboot", 0, QEMU_OPTION_no_reboot
},
6666 { "daemonize", 0, QEMU_OPTION_daemonize
},
6667 { "option-rom", HAS_ARG
, QEMU_OPTION_option_rom
},
6668 #if defined(TARGET_ARM)
6669 { "semihosting", 0, QEMU_OPTION_semihosting
},
6671 { "no-tdf", 0, QEMU_OPTION_tdf
}, /* no time drift fix */
6672 #if defined(__linux__)
6673 { "no-rtc", 0, QEMU_OPTION_no_rtc
},
6675 { "cpu-vendor", HAS_ARG
, QEMU_OPTION_cpu_vendor
},
6679 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6681 /* this stack is only used during signal handling */
6682 #define SIGNAL_STACK_SIZE 32768
6684 static uint8_t *signal_stack
;
6688 /* password input */
6690 static BlockDriverState
*get_bdrv(int index
)
6692 BlockDriverState
*bs
;
6695 bs
= bs_table
[index
];
6696 } else if (index
< 6) {
6697 bs
= fd_table
[index
- 4];
6704 static void read_passwords(void)
6706 BlockDriverState
*bs
;
6710 for(i
= 0; i
< 6; i
++) {
6712 if (bs
&& bdrv_is_encrypted(bs
)) {
6713 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs
));
6714 for(j
= 0; j
< 3; j
++) {
6715 monitor_readline("Password: ",
6716 1, password
, sizeof(password
));
6717 if (bdrv_set_key(bs
, password
) == 0)
6719 term_printf("invalid password\n");
6725 /* XXX: currently we cannot use simultaneously different CPUs */
6726 void register_machines(void)
6728 #if defined(TARGET_I386)
6729 qemu_register_machine(&pc_machine
);
6730 qemu_register_machine(&isapc_machine
);
6731 #elif defined(TARGET_PPC)
6732 qemu_register_machine(&heathrow_machine
);
6733 qemu_register_machine(&core99_machine
);
6734 qemu_register_machine(&prep_machine
);
6735 #elif defined(TARGET_MIPS)
6736 qemu_register_machine(&mips_machine
);
6737 qemu_register_machine(&mips_malta_machine
);
6738 #elif defined(TARGET_SPARC)
6739 #ifdef TARGET_SPARC64
6740 qemu_register_machine(&sun4u_machine
);
6742 qemu_register_machine(&sun4m_machine
);
6744 #elif defined(TARGET_ARM)
6745 qemu_register_machine(&integratorcp926_machine
);
6746 qemu_register_machine(&integratorcp1026_machine
);
6747 qemu_register_machine(&versatilepb_machine
);
6748 qemu_register_machine(&versatileab_machine
);
6749 qemu_register_machine(&realview_machine
);
6750 #elif defined(TARGET_SH4)
6751 qemu_register_machine(&shix_machine
);
6753 #error unsupported CPU
6758 struct soundhw soundhw
[] = {
6765 { .init_isa
= pcspk_audio_init
}
6770 "Creative Sound Blaster 16",
6773 { .init_isa
= SB16_init
}
6780 "Yamaha YMF262 (OPL3)",
6782 "Yamaha YM3812 (OPL2)",
6786 { .init_isa
= Adlib_init
}
6793 "Gravis Ultrasound GF1",
6796 { .init_isa
= GUS_init
}
6802 "ENSONIQ AudioPCI ES1370",
6805 { .init_pci
= es1370_init
}
6808 { NULL
, NULL
, 0, 0, { NULL
} }
6811 static void select_soundhw (const char *optarg
)
6815 if (*optarg
== '?') {
6818 printf ("Valid sound card names (comma separated):\n");
6819 for (c
= soundhw
; c
->name
; ++c
) {
6820 printf ("%-11s %s\n", c
->name
, c
->descr
);
6822 printf ("\n-soundhw all will enable all of the above\n");
6823 exit (*optarg
!= '?');
6831 if (!strcmp (optarg
, "all")) {
6832 for (c
= soundhw
; c
->name
; ++c
) {
6840 e
= strchr (p
, ',');
6841 l
= !e
? strlen (p
) : (size_t) (e
- p
);
6843 for (c
= soundhw
; c
->name
; ++c
) {
6844 if (!strncmp (c
->name
, p
, l
)) {
6853 "Unknown sound card name (too big to show)\n");
6856 fprintf (stderr
, "Unknown sound card name `%.*s'\n",
6861 p
+= l
+ (e
!= NULL
);
6865 goto show_valid_cards
;
6871 static BOOL WINAPI
qemu_ctrl_handler(DWORD type
)
6873 exit(STATUS_CONTROL_C_EXIT
);
6878 #define MAX_NET_CLIENTS 32
6880 static int saved_argc
;
6881 static char **saved_argv
;
6883 void qemu_get_launch_info(int *argc
, char ***argv
, int *opt_daemonize
, const char **opt_incoming
)
6887 *opt_daemonize
= daemonize
;
6888 *opt_incoming
= incoming
;
6891 int main(int argc
, char **argv
)
6893 #ifdef CONFIG_GDBSTUB
6894 int use_gdbstub
, gdbstub_port
;
6897 int snapshot
, linux_boot
;
6898 const char *initrd_filename
;
6899 const char *hd_filename
[MAX_DISKS
], *fd_filename
[MAX_FD
];
6900 const char *kernel_filename
, *kernel_cmdline
;
6901 DisplayState
*ds
= &display_state
;
6902 int cyls
, heads
, secs
, translation
;
6903 char net_clients
[MAX_NET_CLIENTS
][256];
6906 const char *r
, *optarg
;
6907 CharDriverState
*monitor_hd
;
6908 char monitor_device
[128];
6909 char vmchannel_devices
[MAX_VMCHANNEL_DEVICES
][128];
6910 int vmchannel_device_index
;
6911 char serial_devices
[MAX_SERIAL_PORTS
][128];
6912 int serial_device_index
;
6913 char parallel_devices
[MAX_PARALLEL_PORTS
][128];
6914 int parallel_device_index
;
6915 const char *loadvm
= NULL
;
6916 QEMUMachine
*machine
;
6917 char usb_devices
[MAX_USB_CMDLINE
][128];
6918 int usb_devices_index
;
6924 LIST_INIT (&vm_change_state_head
);
6927 struct sigaction act
;
6928 sigfillset(&act
.sa_mask
);
6930 act
.sa_handler
= SIG_IGN
;
6931 sigaction(SIGPIPE
, &act
, NULL
);
6934 SetConsoleCtrlHandler(qemu_ctrl_handler
, TRUE
);
6935 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6936 QEMU to run on a single CPU */
6941 h
= GetCurrentProcess();
6942 if (GetProcessAffinityMask(h
, &mask
, &smask
)) {
6943 for(i
= 0; i
< 32; i
++) {
6944 if (mask
& (1 << i
))
6949 SetProcessAffinityMask(h
, mask
);
6955 register_machines();
6956 machine
= first_machine
;
6957 initrd_filename
= NULL
;
6958 for(i
= 0; i
< MAX_FD
; i
++)
6959 fd_filename
[i
] = NULL
;
6960 for(i
= 0; i
< MAX_DISKS
; i
++)
6961 hd_filename
[i
] = NULL
;
6962 ram_size
= DEFAULT_RAM_SIZE
* 1024 * 1024;
6963 vga_ram_size
= VGA_RAM_SIZE
;
6964 bios_size
= BIOS_SIZE
;
6965 #ifdef CONFIG_GDBSTUB
6967 gdbstub_port
= DEFAULT_GDBSTUB_PORT
;
6971 kernel_filename
= NULL
;
6972 kernel_cmdline
= "";
6978 cyls
= heads
= secs
= 0;
6979 translation
= BIOS_ATA_TRANSLATION_AUTO
;
6980 pstrcpy(monitor_device
, sizeof(monitor_device
), "vc");
6982 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++)
6983 vmchannel_devices
[i
][0] = '\0';
6984 vmchannel_device_index
= 0;
6986 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "vc");
6987 for(i
= 1; i
< MAX_SERIAL_PORTS
; i
++)
6988 serial_devices
[i
][0] = '\0';
6989 serial_device_index
= 0;
6991 pstrcpy(parallel_devices
[0], sizeof(parallel_devices
[0]), "vc");
6992 for(i
= 1; i
< MAX_PARALLEL_PORTS
; i
++)
6993 parallel_devices
[i
][0] = '\0';
6994 parallel_device_index
= 0;
6996 usb_devices_index
= 0;
7001 /* default mac address of the first network interface */
7009 hd_filename
[0] = argv
[optind
++];
7011 const QEMUOption
*popt
;
7014 /* Treat --foo the same as -foo. */
7017 popt
= qemu_options
;
7020 fprintf(stderr
, "%s: invalid option -- '%s'\n",
7024 if (!strcmp(popt
->name
, r
+ 1))
7028 if (popt
->flags
& HAS_ARG
) {
7029 if (optind
>= argc
) {
7030 fprintf(stderr
, "%s: option '%s' requires an argument\n",
7034 optarg
= argv
[optind
++];
7039 switch(popt
->index
) {
7041 machine
= find_machine(optarg
);
7044 printf("Supported machines are:\n");
7045 for(m
= first_machine
; m
!= NULL
; m
= m
->next
) {
7046 printf("%-10s %s%s\n",
7048 m
== first_machine
? " (default)" : "");
7053 case QEMU_OPTION_initrd
:
7054 initrd_filename
= optarg
;
7056 case QEMU_OPTION_hda
:
7057 case QEMU_OPTION_hdb
:
7058 case QEMU_OPTION_hdc
:
7059 case QEMU_OPTION_hdd
:
7062 hd_index
= popt
->index
- QEMU_OPTION_hda
;
7063 hd_filename
[hd_index
] = optarg
;
7064 if (hd_index
== cdrom_index
)
7068 case QEMU_OPTION_snapshot
:
7071 case QEMU_OPTION_hdachs
:
7075 cyls
= strtol(p
, (char **)&p
, 0);
7076 if (cyls
< 1 || cyls
> 16383)
7081 heads
= strtol(p
, (char **)&p
, 0);
7082 if (heads
< 1 || heads
> 16)
7087 secs
= strtol(p
, (char **)&p
, 0);
7088 if (secs
< 1 || secs
> 63)
7092 if (!strcmp(p
, "none"))
7093 translation
= BIOS_ATA_TRANSLATION_NONE
;
7094 else if (!strcmp(p
, "lba"))
7095 translation
= BIOS_ATA_TRANSLATION_LBA
;
7096 else if (!strcmp(p
, "auto"))
7097 translation
= BIOS_ATA_TRANSLATION_AUTO
;
7100 } else if (*p
!= '\0') {
7102 fprintf(stderr
, "qemu: invalid physical CHS format\n");
7107 case QEMU_OPTION_nographic
:
7108 pstrcpy(monitor_device
, sizeof(monitor_device
), "stdio");
7109 pstrcpy(serial_devices
[0], sizeof(serial_devices
[0]), "stdio");
7112 case QEMU_OPTION_kernel
:
7113 kernel_filename
= optarg
;
7115 case QEMU_OPTION_append
:
7116 kernel_cmdline
= optarg
;
7118 case QEMU_OPTION_cdrom
:
7119 if (cdrom_index
>= 0) {
7120 hd_filename
[cdrom_index
] = optarg
;
7123 case QEMU_OPTION_boot
:
7124 boot_device
= optarg
[0];
7125 if (boot_device
!= 'a' &&
7126 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7128 boot_device
!= 'n' &&
7130 boot_device
!= 'c' && boot_device
!= 'd') {
7131 fprintf(stderr
, "qemu: invalid boot device '%c'\n", boot_device
);
7135 case QEMU_OPTION_fda
:
7136 fd_filename
[0] = optarg
;
7138 case QEMU_OPTION_fdb
:
7139 fd_filename
[1] = optarg
;
7142 case QEMU_OPTION_no_fd_bootchk
:
7146 case QEMU_OPTION_no_code_copy
:
7147 code_copy_enabled
= 0;
7149 case QEMU_OPTION_net
:
7150 if (nb_net_clients
>= MAX_NET_CLIENTS
) {
7151 fprintf(stderr
, "qemu: too many network clients\n");
7154 pstrcpy(net_clients
[nb_net_clients
],
7155 sizeof(net_clients
[0]),
7160 case QEMU_OPTION_tftp
:
7161 tftp_prefix
= optarg
;
7164 case QEMU_OPTION_smb
:
7165 net_slirp_smb(optarg
);
7168 case QEMU_OPTION_redir
:
7169 net_slirp_redir(optarg
);
7173 case QEMU_OPTION_audio_help
:
7177 case QEMU_OPTION_soundhw
:
7178 select_soundhw (optarg
);
7185 ram_size
= atoi(optarg
) * 1024 * 1024;
7188 if (ram_size
> PHYS_RAM_MAX_SIZE
) {
7189 fprintf(stderr
, "qemu: at most %d MB RAM can be simulated\n",
7190 PHYS_RAM_MAX_SIZE
/ (1024 * 1024));
7199 mask
= cpu_str_to_log_mask(optarg
);
7201 printf("Log items (comma separated):\n");
7202 for(item
= cpu_log_items
; item
->mask
!= 0; item
++) {
7203 printf("%-10s %s\n", item
->name
, item
->help
);
7210 #ifdef CONFIG_GDBSTUB
7215 gdbstub_port
= atoi(optarg
);
7225 keyboard_layout
= optarg
;
7227 case QEMU_OPTION_localtime
:
7230 case QEMU_OPTION_cirrusvga
:
7231 cirrus_vga_enabled
= 1;
7233 case QEMU_OPTION_std_vga
:
7234 cirrus_vga_enabled
= 0;
7241 w
= strtol(p
, (char **)&p
, 10);
7244 fprintf(stderr
, "qemu: invalid resolution or depth\n");
7250 h
= strtol(p
, (char **)&p
, 10);
7255 depth
= strtol(p
, (char **)&p
, 10);
7256 if (depth
!= 8 && depth
!= 15 && depth
!= 16 &&
7257 depth
!= 24 && depth
!= 32)
7259 } else if (*p
== '\0') {
7260 depth
= graphic_depth
;
7267 graphic_depth
= depth
;
7270 case QEMU_OPTION_monitor
:
7271 pstrcpy(monitor_device
, sizeof(monitor_device
), optarg
);
7273 case QEMU_OPTION_balloon
:
7274 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
7275 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
7279 fprintf(stderr
, "qemu: only one balloon device can be used\n");
7282 sprintf(vmchannel_devices
[vmchannel_device_index
],"di:cdcd,%s", optarg
);
7283 vmchannel_device_index
++;
7286 case QEMU_OPTION_vmchannel
:
7287 if (vmchannel_device_index
>= MAX_VMCHANNEL_DEVICES
) {
7288 fprintf(stderr
, "qemu: too many balloon/vmchannel devices\n");
7291 pstrcpy(vmchannel_devices
[vmchannel_device_index
],
7292 sizeof(vmchannel_devices
[0]), optarg
);
7293 vmchannel_device_index
++;
7295 case QEMU_OPTION_serial
:
7296 if (serial_device_index
>= MAX_SERIAL_PORTS
) {
7297 fprintf(stderr
, "qemu: too many serial ports\n");
7300 pstrcpy(serial_devices
[serial_device_index
],
7301 sizeof(serial_devices
[0]), optarg
);
7302 serial_device_index
++;
7304 case QEMU_OPTION_parallel
:
7305 if (parallel_device_index
>= MAX_PARALLEL_PORTS
) {
7306 fprintf(stderr
, "qemu: too many parallel ports\n");
7309 pstrcpy(parallel_devices
[parallel_device_index
],
7310 sizeof(parallel_devices
[0]), optarg
);
7311 parallel_device_index
++;
7313 case QEMU_OPTION_loadvm
:
7316 case QEMU_OPTION_incoming
:
7319 case QEMU_OPTION_full_screen
:
7323 case QEMU_OPTION_no_quit
:
7327 case QEMU_OPTION_pidfile
:
7328 create_pidfile(optarg
);
7331 case QEMU_OPTION_win2k_hack
:
7332 win2k_install_hack
= 1;
7336 case QEMU_OPTION_no_kqemu
:
7339 case QEMU_OPTION_kernel_kqemu
:
7344 case QEMU_OPTION_no_kvm
:
7348 case QEMU_OPTION_usb
:
7351 case QEMU_OPTION_usbdevice
:
7353 if (usb_devices_index
>= MAX_USB_CMDLINE
) {
7354 fprintf(stderr
, "Too many USB devices\n");
7357 pstrcpy(usb_devices
[usb_devices_index
],
7358 sizeof(usb_devices
[usb_devices_index
]),
7360 usb_devices_index
++;
7362 case QEMU_OPTION_smp
:
7363 smp_cpus
= atoi(optarg
);
7364 if (smp_cpus
< 1 || smp_cpus
> MAX_CPUS
) {
7365 fprintf(stderr
, "Invalid number of CPUs\n");
7369 case QEMU_OPTION_vnc
:
7370 vnc_display
= optarg
;
7372 case QEMU_OPTION_no_acpi
:
7375 case QEMU_OPTION_no_reboot
:
7378 case QEMU_OPTION_daemonize
:
7381 case QEMU_OPTION_option_rom
:
7382 if (nb_option_roms
>= MAX_OPTION_ROMS
) {
7383 fprintf(stderr
, "Too many option ROMs\n");
7386 option_rom
[nb_option_roms
] = optarg
;
7389 case QEMU_OPTION_semihosting
:
7390 semihosting_enabled
= 1;
7392 case QEMU_OPTION_tdf
:
7394 #if defined(__linux__)
7395 case QEMU_OPTION_no_rtc
:
7399 case QEMU_OPTION_cpu_vendor
:
7400 cpu_vendor_string
= optarg
;
7410 if (pipe(fds
) == -1)
7421 len
= read(fds
[0], &status
, 1);
7422 if (len
== -1 && (errno
== EINTR
))
7425 if (len
!= 1 || status
!= 0)
7442 signal(SIGTSTP
, SIG_IGN
);
7443 signal(SIGTTOU
, SIG_IGN
);
7444 signal(SIGTTIN
, SIG_IGN
);
7450 if (kvm_qemu_init() < 0) {
7451 fprintf(stderr
, "Could not initialize KVM, will disable KVM support\n");
7461 linux_boot
= (kernel_filename
!= NULL
);
7464 hd_filename
[0] == '\0' &&
7465 (cdrom_index
>= 0 && hd_filename
[cdrom_index
] == '\0') &&
7466 fd_filename
[0] == '\0')
7469 /* boot to floppy or the default cd if no hard disk defined yet */
7470 if (hd_filename
[0] == '\0' && boot_device
== 'c') {
7471 if (fd_filename
[0] != '\0')
7477 setvbuf(stdout
, NULL
, _IOLBF
, 0);
7487 /* init network clients */
7488 if (nb_net_clients
== 0) {
7489 /* if no clients, we use a default config */
7490 pstrcpy(net_clients
[0], sizeof(net_clients
[0]),
7492 pstrcpy(net_clients
[1], sizeof(net_clients
[0]),
7497 for(i
= 0;i
< nb_net_clients
; i
++) {
7498 if (net_client_init(net_clients
[i
]) < 0)
7503 if (boot_device
== 'n') {
7504 for (i
= 0; i
< nb_nics
; i
++) {
7505 const char *model
= nd_table
[i
].model
;
7509 snprintf(buf
, sizeof(buf
), "%s/pxe-%s.bin", bios_dir
, model
);
7510 if (get_image_size(buf
) > 0) {
7511 option_rom
[nb_option_roms
] = strdup(buf
);
7517 fprintf(stderr
, "No valid PXE rom found for network device\n");
7520 boot_device
= 'c'; /* to prevent confusion by the BIOS */
7524 /* init the memory */
7525 phys_ram_size
= ram_size
+ vga_ram_size
+ bios_size
;
7528 for (i
= 0; i
< nb_option_roms
; i
++) {
7529 int ret
= get_image_size(option_rom
[i
]);
7531 fprintf(stderr
, "Could not load option rom '%s'\n", option_rom
[i
]);
7534 phys_ram_size
+= ret
;
7538 /* Initialize kvm */
7540 phys_ram_size
+= KVM_EXTRA_PAGES
* 4096;
7541 if (kvm_qemu_create_context() < 0) {
7542 fprintf(stderr
, "Could not create KVM context\n");
7546 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7547 if (!phys_ram_base
) {
7548 fprintf(stderr
, "Could not allocate physical memory\n");
7553 phys_ram_base
= qemu_vmalloc(phys_ram_size
);
7554 if (!phys_ram_base
) {
7555 fprintf(stderr
, "Could not allocate physical memory\n");
7560 /* we always create the cdrom drive, even if no disk is there */
7562 if (cdrom_index
>= 0) {
7563 bs_table
[cdrom_index
] = bdrv_new("cdrom");
7564 bdrv_set_type_hint(bs_table
[cdrom_index
], BDRV_TYPE_CDROM
);
7567 /* open the virtual block devices */
7568 for(i
= 0; i
< MAX_DISKS
; i
++) {
7569 if (hd_filename
[i
]) {
7572 snprintf(buf
, sizeof(buf
), "hd%c", i
+ 'a');
7573 bs_table
[i
] = bdrv_new(buf
);
7575 if (bdrv_open(bs_table
[i
], hd_filename
[i
], snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7576 fprintf(stderr
, "qemu: could not open hard disk image '%s'\n",
7580 if (i
== 0 && cyls
!= 0) {
7581 bdrv_set_geometry_hint(bs_table
[i
], cyls
, heads
, secs
);
7582 bdrv_set_translation_hint(bs_table
[i
], translation
);
7587 /* we always create at least one floppy disk */
7588 fd_table
[0] = bdrv_new("fda");
7589 bdrv_set_type_hint(fd_table
[0], BDRV_TYPE_FLOPPY
);
7591 for(i
= 0; i
< MAX_FD
; i
++) {
7592 if (fd_filename
[i
]) {
7595 snprintf(buf
, sizeof(buf
), "fd%c", i
+ 'a');
7596 fd_table
[i
] = bdrv_new(buf
);
7597 bdrv_set_type_hint(fd_table
[i
], BDRV_TYPE_FLOPPY
);
7599 if (fd_filename
[i
] != '\0') {
7600 if (bdrv_open(fd_table
[i
], fd_filename
[i
],
7601 snapshot
? BDRV_O_SNAPSHOT
: 0) < 0) {
7602 fprintf(stderr
, "qemu: could not open floppy disk image '%s'\n",
7610 register_savevm("timer", 0, 2, timer_save
, timer_load
, NULL
);
7611 register_savevm("ram", 0, 3, ram_save
, ram_load
, NULL
);
7617 dumb_display_init(ds
);
7618 } else if (vnc_display
!= NULL
) {
7619 vnc_display_init(ds
, vnc_display
);
7621 #if defined(CONFIG_SDL)
7622 sdl_display_init(ds
, full_screen
);
7623 #elif defined(CONFIG_COCOA)
7624 cocoa_display_init(ds
, full_screen
);
7626 dumb_display_init(ds
);
7630 monitor_hd
= qemu_chr_open(monitor_device
);
7632 fprintf(stderr
, "qemu: could not open monitor device '%s'\n", monitor_device
);
7635 monitor_init(monitor_hd
, !nographic
);
7637 for(i
= 0; i
< MAX_VMCHANNEL_DEVICES
; i
++) {
7638 const char *devname
= vmchannel_devices
[i
];
7639 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7643 if (strstart(devname
, "di:", &devname
)) {
7644 devid
= strtol(devname
, &termn
, 16);
7645 devname
= termn
+ 1;
7648 fprintf(stderr
, "qemu: could not find vmchannel device id '%s'\n",
7652 vmchannel_hds
[i
] = qemu_chr_open(devname
);
7653 if (!vmchannel_hds
[i
]) {
7654 fprintf(stderr
, "qemu: could not open vmchannel device '%s'\n",
7658 vmchannel_init(vmchannel_hds
[i
], devid
, i
);
7662 for(i
= 0; i
< MAX_SERIAL_PORTS
; i
++) {
7663 const char *devname
= serial_devices
[i
];
7664 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7665 serial_hds
[i
] = qemu_chr_open(devname
);
7666 if (!serial_hds
[i
]) {
7667 fprintf(stderr
, "qemu: could not open serial device '%s'\n",
7671 if (!strcmp(devname
, "vc"))
7672 qemu_chr_printf(serial_hds
[i
], "serial%d console\r\n", i
);
7676 for(i
= 0; i
< MAX_PARALLEL_PORTS
; i
++) {
7677 const char *devname
= parallel_devices
[i
];
7678 if (devname
[0] != '\0' && strcmp(devname
, "none")) {
7679 parallel_hds
[i
] = qemu_chr_open(devname
);
7680 if (!parallel_hds
[i
]) {
7681 fprintf(stderr
, "qemu: could not open parallel device '%s'\n",
7685 if (!strcmp(devname
, "vc"))
7686 qemu_chr_printf(parallel_hds
[i
], "parallel%d console\r\n", i
);
7690 machine
->init(ram_size
, vga_ram_size
, boot_device
,
7691 ds
, fd_filename
, snapshot
,
7692 kernel_filename
, kernel_cmdline
, initrd_filename
);
7694 /* init USB devices */
7696 for(i
= 0; i
< usb_devices_index
; i
++) {
7697 if (usb_device_add(usb_devices
[i
]) < 0) {
7698 fprintf(stderr
, "Warning: could not add USB device %s\n",
7704 gui_timer
= qemu_new_timer(rt_clock
, gui_update
, NULL
);
7705 qemu_mod_timer(gui_timer
, qemu_get_clock(rt_clock
));
7707 #ifdef CONFIG_GDBSTUB
7709 /* XXX: use standard host:port notation and modify options
7711 if (gdbserver_start_port(gdbstub_port
) < 0) {
7712 fprintf(stderr
, "qemu: could not open gdbstub device on port '%d'\n",
7725 rc
= migrate_incoming(incoming
);
7727 fprintf(stderr
, "Migration failed rc=%d\n", rc
);
7733 /* XXX: simplify init */
7746 len
= write(fds
[1], &status
, 1);
7747 if (len
== -1 && (errno
== EINTR
))
7754 fd
= open("/dev/null", O_RDWR
);