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>
50 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
55 #include <linux/if_tun.h>
58 #include <linux/rtc.h>
59 #include <linux/ppdev.h>
60 #include <linux/parport.h>
63 #include <sys/ethernet.h>
64 #include <sys/sockio.h>
65 #include <arpa/inet.h>
66 #include <netinet/arp.h>
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_icmp.h> // must come after ip.h
71 #include <netinet/udp.h>
72 #include <netinet/tcp.h>
80 #if defined(CONFIG_SLIRP)
86 #include <sys/timeb.h>
88 #define getopt_long_only getopt_long
89 #define memalign(align, size) malloc(size)
92 #include "qemu_socket.h"
98 #endif /* CONFIG_SDL */
102 #define main qemu_main
103 #endif /* CONFIG_COCOA */
107 #include "exec-all.h"
109 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
111 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
113 #define SMBD_COMMAND "/usr/sbin/smbd"
116 //#define DEBUG_UNUSED_IOPORT
117 //#define DEBUG_IOPORT
119 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
122 #define DEFAULT_RAM_SIZE 144
124 #define DEFAULT_RAM_SIZE 128
127 #define GUI_REFRESH_INTERVAL 30
129 /* Max number of USB devices that can be specified on the commandline. */
130 #define MAX_USB_CMDLINE 8
132 /* XXX: use a two level table to limit memory usage */
133 #define MAX_IOPORTS 65536
135 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
136 char phys_ram_file[1024];
137 void *ioport_opaque[MAX_IOPORTS];
138 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
139 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
140 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
141 to store the VM snapshots */
142 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
143 BlockDriverState *pflash_table[MAX_PFLASH];
144 BlockDriverState *sd_bdrv;
145 BlockDriverState *mtd_bdrv;
146 /* point to the block driver where the snapshots are managed */
147 BlockDriverState *bs_snapshots;
149 static DisplayState display_state;
151 const char* keyboard_layout = NULL;
152 int64_t ticks_per_sec;
153 int boot_device = 'c';
155 int pit_min_timer_count = 0;
157 NICInfo nd_table[MAX_NICS];
160 int cirrus_vga_enabled = 1;
161 int vmsvga_enabled = 0;
163 int graphic_width = 1024;
164 int graphic_height = 768;
165 int graphic_depth = 8;
167 int graphic_width = 800;
168 int graphic_height = 600;
169 int graphic_depth = 15;
174 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
175 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
177 int win2k_install_hack = 0;
180 static VLANState *first_vlan;
182 const char *vnc_display;
183 #if defined(TARGET_SPARC)
185 #elif defined(TARGET_I386)
190 int acpi_enabled = 1;
194 int graphic_rotate = 0;
196 const char *option_rom[MAX_OPTION_ROMS];
198 int semihosting_enabled = 0;
200 const char *qemu_name;
203 unsigned int nb_prom_envs = 0;
204 const char *prom_envs[MAX_PROM_ENVS];
207 /***********************************************************/
208 /* x86 ISA bus support */
210 target_phys_addr_t isa_mem_base = 0;
213 uint32_t default_ioport_readb(void *opaque, uint32_t address)
215 #ifdef DEBUG_UNUSED_IOPORT
216 fprintf(stderr, "unused inb: port=0x%04x\n", address);
221 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
228 /* default is to make two byte accesses */
229 uint32_t default_ioport_readw(void *opaque, uint32_t address)
232 data = ioport_read_table[0][address](ioport_opaque[address], address);
233 address = (address + 1) & (MAX_IOPORTS - 1);
234 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
238 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
240 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
241 address = (address + 1) & (MAX_IOPORTS - 1);
242 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
245 uint32_t default_ioport_readl(void *opaque, uint32_t address)
247 #ifdef DEBUG_UNUSED_IOPORT
248 fprintf(stderr, "unused inl: port=0x%04x\n", address);
253 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
255 #ifdef DEBUG_UNUSED_IOPORT
256 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
260 void init_ioports(void)
264 for(i = 0; i < MAX_IOPORTS; i++) {
265 ioport_read_table[0][i] = default_ioport_readb;
266 ioport_write_table[0][i] = default_ioport_writeb;
267 ioport_read_table[1][i] = default_ioport_readw;
268 ioport_write_table[1][i] = default_ioport_writew;
269 ioport_read_table[2][i] = default_ioport_readl;
270 ioport_write_table[2][i] = default_ioport_writel;
274 /* size is the word size in byte */
275 int register_ioport_read(int start, int length, int size,
276 IOPortReadFunc *func, void *opaque)
282 } else if (size == 2) {
284 } else if (size == 4) {
287 hw_error("register_ioport_read: invalid size");
290 for(i = start; i < start + length; i += size) {
291 ioport_read_table[bsize][i] = func;
292 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
293 hw_error("register_ioport_read: invalid opaque");
294 ioport_opaque[i] = opaque;
299 /* size is the word size in byte */
300 int register_ioport_write(int start, int length, int size,
301 IOPortWriteFunc *func, void *opaque)
307 } else if (size == 2) {
309 } else if (size == 4) {
312 hw_error("register_ioport_write: invalid size");
315 for(i = start; i < start + length; i += size) {
316 ioport_write_table[bsize][i] = func;
317 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
318 hw_error("register_ioport_write: invalid opaque");
319 ioport_opaque[i] = opaque;
324 void isa_unassign_ioport(int start, int length)
328 for(i = start; i < start + length; i++) {
329 ioport_read_table[0][i] = default_ioport_readb;
330 ioport_read_table[1][i] = default_ioport_readw;
331 ioport_read_table[2][i] = default_ioport_readl;
333 ioport_write_table[0][i] = default_ioport_writeb;
334 ioport_write_table[1][i] = default_ioport_writew;
335 ioport_write_table[2][i] = default_ioport_writel;
339 /***********************************************************/
341 void cpu_outb(CPUState *env, int addr, int val)
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outb: %04x %02x\n", addr, val);
347 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
350 env->last_io_time = cpu_get_time_fast();
354 void cpu_outw(CPUState *env, int addr, int val)
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outw: %04x %04x\n", addr, val);
360 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
363 env->last_io_time = cpu_get_time_fast();
367 void cpu_outl(CPUState *env, int addr, int val)
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outl: %04x %08x\n", addr, val);
373 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
376 env->last_io_time = cpu_get_time_fast();
380 int cpu_inb(CPUState *env, int addr)
383 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inb : %04x %02x\n", addr, val);
390 env->last_io_time = cpu_get_time_fast();
395 int cpu_inw(CPUState *env, int addr)
398 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inw : %04x %04x\n", addr, val);
405 env->last_io_time = cpu_get_time_fast();
410 int cpu_inl(CPUState *env, int addr)
413 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inl : %04x %08x\n", addr, val);
420 env->last_io_time = cpu_get_time_fast();
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
435 for(env = first_cpu; env != NULL; env = env->next_cpu) {
436 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
438 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
440 cpu_dump_state(env, stderr, fprintf, 0);
447 /***********************************************************/
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
453 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
455 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
457 qemu_put_kbd_event_opaque = opaque;
458 qemu_put_kbd_event = func;
461 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
462 void *opaque, int absolute,
465 QEMUPutMouseEntry *s, *cursor;
467 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
471 s->qemu_put_mouse_event = func;
472 s->qemu_put_mouse_event_opaque = opaque;
473 s->qemu_put_mouse_event_absolute = absolute;
474 s->qemu_put_mouse_event_name = qemu_strdup(name);
477 if (!qemu_put_mouse_event_head) {
478 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
482 cursor = qemu_put_mouse_event_head;
483 while (cursor->next != NULL)
484 cursor = cursor->next;
487 qemu_put_mouse_event_current = s;
492 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
494 QEMUPutMouseEntry *prev = NULL, *cursor;
496 if (!qemu_put_mouse_event_head || entry == NULL)
499 cursor = qemu_put_mouse_event_head;
500 while (cursor != NULL && cursor != entry) {
502 cursor = cursor->next;
505 if (cursor == NULL) // does not exist or list empty
507 else if (prev == NULL) { // entry is head
508 qemu_put_mouse_event_head = cursor->next;
509 if (qemu_put_mouse_event_current == entry)
510 qemu_put_mouse_event_current = cursor->next;
511 qemu_free(entry->qemu_put_mouse_event_name);
516 prev->next = entry->next;
518 if (qemu_put_mouse_event_current == entry)
519 qemu_put_mouse_event_current = prev;
521 qemu_free(entry->qemu_put_mouse_event_name);
525 void kbd_put_keycode(int keycode)
527 if (qemu_put_kbd_event) {
528 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
532 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
534 QEMUPutMouseEvent *mouse_event;
535 void *mouse_event_opaque;
538 if (!qemu_put_mouse_event_current) {
543 qemu_put_mouse_event_current->qemu_put_mouse_event;
545 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
548 if (graphic_rotate) {
549 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
552 width = graphic_width;
553 mouse_event(mouse_event_opaque,
554 width - dy, dx, dz, buttons_state);
556 mouse_event(mouse_event_opaque,
557 dx, dy, dz, buttons_state);
561 int kbd_mouse_is_absolute(void)
563 if (!qemu_put_mouse_event_current)
566 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
569 void do_info_mice(void)
571 QEMUPutMouseEntry *cursor;
574 if (!qemu_put_mouse_event_head) {
575 term_printf("No mouse devices connected\n");
579 term_printf("Mouse devices available:\n");
580 cursor = qemu_put_mouse_event_head;
581 while (cursor != NULL) {
582 term_printf("%c Mouse #%d: %s\n",
583 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
584 index, cursor->qemu_put_mouse_event_name);
586 cursor = cursor->next;
590 void do_mouse_set(int index)
592 QEMUPutMouseEntry *cursor;
595 if (!qemu_put_mouse_event_head) {
596 term_printf("No mouse devices connected\n");
600 cursor = qemu_put_mouse_event_head;
601 while (cursor != NULL && index != i) {
603 cursor = cursor->next;
607 qemu_put_mouse_event_current = cursor;
609 term_printf("Mouse at given index not found\n");
612 /* compute with 96 bit intermediate result: (a*b)/c */
613 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
618 #ifdef WORDS_BIGENDIAN
628 rl = (uint64_t)u.l.low * (uint64_t)b;
629 rh = (uint64_t)u.l.high * (uint64_t)b;
632 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
636 /***********************************************************/
637 /* real time host monotonic timer */
639 #define QEMU_TIMER_BASE 1000000000LL
643 static int64_t clock_freq;
645 static void init_get_clock(void)
649 ret = QueryPerformanceFrequency(&freq);
651 fprintf(stderr, "Could not calibrate ticks\n");
654 clock_freq = freq.QuadPart;
657 static int64_t get_clock(void)
660 QueryPerformanceCounter(&ti);
661 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
666 static int use_rt_clock;
668 static void init_get_clock(void)
671 #if defined(__linux__)
674 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
681 static int64_t get_clock(void)
683 #if defined(__linux__)
686 clock_gettime(CLOCK_MONOTONIC, &ts);
687 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
691 /* XXX: using gettimeofday leads to problems if the date
692 changes, so it should be avoided. */
694 gettimeofday(&tv, NULL);
695 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
701 /***********************************************************/
702 /* guest cycle counter */
704 static int64_t cpu_ticks_prev;
705 static int64_t cpu_ticks_offset;
706 static int64_t cpu_clock_offset;
707 static int cpu_ticks_enabled;
709 /* return the host CPU cycle counter and handle stop/restart */
710 int64_t cpu_get_ticks(void)
712 if (!cpu_ticks_enabled) {
713 return cpu_ticks_offset;
716 ticks = cpu_get_real_ticks();
717 if (cpu_ticks_prev > ticks) {
718 /* Note: non increasing ticks may happen if the host uses
720 cpu_ticks_offset += cpu_ticks_prev - ticks;
722 cpu_ticks_prev = ticks;
723 return ticks + cpu_ticks_offset;
727 /* return the host CPU monotonic timer and handle stop/restart */
728 static int64_t cpu_get_clock(void)
731 if (!cpu_ticks_enabled) {
732 return cpu_clock_offset;
735 return ti + cpu_clock_offset;
739 /* enable cpu_get_ticks() */
740 void cpu_enable_ticks(void)
742 if (!cpu_ticks_enabled) {
743 cpu_ticks_offset -= cpu_get_real_ticks();
744 cpu_clock_offset -= get_clock();
745 cpu_ticks_enabled = 1;
749 /* disable cpu_get_ticks() : the clock is stopped. You must not call
750 cpu_get_ticks() after that. */
751 void cpu_disable_ticks(void)
753 if (cpu_ticks_enabled) {
754 cpu_ticks_offset = cpu_get_ticks();
755 cpu_clock_offset = cpu_get_clock();
756 cpu_ticks_enabled = 0;
760 /***********************************************************/
763 #define QEMU_TIMER_REALTIME 0
764 #define QEMU_TIMER_VIRTUAL 1
768 /* XXX: add frequency */
776 struct QEMUTimer *next;
782 static QEMUTimer *active_timers[2];
784 static MMRESULT timerID;
785 static HANDLE host_alarm = NULL;
786 static unsigned int period = 1;
788 /* frequency of the times() clock tick */
789 static int timer_freq;
792 QEMUClock *qemu_new_clock(int type)
795 clock = qemu_mallocz(sizeof(QEMUClock));
802 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
806 ts = qemu_mallocz(sizeof(QEMUTimer));
813 void qemu_free_timer(QEMUTimer *ts)
818 /* stop a timer, but do not dealloc it */
819 void qemu_del_timer(QEMUTimer *ts)
823 /* NOTE: this code must be signal safe because
824 qemu_timer_expired() can be called from a signal. */
825 pt = &active_timers[ts->clock->type];
838 /* modify the current timer so that it will be fired when current_time
839 >= expire_time. The corresponding callback will be called. */
840 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
846 /* add the timer in the sorted list */
847 /* NOTE: this code must be signal safe because
848 qemu_timer_expired() can be called from a signal. */
849 pt = &active_timers[ts->clock->type];
854 if (t->expire_time > expire_time)
858 ts->expire_time = expire_time;
863 int qemu_timer_pending(QEMUTimer *ts)
866 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
873 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
877 return (timer_head->expire_time <= current_time);
880 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
886 if (!ts || ts->expire_time > current_time)
888 /* remove timer from the list before calling the callback */
889 *ptimer_head = ts->next;
892 /* run the callback (the timer list can be modified) */
897 int64_t qemu_get_clock(QEMUClock *clock)
899 switch(clock->type) {
900 case QEMU_TIMER_REALTIME:
901 return get_clock() / 1000000;
903 case QEMU_TIMER_VIRTUAL:
904 return cpu_get_clock();
908 static void init_timers(void)
911 ticks_per_sec = QEMU_TIMER_BASE;
912 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
913 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
917 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
919 uint64_t expire_time;
921 if (qemu_timer_pending(ts)) {
922 expire_time = ts->expire_time;
926 qemu_put_be64(f, expire_time);
929 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
931 uint64_t expire_time;
933 expire_time = qemu_get_be64(f);
934 if (expire_time != -1) {
935 qemu_mod_timer(ts, expire_time);
941 static void timer_save(QEMUFile *f, void *opaque)
943 if (cpu_ticks_enabled) {
944 hw_error("cannot save state if virtual timers are running");
946 qemu_put_be64s(f, &cpu_ticks_offset);
947 qemu_put_be64s(f, &ticks_per_sec);
948 qemu_put_be64s(f, &cpu_clock_offset);
951 static int timer_load(QEMUFile *f, void *opaque, int version_id)
953 if (version_id != 1 && version_id != 2)
955 if (cpu_ticks_enabled) {
958 qemu_get_be64s(f, &cpu_ticks_offset);
959 qemu_get_be64s(f, &ticks_per_sec);
960 if (version_id == 2) {
961 qemu_get_be64s(f, &cpu_clock_offset);
967 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
968 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
970 static void host_alarm_handler(int host_signum)
974 #define DISP_FREQ 1000
976 static int64_t delta_min = INT64_MAX;
977 static int64_t delta_max, delta_cum, last_clock, delta, ti;
979 ti = qemu_get_clock(vm_clock);
980 if (last_clock != 0) {
981 delta = ti - last_clock;
982 if (delta < delta_min)
984 if (delta > delta_max)
987 if (++count == DISP_FREQ) {
988 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
989 muldiv64(delta_min, 1000000, ticks_per_sec),
990 muldiv64(delta_max, 1000000, ticks_per_sec),
991 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
992 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
994 delta_min = INT64_MAX;
1002 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1003 qemu_get_clock(vm_clock)) ||
1004 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1005 qemu_get_clock(rt_clock))) {
1007 SetEvent(host_alarm);
1009 CPUState *env = cpu_single_env;
1011 /* stop the currently executing cpu because a timer occured */
1012 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1014 if (env->kqemu_enabled) {
1015 kqemu_cpu_interrupt(env);
1024 #if defined(__linux__)
1026 #define RTC_FREQ 1024
1030 static int start_rtc_timer(void)
1032 rtc_fd = open("/dev/rtc", O_RDONLY);
1035 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1036 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1037 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1038 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1041 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1046 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1052 static int start_rtc_timer(void)
1057 #endif /* !defined(__linux__) */
1059 #endif /* !defined(_WIN32) */
1061 static void init_timer_alarm(void)
1068 ZeroMemory(&tc, sizeof(TIMECAPS));
1069 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1070 if (period < tc.wPeriodMin)
1071 period = tc.wPeriodMin;
1072 timeBeginPeriod(period);
1073 timerID = timeSetEvent(1, // interval (ms)
1074 period, // resolution
1075 host_alarm_handler, // function
1076 (DWORD)&count, // user parameter
1077 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1079 perror("failed timer alarm");
1082 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1084 perror("failed CreateEvent");
1087 qemu_add_wait_object(host_alarm, NULL, NULL);
1089 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1092 struct sigaction act;
1093 struct itimerval itv;
1095 /* get times() syscall frequency */
1096 timer_freq = sysconf(_SC_CLK_TCK);
1099 sigfillset(&act.sa_mask);
1101 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1102 act.sa_flags |= SA_ONSTACK;
1104 act.sa_handler = host_alarm_handler;
1105 sigaction(SIGALRM, &act, NULL);
1107 itv.it_interval.tv_sec = 0;
1108 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1109 itv.it_value.tv_sec = 0;
1110 itv.it_value.tv_usec = 10 * 1000;
1111 setitimer(ITIMER_REAL, &itv, NULL);
1112 /* we probe the tick duration of the kernel to inform the user if
1113 the emulated kernel requested a too high timer frequency */
1114 getitimer(ITIMER_REAL, &itv);
1116 #if defined(__linux__)
1117 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1118 have timers with 1 ms resolution. The correct solution will
1119 be to use the POSIX real time timers available in recent
1121 if (itv.it_interval.tv_usec > 1000 || 1) {
1122 /* try to use /dev/rtc to have a faster timer */
1123 if (start_rtc_timer() < 0)
1125 /* disable itimer */
1126 itv.it_interval.tv_sec = 0;
1127 itv.it_interval.tv_usec = 0;
1128 itv.it_value.tv_sec = 0;
1129 itv.it_value.tv_usec = 0;
1130 setitimer(ITIMER_REAL, &itv, NULL);
1133 sigaction(SIGIO, &act, NULL);
1134 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1135 fcntl(rtc_fd, F_SETOWN, getpid());
1137 #endif /* defined(__linux__) */
1140 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1141 PIT_FREQ) / 1000000;
1147 void quit_timers(void)
1150 timeKillEvent(timerID);
1151 timeEndPeriod(period);
1153 CloseHandle(host_alarm);
1159 /***********************************************************/
1160 /* character device */
1162 static void qemu_chr_event(CharDriverState *s, int event)
1166 s->chr_event(s->handler_opaque, event);
1169 static void qemu_chr_reset_bh(void *opaque)
1171 CharDriverState *s = opaque;
1172 qemu_chr_event(s, CHR_EVENT_RESET);
1173 qemu_bh_delete(s->bh);
1177 void qemu_chr_reset(CharDriverState *s)
1179 if (s->bh == NULL) {
1180 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1181 qemu_bh_schedule(s->bh);
1185 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1187 return s->chr_write(s, buf, len);
1190 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1194 return s->chr_ioctl(s, cmd, arg);
1197 int qemu_chr_can_read(CharDriverState *s)
1199 if (!s->chr_can_read)
1201 return s->chr_can_read(s->handler_opaque);
1204 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1206 s->chr_read(s->handler_opaque, buf, len);
1210 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1215 vsnprintf(buf, sizeof(buf), fmt, ap);
1216 qemu_chr_write(s, buf, strlen(buf));
1220 void qemu_chr_send_event(CharDriverState *s, int event)
1222 if (s->chr_send_event)
1223 s->chr_send_event(s, event);
1226 void qemu_chr_add_handlers(CharDriverState *s,
1227 IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read,
1229 IOEventHandler *fd_event,
1232 s->chr_can_read = fd_can_read;
1233 s->chr_read = fd_read;
1234 s->chr_event = fd_event;
1235 s->handler_opaque = opaque;
1236 if (s->chr_update_read_handler)
1237 s->chr_update_read_handler(s);
1240 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1245 static CharDriverState *qemu_chr_open_null(void)
1247 CharDriverState *chr;
1249 chr = qemu_mallocz(sizeof(CharDriverState));
1252 chr->chr_write = null_chr_write;
1256 /* MUX driver for serial I/O splitting */
1257 static int term_timestamps;
1258 static int64_t term_timestamps_start;
1261 IOCanRWHandler *chr_can_read[MAX_MUX];
1262 IOReadHandler *chr_read[MAX_MUX];
1263 IOEventHandler *chr_event[MAX_MUX];
1264 void *ext_opaque[MAX_MUX];
1265 CharDriverState *drv;
1267 int term_got_escape;
1272 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1274 MuxDriver *d = chr->opaque;
1276 if (!term_timestamps) {
1277 ret = d->drv->chr_write(d->drv, buf, len);
1282 for(i = 0; i < len; i++) {
1283 ret += d->drv->chr_write(d->drv, buf+i, 1);
1284 if (buf[i] == '\n') {
1290 if (term_timestamps_start == -1)
1291 term_timestamps_start = ti;
1292 ti -= term_timestamps_start;
1293 secs = ti / 1000000000;
1294 snprintf(buf1, sizeof(buf1),
1295 "[%02d:%02d:%02d.%03d] ",
1299 (int)((ti / 1000000) % 1000));
1300 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1307 static char *mux_help[] = {
1308 "% h print this help\n\r",
1309 "% x exit emulator\n\r",
1310 "% s save disk data back to file (if -snapshot)\n\r",
1311 "% t toggle console timestamps\n\r"
1312 "% b send break (magic sysrq)\n\r",
1313 "% c switch between console and monitor\n\r",
1318 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1319 static void mux_print_help(CharDriverState *chr)
1322 char ebuf[15] = "Escape-Char";
1323 char cbuf[50] = "\n\r";
1325 if (term_escape_char > 0 && term_escape_char < 26) {
1326 sprintf(cbuf,"\n\r");
1327 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1329 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1331 chr->chr_write(chr, cbuf, strlen(cbuf));
1332 for (i = 0; mux_help[i] != NULL; i++) {
1333 for (j=0; mux_help[i][j] != '\0'; j++) {
1334 if (mux_help[i][j] == '%')
1335 chr->chr_write(chr, ebuf, strlen(ebuf));
1337 chr->chr_write(chr, &mux_help[i][j], 1);
1342 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1344 if (d->term_got_escape) {
1345 d->term_got_escape = 0;
1346 if (ch == term_escape_char)
1351 mux_print_help(chr);
1355 char *term = "QEMU: Terminated\n\r";
1356 chr->chr_write(chr,term,strlen(term));
1363 for (i = 0; i < MAX_DISKS; i++) {
1365 bdrv_commit(bs_table[i]);
1368 bdrv_commit(mtd_bdrv);
1372 qemu_chr_event(chr, CHR_EVENT_BREAK);
1375 /* Switch to the next registered device */
1377 if (chr->focus >= d->mux_cnt)
1381 term_timestamps = !term_timestamps;
1382 term_timestamps_start = -1;
1385 } else if (ch == term_escape_char) {
1386 d->term_got_escape = 1;
1394 static int mux_chr_can_read(void *opaque)
1396 CharDriverState *chr = opaque;
1397 MuxDriver *d = chr->opaque;
1398 if (d->chr_can_read[chr->focus])
1399 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1403 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1405 CharDriverState *chr = opaque;
1406 MuxDriver *d = chr->opaque;
1408 for(i = 0; i < size; i++)
1409 if (mux_proc_byte(chr, d, buf[i]))
1410 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1413 static void mux_chr_event(void *opaque, int event)
1415 CharDriverState *chr = opaque;
1416 MuxDriver *d = chr->opaque;
1419 /* Send the event to all registered listeners */
1420 for (i = 0; i < d->mux_cnt; i++)
1421 if (d->chr_event[i])
1422 d->chr_event[i](d->ext_opaque[i], event);
1425 static void mux_chr_update_read_handler(CharDriverState *chr)
1427 MuxDriver *d = chr->opaque;
1429 if (d->mux_cnt >= MAX_MUX) {
1430 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1433 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1434 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1435 d->chr_read[d->mux_cnt] = chr->chr_read;
1436 d->chr_event[d->mux_cnt] = chr->chr_event;
1437 /* Fix up the real driver with mux routines */
1438 if (d->mux_cnt == 0) {
1439 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1440 mux_chr_event, chr);
1442 chr->focus = d->mux_cnt;
1446 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1448 CharDriverState *chr;
1451 chr = qemu_mallocz(sizeof(CharDriverState));
1454 d = qemu_mallocz(sizeof(MuxDriver));
1463 chr->chr_write = mux_chr_write;
1464 chr->chr_update_read_handler = mux_chr_update_read_handler;
1471 static void socket_cleanup(void)
1476 static int socket_init(void)
1481 ret = WSAStartup(MAKEWORD(2,2), &Data);
1483 err = WSAGetLastError();
1484 fprintf(stderr, "WSAStartup: %d\n", err);
1487 atexit(socket_cleanup);
1491 static int send_all(int fd, const uint8_t *buf, int len1)
1497 ret = send(fd, buf, len, 0);
1500 errno = WSAGetLastError();
1501 if (errno != WSAEWOULDBLOCK) {
1504 } else if (ret == 0) {
1514 void socket_set_nonblock(int fd)
1516 unsigned long opt = 1;
1517 ioctlsocket(fd, FIONBIO, &opt);
1522 static int unix_write(int fd, const uint8_t *buf, int len1)
1528 ret = write(fd, buf, len);
1530 if (errno != EINTR && errno != EAGAIN)
1532 } else if (ret == 0) {
1542 static inline int send_all(int fd, const uint8_t *buf, int len1)
1544 return unix_write(fd, buf, len1);
1547 void socket_set_nonblock(int fd)
1549 fcntl(fd, F_SETFL, O_NONBLOCK);
1551 #endif /* !_WIN32 */
1560 #define STDIO_MAX_CLIENTS 1
1561 static int stdio_nb_clients = 0;
1563 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1565 FDCharDriver *s = chr->opaque;
1566 return unix_write(s->fd_out, buf, len);
1569 static int fd_chr_read_poll(void *opaque)
1571 CharDriverState *chr = opaque;
1572 FDCharDriver *s = chr->opaque;
1574 s->max_size = qemu_chr_can_read(chr);
1578 static void fd_chr_read(void *opaque)
1580 CharDriverState *chr = opaque;
1581 FDCharDriver *s = chr->opaque;
1586 if (len > s->max_size)
1590 size = read(s->fd_in, buf, len);
1592 /* FD has been closed. Remove it from the active list. */
1593 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1597 qemu_chr_read(chr, buf, size);
1601 static void fd_chr_update_read_handler(CharDriverState *chr)
1603 FDCharDriver *s = chr->opaque;
1605 if (s->fd_in >= 0) {
1606 if (nographic && s->fd_in == 0) {
1608 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1609 fd_chr_read, NULL, chr);
1614 /* open a character device to a unix fd */
1615 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1617 CharDriverState *chr;
1620 chr = qemu_mallocz(sizeof(CharDriverState));
1623 s = qemu_mallocz(sizeof(FDCharDriver));
1631 chr->chr_write = fd_chr_write;
1632 chr->chr_update_read_handler = fd_chr_update_read_handler;
1634 qemu_chr_reset(chr);
1639 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1643 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1646 return qemu_chr_open_fd(-1, fd_out);
1649 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1652 char filename_in[256], filename_out[256];
1654 snprintf(filename_in, 256, "%s.in", filename);
1655 snprintf(filename_out, 256, "%s.out", filename);
1656 fd_in = open(filename_in, O_RDWR | O_BINARY);
1657 fd_out = open(filename_out, O_RDWR | O_BINARY);
1658 if (fd_in < 0 || fd_out < 0) {
1663 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1667 return qemu_chr_open_fd(fd_in, fd_out);
1671 /* for STDIO, we handle the case where several clients use it
1674 #define TERM_FIFO_MAX_SIZE 1
1676 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1677 static int term_fifo_size;
1679 static int stdio_read_poll(void *opaque)
1681 CharDriverState *chr = opaque;
1683 /* try to flush the queue if needed */
1684 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1685 qemu_chr_read(chr, term_fifo, 1);
1688 /* see if we can absorb more chars */
1689 if (term_fifo_size == 0)
1695 static void stdio_read(void *opaque)
1699 CharDriverState *chr = opaque;
1701 size = read(0, buf, 1);
1703 /* stdin has been closed. Remove it from the active list. */
1704 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1708 if (qemu_chr_can_read(chr) > 0) {
1709 qemu_chr_read(chr, buf, 1);
1710 } else if (term_fifo_size == 0) {
1711 term_fifo[term_fifo_size++] = buf[0];
1716 /* init terminal so that we can grab keys */
1717 static struct termios oldtty;
1718 static int old_fd0_flags;
1720 static void term_exit(void)
1722 tcsetattr (0, TCSANOW, &oldtty);
1723 fcntl(0, F_SETFL, old_fd0_flags);
1726 static void term_init(void)
1730 tcgetattr (0, &tty);
1732 old_fd0_flags = fcntl(0, F_GETFL);
1734 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1735 |INLCR|IGNCR|ICRNL|IXON);
1736 tty.c_oflag |= OPOST;
1737 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1738 /* if graphical mode, we allow Ctrl-C handling */
1740 tty.c_lflag &= ~ISIG;
1741 tty.c_cflag &= ~(CSIZE|PARENB);
1744 tty.c_cc[VTIME] = 0;
1746 tcsetattr (0, TCSANOW, &tty);
1750 fcntl(0, F_SETFL, O_NONBLOCK);
1753 static CharDriverState *qemu_chr_open_stdio(void)
1755 CharDriverState *chr;
1757 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1759 chr = qemu_chr_open_fd(0, 1);
1760 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1767 #if defined(__linux__) || defined(__sun__)
1768 static CharDriverState *qemu_chr_open_pty(void)
1771 char slave_name[1024];
1772 int master_fd, slave_fd;
1774 #if defined(__linux__)
1775 /* Not satisfying */
1776 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1781 /* Disabling local echo and line-buffered output */
1782 tcgetattr (master_fd, &tty);
1783 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1785 tty.c_cc[VTIME] = 0;
1786 tcsetattr (master_fd, TCSAFLUSH, &tty);
1788 fprintf(stderr, "char device redirected to %s\n", slave_name);
1789 return qemu_chr_open_fd(master_fd, master_fd);
1792 static void tty_serial_init(int fd, int speed,
1793 int parity, int data_bits, int stop_bits)
1799 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1800 speed, parity, data_bits, stop_bits);
1802 tcgetattr (fd, &tty);
1844 cfsetispeed(&tty, spd);
1845 cfsetospeed(&tty, spd);
1847 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1848 |INLCR|IGNCR|ICRNL|IXON);
1849 tty.c_oflag |= OPOST;
1850 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1851 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1872 tty.c_cflag |= PARENB;
1875 tty.c_cflag |= PARENB | PARODD;
1879 tty.c_cflag |= CSTOPB;
1881 tcsetattr (fd, TCSANOW, &tty);
1884 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1886 FDCharDriver *s = chr->opaque;
1889 case CHR_IOCTL_SERIAL_SET_PARAMS:
1891 QEMUSerialSetParams *ssp = arg;
1892 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1893 ssp->data_bits, ssp->stop_bits);
1896 case CHR_IOCTL_SERIAL_SET_BREAK:
1898 int enable = *(int *)arg;
1900 tcsendbreak(s->fd_in, 1);
1909 static CharDriverState *qemu_chr_open_tty(const char *filename)
1911 CharDriverState *chr;
1914 fd = open(filename, O_RDWR | O_NONBLOCK);
1917 fcntl(fd, F_SETFL, O_NONBLOCK);
1918 tty_serial_init(fd, 115200, 'N', 8, 1);
1919 chr = qemu_chr_open_fd(fd, fd);
1922 chr->chr_ioctl = tty_serial_ioctl;
1923 qemu_chr_reset(chr);
1926 #else /* ! __linux__ && ! __sun__ */
1927 static CharDriverState *qemu_chr_open_pty(void)
1931 #endif /* __linux__ || __sun__ */
1933 #if defined(__linux__)
1937 } ParallelCharDriver;
1939 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1941 if (s->mode != mode) {
1943 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1950 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1952 ParallelCharDriver *drv = chr->opaque;
1957 case CHR_IOCTL_PP_READ_DATA:
1958 if (ioctl(fd, PPRDATA, &b) < 0)
1960 *(uint8_t *)arg = b;
1962 case CHR_IOCTL_PP_WRITE_DATA:
1963 b = *(uint8_t *)arg;
1964 if (ioctl(fd, PPWDATA, &b) < 0)
1967 case CHR_IOCTL_PP_READ_CONTROL:
1968 if (ioctl(fd, PPRCONTROL, &b) < 0)
1970 /* Linux gives only the lowest bits, and no way to know data
1971 direction! For better compatibility set the fixed upper
1973 *(uint8_t *)arg = b | 0xc0;
1975 case CHR_IOCTL_PP_WRITE_CONTROL:
1976 b = *(uint8_t *)arg;
1977 if (ioctl(fd, PPWCONTROL, &b) < 0)
1980 case CHR_IOCTL_PP_READ_STATUS:
1981 if (ioctl(fd, PPRSTATUS, &b) < 0)
1983 *(uint8_t *)arg = b;
1985 case CHR_IOCTL_PP_EPP_READ_ADDR:
1986 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1987 struct ParallelIOArg *parg = arg;
1988 int n = read(fd, parg->buffer, parg->count);
1989 if (n != parg->count) {
1994 case CHR_IOCTL_PP_EPP_READ:
1995 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1996 struct ParallelIOArg *parg = arg;
1997 int n = read(fd, parg->buffer, parg->count);
1998 if (n != parg->count) {
2003 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2004 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2005 struct ParallelIOArg *parg = arg;
2006 int n = write(fd, parg->buffer, parg->count);
2007 if (n != parg->count) {
2012 case CHR_IOCTL_PP_EPP_WRITE:
2013 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2014 struct ParallelIOArg *parg = arg;
2015 int n = write(fd, parg->buffer, parg->count);
2016 if (n != parg->count) {
2027 static void pp_close(CharDriverState *chr)
2029 ParallelCharDriver *drv = chr->opaque;
2032 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2033 ioctl(fd, PPRELEASE);
2038 static CharDriverState *qemu_chr_open_pp(const char *filename)
2040 CharDriverState *chr;
2041 ParallelCharDriver *drv;
2044 fd = open(filename, O_RDWR);
2048 if (ioctl(fd, PPCLAIM) < 0) {
2053 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2059 drv->mode = IEEE1284_MODE_COMPAT;
2061 chr = qemu_mallocz(sizeof(CharDriverState));
2067 chr->chr_write = null_chr_write;
2068 chr->chr_ioctl = pp_ioctl;
2069 chr->chr_close = pp_close;
2072 qemu_chr_reset(chr);
2076 #endif /* __linux__ */
2082 HANDLE hcom, hrecv, hsend;
2083 OVERLAPPED orecv, osend;
2088 #define NSENDBUF 2048
2089 #define NRECVBUF 2048
2090 #define MAXCONNECT 1
2091 #define NTIMEOUT 5000
2093 static int win_chr_poll(void *opaque);
2094 static int win_chr_pipe_poll(void *opaque);
2096 static void win_chr_close(CharDriverState *chr)
2098 WinCharState *s = chr->opaque;
2101 CloseHandle(s->hsend);
2105 CloseHandle(s->hrecv);
2109 CloseHandle(s->hcom);
2113 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2115 qemu_del_polling_cb(win_chr_poll, chr);
2118 static int win_chr_init(CharDriverState *chr, const char *filename)
2120 WinCharState *s = chr->opaque;
2122 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2127 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2129 fprintf(stderr, "Failed CreateEvent\n");
2132 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2134 fprintf(stderr, "Failed CreateEvent\n");
2138 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2139 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2140 if (s->hcom == INVALID_HANDLE_VALUE) {
2141 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2146 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2147 fprintf(stderr, "Failed SetupComm\n");
2151 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2152 size = sizeof(COMMCONFIG);
2153 GetDefaultCommConfig(filename, &comcfg, &size);
2154 comcfg.dcb.DCBlength = sizeof(DCB);
2155 CommConfigDialog(filename, NULL, &comcfg);
2157 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2158 fprintf(stderr, "Failed SetCommState\n");
2162 if (!SetCommMask(s->hcom, EV_ERR)) {
2163 fprintf(stderr, "Failed SetCommMask\n");
2167 cto.ReadIntervalTimeout = MAXDWORD;
2168 if (!SetCommTimeouts(s->hcom, &cto)) {
2169 fprintf(stderr, "Failed SetCommTimeouts\n");
2173 if (!ClearCommError(s->hcom, &err, &comstat)) {
2174 fprintf(stderr, "Failed ClearCommError\n");
2177 qemu_add_polling_cb(win_chr_poll, chr);
2185 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2187 WinCharState *s = chr->opaque;
2188 DWORD len, ret, size, err;
2191 ZeroMemory(&s->osend, sizeof(s->osend));
2192 s->osend.hEvent = s->hsend;
2195 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2197 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2199 err = GetLastError();
2200 if (err == ERROR_IO_PENDING) {
2201 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2219 static int win_chr_read_poll(CharDriverState *chr)
2221 WinCharState *s = chr->opaque;
2223 s->max_size = qemu_chr_can_read(chr);
2227 static void win_chr_readfile(CharDriverState *chr)
2229 WinCharState *s = chr->opaque;
2234 ZeroMemory(&s->orecv, sizeof(s->orecv));
2235 s->orecv.hEvent = s->hrecv;
2236 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2238 err = GetLastError();
2239 if (err == ERROR_IO_PENDING) {
2240 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2245 qemu_chr_read(chr, buf, size);
2249 static void win_chr_read(CharDriverState *chr)
2251 WinCharState *s = chr->opaque;
2253 if (s->len > s->max_size)
2254 s->len = s->max_size;
2258 win_chr_readfile(chr);
2261 static int win_chr_poll(void *opaque)
2263 CharDriverState *chr = opaque;
2264 WinCharState *s = chr->opaque;
2268 ClearCommError(s->hcom, &comerr, &status);
2269 if (status.cbInQue > 0) {
2270 s->len = status.cbInQue;
2271 win_chr_read_poll(chr);
2278 static CharDriverState *qemu_chr_open_win(const char *filename)
2280 CharDriverState *chr;
2283 chr = qemu_mallocz(sizeof(CharDriverState));
2286 s = qemu_mallocz(sizeof(WinCharState));
2292 chr->chr_write = win_chr_write;
2293 chr->chr_close = win_chr_close;
2295 if (win_chr_init(chr, filename) < 0) {
2300 qemu_chr_reset(chr);
2304 static int win_chr_pipe_poll(void *opaque)
2306 CharDriverState *chr = opaque;
2307 WinCharState *s = chr->opaque;
2310 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2313 win_chr_read_poll(chr);
2320 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2322 WinCharState *s = chr->opaque;
2330 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2332 fprintf(stderr, "Failed CreateEvent\n");
2335 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2337 fprintf(stderr, "Failed CreateEvent\n");
2341 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2342 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2343 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2345 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2346 if (s->hcom == INVALID_HANDLE_VALUE) {
2347 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2352 ZeroMemory(&ov, sizeof(ov));
2353 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2354 ret = ConnectNamedPipe(s->hcom, &ov);
2356 fprintf(stderr, "Failed ConnectNamedPipe\n");
2360 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2362 fprintf(stderr, "Failed GetOverlappedResult\n");
2364 CloseHandle(ov.hEvent);
2371 CloseHandle(ov.hEvent);
2374 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2383 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2385 CharDriverState *chr;
2388 chr = qemu_mallocz(sizeof(CharDriverState));
2391 s = qemu_mallocz(sizeof(WinCharState));
2397 chr->chr_write = win_chr_write;
2398 chr->chr_close = win_chr_close;
2400 if (win_chr_pipe_init(chr, filename) < 0) {
2405 qemu_chr_reset(chr);
2409 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2411 CharDriverState *chr;
2414 chr = qemu_mallocz(sizeof(CharDriverState));
2417 s = qemu_mallocz(sizeof(WinCharState));
2424 chr->chr_write = win_chr_write;
2425 qemu_chr_reset(chr);
2429 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2431 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2434 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2438 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2439 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2440 if (fd_out == INVALID_HANDLE_VALUE)
2443 return qemu_chr_open_win_file(fd_out);
2445 #endif /* !_WIN32 */
2447 /***********************************************************/
2448 /* UDP Net console */
2452 struct sockaddr_in daddr;
2459 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2461 NetCharDriver *s = chr->opaque;
2463 return sendto(s->fd, buf, len, 0,
2464 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2467 static int udp_chr_read_poll(void *opaque)
2469 CharDriverState *chr = opaque;
2470 NetCharDriver *s = chr->opaque;
2472 s->max_size = qemu_chr_can_read(chr);
2474 /* If there were any stray characters in the queue process them
2477 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2478 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2480 s->max_size = qemu_chr_can_read(chr);
2485 static void udp_chr_read(void *opaque)
2487 CharDriverState *chr = opaque;
2488 NetCharDriver *s = chr->opaque;
2490 if (s->max_size == 0)
2492 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2493 s->bufptr = s->bufcnt;
2498 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2499 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2501 s->max_size = qemu_chr_can_read(chr);
2505 static void udp_chr_update_read_handler(CharDriverState *chr)
2507 NetCharDriver *s = chr->opaque;
2510 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2511 udp_chr_read, NULL, chr);
2515 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2517 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2519 int parse_host_src_port(struct sockaddr_in *haddr,
2520 struct sockaddr_in *saddr,
2523 static CharDriverState *qemu_chr_open_udp(const char *def)
2525 CharDriverState *chr = NULL;
2526 NetCharDriver *s = NULL;
2528 struct sockaddr_in saddr;
2530 chr = qemu_mallocz(sizeof(CharDriverState));
2533 s = qemu_mallocz(sizeof(NetCharDriver));
2537 fd = socket(PF_INET, SOCK_DGRAM, 0);
2539 perror("socket(PF_INET, SOCK_DGRAM)");
2543 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2544 printf("Could not parse: %s\n", def);
2548 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2558 chr->chr_write = udp_chr_write;
2559 chr->chr_update_read_handler = udp_chr_update_read_handler;
2572 /***********************************************************/
2573 /* TCP Net console */
2584 static void tcp_chr_accept(void *opaque);
2586 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2588 TCPCharDriver *s = chr->opaque;
2590 return send_all(s->fd, buf, len);
2592 /* XXX: indicate an error ? */
2597 static int tcp_chr_read_poll(void *opaque)
2599 CharDriverState *chr = opaque;
2600 TCPCharDriver *s = chr->opaque;
2603 s->max_size = qemu_chr_can_read(chr);
2608 #define IAC_BREAK 243
2609 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2611 char *buf, int *size)
2613 /* Handle any telnet client's basic IAC options to satisfy char by
2614 * char mode with no echo. All IAC options will be removed from
2615 * the buf and the do_telnetopt variable will be used to track the
2616 * state of the width of the IAC information.
2618 * IAC commands come in sets of 3 bytes with the exception of the
2619 * "IAC BREAK" command and the double IAC.
2625 for (i = 0; i < *size; i++) {
2626 if (s->do_telnetopt > 1) {
2627 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2628 /* Double IAC means send an IAC */
2632 s->do_telnetopt = 1;
2634 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2635 /* Handle IAC break commands by sending a serial break */
2636 qemu_chr_event(chr, CHR_EVENT_BREAK);
2641 if (s->do_telnetopt >= 4) {
2642 s->do_telnetopt = 1;
2645 if ((unsigned char)buf[i] == IAC) {
2646 s->do_telnetopt = 2;
2657 static void tcp_chr_read(void *opaque)
2659 CharDriverState *chr = opaque;
2660 TCPCharDriver *s = chr->opaque;
2664 if (!s->connected || s->max_size <= 0)
2667 if (len > s->max_size)
2669 size = recv(s->fd, buf, len, 0);
2671 /* connection closed */
2673 if (s->listen_fd >= 0) {
2674 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2676 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2679 } else if (size > 0) {
2680 if (s->do_telnetopt)
2681 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2683 qemu_chr_read(chr, buf, size);
2687 static void tcp_chr_connect(void *opaque)
2689 CharDriverState *chr = opaque;
2690 TCPCharDriver *s = chr->opaque;
2693 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2694 tcp_chr_read, NULL, chr);
2695 qemu_chr_reset(chr);
2698 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2699 static void tcp_chr_telnet_init(int fd)
2702 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2703 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2704 send(fd, (char *)buf, 3, 0);
2705 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2706 send(fd, (char *)buf, 3, 0);
2707 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2708 send(fd, (char *)buf, 3, 0);
2709 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2710 send(fd, (char *)buf, 3, 0);
2713 static void socket_set_nodelay(int fd)
2716 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2719 static void tcp_chr_accept(void *opaque)
2721 CharDriverState *chr = opaque;
2722 TCPCharDriver *s = chr->opaque;
2723 struct sockaddr_in saddr;
2725 struct sockaddr_un uaddr;
2727 struct sockaddr *addr;
2734 len = sizeof(uaddr);
2735 addr = (struct sockaddr *)&uaddr;
2739 len = sizeof(saddr);
2740 addr = (struct sockaddr *)&saddr;
2742 fd = accept(s->listen_fd, addr, &len);
2743 if (fd < 0 && errno != EINTR) {
2745 } else if (fd >= 0) {
2746 if (s->do_telnetopt)
2747 tcp_chr_telnet_init(fd);
2751 socket_set_nonblock(fd);
2753 socket_set_nodelay(fd);
2755 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2756 tcp_chr_connect(chr);
2759 static void tcp_chr_close(CharDriverState *chr)
2761 TCPCharDriver *s = chr->opaque;
2764 if (s->listen_fd >= 0)
2765 closesocket(s->listen_fd);
2769 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2773 CharDriverState *chr = NULL;
2774 TCPCharDriver *s = NULL;
2775 int fd = -1, ret, err, val;
2777 int is_waitconnect = 1;
2780 struct sockaddr_in saddr;
2782 struct sockaddr_un uaddr;
2784 struct sockaddr *addr;
2789 addr = (struct sockaddr *)&uaddr;
2790 addrlen = sizeof(uaddr);
2791 if (parse_unix_path(&uaddr, host_str) < 0)
2796 addr = (struct sockaddr *)&saddr;
2797 addrlen = sizeof(saddr);
2798 if (parse_host_port(&saddr, host_str) < 0)
2803 while((ptr = strchr(ptr,','))) {
2805 if (!strncmp(ptr,"server",6)) {
2807 } else if (!strncmp(ptr,"nowait",6)) {
2809 } else if (!strncmp(ptr,"nodelay",6)) {
2812 printf("Unknown option: %s\n", ptr);
2819 chr = qemu_mallocz(sizeof(CharDriverState));
2822 s = qemu_mallocz(sizeof(TCPCharDriver));
2828 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2831 fd = socket(PF_INET, SOCK_STREAM, 0);
2836 if (!is_waitconnect)
2837 socket_set_nonblock(fd);
2842 s->is_unix = is_unix;
2843 s->do_nodelay = do_nodelay && !is_unix;
2846 chr->chr_write = tcp_chr_write;
2847 chr->chr_close = tcp_chr_close;
2850 /* allow fast reuse */
2854 strncpy(path, uaddr.sun_path, 108);
2861 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2864 ret = bind(fd, addr, addrlen);
2868 ret = listen(fd, 0);
2873 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2875 s->do_telnetopt = 1;
2878 ret = connect(fd, addr, addrlen);
2880 err = socket_error();
2881 if (err == EINTR || err == EWOULDBLOCK) {
2882 } else if (err == EINPROGRESS) {
2885 } else if (err == WSAEALREADY) {
2897 socket_set_nodelay(fd);
2899 tcp_chr_connect(chr);
2901 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2904 if (is_listen && is_waitconnect) {
2905 printf("QEMU waiting for connection on: %s\n", host_str);
2906 tcp_chr_accept(chr);
2907 socket_set_nonblock(s->listen_fd);
2919 CharDriverState *qemu_chr_open(const char *filename)
2923 if (!strcmp(filename, "vc")) {
2924 return text_console_init(&display_state);
2925 } else if (!strcmp(filename, "null")) {
2926 return qemu_chr_open_null();
2928 if (strstart(filename, "tcp:", &p)) {
2929 return qemu_chr_open_tcp(p, 0, 0);
2931 if (strstart(filename, "telnet:", &p)) {
2932 return qemu_chr_open_tcp(p, 1, 0);
2934 if (strstart(filename, "udp:", &p)) {
2935 return qemu_chr_open_udp(p);
2937 if (strstart(filename, "mon:", &p)) {
2938 CharDriverState *drv = qemu_chr_open(p);
2940 drv = qemu_chr_open_mux(drv);
2941 monitor_init(drv, !nographic);
2944 printf("Unable to open driver: %s\n", p);
2948 if (strstart(filename, "unix:", &p)) {
2949 return qemu_chr_open_tcp(p, 0, 1);
2950 } else if (strstart(filename, "file:", &p)) {
2951 return qemu_chr_open_file_out(p);
2952 } else if (strstart(filename, "pipe:", &p)) {
2953 return qemu_chr_open_pipe(p);
2954 } else if (!strcmp(filename, "pty")) {
2955 return qemu_chr_open_pty();
2956 } else if (!strcmp(filename, "stdio")) {
2957 return qemu_chr_open_stdio();
2959 #if defined(__linux__)
2960 if (strstart(filename, "/dev/parport", NULL)) {
2961 return qemu_chr_open_pp(filename);
2964 #if defined(__linux__) || defined(__sun__)
2965 if (strstart(filename, "/dev/", NULL)) {
2966 return qemu_chr_open_tty(filename);
2970 if (strstart(filename, "COM", NULL)) {
2971 return qemu_chr_open_win(filename);
2973 if (strstart(filename, "pipe:", &p)) {
2974 return qemu_chr_open_win_pipe(p);
2976 if (strstart(filename, "con:", NULL)) {
2977 return qemu_chr_open_win_con(filename);
2979 if (strstart(filename, "file:", &p)) {
2980 return qemu_chr_open_win_file_out(p);
2988 void qemu_chr_close(CharDriverState *chr)
2991 chr->chr_close(chr);
2994 /***********************************************************/
2995 /* network device redirectors */
2997 void hex_dump(FILE *f, const uint8_t *buf, int size)
3001 for(i=0;i<size;i+=16) {
3005 fprintf(f, "%08x ", i);
3008 fprintf(f, " %02x", buf[i+j]);
3013 for(j=0;j<len;j++) {
3015 if (c < ' ' || c > '~')
3017 fprintf(f, "%c", c);
3023 static int parse_macaddr(uint8_t *macaddr, const char *p)
3026 for(i = 0; i < 6; i++) {
3027 macaddr[i] = strtol(p, (char **)&p, 16);
3040 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3045 p1 = strchr(p, sep);
3051 if (len > buf_size - 1)
3053 memcpy(buf, p, len);
3060 int parse_host_src_port(struct sockaddr_in *haddr,
3061 struct sockaddr_in *saddr,
3062 const char *input_str)
3064 char *str = strdup(input_str);
3065 char *host_str = str;
3070 * Chop off any extra arguments at the end of the string which
3071 * would start with a comma, then fill in the src port information
3072 * if it was provided else use the "any address" and "any port".
3074 if ((ptr = strchr(str,',')))
3077 if ((src_str = strchr(input_str,'@'))) {
3082 if (parse_host_port(haddr, host_str) < 0)
3085 if (!src_str || *src_str == '\0')
3088 if (parse_host_port(saddr, src_str) < 0)
3099 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3107 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3109 saddr->sin_family = AF_INET;
3110 if (buf[0] == '\0') {
3111 saddr->sin_addr.s_addr = 0;
3113 if (isdigit(buf[0])) {
3114 if (!inet_aton(buf, &saddr->sin_addr))
3117 if ((he = gethostbyname(buf)) == NULL)
3119 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3122 port = strtol(p, (char **)&r, 0);
3125 saddr->sin_port = htons(port);
3130 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3135 len = MIN(108, strlen(str));
3136 p = strchr(str, ',');
3138 len = MIN(len, p - str);
3140 memset(uaddr, 0, sizeof(*uaddr));
3142 uaddr->sun_family = AF_UNIX;
3143 memcpy(uaddr->sun_path, str, len);
3149 /* find or alloc a new VLAN */
3150 VLANState *qemu_find_vlan(int id)
3152 VLANState **pvlan, *vlan;
3153 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3157 vlan = qemu_mallocz(sizeof(VLANState));
3162 pvlan = &first_vlan;
3163 while (*pvlan != NULL)
3164 pvlan = &(*pvlan)->next;
3169 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3170 IOReadHandler *fd_read,
3171 IOCanRWHandler *fd_can_read,
3174 VLANClientState *vc, **pvc;
3175 vc = qemu_mallocz(sizeof(VLANClientState));
3178 vc->fd_read = fd_read;
3179 vc->fd_can_read = fd_can_read;
3180 vc->opaque = opaque;
3184 pvc = &vlan->first_client;
3185 while (*pvc != NULL)
3186 pvc = &(*pvc)->next;
3191 int qemu_can_send_packet(VLANClientState *vc1)
3193 VLANState *vlan = vc1->vlan;
3194 VLANClientState *vc;
3196 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3198 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3205 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3207 VLANState *vlan = vc1->vlan;
3208 VLANClientState *vc;
3211 printf("vlan %d send:\n", vlan->id);
3212 hex_dump(stdout, buf, size);
3214 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3216 vc->fd_read(vc->opaque, buf, size);
3221 #if defined(CONFIG_SLIRP)
3223 /* slirp network adapter */
3225 static int slirp_inited;
3226 static VLANClientState *slirp_vc;
3228 int slirp_can_output(void)
3230 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3233 void slirp_output(const uint8_t *pkt, int pkt_len)
3236 printf("slirp output:\n");
3237 hex_dump(stdout, pkt, pkt_len);
3241 qemu_send_packet(slirp_vc, pkt, pkt_len);
3244 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3247 printf("slirp input:\n");
3248 hex_dump(stdout, buf, size);
3250 slirp_input(buf, size);
3253 static int net_slirp_init(VLANState *vlan)
3255 if (!slirp_inited) {
3259 slirp_vc = qemu_new_vlan_client(vlan,
3260 slirp_receive, NULL, NULL);
3261 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3265 static void net_slirp_redir(const char *redir_str)
3270 struct in_addr guest_addr;
3271 int host_port, guest_port;
3273 if (!slirp_inited) {
3279 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3281 if (!strcmp(buf, "tcp")) {
3283 } else if (!strcmp(buf, "udp")) {
3289 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3291 host_port = strtol(buf, &r, 0);
3295 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3297 if (buf[0] == '\0') {
3298 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3300 if (!inet_aton(buf, &guest_addr))
3303 guest_port = strtol(p, &r, 0);
3307 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3308 fprintf(stderr, "qemu: could not set up redirection\n");
3313 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3321 static void smb_exit(void)
3325 char filename[1024];
3327 /* erase all the files in the directory */
3328 d = opendir(smb_dir);
3333 if (strcmp(de->d_name, ".") != 0 &&
3334 strcmp(de->d_name, "..") != 0) {
3335 snprintf(filename, sizeof(filename), "%s/%s",
3336 smb_dir, de->d_name);
3344 /* automatic user mode samba server configuration */
3345 void net_slirp_smb(const char *exported_dir)
3347 char smb_conf[1024];
3348 char smb_cmdline[1024];
3351 if (!slirp_inited) {
3356 /* XXX: better tmp dir construction */
3357 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3358 if (mkdir(smb_dir, 0700) < 0) {
3359 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3362 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3364 f = fopen(smb_conf, "w");
3366 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3373 "socket address=127.0.0.1\n"
3374 "pid directory=%s\n"
3375 "lock directory=%s\n"
3376 "log file=%s/log.smbd\n"
3377 "smb passwd file=%s/smbpasswd\n"
3378 "security = share\n"
3393 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3394 SMBD_COMMAND, smb_conf);
3396 slirp_add_exec(0, smb_cmdline, 4, 139);
3399 #endif /* !defined(_WIN32) */
3401 #endif /* CONFIG_SLIRP */
3403 #if !defined(_WIN32)
3405 typedef struct TAPState {
3406 VLANClientState *vc;
3410 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3412 TAPState *s = opaque;
3415 ret = write(s->fd, buf, size);
3416 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3423 static void tap_send(void *opaque)
3425 TAPState *s = opaque;
3432 sbuf.maxlen = sizeof(buf);
3434 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3436 size = read(s->fd, buf, sizeof(buf));
3439 qemu_send_packet(s->vc, buf, size);
3445 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3449 s = qemu_mallocz(sizeof(TAPState));
3453 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3454 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3455 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3459 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3460 static int tap_open(char *ifname, int ifname_size)
3466 fd = open("/dev/tap", O_RDWR);
3468 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3473 dev = devname(s.st_rdev, S_IFCHR);
3474 pstrcpy(ifname, ifname_size, dev);
3476 fcntl(fd, F_SETFL, O_NONBLOCK);
3479 #elif defined(__sun__)
3480 #define TUNNEWPPA (('T'<<16) | 0x0001)
3482 * Allocate TAP device, returns opened fd.
3483 * Stores dev name in the first arg(must be large enough).
3485 int tap_alloc(char *dev)
3487 int tap_fd, if_fd, ppa = -1;
3488 static int ip_fd = 0;
3491 static int arp_fd = 0;
3492 int ip_muxid, arp_muxid;
3493 struct strioctl strioc_if, strioc_ppa;
3494 int link_type = I_PLINK;;
3496 char actual_name[32] = "";
3498 memset(&ifr, 0x0, sizeof(ifr));
3502 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3506 /* Check if IP device was opened */
3510 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3511 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3515 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3516 syslog(LOG_ERR, "Can't open /dev/tap");
3520 /* Assign a new PPA and get its unit number. */
3521 strioc_ppa.ic_cmd = TUNNEWPPA;
3522 strioc_ppa.ic_timout = 0;
3523 strioc_ppa.ic_len = sizeof(ppa);
3524 strioc_ppa.ic_dp = (char *)&ppa;
3525 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3526 syslog (LOG_ERR, "Can't assign new interface");
3528 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3529 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3532 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3533 syslog(LOG_ERR, "Can't push IP module");
3537 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3538 syslog(LOG_ERR, "Can't get flags\n");
3540 snprintf (actual_name, 32, "tap%d", ppa);
3541 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3544 /* Assign ppa according to the unit number returned by tun device */
3546 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3547 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3548 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3549 syslog (LOG_ERR, "Can't get flags\n");
3550 /* Push arp module to if_fd */
3551 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3552 syslog (LOG_ERR, "Can't push ARP module (2)");
3554 /* Push arp module to ip_fd */
3555 if (ioctl (ip_fd, I_POP, NULL) < 0)
3556 syslog (LOG_ERR, "I_POP failed\n");
3557 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3558 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3560 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3561 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3563 /* Set ifname to arp */
3564 strioc_if.ic_cmd = SIOCSLIFNAME;
3565 strioc_if.ic_timout = 0;
3566 strioc_if.ic_len = sizeof(ifr);
3567 strioc_if.ic_dp = (char *)𝔦
3568 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3569 syslog (LOG_ERR, "Can't set ifname to arp\n");
3572 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3573 syslog(LOG_ERR, "Can't link TAP device to IP");
3577 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3578 syslog (LOG_ERR, "Can't link TAP device to ARP");
3582 memset(&ifr, 0x0, sizeof(ifr));
3583 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3584 ifr.lifr_ip_muxid = ip_muxid;
3585 ifr.lifr_arp_muxid = arp_muxid;
3587 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3589 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3590 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3591 syslog (LOG_ERR, "Can't set multiplexor id");
3594 sprintf(dev, "tap%d", ppa);
3598 static int tap_open(char *ifname, int ifname_size)
3602 if( (fd = tap_alloc(dev)) < 0 ){
3603 fprintf(stderr, "Cannot allocate TAP device\n");
3606 pstrcpy(ifname, ifname_size, dev);
3607 fcntl(fd, F_SETFL, O_NONBLOCK);
3611 static int tap_open(char *ifname, int ifname_size)
3616 fd = open("/dev/net/tun", O_RDWR);
3618 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3621 memset(&ifr, 0, sizeof(ifr));
3622 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3623 if (ifname[0] != '\0')
3624 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3626 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3627 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3629 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3633 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3634 fcntl(fd, F_SETFL, O_NONBLOCK);
3639 static int net_tap_init(VLANState *vlan, const char *ifname1,
3640 const char *setup_script)
3643 int pid, status, fd;
3648 if (ifname1 != NULL)
3649 pstrcpy(ifname, sizeof(ifname), ifname1);
3652 fd = tap_open(ifname, sizeof(ifname));
3656 if (!setup_script || !strcmp(setup_script, "no"))
3658 if (setup_script[0] != '\0') {
3659 /* try to launch network init script */
3663 int open_max = sysconf (_SC_OPEN_MAX), i;
3664 for (i = 0; i < open_max; i++)
3665 if (i != STDIN_FILENO &&
3666 i != STDOUT_FILENO &&
3667 i != STDERR_FILENO &&
3672 *parg++ = (char *)setup_script;
3675 execv(setup_script, args);
3678 while (waitpid(pid, &status, 0) != pid);
3679 if (!WIFEXITED(status) ||
3680 WEXITSTATUS(status) != 0) {
3681 fprintf(stderr, "%s: could not launch network script\n",
3687 s = net_tap_fd_init(vlan, fd);
3690 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3691 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3695 #endif /* !_WIN32 */
3697 /* network connection */
3698 typedef struct NetSocketState {
3699 VLANClientState *vc;
3701 int state; /* 0 = getting length, 1 = getting data */
3705 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3708 typedef struct NetSocketListenState {
3711 } NetSocketListenState;
3713 /* XXX: we consider we can send the whole packet without blocking */
3714 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3716 NetSocketState *s = opaque;
3720 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3721 send_all(s->fd, buf, size);
3724 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3726 NetSocketState *s = opaque;
3727 sendto(s->fd, buf, size, 0,
3728 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3731 static void net_socket_send(void *opaque)
3733 NetSocketState *s = opaque;
3738 size = recv(s->fd, buf1, sizeof(buf1), 0);
3740 err = socket_error();
3741 if (err != EWOULDBLOCK)
3743 } else if (size == 0) {
3744 /* end of connection */
3746 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3752 /* reassemble a packet from the network */
3758 memcpy(s->buf + s->index, buf, l);
3762 if (s->index == 4) {
3764 s->packet_len = ntohl(*(uint32_t *)s->buf);
3770 l = s->packet_len - s->index;
3773 memcpy(s->buf + s->index, buf, l);
3777 if (s->index >= s->packet_len) {
3778 qemu_send_packet(s->vc, s->buf, s->packet_len);
3787 static void net_socket_send_dgram(void *opaque)
3789 NetSocketState *s = opaque;
3792 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3796 /* end of connection */
3797 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3800 qemu_send_packet(s->vc, s->buf, size);
3803 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3808 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3809 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3810 inet_ntoa(mcastaddr->sin_addr),
3811 (int)ntohl(mcastaddr->sin_addr.s_addr));
3815 fd = socket(PF_INET, SOCK_DGRAM, 0);
3817 perror("socket(PF_INET, SOCK_DGRAM)");
3822 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3823 (const char *)&val, sizeof(val));
3825 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3829 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3835 /* Add host to multicast group */
3836 imr.imr_multiaddr = mcastaddr->sin_addr;
3837 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3839 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3840 (const char *)&imr, sizeof(struct ip_mreq));
3842 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3846 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3848 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3849 (const char *)&val, sizeof(val));
3851 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3855 socket_set_nonblock(fd);
3863 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3866 struct sockaddr_in saddr;
3868 socklen_t saddr_len;
3871 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3872 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3873 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3877 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3879 if (saddr.sin_addr.s_addr==0) {
3880 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3884 /* clone dgram socket */
3885 newfd = net_socket_mcast_create(&saddr);
3887 /* error already reported by net_socket_mcast_create() */
3891 /* clone newfd to fd, close newfd */
3896 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3897 fd, strerror(errno));
3902 s = qemu_mallocz(sizeof(NetSocketState));
3907 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3908 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3910 /* mcast: save bound address as dst */
3911 if (is_connected) s->dgram_dst=saddr;
3913 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3914 "socket: fd=%d (%s mcast=%s:%d)",
3915 fd, is_connected? "cloned" : "",
3916 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3920 static void net_socket_connect(void *opaque)
3922 NetSocketState *s = opaque;
3923 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3926 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3930 s = qemu_mallocz(sizeof(NetSocketState));
3934 s->vc = qemu_new_vlan_client(vlan,
3935 net_socket_receive, NULL, s);
3936 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3937 "socket: fd=%d", fd);
3939 net_socket_connect(s);
3941 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3946 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3949 int so_type=-1, optlen=sizeof(so_type);
3951 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3952 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3957 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3959 return net_socket_fd_init_stream(vlan, fd, is_connected);
3961 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3962 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3963 return net_socket_fd_init_stream(vlan, fd, is_connected);
3968 static void net_socket_accept(void *opaque)
3970 NetSocketListenState *s = opaque;
3972 struct sockaddr_in saddr;
3977 len = sizeof(saddr);
3978 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3979 if (fd < 0 && errno != EINTR) {
3981 } else if (fd >= 0) {
3985 s1 = net_socket_fd_init(s->vlan, fd, 1);
3989 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3990 "socket: connection from %s:%d",
3991 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3995 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3997 NetSocketListenState *s;
3999 struct sockaddr_in saddr;
4001 if (parse_host_port(&saddr, host_str) < 0)
4004 s = qemu_mallocz(sizeof(NetSocketListenState));
4008 fd = socket(PF_INET, SOCK_STREAM, 0);
4013 socket_set_nonblock(fd);
4015 /* allow fast reuse */
4017 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4019 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4024 ret = listen(fd, 0);
4031 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4035 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4038 int fd, connected, ret, err;
4039 struct sockaddr_in saddr;
4041 if (parse_host_port(&saddr, host_str) < 0)
4044 fd = socket(PF_INET, SOCK_STREAM, 0);
4049 socket_set_nonblock(fd);
4053 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4055 err = socket_error();
4056 if (err == EINTR || err == EWOULDBLOCK) {
4057 } else if (err == EINPROGRESS) {
4060 } else if (err == WSAEALREADY) {
4073 s = net_socket_fd_init(vlan, fd, connected);
4076 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4077 "socket: connect to %s:%d",
4078 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4082 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4086 struct sockaddr_in saddr;
4088 if (parse_host_port(&saddr, host_str) < 0)
4092 fd = net_socket_mcast_create(&saddr);
4096 s = net_socket_fd_init(vlan, fd, 0);
4100 s->dgram_dst = saddr;
4102 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4103 "socket: mcast=%s:%d",
4104 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4109 static int get_param_value(char *buf, int buf_size,
4110 const char *tag, const char *str)
4119 while (*p != '\0' && *p != '=') {
4120 if ((q - option) < sizeof(option) - 1)
4128 if (!strcmp(tag, option)) {
4130 while (*p != '\0' && *p != ',') {
4131 if ((q - buf) < buf_size - 1)
4138 while (*p != '\0' && *p != ',') {
4149 static int net_client_init(const char *str)
4160 while (*p != '\0' && *p != ',') {
4161 if ((q - device) < sizeof(device) - 1)
4169 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4170 vlan_id = strtol(buf, NULL, 0);
4172 vlan = qemu_find_vlan(vlan_id);
4174 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4177 if (!strcmp(device, "nic")) {
4181 if (nb_nics >= MAX_NICS) {
4182 fprintf(stderr, "Too Many NICs\n");
4185 nd = &nd_table[nb_nics];
4186 macaddr = nd->macaddr;
4192 macaddr[5] = 0x56 + nb_nics;
4194 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4195 if (parse_macaddr(macaddr, buf) < 0) {
4196 fprintf(stderr, "invalid syntax for ethernet address\n");
4200 if (get_param_value(buf, sizeof(buf), "model", p)) {
4201 nd->model = strdup(buf);
4205 vlan->nb_guest_devs++;
4208 if (!strcmp(device, "none")) {
4209 /* does nothing. It is needed to signal that no network cards
4214 if (!strcmp(device, "user")) {
4215 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4216 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4218 vlan->nb_host_devs++;
4219 ret = net_slirp_init(vlan);
4223 if (!strcmp(device, "tap")) {
4225 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4226 fprintf(stderr, "tap: no interface name\n");
4229 vlan->nb_host_devs++;
4230 ret = tap_win32_init(vlan, ifname);
4233 if (!strcmp(device, "tap")) {
4235 char setup_script[1024];
4237 vlan->nb_host_devs++;
4238 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4239 fd = strtol(buf, NULL, 0);
4241 if (net_tap_fd_init(vlan, fd))
4244 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4247 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4248 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4250 ret = net_tap_init(vlan, ifname, setup_script);
4254 if (!strcmp(device, "socket")) {
4255 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4257 fd = strtol(buf, NULL, 0);
4259 if (net_socket_fd_init(vlan, fd, 1))
4261 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4262 ret = net_socket_listen_init(vlan, buf);
4263 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4264 ret = net_socket_connect_init(vlan, buf);
4265 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4266 ret = net_socket_mcast_init(vlan, buf);
4268 fprintf(stderr, "Unknown socket options: %s\n", p);
4271 vlan->nb_host_devs++;
4274 fprintf(stderr, "Unknown network device: %s\n", device);
4278 fprintf(stderr, "Could not initialize device '%s'\n", device);
4284 void do_info_network(void)
4287 VLANClientState *vc;
4289 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4290 term_printf("VLAN %d devices:\n", vlan->id);
4291 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4292 term_printf(" %s\n", vc->info_str);
4296 /***********************************************************/
4299 static USBPort *used_usb_ports;
4300 static USBPort *free_usb_ports;
4302 /* ??? Maybe change this to register a hub to keep track of the topology. */
4303 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4304 usb_attachfn attach)
4306 port->opaque = opaque;
4307 port->index = index;
4308 port->attach = attach;
4309 port->next = free_usb_ports;
4310 free_usb_ports = port;
4313 static int usb_device_add(const char *devname)
4319 if (!free_usb_ports)
4322 if (strstart(devname, "host:", &p)) {
4323 dev = usb_host_device_open(p);
4324 } else if (!strcmp(devname, "mouse")) {
4325 dev = usb_mouse_init();
4326 } else if (!strcmp(devname, "tablet")) {
4327 dev = usb_tablet_init();
4328 } else if (!strcmp(devname, "keyboard")) {
4329 dev = usb_keyboard_init();
4330 } else if (strstart(devname, "disk:", &p)) {
4331 dev = usb_msd_init(p);
4332 } else if (!strcmp(devname, "wacom-tablet")) {
4333 dev = usb_wacom_init();
4340 /* Find a USB port to add the device to. */
4341 port = free_usb_ports;
4345 /* Create a new hub and chain it on. */
4346 free_usb_ports = NULL;
4347 port->next = used_usb_ports;
4348 used_usb_ports = port;
4350 hub = usb_hub_init(VM_USB_HUB_SIZE);
4351 usb_attach(port, hub);
4352 port = free_usb_ports;
4355 free_usb_ports = port->next;
4356 port->next = used_usb_ports;
4357 used_usb_ports = port;
4358 usb_attach(port, dev);
4362 static int usb_device_del(const char *devname)
4370 if (!used_usb_ports)
4373 p = strchr(devname, '.');
4376 bus_num = strtoul(devname, NULL, 0);
4377 addr = strtoul(p + 1, NULL, 0);
4381 lastp = &used_usb_ports;
4382 port = used_usb_ports;
4383 while (port && port->dev->addr != addr) {
4384 lastp = &port->next;
4392 *lastp = port->next;
4393 usb_attach(port, NULL);
4394 dev->handle_destroy(dev);
4395 port->next = free_usb_ports;
4396 free_usb_ports = port;
4400 void do_usb_add(const char *devname)
4403 ret = usb_device_add(devname);
4405 term_printf("Could not add USB device '%s'\n", devname);
4408 void do_usb_del(const char *devname)
4411 ret = usb_device_del(devname);
4413 term_printf("Could not remove USB device '%s'\n", devname);
4420 const char *speed_str;
4423 term_printf("USB support not enabled\n");
4427 for (port = used_usb_ports; port; port = port->next) {
4431 switch(dev->speed) {
4435 case USB_SPEED_FULL:
4438 case USB_SPEED_HIGH:
4445 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4446 0, dev->addr, speed_str, dev->devname);
4450 /***********************************************************/
4451 /* PCMCIA/Cardbus */
4453 static struct pcmcia_socket_entry_s {
4454 struct pcmcia_socket_s *socket;
4455 struct pcmcia_socket_entry_s *next;
4456 } *pcmcia_sockets = 0;
4458 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4460 struct pcmcia_socket_entry_s *entry;
4462 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4463 entry->socket = socket;
4464 entry->next = pcmcia_sockets;
4465 pcmcia_sockets = entry;
4468 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4470 struct pcmcia_socket_entry_s *entry, **ptr;
4472 ptr = &pcmcia_sockets;
4473 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4474 if (entry->socket == socket) {
4480 void pcmcia_info(void)
4482 struct pcmcia_socket_entry_s *iter;
4483 if (!pcmcia_sockets)
4484 term_printf("No PCMCIA sockets\n");
4486 for (iter = pcmcia_sockets; iter; iter = iter->next)
4487 term_printf("%s: %s\n", iter->socket->slot_string,
4488 iter->socket->attached ? iter->socket->card_string :
4492 /***********************************************************/
4495 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4499 static void dumb_resize(DisplayState *ds, int w, int h)
4503 static void dumb_refresh(DisplayState *ds)
4505 #if defined(CONFIG_SDL)
4510 static void dumb_display_init(DisplayState *ds)
4515 ds->dpy_update = dumb_update;
4516 ds->dpy_resize = dumb_resize;
4517 ds->dpy_refresh = dumb_refresh;
4520 /***********************************************************/
4523 #define MAX_IO_HANDLERS 64
4525 typedef struct IOHandlerRecord {
4527 IOCanRWHandler *fd_read_poll;
4529 IOHandler *fd_write;
4532 /* temporary data */
4534 struct IOHandlerRecord *next;
4537 static IOHandlerRecord *first_io_handler;
4539 /* XXX: fd_read_poll should be suppressed, but an API change is
4540 necessary in the character devices to suppress fd_can_read(). */
4541 int qemu_set_fd_handler2(int fd,
4542 IOCanRWHandler *fd_read_poll,
4544 IOHandler *fd_write,
4547 IOHandlerRecord **pioh, *ioh;
4549 if (!fd_read && !fd_write) {
4550 pioh = &first_io_handler;
4555 if (ioh->fd == fd) {
4562 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4566 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4569 ioh->next = first_io_handler;
4570 first_io_handler = ioh;
4573 ioh->fd_read_poll = fd_read_poll;
4574 ioh->fd_read = fd_read;
4575 ioh->fd_write = fd_write;
4576 ioh->opaque = opaque;
4582 int qemu_set_fd_handler(int fd,
4584 IOHandler *fd_write,
4587 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4590 /***********************************************************/
4591 /* Polling handling */
4593 typedef struct PollingEntry {
4596 struct PollingEntry *next;
4599 static PollingEntry *first_polling_entry;
4601 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4603 PollingEntry **ppe, *pe;
4604 pe = qemu_mallocz(sizeof(PollingEntry));
4608 pe->opaque = opaque;
4609 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4614 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4616 PollingEntry **ppe, *pe;
4617 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4619 if (pe->func == func && pe->opaque == opaque) {
4628 /***********************************************************/
4629 /* Wait objects support */
4630 typedef struct WaitObjects {
4632 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4633 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4634 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4637 static WaitObjects wait_objects = {0};
4639 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4641 WaitObjects *w = &wait_objects;
4643 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4645 w->events[w->num] = handle;
4646 w->func[w->num] = func;
4647 w->opaque[w->num] = opaque;
4652 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4655 WaitObjects *w = &wait_objects;
4658 for (i = 0; i < w->num; i++) {
4659 if (w->events[i] == handle)
4662 w->events[i] = w->events[i + 1];
4663 w->func[i] = w->func[i + 1];
4664 w->opaque[i] = w->opaque[i + 1];
4672 /***********************************************************/
4673 /* savevm/loadvm support */
4675 #define IO_BUF_SIZE 32768
4679 BlockDriverState *bs;
4682 int64_t base_offset;
4683 int64_t buf_offset; /* start of buffer when writing, end of buffer
4686 int buf_size; /* 0 when writing */
4687 uint8_t buf[IO_BUF_SIZE];
4690 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4694 f = qemu_mallocz(sizeof(QEMUFile));
4697 if (!strcmp(mode, "wb")) {
4699 } else if (!strcmp(mode, "rb")) {
4704 f->outfile = fopen(filename, mode);
4716 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4720 f = qemu_mallocz(sizeof(QEMUFile));
4725 f->is_writable = is_writable;
4726 f->base_offset = offset;
4730 void qemu_fflush(QEMUFile *f)
4732 if (!f->is_writable)
4734 if (f->buf_index > 0) {
4736 fseek(f->outfile, f->buf_offset, SEEK_SET);
4737 fwrite(f->buf, 1, f->buf_index, f->outfile);
4739 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4740 f->buf, f->buf_index);
4742 f->buf_offset += f->buf_index;
4747 static void qemu_fill_buffer(QEMUFile *f)
4754 fseek(f->outfile, f->buf_offset, SEEK_SET);
4755 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4759 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4760 f->buf, IO_BUF_SIZE);
4766 f->buf_offset += len;
4769 void qemu_fclose(QEMUFile *f)
4779 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4783 l = IO_BUF_SIZE - f->buf_index;
4786 memcpy(f->buf + f->buf_index, buf, l);
4790 if (f->buf_index >= IO_BUF_SIZE)
4795 void qemu_put_byte(QEMUFile *f, int v)
4797 f->buf[f->buf_index++] = v;
4798 if (f->buf_index >= IO_BUF_SIZE)
4802 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4808 l = f->buf_size - f->buf_index;
4810 qemu_fill_buffer(f);
4811 l = f->buf_size - f->buf_index;
4817 memcpy(buf, f->buf + f->buf_index, l);
4822 return size1 - size;
4825 int qemu_get_byte(QEMUFile *f)
4827 if (f->buf_index >= f->buf_size) {
4828 qemu_fill_buffer(f);
4829 if (f->buf_index >= f->buf_size)
4832 return f->buf[f->buf_index++];
4835 int64_t qemu_ftell(QEMUFile *f)
4837 return f->buf_offset - f->buf_size + f->buf_index;
4840 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4842 if (whence == SEEK_SET) {
4844 } else if (whence == SEEK_CUR) {
4845 pos += qemu_ftell(f);
4847 /* SEEK_END not supported */
4850 if (f->is_writable) {
4852 f->buf_offset = pos;
4854 f->buf_offset = pos;
4861 void qemu_put_be16(QEMUFile *f, unsigned int v)
4863 qemu_put_byte(f, v >> 8);
4864 qemu_put_byte(f, v);
4867 void qemu_put_be32(QEMUFile *f, unsigned int v)
4869 qemu_put_byte(f, v >> 24);
4870 qemu_put_byte(f, v >> 16);
4871 qemu_put_byte(f, v >> 8);
4872 qemu_put_byte(f, v);
4875 void qemu_put_be64(QEMUFile *f, uint64_t v)
4877 qemu_put_be32(f, v >> 32);
4878 qemu_put_be32(f, v);
4881 unsigned int qemu_get_be16(QEMUFile *f)
4884 v = qemu_get_byte(f) << 8;
4885 v |= qemu_get_byte(f);
4889 unsigned int qemu_get_be32(QEMUFile *f)
4892 v = qemu_get_byte(f) << 24;
4893 v |= qemu_get_byte(f) << 16;
4894 v |= qemu_get_byte(f) << 8;
4895 v |= qemu_get_byte(f);
4899 uint64_t qemu_get_be64(QEMUFile *f)
4902 v = (uint64_t)qemu_get_be32(f) << 32;
4903 v |= qemu_get_be32(f);
4907 typedef struct SaveStateEntry {
4911 SaveStateHandler *save_state;
4912 LoadStateHandler *load_state;
4914 struct SaveStateEntry *next;
4917 static SaveStateEntry *first_se;
4919 int register_savevm(const char *idstr,
4922 SaveStateHandler *save_state,
4923 LoadStateHandler *load_state,
4926 SaveStateEntry *se, **pse;
4928 se = qemu_malloc(sizeof(SaveStateEntry));
4931 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4932 se->instance_id = instance_id;
4933 se->version_id = version_id;
4934 se->save_state = save_state;
4935 se->load_state = load_state;
4936 se->opaque = opaque;
4939 /* add at the end of list */
4941 while (*pse != NULL)
4942 pse = &(*pse)->next;
4947 #define QEMU_VM_FILE_MAGIC 0x5145564d
4948 #define QEMU_VM_FILE_VERSION 0x00000002
4950 int qemu_savevm_state(QEMUFile *f)
4954 int64_t cur_pos, len_pos, total_len_pos;
4956 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4957 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4958 total_len_pos = qemu_ftell(f);
4959 qemu_put_be64(f, 0); /* total size */
4961 for(se = first_se; se != NULL; se = se->next) {
4963 len = strlen(se->idstr);
4964 qemu_put_byte(f, len);
4965 qemu_put_buffer(f, se->idstr, len);
4967 qemu_put_be32(f, se->instance_id);
4968 qemu_put_be32(f, se->version_id);
4970 /* record size: filled later */
4971 len_pos = qemu_ftell(f);
4972 qemu_put_be32(f, 0);
4974 se->save_state(f, se->opaque);
4976 /* fill record size */
4977 cur_pos = qemu_ftell(f);
4978 len = cur_pos - len_pos - 4;
4979 qemu_fseek(f, len_pos, SEEK_SET);
4980 qemu_put_be32(f, len);
4981 qemu_fseek(f, cur_pos, SEEK_SET);
4983 cur_pos = qemu_ftell(f);
4984 qemu_fseek(f, total_len_pos, SEEK_SET);
4985 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4986 qemu_fseek(f, cur_pos, SEEK_SET);
4992 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4996 for(se = first_se; se != NULL; se = se->next) {
4997 if (!strcmp(se->idstr, idstr) &&
4998 instance_id == se->instance_id)
5004 int qemu_loadvm_state(QEMUFile *f)
5007 int len, ret, instance_id, record_len, version_id;
5008 int64_t total_len, end_pos, cur_pos;
5012 v = qemu_get_be32(f);
5013 if (v != QEMU_VM_FILE_MAGIC)
5015 v = qemu_get_be32(f);
5016 if (v != QEMU_VM_FILE_VERSION) {
5021 total_len = qemu_get_be64(f);
5022 end_pos = total_len + qemu_ftell(f);
5024 if (qemu_ftell(f) >= end_pos)
5026 len = qemu_get_byte(f);
5027 qemu_get_buffer(f, idstr, len);
5029 instance_id = qemu_get_be32(f);
5030 version_id = qemu_get_be32(f);
5031 record_len = qemu_get_be32(f);
5033 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5034 idstr, instance_id, version_id, record_len);
5036 cur_pos = qemu_ftell(f);
5037 se = find_se(idstr, instance_id);
5039 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5040 instance_id, idstr);
5042 ret = se->load_state(f, se->opaque, version_id);
5044 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5045 instance_id, idstr);
5048 /* always seek to exact end of record */
5049 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5056 /* device can contain snapshots */
5057 static int bdrv_can_snapshot(BlockDriverState *bs)
5060 !bdrv_is_removable(bs) &&
5061 !bdrv_is_read_only(bs));
5064 /* device must be snapshots in order to have a reliable snapshot */
5065 static int bdrv_has_snapshot(BlockDriverState *bs)
5068 !bdrv_is_removable(bs) &&
5069 !bdrv_is_read_only(bs));
5072 static BlockDriverState *get_bs_snapshots(void)
5074 BlockDriverState *bs;
5078 return bs_snapshots;
5079 for(i = 0; i <= MAX_DISKS; i++) {
5081 if (bdrv_can_snapshot(bs))
5090 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5093 QEMUSnapshotInfo *sn_tab, *sn;
5097 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5100 for(i = 0; i < nb_sns; i++) {
5102 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5112 void do_savevm(const char *name)
5114 BlockDriverState *bs, *bs1;
5115 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5116 int must_delete, ret, i;
5117 BlockDriverInfo bdi1, *bdi = &bdi1;
5119 int saved_vm_running;
5126 bs = get_bs_snapshots();
5128 term_printf("No block device can accept snapshots\n");
5132 /* ??? Should this occur after vm_stop? */
5135 saved_vm_running = vm_running;
5140 ret = bdrv_snapshot_find(bs, old_sn, name);
5145 memset(sn, 0, sizeof(*sn));
5147 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5148 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5151 pstrcpy(sn->name, sizeof(sn->name), name);
5154 /* fill auxiliary fields */
5157 sn->date_sec = tb.time;
5158 sn->date_nsec = tb.millitm * 1000000;
5160 gettimeofday(&tv, NULL);
5161 sn->date_sec = tv.tv_sec;
5162 sn->date_nsec = tv.tv_usec * 1000;
5164 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5166 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5167 term_printf("Device %s does not support VM state snapshots\n",
5168 bdrv_get_device_name(bs));
5172 /* save the VM state */
5173 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5175 term_printf("Could not open VM state file\n");
5178 ret = qemu_savevm_state(f);
5179 sn->vm_state_size = qemu_ftell(f);
5182 term_printf("Error %d while writing VM\n", ret);
5186 /* create the snapshots */
5188 for(i = 0; i < MAX_DISKS; i++) {
5190 if (bdrv_has_snapshot(bs1)) {
5192 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5194 term_printf("Error while deleting snapshot on '%s'\n",
5195 bdrv_get_device_name(bs1));
5198 ret = bdrv_snapshot_create(bs1, sn);
5200 term_printf("Error while creating snapshot on '%s'\n",
5201 bdrv_get_device_name(bs1));
5207 if (saved_vm_running)
5211 void do_loadvm(const char *name)
5213 BlockDriverState *bs, *bs1;
5214 BlockDriverInfo bdi1, *bdi = &bdi1;
5217 int saved_vm_running;
5219 bs = get_bs_snapshots();
5221 term_printf("No block device supports snapshots\n");
5225 /* Flush all IO requests so they don't interfere with the new state. */
5228 saved_vm_running = vm_running;
5231 for(i = 0; i <= MAX_DISKS; i++) {
5233 if (bdrv_has_snapshot(bs1)) {
5234 ret = bdrv_snapshot_goto(bs1, name);
5237 term_printf("Warning: ");
5240 term_printf("Snapshots not supported on device '%s'\n",
5241 bdrv_get_device_name(bs1));
5244 term_printf("Could not find snapshot '%s' on device '%s'\n",
5245 name, bdrv_get_device_name(bs1));
5248 term_printf("Error %d while activating snapshot on '%s'\n",
5249 ret, bdrv_get_device_name(bs1));
5252 /* fatal on snapshot block device */
5259 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5260 term_printf("Device %s does not support VM state snapshots\n",
5261 bdrv_get_device_name(bs));
5265 /* restore the VM state */
5266 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5268 term_printf("Could not open VM state file\n");
5271 ret = qemu_loadvm_state(f);
5274 term_printf("Error %d while loading VM state\n", ret);
5277 if (saved_vm_running)
5281 void do_delvm(const char *name)
5283 BlockDriverState *bs, *bs1;
5286 bs = get_bs_snapshots();
5288 term_printf("No block device supports snapshots\n");
5292 for(i = 0; i <= MAX_DISKS; i++) {
5294 if (bdrv_has_snapshot(bs1)) {
5295 ret = bdrv_snapshot_delete(bs1, name);
5297 if (ret == -ENOTSUP)
5298 term_printf("Snapshots not supported on device '%s'\n",
5299 bdrv_get_device_name(bs1));
5301 term_printf("Error %d while deleting snapshot on '%s'\n",
5302 ret, bdrv_get_device_name(bs1));
5308 void do_info_snapshots(void)
5310 BlockDriverState *bs, *bs1;
5311 QEMUSnapshotInfo *sn_tab, *sn;
5315 bs = get_bs_snapshots();
5317 term_printf("No available block device supports snapshots\n");
5320 term_printf("Snapshot devices:");
5321 for(i = 0; i <= MAX_DISKS; i++) {
5323 if (bdrv_has_snapshot(bs1)) {
5325 term_printf(" %s", bdrv_get_device_name(bs1));
5330 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5332 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5335 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5336 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5337 for(i = 0; i < nb_sns; i++) {
5339 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5344 /***********************************************************/
5345 /* cpu save/restore */
5347 #if defined(TARGET_I386)
5349 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5351 qemu_put_be32(f, dt->selector);
5352 qemu_put_betl(f, dt->base);
5353 qemu_put_be32(f, dt->limit);
5354 qemu_put_be32(f, dt->flags);
5357 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5359 dt->selector = qemu_get_be32(f);
5360 dt->base = qemu_get_betl(f);
5361 dt->limit = qemu_get_be32(f);
5362 dt->flags = qemu_get_be32(f);
5365 void cpu_save(QEMUFile *f, void *opaque)
5367 CPUState *env = opaque;
5368 uint16_t fptag, fpus, fpuc, fpregs_format;
5372 for(i = 0; i < CPU_NB_REGS; i++)
5373 qemu_put_betls(f, &env->regs[i]);
5374 qemu_put_betls(f, &env->eip);
5375 qemu_put_betls(f, &env->eflags);
5376 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5377 qemu_put_be32s(f, &hflags);
5381 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5383 for(i = 0; i < 8; i++) {
5384 fptag |= ((!env->fptags[i]) << i);
5387 qemu_put_be16s(f, &fpuc);
5388 qemu_put_be16s(f, &fpus);
5389 qemu_put_be16s(f, &fptag);
5391 #ifdef USE_X86LDOUBLE
5396 qemu_put_be16s(f, &fpregs_format);
5398 for(i = 0; i < 8; i++) {
5399 #ifdef USE_X86LDOUBLE
5403 /* we save the real CPU data (in case of MMX usage only 'mant'
5404 contains the MMX register */
5405 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5406 qemu_put_be64(f, mant);
5407 qemu_put_be16(f, exp);
5410 /* if we use doubles for float emulation, we save the doubles to
5411 avoid losing information in case of MMX usage. It can give
5412 problems if the image is restored on a CPU where long
5413 doubles are used instead. */
5414 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5418 for(i = 0; i < 6; i++)
5419 cpu_put_seg(f, &env->segs[i]);
5420 cpu_put_seg(f, &env->ldt);
5421 cpu_put_seg(f, &env->tr);
5422 cpu_put_seg(f, &env->gdt);
5423 cpu_put_seg(f, &env->idt);
5425 qemu_put_be32s(f, &env->sysenter_cs);
5426 qemu_put_be32s(f, &env->sysenter_esp);
5427 qemu_put_be32s(f, &env->sysenter_eip);
5429 qemu_put_betls(f, &env->cr[0]);
5430 qemu_put_betls(f, &env->cr[2]);
5431 qemu_put_betls(f, &env->cr[3]);
5432 qemu_put_betls(f, &env->cr[4]);
5434 for(i = 0; i < 8; i++)
5435 qemu_put_betls(f, &env->dr[i]);
5438 qemu_put_be32s(f, &env->a20_mask);
5441 qemu_put_be32s(f, &env->mxcsr);
5442 for(i = 0; i < CPU_NB_REGS; i++) {
5443 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5444 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5447 #ifdef TARGET_X86_64
5448 qemu_put_be64s(f, &env->efer);
5449 qemu_put_be64s(f, &env->star);
5450 qemu_put_be64s(f, &env->lstar);
5451 qemu_put_be64s(f, &env->cstar);
5452 qemu_put_be64s(f, &env->fmask);
5453 qemu_put_be64s(f, &env->kernelgsbase);
5455 qemu_put_be32s(f, &env->smbase);
5458 #ifdef USE_X86LDOUBLE
5459 /* XXX: add that in a FPU generic layer */
5460 union x86_longdouble {
5465 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5466 #define EXPBIAS1 1023
5467 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5468 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5470 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5474 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5475 /* exponent + sign */
5476 e = EXPD1(temp) - EXPBIAS1 + 16383;
5477 e |= SIGND1(temp) >> 16;
5482 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5484 CPUState *env = opaque;
5487 uint16_t fpus, fpuc, fptag, fpregs_format;
5489 if (version_id != 3 && version_id != 4)
5491 for(i = 0; i < CPU_NB_REGS; i++)
5492 qemu_get_betls(f, &env->regs[i]);
5493 qemu_get_betls(f, &env->eip);
5494 qemu_get_betls(f, &env->eflags);
5495 qemu_get_be32s(f, &hflags);
5497 qemu_get_be16s(f, &fpuc);
5498 qemu_get_be16s(f, &fpus);
5499 qemu_get_be16s(f, &fptag);
5500 qemu_get_be16s(f, &fpregs_format);
5502 /* NOTE: we cannot always restore the FPU state if the image come
5503 from a host with a different 'USE_X86LDOUBLE' define. We guess
5504 if we are in an MMX state to restore correctly in that case. */
5505 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5506 for(i = 0; i < 8; i++) {
5510 switch(fpregs_format) {
5512 mant = qemu_get_be64(f);
5513 exp = qemu_get_be16(f);
5514 #ifdef USE_X86LDOUBLE
5515 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5517 /* difficult case */
5519 env->fpregs[i].mmx.MMX_Q(0) = mant;
5521 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5525 mant = qemu_get_be64(f);
5526 #ifdef USE_X86LDOUBLE
5528 union x86_longdouble *p;
5529 /* difficult case */
5530 p = (void *)&env->fpregs[i];
5535 fp64_to_fp80(p, mant);
5539 env->fpregs[i].mmx.MMX_Q(0) = mant;
5548 /* XXX: restore FPU round state */
5549 env->fpstt = (fpus >> 11) & 7;
5550 env->fpus = fpus & ~0x3800;
5552 for(i = 0; i < 8; i++) {
5553 env->fptags[i] = (fptag >> i) & 1;
5556 for(i = 0; i < 6; i++)
5557 cpu_get_seg(f, &env->segs[i]);
5558 cpu_get_seg(f, &env->ldt);
5559 cpu_get_seg(f, &env->tr);
5560 cpu_get_seg(f, &env->gdt);
5561 cpu_get_seg(f, &env->idt);
5563 qemu_get_be32s(f, &env->sysenter_cs);
5564 qemu_get_be32s(f, &env->sysenter_esp);
5565 qemu_get_be32s(f, &env->sysenter_eip);
5567 qemu_get_betls(f, &env->cr[0]);
5568 qemu_get_betls(f, &env->cr[2]);
5569 qemu_get_betls(f, &env->cr[3]);
5570 qemu_get_betls(f, &env->cr[4]);
5572 for(i = 0; i < 8; i++)
5573 qemu_get_betls(f, &env->dr[i]);
5576 qemu_get_be32s(f, &env->a20_mask);
5578 qemu_get_be32s(f, &env->mxcsr);
5579 for(i = 0; i < CPU_NB_REGS; i++) {
5580 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5581 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5584 #ifdef TARGET_X86_64
5585 qemu_get_be64s(f, &env->efer);
5586 qemu_get_be64s(f, &env->star);
5587 qemu_get_be64s(f, &env->lstar);
5588 qemu_get_be64s(f, &env->cstar);
5589 qemu_get_be64s(f, &env->fmask);
5590 qemu_get_be64s(f, &env->kernelgsbase);
5592 if (version_id >= 4)
5593 qemu_get_be32s(f, &env->smbase);
5595 /* XXX: compute hflags from scratch, except for CPL and IIF */
5596 env->hflags = hflags;
5601 #elif defined(TARGET_PPC)
5602 void cpu_save(QEMUFile *f, void *opaque)
5606 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5611 #elif defined(TARGET_MIPS)
5612 void cpu_save(QEMUFile *f, void *opaque)
5616 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5621 #elif defined(TARGET_SPARC)
5622 void cpu_save(QEMUFile *f, void *opaque)
5624 CPUState *env = opaque;
5628 for(i = 0; i < 8; i++)
5629 qemu_put_betls(f, &env->gregs[i]);
5630 for(i = 0; i < NWINDOWS * 16; i++)
5631 qemu_put_betls(f, &env->regbase[i]);
5634 for(i = 0; i < TARGET_FPREGS; i++) {
5640 qemu_put_be32(f, u.i);
5643 qemu_put_betls(f, &env->pc);
5644 qemu_put_betls(f, &env->npc);
5645 qemu_put_betls(f, &env->y);
5647 qemu_put_be32(f, tmp);
5648 qemu_put_betls(f, &env->fsr);
5649 qemu_put_betls(f, &env->tbr);
5650 #ifndef TARGET_SPARC64
5651 qemu_put_be32s(f, &env->wim);
5653 for(i = 0; i < 16; i++)
5654 qemu_put_be32s(f, &env->mmuregs[i]);
5658 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5660 CPUState *env = opaque;
5664 for(i = 0; i < 8; i++)
5665 qemu_get_betls(f, &env->gregs[i]);
5666 for(i = 0; i < NWINDOWS * 16; i++)
5667 qemu_get_betls(f, &env->regbase[i]);
5670 for(i = 0; i < TARGET_FPREGS; i++) {
5675 u.i = qemu_get_be32(f);
5679 qemu_get_betls(f, &env->pc);
5680 qemu_get_betls(f, &env->npc);
5681 qemu_get_betls(f, &env->y);
5682 tmp = qemu_get_be32(f);
5683 env->cwp = 0; /* needed to ensure that the wrapping registers are
5684 correctly updated */
5686 qemu_get_betls(f, &env->fsr);
5687 qemu_get_betls(f, &env->tbr);
5688 #ifndef TARGET_SPARC64
5689 qemu_get_be32s(f, &env->wim);
5691 for(i = 0; i < 16; i++)
5692 qemu_get_be32s(f, &env->mmuregs[i]);
5698 #elif defined(TARGET_ARM)
5700 void cpu_save(QEMUFile *f, void *opaque)
5703 CPUARMState *env = (CPUARMState *)opaque;
5705 for (i = 0; i < 16; i++) {
5706 qemu_put_be32(f, env->regs[i]);
5708 qemu_put_be32(f, cpsr_read(env));
5709 qemu_put_be32(f, env->spsr);
5710 for (i = 0; i < 6; i++) {
5711 qemu_put_be32(f, env->banked_spsr[i]);
5712 qemu_put_be32(f, env->banked_r13[i]);
5713 qemu_put_be32(f, env->banked_r14[i]);
5715 for (i = 0; i < 5; i++) {
5716 qemu_put_be32(f, env->usr_regs[i]);
5717 qemu_put_be32(f, env->fiq_regs[i]);
5719 qemu_put_be32(f, env->cp15.c0_cpuid);
5720 qemu_put_be32(f, env->cp15.c0_cachetype);
5721 qemu_put_be32(f, env->cp15.c1_sys);
5722 qemu_put_be32(f, env->cp15.c1_coproc);
5723 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5724 qemu_put_be32(f, env->cp15.c2_base);
5725 qemu_put_be32(f, env->cp15.c2_data);
5726 qemu_put_be32(f, env->cp15.c2_insn);
5727 qemu_put_be32(f, env->cp15.c3);
5728 qemu_put_be32(f, env->cp15.c5_insn);
5729 qemu_put_be32(f, env->cp15.c5_data);
5730 for (i = 0; i < 8; i++) {
5731 qemu_put_be32(f, env->cp15.c6_region[i]);
5733 qemu_put_be32(f, env->cp15.c6_insn);
5734 qemu_put_be32(f, env->cp15.c6_data);
5735 qemu_put_be32(f, env->cp15.c9_insn);
5736 qemu_put_be32(f, env->cp15.c9_data);
5737 qemu_put_be32(f, env->cp15.c13_fcse);
5738 qemu_put_be32(f, env->cp15.c13_context);
5739 qemu_put_be32(f, env->cp15.c15_cpar);
5741 qemu_put_be32(f, env->features);
5743 if (arm_feature(env, ARM_FEATURE_VFP)) {
5744 for (i = 0; i < 16; i++) {
5746 u.d = env->vfp.regs[i];
5747 qemu_put_be32(f, u.l.upper);
5748 qemu_put_be32(f, u.l.lower);
5750 for (i = 0; i < 16; i++) {
5751 qemu_put_be32(f, env->vfp.xregs[i]);
5754 /* TODO: Should use proper FPSCR access functions. */
5755 qemu_put_be32(f, env->vfp.vec_len);
5756 qemu_put_be32(f, env->vfp.vec_stride);
5759 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5760 for (i = 0; i < 16; i++) {
5761 qemu_put_be64(f, env->iwmmxt.regs[i]);
5763 for (i = 0; i < 16; i++) {
5764 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5769 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5771 CPUARMState *env = (CPUARMState *)opaque;
5774 if (version_id != 0)
5777 for (i = 0; i < 16; i++) {
5778 env->regs[i] = qemu_get_be32(f);
5780 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5781 env->spsr = qemu_get_be32(f);
5782 for (i = 0; i < 6; i++) {
5783 env->banked_spsr[i] = qemu_get_be32(f);
5784 env->banked_r13[i] = qemu_get_be32(f);
5785 env->banked_r14[i] = qemu_get_be32(f);
5787 for (i = 0; i < 5; i++) {
5788 env->usr_regs[i] = qemu_get_be32(f);
5789 env->fiq_regs[i] = qemu_get_be32(f);
5791 env->cp15.c0_cpuid = qemu_get_be32(f);
5792 env->cp15.c0_cachetype = qemu_get_be32(f);
5793 env->cp15.c1_sys = qemu_get_be32(f);
5794 env->cp15.c1_coproc = qemu_get_be32(f);
5795 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5796 env->cp15.c2_base = qemu_get_be32(f);
5797 env->cp15.c2_data = qemu_get_be32(f);
5798 env->cp15.c2_insn = qemu_get_be32(f);
5799 env->cp15.c3 = qemu_get_be32(f);
5800 env->cp15.c5_insn = qemu_get_be32(f);
5801 env->cp15.c5_data = qemu_get_be32(f);
5802 for (i = 0; i < 8; i++) {
5803 env->cp15.c6_region[i] = qemu_get_be32(f);
5805 env->cp15.c6_insn = qemu_get_be32(f);
5806 env->cp15.c6_data = qemu_get_be32(f);
5807 env->cp15.c9_insn = qemu_get_be32(f);
5808 env->cp15.c9_data = qemu_get_be32(f);
5809 env->cp15.c13_fcse = qemu_get_be32(f);
5810 env->cp15.c13_context = qemu_get_be32(f);
5811 env->cp15.c15_cpar = qemu_get_be32(f);
5813 env->features = qemu_get_be32(f);
5815 if (arm_feature(env, ARM_FEATURE_VFP)) {
5816 for (i = 0; i < 16; i++) {
5818 u.l.upper = qemu_get_be32(f);
5819 u.l.lower = qemu_get_be32(f);
5820 env->vfp.regs[i] = u.d;
5822 for (i = 0; i < 16; i++) {
5823 env->vfp.xregs[i] = qemu_get_be32(f);
5826 /* TODO: Should use proper FPSCR access functions. */
5827 env->vfp.vec_len = qemu_get_be32(f);
5828 env->vfp.vec_stride = qemu_get_be32(f);
5831 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5832 for (i = 0; i < 16; i++) {
5833 env->iwmmxt.regs[i] = qemu_get_be64(f);
5835 for (i = 0; i < 16; i++) {
5836 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5845 #warning No CPU save/restore functions
5849 /***********************************************************/
5850 /* ram save/restore */
5852 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5856 v = qemu_get_byte(f);
5859 if (qemu_get_buffer(f, buf, len) != len)
5863 v = qemu_get_byte(f);
5864 memset(buf, v, len);
5872 static int ram_load_v1(QEMUFile *f, void *opaque)
5876 if (qemu_get_be32(f) != phys_ram_size)
5878 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5879 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5886 #define BDRV_HASH_BLOCK_SIZE 1024
5887 #define IOBUF_SIZE 4096
5888 #define RAM_CBLOCK_MAGIC 0xfabe
5890 typedef struct RamCompressState {
5893 uint8_t buf[IOBUF_SIZE];
5896 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5899 memset(s, 0, sizeof(*s));
5901 ret = deflateInit2(&s->zstream, 1,
5903 9, Z_DEFAULT_STRATEGY);
5906 s->zstream.avail_out = IOBUF_SIZE;
5907 s->zstream.next_out = s->buf;
5911 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5913 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5914 qemu_put_be16(s->f, len);
5915 qemu_put_buffer(s->f, buf, len);
5918 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5922 s->zstream.avail_in = len;
5923 s->zstream.next_in = (uint8_t *)buf;
5924 while (s->zstream.avail_in > 0) {
5925 ret = deflate(&s->zstream, Z_NO_FLUSH);
5928 if (s->zstream.avail_out == 0) {
5929 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5930 s->zstream.avail_out = IOBUF_SIZE;
5931 s->zstream.next_out = s->buf;
5937 static void ram_compress_close(RamCompressState *s)
5941 /* compress last bytes */
5943 ret = deflate(&s->zstream, Z_FINISH);
5944 if (ret == Z_OK || ret == Z_STREAM_END) {
5945 len = IOBUF_SIZE - s->zstream.avail_out;
5947 ram_put_cblock(s, s->buf, len);
5949 s->zstream.avail_out = IOBUF_SIZE;
5950 s->zstream.next_out = s->buf;
5951 if (ret == Z_STREAM_END)
5958 deflateEnd(&s->zstream);
5961 typedef struct RamDecompressState {
5964 uint8_t buf[IOBUF_SIZE];
5965 } RamDecompressState;
5967 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5970 memset(s, 0, sizeof(*s));
5972 ret = inflateInit(&s->zstream);
5978 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5982 s->zstream.avail_out = len;
5983 s->zstream.next_out = buf;
5984 while (s->zstream.avail_out > 0) {
5985 if (s->zstream.avail_in == 0) {
5986 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5988 clen = qemu_get_be16(s->f);
5989 if (clen > IOBUF_SIZE)
5991 qemu_get_buffer(s->f, s->buf, clen);
5992 s->zstream.avail_in = clen;
5993 s->zstream.next_in = s->buf;
5995 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5996 if (ret != Z_OK && ret != Z_STREAM_END) {
6003 static void ram_decompress_close(RamDecompressState *s)
6005 inflateEnd(&s->zstream);
6008 static void ram_save(QEMUFile *f, void *opaque)
6011 RamCompressState s1, *s = &s1;
6014 qemu_put_be32(f, phys_ram_size);
6015 if (ram_compress_open(s, f) < 0)
6017 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6019 if (tight_savevm_enabled) {
6023 /* find if the memory block is available on a virtual
6026 for(j = 0; j < MAX_DISKS; j++) {
6028 sector_num = bdrv_hash_find(bs_table[j],
6029 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6030 if (sector_num >= 0)
6035 goto normal_compress;
6038 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6039 ram_compress_buf(s, buf, 10);
6045 ram_compress_buf(s, buf, 1);
6046 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6049 ram_compress_close(s);
6052 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6054 RamDecompressState s1, *s = &s1;
6058 if (version_id == 1)
6059 return ram_load_v1(f, opaque);
6060 if (version_id != 2)
6062 if (qemu_get_be32(f) != phys_ram_size)
6064 if (ram_decompress_open(s, f) < 0)
6066 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6067 if (ram_decompress_buf(s, buf, 1) < 0) {
6068 fprintf(stderr, "Error while reading ram block header\n");
6072 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6073 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6082 ram_decompress_buf(s, buf + 1, 9);
6084 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6085 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6086 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6089 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6090 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6091 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6092 bs_index, sector_num);
6099 printf("Error block header\n");
6103 ram_decompress_close(s);
6107 /***********************************************************/
6108 /* bottom halves (can be seen as timers which expire ASAP) */
6117 static QEMUBH *first_bh = NULL;
6119 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6122 bh = qemu_mallocz(sizeof(QEMUBH));
6126 bh->opaque = opaque;
6130 int qemu_bh_poll(void)
6149 void qemu_bh_schedule(QEMUBH *bh)
6151 CPUState *env = cpu_single_env;
6155 bh->next = first_bh;
6158 /* stop the currently executing CPU to execute the BH ASAP */
6160 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6164 void qemu_bh_cancel(QEMUBH *bh)
6167 if (bh->scheduled) {
6170 pbh = &(*pbh)->next;
6176 void qemu_bh_delete(QEMUBH *bh)
6182 /***********************************************************/
6183 /* machine registration */
6185 QEMUMachine *first_machine = NULL;
6187 int qemu_register_machine(QEMUMachine *m)
6190 pm = &first_machine;
6198 QEMUMachine *find_machine(const char *name)
6202 for(m = first_machine; m != NULL; m = m->next) {
6203 if (!strcmp(m->name, name))
6209 /***********************************************************/
6210 /* main execution loop */
6212 void gui_update(void *opaque)
6214 DisplayState *ds = opaque;
6215 ds->dpy_refresh(ds);
6216 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6219 struct vm_change_state_entry {
6220 VMChangeStateHandler *cb;
6222 LIST_ENTRY (vm_change_state_entry) entries;
6225 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6227 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6230 VMChangeStateEntry *e;
6232 e = qemu_mallocz(sizeof (*e));
6238 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6242 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6244 LIST_REMOVE (e, entries);
6248 static void vm_state_notify(int running)
6250 VMChangeStateEntry *e;
6252 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6253 e->cb(e->opaque, running);
6257 /* XXX: support several handlers */
6258 static VMStopHandler *vm_stop_cb;
6259 static void *vm_stop_opaque;
6261 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6264 vm_stop_opaque = opaque;
6268 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6282 void vm_stop(int reason)
6285 cpu_disable_ticks();
6289 vm_stop_cb(vm_stop_opaque, reason);
6296 /* reset/shutdown handler */
6298 typedef struct QEMUResetEntry {
6299 QEMUResetHandler *func;
6301 struct QEMUResetEntry *next;
6304 static QEMUResetEntry *first_reset_entry;
6305 static int reset_requested;
6306 static int shutdown_requested;
6307 static int powerdown_requested;
6309 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6311 QEMUResetEntry **pre, *re;
6313 pre = &first_reset_entry;
6314 while (*pre != NULL)
6315 pre = &(*pre)->next;
6316 re = qemu_mallocz(sizeof(QEMUResetEntry));
6318 re->opaque = opaque;
6323 static void qemu_system_reset(void)
6327 /* reset all devices */
6328 for(re = first_reset_entry; re != NULL; re = re->next) {
6329 re->func(re->opaque);
6333 void qemu_system_reset_request(void)
6336 shutdown_requested = 1;
6338 reset_requested = 1;
6341 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6344 void qemu_system_shutdown_request(void)
6346 shutdown_requested = 1;
6348 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6351 void qemu_system_powerdown_request(void)
6353 powerdown_requested = 1;
6355 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6358 void main_loop_wait(int timeout)
6360 IOHandlerRecord *ioh;
6361 fd_set rfds, wfds, xfds;
6370 /* XXX: need to suppress polling by better using win32 events */
6372 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6373 ret |= pe->func(pe->opaque);
6378 WaitObjects *w = &wait_objects;
6380 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6381 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6382 if (w->func[ret - WAIT_OBJECT_0])
6383 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6385 /* Check for additional signaled events */
6386 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6388 /* Check if event is signaled */
6389 ret2 = WaitForSingleObject(w->events[i], 0);
6390 if(ret2 == WAIT_OBJECT_0) {
6392 w->func[i](w->opaque[i]);
6393 } else if (ret2 == WAIT_TIMEOUT) {
6395 err = GetLastError();
6396 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6399 } else if (ret == WAIT_TIMEOUT) {
6401 err = GetLastError();
6402 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6406 /* poll any events */
6407 /* XXX: separate device handlers from system ones */
6412 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6416 (!ioh->fd_read_poll ||
6417 ioh->fd_read_poll(ioh->opaque) != 0)) {
6418 FD_SET(ioh->fd, &rfds);
6422 if (ioh->fd_write) {
6423 FD_SET(ioh->fd, &wfds);
6433 tv.tv_usec = timeout * 1000;
6435 #if defined(CONFIG_SLIRP)
6437 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6440 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6442 IOHandlerRecord **pioh;
6444 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6447 if (FD_ISSET(ioh->fd, &rfds)) {
6448 ioh->fd_read(ioh->opaque);
6450 if (FD_ISSET(ioh->fd, &wfds)) {
6451 ioh->fd_write(ioh->opaque);
6455 /* remove deleted IO handlers */
6456 pioh = &first_io_handler;
6466 #if defined(CONFIG_SLIRP)
6473 slirp_select_poll(&rfds, &wfds, &xfds);
6479 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6480 qemu_get_clock(vm_clock));
6481 /* run dma transfers, if any */
6485 /* real time timers */
6486 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6487 qemu_get_clock(rt_clock));
6489 /* Check bottom-halves last in case any of the earlier events triggered
6495 static CPUState *cur_cpu;
6500 #ifdef CONFIG_PROFILER
6505 cur_cpu = first_cpu;
6512 env = env->next_cpu;
6515 #ifdef CONFIG_PROFILER
6516 ti = profile_getclock();
6518 ret = cpu_exec(env);
6519 #ifdef CONFIG_PROFILER
6520 qemu_time += profile_getclock() - ti;
6522 if (ret == EXCP_HLT) {
6523 /* Give the next CPU a chance to run. */
6527 if (ret != EXCP_HALTED)
6529 /* all CPUs are halted ? */
6535 if (shutdown_requested) {
6536 ret = EXCP_INTERRUPT;
6539 if (reset_requested) {
6540 reset_requested = 0;
6541 qemu_system_reset();
6542 ret = EXCP_INTERRUPT;
6544 if (powerdown_requested) {
6545 powerdown_requested = 0;
6546 qemu_system_powerdown();
6547 ret = EXCP_INTERRUPT;
6549 if (ret == EXCP_DEBUG) {
6550 vm_stop(EXCP_DEBUG);
6552 /* If all cpus are halted then wait until the next IRQ */
6553 /* XXX: use timeout computed from timers */
6554 if (ret == EXCP_HALTED)
6561 #ifdef CONFIG_PROFILER
6562 ti = profile_getclock();
6564 main_loop_wait(timeout);
6565 #ifdef CONFIG_PROFILER
6566 dev_time += profile_getclock() - ti;
6569 cpu_disable_ticks();
6573 static void help(const char *optarg)
6575 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6576 "usage: %s [options] [disk_image]\n"
6578 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6580 "Standard options:\n"
6581 "-M machine select emulated machine (-M ? for list)\n"
6582 "-cpu cpu select CPU (-cpu ? for list)\n"
6583 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6584 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6585 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6586 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6587 "-mtdblock file use 'file' as on-board Flash memory image\n"
6588 "-sd file use 'file' as SecureDigital card image\n"
6589 "-pflash file use 'file' as a parallel flash image\n"
6590 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6591 "-snapshot write to temporary files instead of disk image files\n"
6593 "-no-frame open SDL window without a frame and window decorations\n"
6594 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6595 "-no-quit disable SDL window close capability\n"
6598 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6600 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6601 "-smp n set the number of CPUs to 'n' [default=1]\n"
6602 "-nographic disable graphical output and redirect serial I/Os to console\n"
6603 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6605 "-k language use keyboard layout (for example \"fr\" for French)\n"
6608 "-audio-help print list of audio drivers and their options\n"
6609 "-soundhw c1,... enable audio support\n"
6610 " and only specified sound cards (comma separated list)\n"
6611 " use -soundhw ? to get the list of supported cards\n"
6612 " use -soundhw all to enable all of them\n"
6614 "-localtime set the real time clock to local time [default=utc]\n"
6615 "-full-screen start in full screen\n"
6617 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6619 "-usb enable the USB driver (will be the default soon)\n"
6620 "-usbdevice name add the host or guest USB device 'name'\n"
6621 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6622 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6624 "-name string set the name of the guest\n"
6626 "Network options:\n"
6627 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6628 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6630 "-net user[,vlan=n][,hostname=host]\n"
6631 " connect the user mode network stack to VLAN 'n' and send\n"
6632 " hostname 'host' to DHCP clients\n"
6635 "-net tap[,vlan=n],ifname=name\n"
6636 " connect the host TAP network interface to VLAN 'n'\n"
6638 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6639 " connect the host TAP network interface to VLAN 'n' and use\n"
6640 " the network script 'file' (default=%s);\n"
6641 " use 'script=no' to disable script execution;\n"
6642 " use 'fd=h' to connect to an already opened TAP interface\n"
6644 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6645 " connect the vlan 'n' to another VLAN using a socket connection\n"
6646 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6647 " connect the vlan 'n' to multicast maddr and port\n"
6648 "-net none use it alone to have zero network devices; if no -net option\n"
6649 " is provided, the default is '-net nic -net user'\n"
6652 "-tftp dir allow tftp access to files in dir [-net user]\n"
6653 "-bootp file advertise file in BOOTP replies\n"
6655 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6657 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6658 " redirect TCP or UDP connections from host to guest [-net user]\n"
6661 "Linux boot specific:\n"
6662 "-kernel bzImage use 'bzImage' as kernel image\n"
6663 "-append cmdline use 'cmdline' as kernel command line\n"
6664 "-initrd file use 'file' as initial ram disk\n"
6666 "Debug/Expert options:\n"
6667 "-monitor dev redirect the monitor to char device 'dev'\n"
6668 "-serial dev redirect the serial port to char device 'dev'\n"
6669 "-parallel dev redirect the parallel port to char device 'dev'\n"
6670 "-pidfile file Write PID to 'file'\n"
6671 "-S freeze CPU at startup (use 'c' to start execution)\n"
6672 "-s wait gdb connection to port\n"
6673 "-p port set gdb connection port [default=%s]\n"
6674 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6675 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6676 " translation (t=none or lba) (usually qemu can guess them)\n"
6677 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6679 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6680 "-no-kqemu disable KQEMU kernel module usage\n"
6682 #ifdef USE_CODE_COPY
6683 "-no-code-copy disable code copy acceleration\n"
6686 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6687 " (default is CL-GD5446 PCI VGA)\n"
6688 "-no-acpi disable ACPI\n"
6690 "-no-reboot exit instead of rebooting\n"
6691 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6692 "-vnc display start a VNC server on display\n"
6694 "-daemonize daemonize QEMU after initializing\n"
6696 "-option-rom rom load a file, rom, into the option ROM space\n"
6698 "-prom-env variable=value set OpenBIOS nvram variables\n"
6701 "During emulation, the following keys are useful:\n"
6702 "ctrl-alt-f toggle full screen\n"
6703 "ctrl-alt-n switch to virtual console 'n'\n"
6704 "ctrl-alt toggle mouse and keyboard grab\n"
6706 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6711 DEFAULT_NETWORK_SCRIPT,
6713 DEFAULT_GDBSTUB_PORT,
6715 exit(strcmp(optarg, "?"));
6718 #define HAS_ARG 0x0001
6732 QEMU_OPTION_mtdblock,
6736 QEMU_OPTION_snapshot,
6738 QEMU_OPTION_no_fd_bootchk,
6741 QEMU_OPTION_nographic,
6742 QEMU_OPTION_portrait,
6744 QEMU_OPTION_audio_help,
6745 QEMU_OPTION_soundhw,
6764 QEMU_OPTION_no_code_copy,
6766 QEMU_OPTION_localtime,
6767 QEMU_OPTION_cirrusvga,
6770 QEMU_OPTION_std_vga,
6772 QEMU_OPTION_monitor,
6774 QEMU_OPTION_parallel,
6776 QEMU_OPTION_full_screen,
6777 QEMU_OPTION_no_frame,
6778 QEMU_OPTION_alt_grab,
6779 QEMU_OPTION_no_quit,
6780 QEMU_OPTION_pidfile,
6781 QEMU_OPTION_no_kqemu,
6782 QEMU_OPTION_kernel_kqemu,
6783 QEMU_OPTION_win2k_hack,
6785 QEMU_OPTION_usbdevice,
6788 QEMU_OPTION_no_acpi,
6789 QEMU_OPTION_no_reboot,
6790 QEMU_OPTION_show_cursor,
6791 QEMU_OPTION_daemonize,
6792 QEMU_OPTION_option_rom,
6793 QEMU_OPTION_semihosting,
6795 QEMU_OPTION_prom_env,
6798 typedef struct QEMUOption {
6804 const QEMUOption qemu_options[] = {
6805 { "h", 0, QEMU_OPTION_h },
6806 { "help", 0, QEMU_OPTION_h },
6808 { "M", HAS_ARG, QEMU_OPTION_M },
6809 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6810 { "fda", HAS_ARG, QEMU_OPTION_fda },
6811 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6812 { "hda", HAS_ARG, QEMU_OPTION_hda },
6813 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6814 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6815 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6816 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6817 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6818 { "sd", HAS_ARG, QEMU_OPTION_sd },
6819 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6820 { "boot", HAS_ARG, QEMU_OPTION_boot },
6821 { "snapshot", 0, QEMU_OPTION_snapshot },
6823 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6825 { "m", HAS_ARG, QEMU_OPTION_m },
6826 { "nographic", 0, QEMU_OPTION_nographic },
6827 { "portrait", 0, QEMU_OPTION_portrait },
6828 { "k", HAS_ARG, QEMU_OPTION_k },
6830 { "audio-help", 0, QEMU_OPTION_audio_help },
6831 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6834 { "net", HAS_ARG, QEMU_OPTION_net},
6836 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6837 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6839 { "smb", HAS_ARG, QEMU_OPTION_smb },
6841 { "redir", HAS_ARG, QEMU_OPTION_redir },
6844 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6845 { "append", HAS_ARG, QEMU_OPTION_append },
6846 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6848 { "S", 0, QEMU_OPTION_S },
6849 { "s", 0, QEMU_OPTION_s },
6850 { "p", HAS_ARG, QEMU_OPTION_p },
6851 { "d", HAS_ARG, QEMU_OPTION_d },
6852 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6853 { "L", HAS_ARG, QEMU_OPTION_L },
6854 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6856 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6857 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6859 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6860 { "g", 1, QEMU_OPTION_g },
6862 { "localtime", 0, QEMU_OPTION_localtime },
6863 { "std-vga", 0, QEMU_OPTION_std_vga },
6864 { "echr", HAS_ARG, QEMU_OPTION_echr },
6865 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6866 { "serial", HAS_ARG, QEMU_OPTION_serial },
6867 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6868 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6869 { "full-screen", 0, QEMU_OPTION_full_screen },
6871 { "no-frame", 0, QEMU_OPTION_no_frame },
6872 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6873 { "no-quit", 0, QEMU_OPTION_no_quit },
6875 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6876 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6877 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6878 { "smp", HAS_ARG, QEMU_OPTION_smp },
6879 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6881 /* temporary options */
6882 { "usb", 0, QEMU_OPTION_usb },
6883 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6884 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6885 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6886 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6887 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6888 { "daemonize", 0, QEMU_OPTION_daemonize },
6889 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6890 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6891 { "semihosting", 0, QEMU_OPTION_semihosting },
6893 { "name", HAS_ARG, QEMU_OPTION_name },
6894 #if defined(TARGET_SPARC)
6895 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6900 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6902 /* this stack is only used during signal handling */
6903 #define SIGNAL_STACK_SIZE 32768
6905 static uint8_t *signal_stack;
6909 /* password input */
6911 int qemu_key_check(BlockDriverState *bs, const char *name)
6916 if (!bdrv_is_encrypted(bs))
6919 term_printf("%s is encrypted.\n", name);
6920 for(i = 0; i < 3; i++) {
6921 monitor_readline("Password: ", 1, password, sizeof(password));
6922 if (bdrv_set_key(bs, password) == 0)
6924 term_printf("invalid password\n");
6929 static BlockDriverState *get_bdrv(int index)
6931 BlockDriverState *bs;
6934 bs = bs_table[index];
6935 } else if (index < 6) {
6936 bs = fd_table[index - 4];
6943 static void read_passwords(void)
6945 BlockDriverState *bs;
6948 for(i = 0; i < 6; i++) {
6951 qemu_key_check(bs, bdrv_get_device_name(bs));
6955 /* XXX: currently we cannot use simultaneously different CPUs */
6956 void register_machines(void)
6958 #if defined(TARGET_I386)
6959 qemu_register_machine(&pc_machine);
6960 qemu_register_machine(&isapc_machine);
6961 #elif defined(TARGET_PPC)
6962 qemu_register_machine(&heathrow_machine);
6963 qemu_register_machine(&core99_machine);
6964 qemu_register_machine(&prep_machine);
6965 qemu_register_machine(&ref405ep_machine);
6966 qemu_register_machine(&taihu_machine);
6967 #elif defined(TARGET_MIPS)
6968 qemu_register_machine(&mips_machine);
6969 qemu_register_machine(&mips_malta_machine);
6970 qemu_register_machine(&mips_pica61_machine);
6971 #elif defined(TARGET_SPARC)
6972 #ifdef TARGET_SPARC64
6973 qemu_register_machine(&sun4u_machine);
6975 qemu_register_machine(&ss5_machine);
6976 qemu_register_machine(&ss10_machine);
6978 #elif defined(TARGET_ARM)
6979 qemu_register_machine(&integratorcp_machine);
6980 qemu_register_machine(&versatilepb_machine);
6981 qemu_register_machine(&versatileab_machine);
6982 qemu_register_machine(&realview_machine);
6983 qemu_register_machine(&akitapda_machine);
6984 qemu_register_machine(&spitzpda_machine);
6985 qemu_register_machine(&borzoipda_machine);
6986 qemu_register_machine(&terrierpda_machine);
6987 #elif defined(TARGET_SH4)
6988 qemu_register_machine(&shix_machine);
6989 #elif defined(TARGET_ALPHA)
6991 #elif defined(TARGET_M68K)
6992 qemu_register_machine(&mcf5208evb_machine);
6993 qemu_register_machine(&an5206_machine);
6995 #error unsupported CPU
7000 struct soundhw soundhw[] = {
7001 #ifdef HAS_AUDIO_CHOICE
7008 { .init_isa = pcspk_audio_init }
7013 "Creative Sound Blaster 16",
7016 { .init_isa = SB16_init }
7023 "Yamaha YMF262 (OPL3)",
7025 "Yamaha YM3812 (OPL2)",
7029 { .init_isa = Adlib_init }
7036 "Gravis Ultrasound GF1",
7039 { .init_isa = GUS_init }
7045 "ENSONIQ AudioPCI ES1370",
7048 { .init_pci = es1370_init }
7052 { NULL, NULL, 0, 0, { NULL } }
7055 static void select_soundhw (const char *optarg)
7059 if (*optarg == '?') {
7062 printf ("Valid sound card names (comma separated):\n");
7063 for (c = soundhw; c->name; ++c) {
7064 printf ("%-11s %s\n", c->name, c->descr);
7066 printf ("\n-soundhw all will enable all of the above\n");
7067 exit (*optarg != '?');
7075 if (!strcmp (optarg, "all")) {
7076 for (c = soundhw; c->name; ++c) {
7084 e = strchr (p, ',');
7085 l = !e ? strlen (p) : (size_t) (e - p);
7087 for (c = soundhw; c->name; ++c) {
7088 if (!strncmp (c->name, p, l)) {
7097 "Unknown sound card name (too big to show)\n");
7100 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7105 p += l + (e != NULL);
7109 goto show_valid_cards;
7115 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7117 exit(STATUS_CONTROL_C_EXIT);
7122 #define MAX_NET_CLIENTS 32
7124 int main(int argc, char **argv)
7126 #ifdef CONFIG_GDBSTUB
7128 const char *gdbstub_port;
7130 int i, cdrom_index, pflash_index;
7131 int snapshot, linux_boot;
7132 const char *initrd_filename;
7133 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7134 const char *pflash_filename[MAX_PFLASH];
7135 const char *sd_filename;
7136 const char *mtd_filename;
7137 const char *kernel_filename, *kernel_cmdline;
7138 DisplayState *ds = &display_state;
7139 int cyls, heads, secs, translation;
7140 char net_clients[MAX_NET_CLIENTS][256];
7143 const char *r, *optarg;
7144 CharDriverState *monitor_hd;
7145 char monitor_device[128];
7146 char serial_devices[MAX_SERIAL_PORTS][128];
7147 int serial_device_index;
7148 char parallel_devices[MAX_PARALLEL_PORTS][128];
7149 int parallel_device_index;
7150 const char *loadvm = NULL;
7151 QEMUMachine *machine;
7152 const char *cpu_model;
7153 char usb_devices[MAX_USB_CMDLINE][128];
7154 int usb_devices_index;
7156 const char *pid_file = NULL;
7159 LIST_INIT (&vm_change_state_head);
7162 struct sigaction act;
7163 sigfillset(&act.sa_mask);
7165 act.sa_handler = SIG_IGN;
7166 sigaction(SIGPIPE, &act, NULL);
7169 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7170 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7171 QEMU to run on a single CPU */
7176 h = GetCurrentProcess();
7177 if (GetProcessAffinityMask(h, &mask, &smask)) {
7178 for(i = 0; i < 32; i++) {
7179 if (mask & (1 << i))
7184 SetProcessAffinityMask(h, mask);
7190 register_machines();
7191 machine = first_machine;
7193 initrd_filename = NULL;
7194 for(i = 0; i < MAX_FD; i++)
7195 fd_filename[i] = NULL;
7196 for(i = 0; i < MAX_DISKS; i++)
7197 hd_filename[i] = NULL;
7198 for(i = 0; i < MAX_PFLASH; i++)
7199 pflash_filename[i] = NULL;
7202 mtd_filename = NULL;
7203 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7204 vga_ram_size = VGA_RAM_SIZE;
7205 #ifdef CONFIG_GDBSTUB
7207 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7211 kernel_filename = NULL;
7212 kernel_cmdline = "";
7218 cyls = heads = secs = 0;
7219 translation = BIOS_ATA_TRANSLATION_AUTO;
7220 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7222 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7223 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7224 serial_devices[i][0] = '\0';
7225 serial_device_index = 0;
7227 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7228 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7229 parallel_devices[i][0] = '\0';
7230 parallel_device_index = 0;
7232 usb_devices_index = 0;
7237 /* default mac address of the first network interface */
7245 hd_filename[0] = argv[optind++];
7247 const QEMUOption *popt;
7250 /* Treat --foo the same as -foo. */
7253 popt = qemu_options;
7256 fprintf(stderr, "%s: invalid option -- '%s'\n",
7260 if (!strcmp(popt->name, r + 1))
7264 if (popt->flags & HAS_ARG) {
7265 if (optind >= argc) {
7266 fprintf(stderr, "%s: option '%s' requires an argument\n",
7270 optarg = argv[optind++];
7275 switch(popt->index) {
7277 machine = find_machine(optarg);
7280 printf("Supported machines are:\n");
7281 for(m = first_machine; m != NULL; m = m->next) {
7282 printf("%-10s %s%s\n",
7284 m == first_machine ? " (default)" : "");
7289 case QEMU_OPTION_cpu:
7290 /* hw initialization will check this */
7291 if (optarg[0] == '?') {
7292 #if defined(TARGET_PPC)
7293 ppc_cpu_list(stdout, &fprintf);
7294 #elif defined(TARGET_ARM)
7296 #elif defined(TARGET_MIPS)
7297 mips_cpu_list(stdout, &fprintf);
7298 #elif defined(TARGET_SPARC)
7299 sparc_cpu_list(stdout, &fprintf);
7306 case QEMU_OPTION_initrd:
7307 initrd_filename = optarg;
7309 case QEMU_OPTION_hda:
7310 case QEMU_OPTION_hdb:
7311 case QEMU_OPTION_hdc:
7312 case QEMU_OPTION_hdd:
7315 hd_index = popt->index - QEMU_OPTION_hda;
7316 hd_filename[hd_index] = optarg;
7317 if (hd_index == cdrom_index)
7321 case QEMU_OPTION_mtdblock:
7322 mtd_filename = optarg;
7324 case QEMU_OPTION_sd:
7325 sd_filename = optarg;
7327 case QEMU_OPTION_pflash:
7328 if (pflash_index >= MAX_PFLASH) {
7329 fprintf(stderr, "qemu: too many parallel flash images\n");
7332 pflash_filename[pflash_index++] = optarg;
7334 case QEMU_OPTION_snapshot:
7337 case QEMU_OPTION_hdachs:
7341 cyls = strtol(p, (char **)&p, 0);
7342 if (cyls < 1 || cyls > 16383)
7347 heads = strtol(p, (char **)&p, 0);
7348 if (heads < 1 || heads > 16)
7353 secs = strtol(p, (char **)&p, 0);
7354 if (secs < 1 || secs > 63)
7358 if (!strcmp(p, "none"))
7359 translation = BIOS_ATA_TRANSLATION_NONE;
7360 else if (!strcmp(p, "lba"))
7361 translation = BIOS_ATA_TRANSLATION_LBA;
7362 else if (!strcmp(p, "auto"))
7363 translation = BIOS_ATA_TRANSLATION_AUTO;
7366 } else if (*p != '\0') {
7368 fprintf(stderr, "qemu: invalid physical CHS format\n");
7373 case QEMU_OPTION_nographic:
7374 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7375 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7376 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7379 case QEMU_OPTION_portrait:
7382 case QEMU_OPTION_kernel:
7383 kernel_filename = optarg;
7385 case QEMU_OPTION_append:
7386 kernel_cmdline = optarg;
7388 case QEMU_OPTION_cdrom:
7389 if (cdrom_index >= 0) {
7390 hd_filename[cdrom_index] = optarg;
7393 case QEMU_OPTION_boot:
7394 boot_device = optarg[0];
7395 if (boot_device != 'a' &&
7396 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7398 boot_device != 'n' &&
7400 boot_device != 'c' && boot_device != 'd') {
7401 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7405 case QEMU_OPTION_fda:
7406 fd_filename[0] = optarg;
7408 case QEMU_OPTION_fdb:
7409 fd_filename[1] = optarg;
7412 case QEMU_OPTION_no_fd_bootchk:
7416 case QEMU_OPTION_no_code_copy:
7417 code_copy_enabled = 0;
7419 case QEMU_OPTION_net:
7420 if (nb_net_clients >= MAX_NET_CLIENTS) {
7421 fprintf(stderr, "qemu: too many network clients\n");
7424 pstrcpy(net_clients[nb_net_clients],
7425 sizeof(net_clients[0]),
7430 case QEMU_OPTION_tftp:
7431 tftp_prefix = optarg;
7433 case QEMU_OPTION_bootp:
7434 bootp_filename = optarg;
7437 case QEMU_OPTION_smb:
7438 net_slirp_smb(optarg);
7441 case QEMU_OPTION_redir:
7442 net_slirp_redir(optarg);
7446 case QEMU_OPTION_audio_help:
7450 case QEMU_OPTION_soundhw:
7451 select_soundhw (optarg);
7458 ram_size = atoi(optarg) * 1024 * 1024;
7461 if (ram_size > PHYS_RAM_MAX_SIZE) {
7462 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7463 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7472 mask = cpu_str_to_log_mask(optarg);
7474 printf("Log items (comma separated):\n");
7475 for(item = cpu_log_items; item->mask != 0; item++) {
7476 printf("%-10s %s\n", item->name, item->help);
7483 #ifdef CONFIG_GDBSTUB
7488 gdbstub_port = optarg;
7498 keyboard_layout = optarg;
7500 case QEMU_OPTION_localtime:
7503 case QEMU_OPTION_cirrusvga:
7504 cirrus_vga_enabled = 1;
7507 case QEMU_OPTION_vmsvga:
7508 cirrus_vga_enabled = 0;
7511 case QEMU_OPTION_std_vga:
7512 cirrus_vga_enabled = 0;
7520 w = strtol(p, (char **)&p, 10);
7523 fprintf(stderr, "qemu: invalid resolution or depth\n");
7529 h = strtol(p, (char **)&p, 10);
7534 depth = strtol(p, (char **)&p, 10);
7535 if (depth != 8 && depth != 15 && depth != 16 &&
7536 depth != 24 && depth != 32)
7538 } else if (*p == '\0') {
7539 depth = graphic_depth;
7546 graphic_depth = depth;
7549 case QEMU_OPTION_echr:
7552 term_escape_char = strtol(optarg, &r, 0);
7554 printf("Bad argument to echr\n");
7557 case QEMU_OPTION_monitor:
7558 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7560 case QEMU_OPTION_serial:
7561 if (serial_device_index >= MAX_SERIAL_PORTS) {
7562 fprintf(stderr, "qemu: too many serial ports\n");
7565 pstrcpy(serial_devices[serial_device_index],
7566 sizeof(serial_devices[0]), optarg);
7567 serial_device_index++;
7569 case QEMU_OPTION_parallel:
7570 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7571 fprintf(stderr, "qemu: too many parallel ports\n");
7574 pstrcpy(parallel_devices[parallel_device_index],
7575 sizeof(parallel_devices[0]), optarg);
7576 parallel_device_index++;
7578 case QEMU_OPTION_loadvm:
7581 case QEMU_OPTION_full_screen:
7585 case QEMU_OPTION_no_frame:
7588 case QEMU_OPTION_alt_grab:
7591 case QEMU_OPTION_no_quit:
7595 case QEMU_OPTION_pidfile:
7599 case QEMU_OPTION_win2k_hack:
7600 win2k_install_hack = 1;
7604 case QEMU_OPTION_no_kqemu:
7607 case QEMU_OPTION_kernel_kqemu:
7611 case QEMU_OPTION_usb:
7614 case QEMU_OPTION_usbdevice:
7616 if (usb_devices_index >= MAX_USB_CMDLINE) {
7617 fprintf(stderr, "Too many USB devices\n");
7620 pstrcpy(usb_devices[usb_devices_index],
7621 sizeof(usb_devices[usb_devices_index]),
7623 usb_devices_index++;
7625 case QEMU_OPTION_smp:
7626 smp_cpus = atoi(optarg);
7627 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7628 fprintf(stderr, "Invalid number of CPUs\n");
7632 case QEMU_OPTION_vnc:
7633 vnc_display = optarg;
7635 case QEMU_OPTION_no_acpi:
7638 case QEMU_OPTION_no_reboot:
7641 case QEMU_OPTION_show_cursor:
7644 case QEMU_OPTION_daemonize:
7647 case QEMU_OPTION_option_rom:
7648 if (nb_option_roms >= MAX_OPTION_ROMS) {
7649 fprintf(stderr, "Too many option ROMs\n");
7652 option_rom[nb_option_roms] = optarg;
7655 case QEMU_OPTION_semihosting:
7656 semihosting_enabled = 1;
7658 case QEMU_OPTION_name:
7662 case QEMU_OPTION_prom_env:
7663 if (nb_prom_envs >= MAX_PROM_ENVS) {
7664 fprintf(stderr, "Too many prom variables\n");
7667 prom_envs[nb_prom_envs] = optarg;
7676 if (daemonize && !nographic && vnc_display == NULL) {
7677 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7684 if (pipe(fds) == -1)
7695 len = read(fds[0], &status, 1);
7696 if (len == -1 && (errno == EINTR))
7701 else if (status == 1) {
7702 fprintf(stderr, "Could not acquire pidfile\n");
7720 signal(SIGTSTP, SIG_IGN);
7721 signal(SIGTTOU, SIG_IGN);
7722 signal(SIGTTIN, SIG_IGN);
7726 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7729 write(fds[1], &status, 1);
7731 fprintf(stderr, "Could not acquire pid file\n");
7739 linux_boot = (kernel_filename != NULL);
7742 boot_device != 'n' &&
7743 hd_filename[0] == '\0' &&
7744 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7745 fd_filename[0] == '\0')
7748 /* boot to floppy or the default cd if no hard disk defined yet */
7749 if (hd_filename[0] == '\0' && boot_device == 'c') {
7750 if (fd_filename[0] != '\0')
7756 setvbuf(stdout, NULL, _IOLBF, 0);
7766 /* init network clients */
7767 if (nb_net_clients == 0) {
7768 /* if no clients, we use a default config */
7769 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7771 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7776 for(i = 0;i < nb_net_clients; i++) {
7777 if (net_client_init(net_clients[i]) < 0)
7780 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7781 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7783 if (vlan->nb_guest_devs == 0) {
7784 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7787 if (vlan->nb_host_devs == 0)
7789 "Warning: vlan %d is not connected to host network\n",
7794 if (boot_device == 'n') {
7795 for (i = 0; i < nb_nics; i++) {
7796 const char *model = nd_table[i].model;
7800 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7801 if (get_image_size(buf) > 0) {
7802 option_rom[nb_option_roms] = strdup(buf);
7808 fprintf(stderr, "No valid PXE rom found for network device\n");
7811 boot_device = 'c'; /* to prevent confusion by the BIOS */
7815 /* init the memory */
7816 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7818 phys_ram_base = qemu_vmalloc(phys_ram_size);
7819 if (!phys_ram_base) {
7820 fprintf(stderr, "Could not allocate physical memory\n");
7824 /* we always create the cdrom drive, even if no disk is there */
7826 if (cdrom_index >= 0) {
7827 bs_table[cdrom_index] = bdrv_new("cdrom");
7828 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7831 /* open the virtual block devices */
7832 for(i = 0; i < MAX_DISKS; i++) {
7833 if (hd_filename[i]) {
7836 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7837 bs_table[i] = bdrv_new(buf);
7839 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7840 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7844 if (i == 0 && cyls != 0) {
7845 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7846 bdrv_set_translation_hint(bs_table[i], translation);
7851 /* we always create at least one floppy disk */
7852 fd_table[0] = bdrv_new("fda");
7853 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7855 for(i = 0; i < MAX_FD; i++) {
7856 if (fd_filename[i]) {
7859 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7860 fd_table[i] = bdrv_new(buf);
7861 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7863 if (fd_filename[i][0] != '\0') {
7864 if (bdrv_open(fd_table[i], fd_filename[i],
7865 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7866 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7874 /* Open the virtual parallel flash block devices */
7875 for(i = 0; i < MAX_PFLASH; i++) {
7876 if (pflash_filename[i]) {
7877 if (!pflash_table[i]) {
7879 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7880 pflash_table[i] = bdrv_new(buf);
7882 if (bdrv_open(pflash_table[i], pflash_filename[i],
7883 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7884 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7885 pflash_filename[i]);
7891 sd_bdrv = bdrv_new ("sd");
7892 /* FIXME: This isn't really a floppy, but it's a reasonable
7894 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7896 if (bdrv_open(sd_bdrv, sd_filename,
7897 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7898 fprintf(stderr, "qemu: could not open SD card image %s\n",
7901 qemu_key_check(sd_bdrv, sd_filename);
7905 mtd_bdrv = bdrv_new ("mtd");
7906 if (bdrv_open(mtd_bdrv, mtd_filename,
7907 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7908 qemu_key_check(mtd_bdrv, mtd_filename)) {
7909 fprintf(stderr, "qemu: could not open Flash image %s\n",
7911 bdrv_delete(mtd_bdrv);
7916 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7917 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7922 memset(&display_state, 0, sizeof(display_state));
7924 /* nearly nothing to do */
7925 dumb_display_init(ds);
7926 } else if (vnc_display != NULL) {
7927 vnc_display_init(ds, vnc_display);
7929 #if defined(CONFIG_SDL)
7930 sdl_display_init(ds, full_screen, no_frame);
7931 #elif defined(CONFIG_COCOA)
7932 cocoa_display_init(ds, full_screen);
7936 /* Maintain compatibility with multiple stdio monitors */
7937 if (!strcmp(monitor_device,"stdio")) {
7938 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7939 if (!strcmp(serial_devices[i],"mon:stdio")) {
7940 monitor_device[0] = '\0';
7942 } else if (!strcmp(serial_devices[i],"stdio")) {
7943 monitor_device[0] = '\0';
7944 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7949 if (monitor_device[0] != '\0') {
7950 monitor_hd = qemu_chr_open(monitor_device);
7952 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7955 monitor_init(monitor_hd, !nographic);
7958 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7959 const char *devname = serial_devices[i];
7960 if (devname[0] != '\0' && strcmp(devname, "none")) {
7961 serial_hds[i] = qemu_chr_open(devname);
7962 if (!serial_hds[i]) {
7963 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7967 if (!strcmp(devname, "vc"))
7968 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7972 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7973 const char *devname = parallel_devices[i];
7974 if (devname[0] != '\0' && strcmp(devname, "none")) {
7975 parallel_hds[i] = qemu_chr_open(devname);
7976 if (!parallel_hds[i]) {
7977 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7981 if (!strcmp(devname, "vc"))
7982 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7986 machine->init(ram_size, vga_ram_size, boot_device,
7987 ds, fd_filename, snapshot,
7988 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7990 /* init USB devices */
7992 for(i = 0; i < usb_devices_index; i++) {
7993 if (usb_device_add(usb_devices[i]) < 0) {
7994 fprintf(stderr, "Warning: could not add USB device %s\n",
8000 if (display_state.dpy_refresh) {
8001 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8002 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8005 #ifdef CONFIG_GDBSTUB
8007 /* XXX: use standard host:port notation and modify options
8009 if (gdbserver_start(gdbstub_port) < 0) {
8010 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8020 /* XXX: simplify init */
8033 len = write(fds[1], &status, 1);
8034 if (len == -1 && (errno == EINTR))
8040 fd = open("/dev/null", O_RDWR);