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__)
1768 static CharDriverState *qemu_chr_open_pty(void)
1771 char slave_name[1024];
1772 int master_fd, slave_fd;
1774 /* Not satisfying */
1775 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1779 /* Disabling local echo and line-buffered output */
1780 tcgetattr (master_fd, &tty);
1781 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1783 tty.c_cc[VTIME] = 0;
1784 tcsetattr (master_fd, TCSAFLUSH, &tty);
1786 fprintf(stderr, "char device redirected to %s\n", slave_name);
1787 return qemu_chr_open_fd(master_fd, master_fd);
1790 static void tty_serial_init(int fd, int speed,
1791 int parity, int data_bits, int stop_bits)
1797 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1798 speed, parity, data_bits, stop_bits);
1800 tcgetattr (fd, &tty);
1842 cfsetispeed(&tty, spd);
1843 cfsetospeed(&tty, spd);
1845 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1846 |INLCR|IGNCR|ICRNL|IXON);
1847 tty.c_oflag |= OPOST;
1848 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1849 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1870 tty.c_cflag |= PARENB;
1873 tty.c_cflag |= PARENB | PARODD;
1877 tty.c_cflag |= CSTOPB;
1879 tcsetattr (fd, TCSANOW, &tty);
1882 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1884 FDCharDriver *s = chr->opaque;
1887 case CHR_IOCTL_SERIAL_SET_PARAMS:
1889 QEMUSerialSetParams *ssp = arg;
1890 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1891 ssp->data_bits, ssp->stop_bits);
1894 case CHR_IOCTL_SERIAL_SET_BREAK:
1896 int enable = *(int *)arg;
1898 tcsendbreak(s->fd_in, 1);
1907 static CharDriverState *qemu_chr_open_tty(const char *filename)
1909 CharDriverState *chr;
1912 fd = open(filename, O_RDWR | O_NONBLOCK);
1915 fcntl(fd, F_SETFL, O_NONBLOCK);
1916 tty_serial_init(fd, 115200, 'N', 8, 1);
1917 chr = qemu_chr_open_fd(fd, fd);
1920 chr->chr_ioctl = tty_serial_ioctl;
1921 qemu_chr_reset(chr);
1928 } ParallelCharDriver;
1930 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1932 if (s->mode != mode) {
1934 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1941 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1943 ParallelCharDriver *drv = chr->opaque;
1948 case CHR_IOCTL_PP_READ_DATA:
1949 if (ioctl(fd, PPRDATA, &b) < 0)
1951 *(uint8_t *)arg = b;
1953 case CHR_IOCTL_PP_WRITE_DATA:
1954 b = *(uint8_t *)arg;
1955 if (ioctl(fd, PPWDATA, &b) < 0)
1958 case CHR_IOCTL_PP_READ_CONTROL:
1959 if (ioctl(fd, PPRCONTROL, &b) < 0)
1961 /* Linux gives only the lowest bits, and no way to know data
1962 direction! For better compatibility set the fixed upper
1964 *(uint8_t *)arg = b | 0xc0;
1966 case CHR_IOCTL_PP_WRITE_CONTROL:
1967 b = *(uint8_t *)arg;
1968 if (ioctl(fd, PPWCONTROL, &b) < 0)
1971 case CHR_IOCTL_PP_READ_STATUS:
1972 if (ioctl(fd, PPRSTATUS, &b) < 0)
1974 *(uint8_t *)arg = b;
1976 case CHR_IOCTL_PP_EPP_READ_ADDR:
1977 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1978 struct ParallelIOArg *parg = arg;
1979 int n = read(fd, parg->buffer, parg->count);
1980 if (n != parg->count) {
1985 case CHR_IOCTL_PP_EPP_READ:
1986 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
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_WRITE_ADDR:
1995 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1996 struct ParallelIOArg *parg = arg;
1997 int n = write(fd, parg->buffer, parg->count);
1998 if (n != parg->count) {
2003 case CHR_IOCTL_PP_EPP_WRITE:
2004 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2005 struct ParallelIOArg *parg = arg;
2006 int n = write(fd, parg->buffer, parg->count);
2007 if (n != parg->count) {
2018 static void pp_close(CharDriverState *chr)
2020 ParallelCharDriver *drv = chr->opaque;
2023 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2024 ioctl(fd, PPRELEASE);
2029 static CharDriverState *qemu_chr_open_pp(const char *filename)
2031 CharDriverState *chr;
2032 ParallelCharDriver *drv;
2035 fd = open(filename, O_RDWR);
2039 if (ioctl(fd, PPCLAIM) < 0) {
2044 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2050 drv->mode = IEEE1284_MODE_COMPAT;
2052 chr = qemu_mallocz(sizeof(CharDriverState));
2058 chr->chr_write = null_chr_write;
2059 chr->chr_ioctl = pp_ioctl;
2060 chr->chr_close = pp_close;
2063 qemu_chr_reset(chr);
2069 static CharDriverState *qemu_chr_open_pty(void)
2075 #endif /* !defined(_WIN32) */
2080 HANDLE hcom, hrecv, hsend;
2081 OVERLAPPED orecv, osend;
2086 #define NSENDBUF 2048
2087 #define NRECVBUF 2048
2088 #define MAXCONNECT 1
2089 #define NTIMEOUT 5000
2091 static int win_chr_poll(void *opaque);
2092 static int win_chr_pipe_poll(void *opaque);
2094 static void win_chr_close(CharDriverState *chr)
2096 WinCharState *s = chr->opaque;
2099 CloseHandle(s->hsend);
2103 CloseHandle(s->hrecv);
2107 CloseHandle(s->hcom);
2111 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2113 qemu_del_polling_cb(win_chr_poll, chr);
2116 static int win_chr_init(CharDriverState *chr, const char *filename)
2118 WinCharState *s = chr->opaque;
2120 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2125 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2127 fprintf(stderr, "Failed CreateEvent\n");
2130 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2132 fprintf(stderr, "Failed CreateEvent\n");
2136 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2137 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2138 if (s->hcom == INVALID_HANDLE_VALUE) {
2139 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2144 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2145 fprintf(stderr, "Failed SetupComm\n");
2149 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2150 size = sizeof(COMMCONFIG);
2151 GetDefaultCommConfig(filename, &comcfg, &size);
2152 comcfg.dcb.DCBlength = sizeof(DCB);
2153 CommConfigDialog(filename, NULL, &comcfg);
2155 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2156 fprintf(stderr, "Failed SetCommState\n");
2160 if (!SetCommMask(s->hcom, EV_ERR)) {
2161 fprintf(stderr, "Failed SetCommMask\n");
2165 cto.ReadIntervalTimeout = MAXDWORD;
2166 if (!SetCommTimeouts(s->hcom, &cto)) {
2167 fprintf(stderr, "Failed SetCommTimeouts\n");
2171 if (!ClearCommError(s->hcom, &err, &comstat)) {
2172 fprintf(stderr, "Failed ClearCommError\n");
2175 qemu_add_polling_cb(win_chr_poll, chr);
2183 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2185 WinCharState *s = chr->opaque;
2186 DWORD len, ret, size, err;
2189 ZeroMemory(&s->osend, sizeof(s->osend));
2190 s->osend.hEvent = s->hsend;
2193 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2195 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2197 err = GetLastError();
2198 if (err == ERROR_IO_PENDING) {
2199 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2217 static int win_chr_read_poll(CharDriverState *chr)
2219 WinCharState *s = chr->opaque;
2221 s->max_size = qemu_chr_can_read(chr);
2225 static void win_chr_readfile(CharDriverState *chr)
2227 WinCharState *s = chr->opaque;
2232 ZeroMemory(&s->orecv, sizeof(s->orecv));
2233 s->orecv.hEvent = s->hrecv;
2234 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2236 err = GetLastError();
2237 if (err == ERROR_IO_PENDING) {
2238 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2243 qemu_chr_read(chr, buf, size);
2247 static void win_chr_read(CharDriverState *chr)
2249 WinCharState *s = chr->opaque;
2251 if (s->len > s->max_size)
2252 s->len = s->max_size;
2256 win_chr_readfile(chr);
2259 static int win_chr_poll(void *opaque)
2261 CharDriverState *chr = opaque;
2262 WinCharState *s = chr->opaque;
2266 ClearCommError(s->hcom, &comerr, &status);
2267 if (status.cbInQue > 0) {
2268 s->len = status.cbInQue;
2269 win_chr_read_poll(chr);
2276 static CharDriverState *qemu_chr_open_win(const char *filename)
2278 CharDriverState *chr;
2281 chr = qemu_mallocz(sizeof(CharDriverState));
2284 s = qemu_mallocz(sizeof(WinCharState));
2290 chr->chr_write = win_chr_write;
2291 chr->chr_close = win_chr_close;
2293 if (win_chr_init(chr, filename) < 0) {
2298 qemu_chr_reset(chr);
2302 static int win_chr_pipe_poll(void *opaque)
2304 CharDriverState *chr = opaque;
2305 WinCharState *s = chr->opaque;
2308 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2311 win_chr_read_poll(chr);
2318 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2320 WinCharState *s = chr->opaque;
2328 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2330 fprintf(stderr, "Failed CreateEvent\n");
2333 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2335 fprintf(stderr, "Failed CreateEvent\n");
2339 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2340 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2341 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2343 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2344 if (s->hcom == INVALID_HANDLE_VALUE) {
2345 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2350 ZeroMemory(&ov, sizeof(ov));
2351 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2352 ret = ConnectNamedPipe(s->hcom, &ov);
2354 fprintf(stderr, "Failed ConnectNamedPipe\n");
2358 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2360 fprintf(stderr, "Failed GetOverlappedResult\n");
2362 CloseHandle(ov.hEvent);
2369 CloseHandle(ov.hEvent);
2372 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2381 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2383 CharDriverState *chr;
2386 chr = qemu_mallocz(sizeof(CharDriverState));
2389 s = qemu_mallocz(sizeof(WinCharState));
2395 chr->chr_write = win_chr_write;
2396 chr->chr_close = win_chr_close;
2398 if (win_chr_pipe_init(chr, filename) < 0) {
2403 qemu_chr_reset(chr);
2407 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2409 CharDriverState *chr;
2412 chr = qemu_mallocz(sizeof(CharDriverState));
2415 s = qemu_mallocz(sizeof(WinCharState));
2422 chr->chr_write = win_chr_write;
2423 qemu_chr_reset(chr);
2427 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2429 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2432 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2436 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2437 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2438 if (fd_out == INVALID_HANDLE_VALUE)
2441 return qemu_chr_open_win_file(fd_out);
2445 /***********************************************************/
2446 /* UDP Net console */
2450 struct sockaddr_in daddr;
2457 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2459 NetCharDriver *s = chr->opaque;
2461 return sendto(s->fd, buf, len, 0,
2462 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2465 static int udp_chr_read_poll(void *opaque)
2467 CharDriverState *chr = opaque;
2468 NetCharDriver *s = chr->opaque;
2470 s->max_size = qemu_chr_can_read(chr);
2472 /* If there were any stray characters in the queue process them
2475 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2476 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2478 s->max_size = qemu_chr_can_read(chr);
2483 static void udp_chr_read(void *opaque)
2485 CharDriverState *chr = opaque;
2486 NetCharDriver *s = chr->opaque;
2488 if (s->max_size == 0)
2490 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2491 s->bufptr = s->bufcnt;
2496 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2497 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2499 s->max_size = qemu_chr_can_read(chr);
2503 static void udp_chr_update_read_handler(CharDriverState *chr)
2505 NetCharDriver *s = chr->opaque;
2508 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2509 udp_chr_read, NULL, chr);
2513 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2515 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2517 int parse_host_src_port(struct sockaddr_in *haddr,
2518 struct sockaddr_in *saddr,
2521 static CharDriverState *qemu_chr_open_udp(const char *def)
2523 CharDriverState *chr = NULL;
2524 NetCharDriver *s = NULL;
2526 struct sockaddr_in saddr;
2528 chr = qemu_mallocz(sizeof(CharDriverState));
2531 s = qemu_mallocz(sizeof(NetCharDriver));
2535 fd = socket(PF_INET, SOCK_DGRAM, 0);
2537 perror("socket(PF_INET, SOCK_DGRAM)");
2541 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2542 printf("Could not parse: %s\n", def);
2546 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2556 chr->chr_write = udp_chr_write;
2557 chr->chr_update_read_handler = udp_chr_update_read_handler;
2570 /***********************************************************/
2571 /* TCP Net console */
2582 static void tcp_chr_accept(void *opaque);
2584 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2586 TCPCharDriver *s = chr->opaque;
2588 return send_all(s->fd, buf, len);
2590 /* XXX: indicate an error ? */
2595 static int tcp_chr_read_poll(void *opaque)
2597 CharDriverState *chr = opaque;
2598 TCPCharDriver *s = chr->opaque;
2601 s->max_size = qemu_chr_can_read(chr);
2606 #define IAC_BREAK 243
2607 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2609 char *buf, int *size)
2611 /* Handle any telnet client's basic IAC options to satisfy char by
2612 * char mode with no echo. All IAC options will be removed from
2613 * the buf and the do_telnetopt variable will be used to track the
2614 * state of the width of the IAC information.
2616 * IAC commands come in sets of 3 bytes with the exception of the
2617 * "IAC BREAK" command and the double IAC.
2623 for (i = 0; i < *size; i++) {
2624 if (s->do_telnetopt > 1) {
2625 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2626 /* Double IAC means send an IAC */
2630 s->do_telnetopt = 1;
2632 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2633 /* Handle IAC break commands by sending a serial break */
2634 qemu_chr_event(chr, CHR_EVENT_BREAK);
2639 if (s->do_telnetopt >= 4) {
2640 s->do_telnetopt = 1;
2643 if ((unsigned char)buf[i] == IAC) {
2644 s->do_telnetopt = 2;
2655 static void tcp_chr_read(void *opaque)
2657 CharDriverState *chr = opaque;
2658 TCPCharDriver *s = chr->opaque;
2662 if (!s->connected || s->max_size <= 0)
2665 if (len > s->max_size)
2667 size = recv(s->fd, buf, len, 0);
2669 /* connection closed */
2671 if (s->listen_fd >= 0) {
2672 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2674 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2677 } else if (size > 0) {
2678 if (s->do_telnetopt)
2679 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2681 qemu_chr_read(chr, buf, size);
2685 static void tcp_chr_connect(void *opaque)
2687 CharDriverState *chr = opaque;
2688 TCPCharDriver *s = chr->opaque;
2691 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2692 tcp_chr_read, NULL, chr);
2693 qemu_chr_reset(chr);
2696 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2697 static void tcp_chr_telnet_init(int fd)
2700 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2701 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2702 send(fd, (char *)buf, 3, 0);
2703 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2704 send(fd, (char *)buf, 3, 0);
2705 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2706 send(fd, (char *)buf, 3, 0);
2707 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2708 send(fd, (char *)buf, 3, 0);
2711 static void socket_set_nodelay(int fd)
2714 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2717 static void tcp_chr_accept(void *opaque)
2719 CharDriverState *chr = opaque;
2720 TCPCharDriver *s = chr->opaque;
2721 struct sockaddr_in saddr;
2723 struct sockaddr_un uaddr;
2725 struct sockaddr *addr;
2732 len = sizeof(uaddr);
2733 addr = (struct sockaddr *)&uaddr;
2737 len = sizeof(saddr);
2738 addr = (struct sockaddr *)&saddr;
2740 fd = accept(s->listen_fd, addr, &len);
2741 if (fd < 0 && errno != EINTR) {
2743 } else if (fd >= 0) {
2744 if (s->do_telnetopt)
2745 tcp_chr_telnet_init(fd);
2749 socket_set_nonblock(fd);
2751 socket_set_nodelay(fd);
2753 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2754 tcp_chr_connect(chr);
2757 static void tcp_chr_close(CharDriverState *chr)
2759 TCPCharDriver *s = chr->opaque;
2762 if (s->listen_fd >= 0)
2763 closesocket(s->listen_fd);
2767 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2771 CharDriverState *chr = NULL;
2772 TCPCharDriver *s = NULL;
2773 int fd = -1, ret, err, val;
2775 int is_waitconnect = 1;
2778 struct sockaddr_in saddr;
2780 struct sockaddr_un uaddr;
2782 struct sockaddr *addr;
2787 addr = (struct sockaddr *)&uaddr;
2788 addrlen = sizeof(uaddr);
2789 if (parse_unix_path(&uaddr, host_str) < 0)
2794 addr = (struct sockaddr *)&saddr;
2795 addrlen = sizeof(saddr);
2796 if (parse_host_port(&saddr, host_str) < 0)
2801 while((ptr = strchr(ptr,','))) {
2803 if (!strncmp(ptr,"server",6)) {
2805 } else if (!strncmp(ptr,"nowait",6)) {
2807 } else if (!strncmp(ptr,"nodelay",6)) {
2810 printf("Unknown option: %s\n", ptr);
2817 chr = qemu_mallocz(sizeof(CharDriverState));
2820 s = qemu_mallocz(sizeof(TCPCharDriver));
2826 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2829 fd = socket(PF_INET, SOCK_STREAM, 0);
2834 if (!is_waitconnect)
2835 socket_set_nonblock(fd);
2840 s->is_unix = is_unix;
2841 s->do_nodelay = do_nodelay && !is_unix;
2844 chr->chr_write = tcp_chr_write;
2845 chr->chr_close = tcp_chr_close;
2848 /* allow fast reuse */
2852 strncpy(path, uaddr.sun_path, 108);
2859 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2862 ret = bind(fd, addr, addrlen);
2866 ret = listen(fd, 0);
2871 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2873 s->do_telnetopt = 1;
2876 ret = connect(fd, addr, addrlen);
2878 err = socket_error();
2879 if (err == EINTR || err == EWOULDBLOCK) {
2880 } else if (err == EINPROGRESS) {
2883 } else if (err == WSAEALREADY) {
2895 socket_set_nodelay(fd);
2897 tcp_chr_connect(chr);
2899 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2902 if (is_listen && is_waitconnect) {
2903 printf("QEMU waiting for connection on: %s\n", host_str);
2904 tcp_chr_accept(chr);
2905 socket_set_nonblock(s->listen_fd);
2917 CharDriverState *qemu_chr_open(const char *filename)
2921 if (!strcmp(filename, "vc")) {
2922 return text_console_init(&display_state);
2923 } else if (!strcmp(filename, "null")) {
2924 return qemu_chr_open_null();
2926 if (strstart(filename, "tcp:", &p)) {
2927 return qemu_chr_open_tcp(p, 0, 0);
2929 if (strstart(filename, "telnet:", &p)) {
2930 return qemu_chr_open_tcp(p, 1, 0);
2932 if (strstart(filename, "udp:", &p)) {
2933 return qemu_chr_open_udp(p);
2935 if (strstart(filename, "mon:", &p)) {
2936 CharDriverState *drv = qemu_chr_open(p);
2938 drv = qemu_chr_open_mux(drv);
2939 monitor_init(drv, !nographic);
2942 printf("Unable to open driver: %s\n", p);
2946 if (strstart(filename, "unix:", &p)) {
2947 return qemu_chr_open_tcp(p, 0, 1);
2948 } else if (strstart(filename, "file:", &p)) {
2949 return qemu_chr_open_file_out(p);
2950 } else if (strstart(filename, "pipe:", &p)) {
2951 return qemu_chr_open_pipe(p);
2952 } else if (!strcmp(filename, "pty")) {
2953 return qemu_chr_open_pty();
2954 } else if (!strcmp(filename, "stdio")) {
2955 return qemu_chr_open_stdio();
2958 #if defined(__linux__)
2959 if (strstart(filename, "/dev/parport", NULL)) {
2960 return qemu_chr_open_pp(filename);
2962 if (strstart(filename, "/dev/", NULL)) {
2963 return qemu_chr_open_tty(filename);
2967 if (strstart(filename, "COM", NULL)) {
2968 return qemu_chr_open_win(filename);
2970 if (strstart(filename, "pipe:", &p)) {
2971 return qemu_chr_open_win_pipe(p);
2973 if (strstart(filename, "con:", NULL)) {
2974 return qemu_chr_open_win_con(filename);
2976 if (strstart(filename, "file:", &p)) {
2977 return qemu_chr_open_win_file_out(p);
2985 void qemu_chr_close(CharDriverState *chr)
2988 chr->chr_close(chr);
2991 /***********************************************************/
2992 /* network device redirectors */
2994 void hex_dump(FILE *f, const uint8_t *buf, int size)
2998 for(i=0;i<size;i+=16) {
3002 fprintf(f, "%08x ", i);
3005 fprintf(f, " %02x", buf[i+j]);
3010 for(j=0;j<len;j++) {
3012 if (c < ' ' || c > '~')
3014 fprintf(f, "%c", c);
3020 static int parse_macaddr(uint8_t *macaddr, const char *p)
3023 for(i = 0; i < 6; i++) {
3024 macaddr[i] = strtol(p, (char **)&p, 16);
3037 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3042 p1 = strchr(p, sep);
3048 if (len > buf_size - 1)
3050 memcpy(buf, p, len);
3057 int parse_host_src_port(struct sockaddr_in *haddr,
3058 struct sockaddr_in *saddr,
3059 const char *input_str)
3061 char *str = strdup(input_str);
3062 char *host_str = str;
3067 * Chop off any extra arguments at the end of the string which
3068 * would start with a comma, then fill in the src port information
3069 * if it was provided else use the "any address" and "any port".
3071 if ((ptr = strchr(str,',')))
3074 if ((src_str = strchr(input_str,'@'))) {
3079 if (parse_host_port(haddr, host_str) < 0)
3082 if (!src_str || *src_str == '\0')
3085 if (parse_host_port(saddr, src_str) < 0)
3096 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3104 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3106 saddr->sin_family = AF_INET;
3107 if (buf[0] == '\0') {
3108 saddr->sin_addr.s_addr = 0;
3110 if (isdigit(buf[0])) {
3111 if (!inet_aton(buf, &saddr->sin_addr))
3114 if ((he = gethostbyname(buf)) == NULL)
3116 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3119 port = strtol(p, (char **)&r, 0);
3122 saddr->sin_port = htons(port);
3127 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3132 len = MIN(108, strlen(str));
3133 p = strchr(str, ',');
3135 len = MIN(len, p - str);
3137 memset(uaddr, 0, sizeof(*uaddr));
3139 uaddr->sun_family = AF_UNIX;
3140 memcpy(uaddr->sun_path, str, len);
3146 /* find or alloc a new VLAN */
3147 VLANState *qemu_find_vlan(int id)
3149 VLANState **pvlan, *vlan;
3150 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3154 vlan = qemu_mallocz(sizeof(VLANState));
3159 pvlan = &first_vlan;
3160 while (*pvlan != NULL)
3161 pvlan = &(*pvlan)->next;
3166 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3167 IOReadHandler *fd_read,
3168 IOCanRWHandler *fd_can_read,
3171 VLANClientState *vc, **pvc;
3172 vc = qemu_mallocz(sizeof(VLANClientState));
3175 vc->fd_read = fd_read;
3176 vc->fd_can_read = fd_can_read;
3177 vc->opaque = opaque;
3181 pvc = &vlan->first_client;
3182 while (*pvc != NULL)
3183 pvc = &(*pvc)->next;
3188 int qemu_can_send_packet(VLANClientState *vc1)
3190 VLANState *vlan = vc1->vlan;
3191 VLANClientState *vc;
3193 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3195 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3202 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3204 VLANState *vlan = vc1->vlan;
3205 VLANClientState *vc;
3208 printf("vlan %d send:\n", vlan->id);
3209 hex_dump(stdout, buf, size);
3211 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3213 vc->fd_read(vc->opaque, buf, size);
3218 #if defined(CONFIG_SLIRP)
3220 /* slirp network adapter */
3222 static int slirp_inited;
3223 static VLANClientState *slirp_vc;
3225 int slirp_can_output(void)
3227 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3230 void slirp_output(const uint8_t *pkt, int pkt_len)
3233 printf("slirp output:\n");
3234 hex_dump(stdout, pkt, pkt_len);
3238 qemu_send_packet(slirp_vc, pkt, pkt_len);
3241 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3244 printf("slirp input:\n");
3245 hex_dump(stdout, buf, size);
3247 slirp_input(buf, size);
3250 static int net_slirp_init(VLANState *vlan)
3252 if (!slirp_inited) {
3256 slirp_vc = qemu_new_vlan_client(vlan,
3257 slirp_receive, NULL, NULL);
3258 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3262 static void net_slirp_redir(const char *redir_str)
3267 struct in_addr guest_addr;
3268 int host_port, guest_port;
3270 if (!slirp_inited) {
3276 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3278 if (!strcmp(buf, "tcp")) {
3280 } else if (!strcmp(buf, "udp")) {
3286 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3288 host_port = strtol(buf, &r, 0);
3292 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3294 if (buf[0] == '\0') {
3295 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3297 if (!inet_aton(buf, &guest_addr))
3300 guest_port = strtol(p, &r, 0);
3304 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3305 fprintf(stderr, "qemu: could not set up redirection\n");
3310 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3318 static void smb_exit(void)
3322 char filename[1024];
3324 /* erase all the files in the directory */
3325 d = opendir(smb_dir);
3330 if (strcmp(de->d_name, ".") != 0 &&
3331 strcmp(de->d_name, "..") != 0) {
3332 snprintf(filename, sizeof(filename), "%s/%s",
3333 smb_dir, de->d_name);
3341 /* automatic user mode samba server configuration */
3342 void net_slirp_smb(const char *exported_dir)
3344 char smb_conf[1024];
3345 char smb_cmdline[1024];
3348 if (!slirp_inited) {
3353 /* XXX: better tmp dir construction */
3354 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3355 if (mkdir(smb_dir, 0700) < 0) {
3356 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3359 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3361 f = fopen(smb_conf, "w");
3363 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3370 "socket address=127.0.0.1\n"
3371 "pid directory=%s\n"
3372 "lock directory=%s\n"
3373 "log file=%s/log.smbd\n"
3374 "smb passwd file=%s/smbpasswd\n"
3375 "security = share\n"
3390 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3391 SMBD_COMMAND, smb_conf);
3393 slirp_add_exec(0, smb_cmdline, 4, 139);
3396 #endif /* !defined(_WIN32) */
3398 #endif /* CONFIG_SLIRP */
3400 #if !defined(_WIN32)
3402 typedef struct TAPState {
3403 VLANClientState *vc;
3407 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3409 TAPState *s = opaque;
3412 ret = write(s->fd, buf, size);
3413 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3420 static void tap_send(void *opaque)
3422 TAPState *s = opaque;
3429 sbuf.maxlen = sizeof(buf);
3431 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3433 size = read(s->fd, buf, sizeof(buf));
3436 qemu_send_packet(s->vc, buf, size);
3442 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3446 s = qemu_mallocz(sizeof(TAPState));
3450 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3451 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3452 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3456 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3457 static int tap_open(char *ifname, int ifname_size)
3463 fd = open("/dev/tap", O_RDWR);
3465 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3470 dev = devname(s.st_rdev, S_IFCHR);
3471 pstrcpy(ifname, ifname_size, dev);
3473 fcntl(fd, F_SETFL, O_NONBLOCK);
3476 #elif defined(__sun__)
3477 #define TUNNEWPPA (('T'<<16) | 0x0001)
3479 * Allocate TAP device, returns opened fd.
3480 * Stores dev name in the first arg(must be large enough).
3482 int tap_alloc(char *dev)
3484 int tap_fd, if_fd, ppa = -1;
3485 static int ip_fd = 0;
3488 static int arp_fd = 0;
3489 int ip_muxid, arp_muxid;
3490 struct strioctl strioc_if, strioc_ppa;
3491 int link_type = I_PLINK;;
3493 char actual_name[32] = "";
3495 memset(&ifr, 0x0, sizeof(ifr));
3499 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3503 /* Check if IP device was opened */
3507 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3508 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3512 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3513 syslog(LOG_ERR, "Can't open /dev/tap");
3517 /* Assign a new PPA and get its unit number. */
3518 strioc_ppa.ic_cmd = TUNNEWPPA;
3519 strioc_ppa.ic_timout = 0;
3520 strioc_ppa.ic_len = sizeof(ppa);
3521 strioc_ppa.ic_dp = (char *)&ppa;
3522 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3523 syslog (LOG_ERR, "Can't assign new interface");
3525 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3526 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3529 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3530 syslog(LOG_ERR, "Can't push IP module");
3534 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3535 syslog(LOG_ERR, "Can't get flags\n");
3537 snprintf (actual_name, 32, "tap%d", ppa);
3538 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3541 /* Assign ppa according to the unit number returned by tun device */
3543 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3544 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3545 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3546 syslog (LOG_ERR, "Can't get flags\n");
3547 /* Push arp module to if_fd */
3548 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3549 syslog (LOG_ERR, "Can't push ARP module (2)");
3551 /* Push arp module to ip_fd */
3552 if (ioctl (ip_fd, I_POP, NULL) < 0)
3553 syslog (LOG_ERR, "I_POP failed\n");
3554 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3555 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3557 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3558 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3560 /* Set ifname to arp */
3561 strioc_if.ic_cmd = SIOCSLIFNAME;
3562 strioc_if.ic_timout = 0;
3563 strioc_if.ic_len = sizeof(ifr);
3564 strioc_if.ic_dp = (char *)𝔦
3565 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3566 syslog (LOG_ERR, "Can't set ifname to arp\n");
3569 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3570 syslog(LOG_ERR, "Can't link TAP device to IP");
3574 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3575 syslog (LOG_ERR, "Can't link TAP device to ARP");
3579 memset(&ifr, 0x0, sizeof(ifr));
3580 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3581 ifr.lifr_ip_muxid = ip_muxid;
3582 ifr.lifr_arp_muxid = arp_muxid;
3584 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3586 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3587 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3588 syslog (LOG_ERR, "Can't set multiplexor id");
3591 sprintf(dev, "tap%d", ppa);
3595 static int tap_open(char *ifname, int ifname_size)
3599 if( (fd = tap_alloc(dev)) < 0 ){
3600 fprintf(stderr, "Cannot allocate TAP device\n");
3603 pstrcpy(ifname, ifname_size, dev);
3604 fcntl(fd, F_SETFL, O_NONBLOCK);
3608 static int tap_open(char *ifname, int ifname_size)
3613 fd = open("/dev/net/tun", O_RDWR);
3615 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3618 memset(&ifr, 0, sizeof(ifr));
3619 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3620 if (ifname[0] != '\0')
3621 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3623 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3624 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3626 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3630 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3631 fcntl(fd, F_SETFL, O_NONBLOCK);
3636 static int net_tap_init(VLANState *vlan, const char *ifname1,
3637 const char *setup_script)
3640 int pid, status, fd;
3645 if (ifname1 != NULL)
3646 pstrcpy(ifname, sizeof(ifname), ifname1);
3649 fd = tap_open(ifname, sizeof(ifname));
3653 if (!setup_script || !strcmp(setup_script, "no"))
3655 if (setup_script[0] != '\0') {
3656 /* try to launch network init script */
3660 int open_max = sysconf (_SC_OPEN_MAX), i;
3661 for (i = 0; i < open_max; i++)
3662 if (i != STDIN_FILENO &&
3663 i != STDOUT_FILENO &&
3664 i != STDERR_FILENO &&
3669 *parg++ = (char *)setup_script;
3672 execv(setup_script, args);
3675 while (waitpid(pid, &status, 0) != pid);
3676 if (!WIFEXITED(status) ||
3677 WEXITSTATUS(status) != 0) {
3678 fprintf(stderr, "%s: could not launch network script\n",
3684 s = net_tap_fd_init(vlan, fd);
3687 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3688 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3692 #endif /* !_WIN32 */
3694 /* network connection */
3695 typedef struct NetSocketState {
3696 VLANClientState *vc;
3698 int state; /* 0 = getting length, 1 = getting data */
3702 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3705 typedef struct NetSocketListenState {
3708 } NetSocketListenState;
3710 /* XXX: we consider we can send the whole packet without blocking */
3711 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3713 NetSocketState *s = opaque;
3717 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3718 send_all(s->fd, buf, size);
3721 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3723 NetSocketState *s = opaque;
3724 sendto(s->fd, buf, size, 0,
3725 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3728 static void net_socket_send(void *opaque)
3730 NetSocketState *s = opaque;
3735 size = recv(s->fd, buf1, sizeof(buf1), 0);
3737 err = socket_error();
3738 if (err != EWOULDBLOCK)
3740 } else if (size == 0) {
3741 /* end of connection */
3743 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3749 /* reassemble a packet from the network */
3755 memcpy(s->buf + s->index, buf, l);
3759 if (s->index == 4) {
3761 s->packet_len = ntohl(*(uint32_t *)s->buf);
3767 l = s->packet_len - s->index;
3770 memcpy(s->buf + s->index, buf, l);
3774 if (s->index >= s->packet_len) {
3775 qemu_send_packet(s->vc, s->buf, s->packet_len);
3784 static void net_socket_send_dgram(void *opaque)
3786 NetSocketState *s = opaque;
3789 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3793 /* end of connection */
3794 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3797 qemu_send_packet(s->vc, s->buf, size);
3800 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3805 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3806 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3807 inet_ntoa(mcastaddr->sin_addr),
3808 (int)ntohl(mcastaddr->sin_addr.s_addr));
3812 fd = socket(PF_INET, SOCK_DGRAM, 0);
3814 perror("socket(PF_INET, SOCK_DGRAM)");
3819 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3820 (const char *)&val, sizeof(val));
3822 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3826 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3832 /* Add host to multicast group */
3833 imr.imr_multiaddr = mcastaddr->sin_addr;
3834 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3836 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3837 (const char *)&imr, sizeof(struct ip_mreq));
3839 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3843 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3845 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3846 (const char *)&val, sizeof(val));
3848 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3852 socket_set_nonblock(fd);
3860 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3863 struct sockaddr_in saddr;
3865 socklen_t saddr_len;
3868 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3869 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3870 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3874 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3876 if (saddr.sin_addr.s_addr==0) {
3877 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3881 /* clone dgram socket */
3882 newfd = net_socket_mcast_create(&saddr);
3884 /* error already reported by net_socket_mcast_create() */
3888 /* clone newfd to fd, close newfd */
3893 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3894 fd, strerror(errno));
3899 s = qemu_mallocz(sizeof(NetSocketState));
3904 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3905 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3907 /* mcast: save bound address as dst */
3908 if (is_connected) s->dgram_dst=saddr;
3910 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3911 "socket: fd=%d (%s mcast=%s:%d)",
3912 fd, is_connected? "cloned" : "",
3913 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3917 static void net_socket_connect(void *opaque)
3919 NetSocketState *s = opaque;
3920 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3923 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3927 s = qemu_mallocz(sizeof(NetSocketState));
3931 s->vc = qemu_new_vlan_client(vlan,
3932 net_socket_receive, NULL, s);
3933 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3934 "socket: fd=%d", fd);
3936 net_socket_connect(s);
3938 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3943 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3946 int so_type=-1, optlen=sizeof(so_type);
3948 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3949 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3954 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3956 return net_socket_fd_init_stream(vlan, fd, is_connected);
3958 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3959 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3960 return net_socket_fd_init_stream(vlan, fd, is_connected);
3965 static void net_socket_accept(void *opaque)
3967 NetSocketListenState *s = opaque;
3969 struct sockaddr_in saddr;
3974 len = sizeof(saddr);
3975 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3976 if (fd < 0 && errno != EINTR) {
3978 } else if (fd >= 0) {
3982 s1 = net_socket_fd_init(s->vlan, fd, 1);
3986 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3987 "socket: connection from %s:%d",
3988 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3992 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3994 NetSocketListenState *s;
3996 struct sockaddr_in saddr;
3998 if (parse_host_port(&saddr, host_str) < 0)
4001 s = qemu_mallocz(sizeof(NetSocketListenState));
4005 fd = socket(PF_INET, SOCK_STREAM, 0);
4010 socket_set_nonblock(fd);
4012 /* allow fast reuse */
4014 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4016 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4021 ret = listen(fd, 0);
4028 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4032 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4035 int fd, connected, ret, err;
4036 struct sockaddr_in saddr;
4038 if (parse_host_port(&saddr, host_str) < 0)
4041 fd = socket(PF_INET, SOCK_STREAM, 0);
4046 socket_set_nonblock(fd);
4050 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4052 err = socket_error();
4053 if (err == EINTR || err == EWOULDBLOCK) {
4054 } else if (err == EINPROGRESS) {
4057 } else if (err == WSAEALREADY) {
4070 s = net_socket_fd_init(vlan, fd, connected);
4073 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4074 "socket: connect to %s:%d",
4075 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4079 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4083 struct sockaddr_in saddr;
4085 if (parse_host_port(&saddr, host_str) < 0)
4089 fd = net_socket_mcast_create(&saddr);
4093 s = net_socket_fd_init(vlan, fd, 0);
4097 s->dgram_dst = saddr;
4099 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4100 "socket: mcast=%s:%d",
4101 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4106 static int get_param_value(char *buf, int buf_size,
4107 const char *tag, const char *str)
4116 while (*p != '\0' && *p != '=') {
4117 if ((q - option) < sizeof(option) - 1)
4125 if (!strcmp(tag, option)) {
4127 while (*p != '\0' && *p != ',') {
4128 if ((q - buf) < buf_size - 1)
4135 while (*p != '\0' && *p != ',') {
4146 static int net_client_init(const char *str)
4157 while (*p != '\0' && *p != ',') {
4158 if ((q - device) < sizeof(device) - 1)
4166 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4167 vlan_id = strtol(buf, NULL, 0);
4169 vlan = qemu_find_vlan(vlan_id);
4171 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4174 if (!strcmp(device, "nic")) {
4178 if (nb_nics >= MAX_NICS) {
4179 fprintf(stderr, "Too Many NICs\n");
4182 nd = &nd_table[nb_nics];
4183 macaddr = nd->macaddr;
4189 macaddr[5] = 0x56 + nb_nics;
4191 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4192 if (parse_macaddr(macaddr, buf) < 0) {
4193 fprintf(stderr, "invalid syntax for ethernet address\n");
4197 if (get_param_value(buf, sizeof(buf), "model", p)) {
4198 nd->model = strdup(buf);
4202 vlan->nb_guest_devs++;
4205 if (!strcmp(device, "none")) {
4206 /* does nothing. It is needed to signal that no network cards
4211 if (!strcmp(device, "user")) {
4212 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4213 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4215 vlan->nb_host_devs++;
4216 ret = net_slirp_init(vlan);
4220 if (!strcmp(device, "tap")) {
4222 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4223 fprintf(stderr, "tap: no interface name\n");
4226 vlan->nb_host_devs++;
4227 ret = tap_win32_init(vlan, ifname);
4230 if (!strcmp(device, "tap")) {
4232 char setup_script[1024];
4234 vlan->nb_host_devs++;
4235 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4236 fd = strtol(buf, NULL, 0);
4238 if (net_tap_fd_init(vlan, fd))
4241 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4244 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4245 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4247 ret = net_tap_init(vlan, ifname, setup_script);
4251 if (!strcmp(device, "socket")) {
4252 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4254 fd = strtol(buf, NULL, 0);
4256 if (net_socket_fd_init(vlan, fd, 1))
4258 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4259 ret = net_socket_listen_init(vlan, buf);
4260 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4261 ret = net_socket_connect_init(vlan, buf);
4262 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4263 ret = net_socket_mcast_init(vlan, buf);
4265 fprintf(stderr, "Unknown socket options: %s\n", p);
4268 vlan->nb_host_devs++;
4271 fprintf(stderr, "Unknown network device: %s\n", device);
4275 fprintf(stderr, "Could not initialize device '%s'\n", device);
4281 void do_info_network(void)
4284 VLANClientState *vc;
4286 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4287 term_printf("VLAN %d devices:\n", vlan->id);
4288 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4289 term_printf(" %s\n", vc->info_str);
4293 /***********************************************************/
4296 static USBPort *used_usb_ports;
4297 static USBPort *free_usb_ports;
4299 /* ??? Maybe change this to register a hub to keep track of the topology. */
4300 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4301 usb_attachfn attach)
4303 port->opaque = opaque;
4304 port->index = index;
4305 port->attach = attach;
4306 port->next = free_usb_ports;
4307 free_usb_ports = port;
4310 static int usb_device_add(const char *devname)
4316 if (!free_usb_ports)
4319 if (strstart(devname, "host:", &p)) {
4320 dev = usb_host_device_open(p);
4321 } else if (!strcmp(devname, "mouse")) {
4322 dev = usb_mouse_init();
4323 } else if (!strcmp(devname, "tablet")) {
4324 dev = usb_tablet_init();
4325 } else if (!strcmp(devname, "keyboard")) {
4326 dev = usb_keyboard_init();
4327 } else if (strstart(devname, "disk:", &p)) {
4328 dev = usb_msd_init(p);
4329 } else if (!strcmp(devname, "wacom-tablet")) {
4330 dev = usb_wacom_init();
4337 /* Find a USB port to add the device to. */
4338 port = free_usb_ports;
4342 /* Create a new hub and chain it on. */
4343 free_usb_ports = NULL;
4344 port->next = used_usb_ports;
4345 used_usb_ports = port;
4347 hub = usb_hub_init(VM_USB_HUB_SIZE);
4348 usb_attach(port, hub);
4349 port = free_usb_ports;
4352 free_usb_ports = port->next;
4353 port->next = used_usb_ports;
4354 used_usb_ports = port;
4355 usb_attach(port, dev);
4359 static int usb_device_del(const char *devname)
4367 if (!used_usb_ports)
4370 p = strchr(devname, '.');
4373 bus_num = strtoul(devname, NULL, 0);
4374 addr = strtoul(p + 1, NULL, 0);
4378 lastp = &used_usb_ports;
4379 port = used_usb_ports;
4380 while (port && port->dev->addr != addr) {
4381 lastp = &port->next;
4389 *lastp = port->next;
4390 usb_attach(port, NULL);
4391 dev->handle_destroy(dev);
4392 port->next = free_usb_ports;
4393 free_usb_ports = port;
4397 void do_usb_add(const char *devname)
4400 ret = usb_device_add(devname);
4402 term_printf("Could not add USB device '%s'\n", devname);
4405 void do_usb_del(const char *devname)
4408 ret = usb_device_del(devname);
4410 term_printf("Could not remove USB device '%s'\n", devname);
4417 const char *speed_str;
4420 term_printf("USB support not enabled\n");
4424 for (port = used_usb_ports; port; port = port->next) {
4428 switch(dev->speed) {
4432 case USB_SPEED_FULL:
4435 case USB_SPEED_HIGH:
4442 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4443 0, dev->addr, speed_str, dev->devname);
4447 /***********************************************************/
4448 /* PCMCIA/Cardbus */
4450 static struct pcmcia_socket_entry_s {
4451 struct pcmcia_socket_s *socket;
4452 struct pcmcia_socket_entry_s *next;
4453 } *pcmcia_sockets = 0;
4455 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4457 struct pcmcia_socket_entry_s *entry;
4459 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4460 entry->socket = socket;
4461 entry->next = pcmcia_sockets;
4462 pcmcia_sockets = entry;
4465 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4467 struct pcmcia_socket_entry_s *entry, **ptr;
4469 ptr = &pcmcia_sockets;
4470 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4471 if (entry->socket == socket) {
4477 void pcmcia_info(void)
4479 struct pcmcia_socket_entry_s *iter;
4480 if (!pcmcia_sockets)
4481 term_printf("No PCMCIA sockets\n");
4483 for (iter = pcmcia_sockets; iter; iter = iter->next)
4484 term_printf("%s: %s\n", iter->socket->slot_string,
4485 iter->socket->attached ? iter->socket->card_string :
4489 /***********************************************************/
4492 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4496 static void dumb_resize(DisplayState *ds, int w, int h)
4500 static void dumb_refresh(DisplayState *ds)
4502 #if defined(CONFIG_SDL)
4507 static void dumb_display_init(DisplayState *ds)
4512 ds->dpy_update = dumb_update;
4513 ds->dpy_resize = dumb_resize;
4514 ds->dpy_refresh = dumb_refresh;
4517 /***********************************************************/
4520 #define MAX_IO_HANDLERS 64
4522 typedef struct IOHandlerRecord {
4524 IOCanRWHandler *fd_read_poll;
4526 IOHandler *fd_write;
4529 /* temporary data */
4531 struct IOHandlerRecord *next;
4534 static IOHandlerRecord *first_io_handler;
4536 /* XXX: fd_read_poll should be suppressed, but an API change is
4537 necessary in the character devices to suppress fd_can_read(). */
4538 int qemu_set_fd_handler2(int fd,
4539 IOCanRWHandler *fd_read_poll,
4541 IOHandler *fd_write,
4544 IOHandlerRecord **pioh, *ioh;
4546 if (!fd_read && !fd_write) {
4547 pioh = &first_io_handler;
4552 if (ioh->fd == fd) {
4559 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4563 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4566 ioh->next = first_io_handler;
4567 first_io_handler = ioh;
4570 ioh->fd_read_poll = fd_read_poll;
4571 ioh->fd_read = fd_read;
4572 ioh->fd_write = fd_write;
4573 ioh->opaque = opaque;
4579 int qemu_set_fd_handler(int fd,
4581 IOHandler *fd_write,
4584 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4587 /***********************************************************/
4588 /* Polling handling */
4590 typedef struct PollingEntry {
4593 struct PollingEntry *next;
4596 static PollingEntry *first_polling_entry;
4598 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4600 PollingEntry **ppe, *pe;
4601 pe = qemu_mallocz(sizeof(PollingEntry));
4605 pe->opaque = opaque;
4606 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4611 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4613 PollingEntry **ppe, *pe;
4614 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4616 if (pe->func == func && pe->opaque == opaque) {
4625 /***********************************************************/
4626 /* Wait objects support */
4627 typedef struct WaitObjects {
4629 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4630 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4631 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4634 static WaitObjects wait_objects = {0};
4636 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4638 WaitObjects *w = &wait_objects;
4640 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4642 w->events[w->num] = handle;
4643 w->func[w->num] = func;
4644 w->opaque[w->num] = opaque;
4649 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4652 WaitObjects *w = &wait_objects;
4655 for (i = 0; i < w->num; i++) {
4656 if (w->events[i] == handle)
4659 w->events[i] = w->events[i + 1];
4660 w->func[i] = w->func[i + 1];
4661 w->opaque[i] = w->opaque[i + 1];
4669 /***********************************************************/
4670 /* savevm/loadvm support */
4672 #define IO_BUF_SIZE 32768
4676 BlockDriverState *bs;
4679 int64_t base_offset;
4680 int64_t buf_offset; /* start of buffer when writing, end of buffer
4683 int buf_size; /* 0 when writing */
4684 uint8_t buf[IO_BUF_SIZE];
4687 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4691 f = qemu_mallocz(sizeof(QEMUFile));
4694 if (!strcmp(mode, "wb")) {
4696 } else if (!strcmp(mode, "rb")) {
4701 f->outfile = fopen(filename, mode);
4713 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4717 f = qemu_mallocz(sizeof(QEMUFile));
4722 f->is_writable = is_writable;
4723 f->base_offset = offset;
4727 void qemu_fflush(QEMUFile *f)
4729 if (!f->is_writable)
4731 if (f->buf_index > 0) {
4733 fseek(f->outfile, f->buf_offset, SEEK_SET);
4734 fwrite(f->buf, 1, f->buf_index, f->outfile);
4736 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4737 f->buf, f->buf_index);
4739 f->buf_offset += f->buf_index;
4744 static void qemu_fill_buffer(QEMUFile *f)
4751 fseek(f->outfile, f->buf_offset, SEEK_SET);
4752 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4756 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4757 f->buf, IO_BUF_SIZE);
4763 f->buf_offset += len;
4766 void qemu_fclose(QEMUFile *f)
4776 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4780 l = IO_BUF_SIZE - f->buf_index;
4783 memcpy(f->buf + f->buf_index, buf, l);
4787 if (f->buf_index >= IO_BUF_SIZE)
4792 void qemu_put_byte(QEMUFile *f, int v)
4794 f->buf[f->buf_index++] = v;
4795 if (f->buf_index >= IO_BUF_SIZE)
4799 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4805 l = f->buf_size - f->buf_index;
4807 qemu_fill_buffer(f);
4808 l = f->buf_size - f->buf_index;
4814 memcpy(buf, f->buf + f->buf_index, l);
4819 return size1 - size;
4822 int qemu_get_byte(QEMUFile *f)
4824 if (f->buf_index >= f->buf_size) {
4825 qemu_fill_buffer(f);
4826 if (f->buf_index >= f->buf_size)
4829 return f->buf[f->buf_index++];
4832 int64_t qemu_ftell(QEMUFile *f)
4834 return f->buf_offset - f->buf_size + f->buf_index;
4837 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4839 if (whence == SEEK_SET) {
4841 } else if (whence == SEEK_CUR) {
4842 pos += qemu_ftell(f);
4844 /* SEEK_END not supported */
4847 if (f->is_writable) {
4849 f->buf_offset = pos;
4851 f->buf_offset = pos;
4858 void qemu_put_be16(QEMUFile *f, unsigned int v)
4860 qemu_put_byte(f, v >> 8);
4861 qemu_put_byte(f, v);
4864 void qemu_put_be32(QEMUFile *f, unsigned int v)
4866 qemu_put_byte(f, v >> 24);
4867 qemu_put_byte(f, v >> 16);
4868 qemu_put_byte(f, v >> 8);
4869 qemu_put_byte(f, v);
4872 void qemu_put_be64(QEMUFile *f, uint64_t v)
4874 qemu_put_be32(f, v >> 32);
4875 qemu_put_be32(f, v);
4878 unsigned int qemu_get_be16(QEMUFile *f)
4881 v = qemu_get_byte(f) << 8;
4882 v |= qemu_get_byte(f);
4886 unsigned int qemu_get_be32(QEMUFile *f)
4889 v = qemu_get_byte(f) << 24;
4890 v |= qemu_get_byte(f) << 16;
4891 v |= qemu_get_byte(f) << 8;
4892 v |= qemu_get_byte(f);
4896 uint64_t qemu_get_be64(QEMUFile *f)
4899 v = (uint64_t)qemu_get_be32(f) << 32;
4900 v |= qemu_get_be32(f);
4904 typedef struct SaveStateEntry {
4908 SaveStateHandler *save_state;
4909 LoadStateHandler *load_state;
4911 struct SaveStateEntry *next;
4914 static SaveStateEntry *first_se;
4916 int register_savevm(const char *idstr,
4919 SaveStateHandler *save_state,
4920 LoadStateHandler *load_state,
4923 SaveStateEntry *se, **pse;
4925 se = qemu_malloc(sizeof(SaveStateEntry));
4928 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4929 se->instance_id = instance_id;
4930 se->version_id = version_id;
4931 se->save_state = save_state;
4932 se->load_state = load_state;
4933 se->opaque = opaque;
4936 /* add at the end of list */
4938 while (*pse != NULL)
4939 pse = &(*pse)->next;
4944 #define QEMU_VM_FILE_MAGIC 0x5145564d
4945 #define QEMU_VM_FILE_VERSION 0x00000002
4947 int qemu_savevm_state(QEMUFile *f)
4951 int64_t cur_pos, len_pos, total_len_pos;
4953 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4954 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4955 total_len_pos = qemu_ftell(f);
4956 qemu_put_be64(f, 0); /* total size */
4958 for(se = first_se; se != NULL; se = se->next) {
4960 len = strlen(se->idstr);
4961 qemu_put_byte(f, len);
4962 qemu_put_buffer(f, se->idstr, len);
4964 qemu_put_be32(f, se->instance_id);
4965 qemu_put_be32(f, se->version_id);
4967 /* record size: filled later */
4968 len_pos = qemu_ftell(f);
4969 qemu_put_be32(f, 0);
4971 se->save_state(f, se->opaque);
4973 /* fill record size */
4974 cur_pos = qemu_ftell(f);
4975 len = cur_pos - len_pos - 4;
4976 qemu_fseek(f, len_pos, SEEK_SET);
4977 qemu_put_be32(f, len);
4978 qemu_fseek(f, cur_pos, SEEK_SET);
4980 cur_pos = qemu_ftell(f);
4981 qemu_fseek(f, total_len_pos, SEEK_SET);
4982 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4983 qemu_fseek(f, cur_pos, SEEK_SET);
4989 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4993 for(se = first_se; se != NULL; se = se->next) {
4994 if (!strcmp(se->idstr, idstr) &&
4995 instance_id == se->instance_id)
5001 int qemu_loadvm_state(QEMUFile *f)
5004 int len, ret, instance_id, record_len, version_id;
5005 int64_t total_len, end_pos, cur_pos;
5009 v = qemu_get_be32(f);
5010 if (v != QEMU_VM_FILE_MAGIC)
5012 v = qemu_get_be32(f);
5013 if (v != QEMU_VM_FILE_VERSION) {
5018 total_len = qemu_get_be64(f);
5019 end_pos = total_len + qemu_ftell(f);
5021 if (qemu_ftell(f) >= end_pos)
5023 len = qemu_get_byte(f);
5024 qemu_get_buffer(f, idstr, len);
5026 instance_id = qemu_get_be32(f);
5027 version_id = qemu_get_be32(f);
5028 record_len = qemu_get_be32(f);
5030 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5031 idstr, instance_id, version_id, record_len);
5033 cur_pos = qemu_ftell(f);
5034 se = find_se(idstr, instance_id);
5036 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5037 instance_id, idstr);
5039 ret = se->load_state(f, se->opaque, version_id);
5041 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5042 instance_id, idstr);
5045 /* always seek to exact end of record */
5046 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5053 /* device can contain snapshots */
5054 static int bdrv_can_snapshot(BlockDriverState *bs)
5057 !bdrv_is_removable(bs) &&
5058 !bdrv_is_read_only(bs));
5061 /* device must be snapshots in order to have a reliable snapshot */
5062 static int bdrv_has_snapshot(BlockDriverState *bs)
5065 !bdrv_is_removable(bs) &&
5066 !bdrv_is_read_only(bs));
5069 static BlockDriverState *get_bs_snapshots(void)
5071 BlockDriverState *bs;
5075 return bs_snapshots;
5076 for(i = 0; i <= MAX_DISKS; i++) {
5078 if (bdrv_can_snapshot(bs))
5087 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5090 QEMUSnapshotInfo *sn_tab, *sn;
5094 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5097 for(i = 0; i < nb_sns; i++) {
5099 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5109 void do_savevm(const char *name)
5111 BlockDriverState *bs, *bs1;
5112 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5113 int must_delete, ret, i;
5114 BlockDriverInfo bdi1, *bdi = &bdi1;
5116 int saved_vm_running;
5123 bs = get_bs_snapshots();
5125 term_printf("No block device can accept snapshots\n");
5129 /* ??? Should this occur after vm_stop? */
5132 saved_vm_running = vm_running;
5137 ret = bdrv_snapshot_find(bs, old_sn, name);
5142 memset(sn, 0, sizeof(*sn));
5144 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5145 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5148 pstrcpy(sn->name, sizeof(sn->name), name);
5151 /* fill auxiliary fields */
5154 sn->date_sec = tb.time;
5155 sn->date_nsec = tb.millitm * 1000000;
5157 gettimeofday(&tv, NULL);
5158 sn->date_sec = tv.tv_sec;
5159 sn->date_nsec = tv.tv_usec * 1000;
5161 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5163 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5164 term_printf("Device %s does not support VM state snapshots\n",
5165 bdrv_get_device_name(bs));
5169 /* save the VM state */
5170 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5172 term_printf("Could not open VM state file\n");
5175 ret = qemu_savevm_state(f);
5176 sn->vm_state_size = qemu_ftell(f);
5179 term_printf("Error %d while writing VM\n", ret);
5183 /* create the snapshots */
5185 for(i = 0; i < MAX_DISKS; i++) {
5187 if (bdrv_has_snapshot(bs1)) {
5189 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5191 term_printf("Error while deleting snapshot on '%s'\n",
5192 bdrv_get_device_name(bs1));
5195 ret = bdrv_snapshot_create(bs1, sn);
5197 term_printf("Error while creating snapshot on '%s'\n",
5198 bdrv_get_device_name(bs1));
5204 if (saved_vm_running)
5208 void do_loadvm(const char *name)
5210 BlockDriverState *bs, *bs1;
5211 BlockDriverInfo bdi1, *bdi = &bdi1;
5214 int saved_vm_running;
5216 bs = get_bs_snapshots();
5218 term_printf("No block device supports snapshots\n");
5222 /* Flush all IO requests so they don't interfere with the new state. */
5225 saved_vm_running = vm_running;
5228 for(i = 0; i <= MAX_DISKS; i++) {
5230 if (bdrv_has_snapshot(bs1)) {
5231 ret = bdrv_snapshot_goto(bs1, name);
5234 term_printf("Warning: ");
5237 term_printf("Snapshots not supported on device '%s'\n",
5238 bdrv_get_device_name(bs1));
5241 term_printf("Could not find snapshot '%s' on device '%s'\n",
5242 name, bdrv_get_device_name(bs1));
5245 term_printf("Error %d while activating snapshot on '%s'\n",
5246 ret, bdrv_get_device_name(bs1));
5249 /* fatal on snapshot block device */
5256 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5257 term_printf("Device %s does not support VM state snapshots\n",
5258 bdrv_get_device_name(bs));
5262 /* restore the VM state */
5263 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5265 term_printf("Could not open VM state file\n");
5268 ret = qemu_loadvm_state(f);
5271 term_printf("Error %d while loading VM state\n", ret);
5274 if (saved_vm_running)
5278 void do_delvm(const char *name)
5280 BlockDriverState *bs, *bs1;
5283 bs = get_bs_snapshots();
5285 term_printf("No block device supports snapshots\n");
5289 for(i = 0; i <= MAX_DISKS; i++) {
5291 if (bdrv_has_snapshot(bs1)) {
5292 ret = bdrv_snapshot_delete(bs1, name);
5294 if (ret == -ENOTSUP)
5295 term_printf("Snapshots not supported on device '%s'\n",
5296 bdrv_get_device_name(bs1));
5298 term_printf("Error %d while deleting snapshot on '%s'\n",
5299 ret, bdrv_get_device_name(bs1));
5305 void do_info_snapshots(void)
5307 BlockDriverState *bs, *bs1;
5308 QEMUSnapshotInfo *sn_tab, *sn;
5312 bs = get_bs_snapshots();
5314 term_printf("No available block device supports snapshots\n");
5317 term_printf("Snapshot devices:");
5318 for(i = 0; i <= MAX_DISKS; i++) {
5320 if (bdrv_has_snapshot(bs1)) {
5322 term_printf(" %s", bdrv_get_device_name(bs1));
5327 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5329 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5332 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5333 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5334 for(i = 0; i < nb_sns; i++) {
5336 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5341 /***********************************************************/
5342 /* cpu save/restore */
5344 #if defined(TARGET_I386)
5346 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5348 qemu_put_be32(f, dt->selector);
5349 qemu_put_betl(f, dt->base);
5350 qemu_put_be32(f, dt->limit);
5351 qemu_put_be32(f, dt->flags);
5354 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5356 dt->selector = qemu_get_be32(f);
5357 dt->base = qemu_get_betl(f);
5358 dt->limit = qemu_get_be32(f);
5359 dt->flags = qemu_get_be32(f);
5362 void cpu_save(QEMUFile *f, void *opaque)
5364 CPUState *env = opaque;
5365 uint16_t fptag, fpus, fpuc, fpregs_format;
5369 for(i = 0; i < CPU_NB_REGS; i++)
5370 qemu_put_betls(f, &env->regs[i]);
5371 qemu_put_betls(f, &env->eip);
5372 qemu_put_betls(f, &env->eflags);
5373 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5374 qemu_put_be32s(f, &hflags);
5378 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5380 for(i = 0; i < 8; i++) {
5381 fptag |= ((!env->fptags[i]) << i);
5384 qemu_put_be16s(f, &fpuc);
5385 qemu_put_be16s(f, &fpus);
5386 qemu_put_be16s(f, &fptag);
5388 #ifdef USE_X86LDOUBLE
5393 qemu_put_be16s(f, &fpregs_format);
5395 for(i = 0; i < 8; i++) {
5396 #ifdef USE_X86LDOUBLE
5400 /* we save the real CPU data (in case of MMX usage only 'mant'
5401 contains the MMX register */
5402 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5403 qemu_put_be64(f, mant);
5404 qemu_put_be16(f, exp);
5407 /* if we use doubles for float emulation, we save the doubles to
5408 avoid losing information in case of MMX usage. It can give
5409 problems if the image is restored on a CPU where long
5410 doubles are used instead. */
5411 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5415 for(i = 0; i < 6; i++)
5416 cpu_put_seg(f, &env->segs[i]);
5417 cpu_put_seg(f, &env->ldt);
5418 cpu_put_seg(f, &env->tr);
5419 cpu_put_seg(f, &env->gdt);
5420 cpu_put_seg(f, &env->idt);
5422 qemu_put_be32s(f, &env->sysenter_cs);
5423 qemu_put_be32s(f, &env->sysenter_esp);
5424 qemu_put_be32s(f, &env->sysenter_eip);
5426 qemu_put_betls(f, &env->cr[0]);
5427 qemu_put_betls(f, &env->cr[2]);
5428 qemu_put_betls(f, &env->cr[3]);
5429 qemu_put_betls(f, &env->cr[4]);
5431 for(i = 0; i < 8; i++)
5432 qemu_put_betls(f, &env->dr[i]);
5435 qemu_put_be32s(f, &env->a20_mask);
5438 qemu_put_be32s(f, &env->mxcsr);
5439 for(i = 0; i < CPU_NB_REGS; i++) {
5440 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5441 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5444 #ifdef TARGET_X86_64
5445 qemu_put_be64s(f, &env->efer);
5446 qemu_put_be64s(f, &env->star);
5447 qemu_put_be64s(f, &env->lstar);
5448 qemu_put_be64s(f, &env->cstar);
5449 qemu_put_be64s(f, &env->fmask);
5450 qemu_put_be64s(f, &env->kernelgsbase);
5452 qemu_put_be32s(f, &env->smbase);
5455 #ifdef USE_X86LDOUBLE
5456 /* XXX: add that in a FPU generic layer */
5457 union x86_longdouble {
5462 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5463 #define EXPBIAS1 1023
5464 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5465 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5467 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5471 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5472 /* exponent + sign */
5473 e = EXPD1(temp) - EXPBIAS1 + 16383;
5474 e |= SIGND1(temp) >> 16;
5479 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5481 CPUState *env = opaque;
5484 uint16_t fpus, fpuc, fptag, fpregs_format;
5486 if (version_id != 3 && version_id != 4)
5488 for(i = 0; i < CPU_NB_REGS; i++)
5489 qemu_get_betls(f, &env->regs[i]);
5490 qemu_get_betls(f, &env->eip);
5491 qemu_get_betls(f, &env->eflags);
5492 qemu_get_be32s(f, &hflags);
5494 qemu_get_be16s(f, &fpuc);
5495 qemu_get_be16s(f, &fpus);
5496 qemu_get_be16s(f, &fptag);
5497 qemu_get_be16s(f, &fpregs_format);
5499 /* NOTE: we cannot always restore the FPU state if the image come
5500 from a host with a different 'USE_X86LDOUBLE' define. We guess
5501 if we are in an MMX state to restore correctly in that case. */
5502 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5503 for(i = 0; i < 8; i++) {
5507 switch(fpregs_format) {
5509 mant = qemu_get_be64(f);
5510 exp = qemu_get_be16(f);
5511 #ifdef USE_X86LDOUBLE
5512 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5514 /* difficult case */
5516 env->fpregs[i].mmx.MMX_Q(0) = mant;
5518 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5522 mant = qemu_get_be64(f);
5523 #ifdef USE_X86LDOUBLE
5525 union x86_longdouble *p;
5526 /* difficult case */
5527 p = (void *)&env->fpregs[i];
5532 fp64_to_fp80(p, mant);
5536 env->fpregs[i].mmx.MMX_Q(0) = mant;
5545 /* XXX: restore FPU round state */
5546 env->fpstt = (fpus >> 11) & 7;
5547 env->fpus = fpus & ~0x3800;
5549 for(i = 0; i < 8; i++) {
5550 env->fptags[i] = (fptag >> i) & 1;
5553 for(i = 0; i < 6; i++)
5554 cpu_get_seg(f, &env->segs[i]);
5555 cpu_get_seg(f, &env->ldt);
5556 cpu_get_seg(f, &env->tr);
5557 cpu_get_seg(f, &env->gdt);
5558 cpu_get_seg(f, &env->idt);
5560 qemu_get_be32s(f, &env->sysenter_cs);
5561 qemu_get_be32s(f, &env->sysenter_esp);
5562 qemu_get_be32s(f, &env->sysenter_eip);
5564 qemu_get_betls(f, &env->cr[0]);
5565 qemu_get_betls(f, &env->cr[2]);
5566 qemu_get_betls(f, &env->cr[3]);
5567 qemu_get_betls(f, &env->cr[4]);
5569 for(i = 0; i < 8; i++)
5570 qemu_get_betls(f, &env->dr[i]);
5573 qemu_get_be32s(f, &env->a20_mask);
5575 qemu_get_be32s(f, &env->mxcsr);
5576 for(i = 0; i < CPU_NB_REGS; i++) {
5577 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5578 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5581 #ifdef TARGET_X86_64
5582 qemu_get_be64s(f, &env->efer);
5583 qemu_get_be64s(f, &env->star);
5584 qemu_get_be64s(f, &env->lstar);
5585 qemu_get_be64s(f, &env->cstar);
5586 qemu_get_be64s(f, &env->fmask);
5587 qemu_get_be64s(f, &env->kernelgsbase);
5589 if (version_id >= 4)
5590 qemu_get_be32s(f, &env->smbase);
5592 /* XXX: compute hflags from scratch, except for CPL and IIF */
5593 env->hflags = hflags;
5598 #elif defined(TARGET_PPC)
5599 void cpu_save(QEMUFile *f, void *opaque)
5603 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5608 #elif defined(TARGET_MIPS)
5609 void cpu_save(QEMUFile *f, void *opaque)
5613 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5618 #elif defined(TARGET_SPARC)
5619 void cpu_save(QEMUFile *f, void *opaque)
5621 CPUState *env = opaque;
5625 for(i = 0; i < 8; i++)
5626 qemu_put_betls(f, &env->gregs[i]);
5627 for(i = 0; i < NWINDOWS * 16; i++)
5628 qemu_put_betls(f, &env->regbase[i]);
5631 for(i = 0; i < TARGET_FPREGS; i++) {
5637 qemu_put_be32(f, u.i);
5640 qemu_put_betls(f, &env->pc);
5641 qemu_put_betls(f, &env->npc);
5642 qemu_put_betls(f, &env->y);
5644 qemu_put_be32(f, tmp);
5645 qemu_put_betls(f, &env->fsr);
5646 qemu_put_betls(f, &env->tbr);
5647 #ifndef TARGET_SPARC64
5648 qemu_put_be32s(f, &env->wim);
5650 for(i = 0; i < 16; i++)
5651 qemu_put_be32s(f, &env->mmuregs[i]);
5655 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5657 CPUState *env = opaque;
5661 for(i = 0; i < 8; i++)
5662 qemu_get_betls(f, &env->gregs[i]);
5663 for(i = 0; i < NWINDOWS * 16; i++)
5664 qemu_get_betls(f, &env->regbase[i]);
5667 for(i = 0; i < TARGET_FPREGS; i++) {
5672 u.i = qemu_get_be32(f);
5676 qemu_get_betls(f, &env->pc);
5677 qemu_get_betls(f, &env->npc);
5678 qemu_get_betls(f, &env->y);
5679 tmp = qemu_get_be32(f);
5680 env->cwp = 0; /* needed to ensure that the wrapping registers are
5681 correctly updated */
5683 qemu_get_betls(f, &env->fsr);
5684 qemu_get_betls(f, &env->tbr);
5685 #ifndef TARGET_SPARC64
5686 qemu_get_be32s(f, &env->wim);
5688 for(i = 0; i < 16; i++)
5689 qemu_get_be32s(f, &env->mmuregs[i]);
5695 #elif defined(TARGET_ARM)
5697 void cpu_save(QEMUFile *f, void *opaque)
5700 CPUARMState *env = (CPUARMState *)opaque;
5702 for (i = 0; i < 16; i++) {
5703 qemu_put_be32(f, env->regs[i]);
5705 qemu_put_be32(f, cpsr_read(env));
5706 qemu_put_be32(f, env->spsr);
5707 for (i = 0; i < 6; i++) {
5708 qemu_put_be32(f, env->banked_spsr[i]);
5709 qemu_put_be32(f, env->banked_r13[i]);
5710 qemu_put_be32(f, env->banked_r14[i]);
5712 for (i = 0; i < 5; i++) {
5713 qemu_put_be32(f, env->usr_regs[i]);
5714 qemu_put_be32(f, env->fiq_regs[i]);
5716 qemu_put_be32(f, env->cp15.c0_cpuid);
5717 qemu_put_be32(f, env->cp15.c0_cachetype);
5718 qemu_put_be32(f, env->cp15.c1_sys);
5719 qemu_put_be32(f, env->cp15.c1_coproc);
5720 qemu_put_be32(f, env->cp15.c2_base);
5721 qemu_put_be32(f, env->cp15.c2_data);
5722 qemu_put_be32(f, env->cp15.c2_insn);
5723 qemu_put_be32(f, env->cp15.c3);
5724 qemu_put_be32(f, env->cp15.c5_insn);
5725 qemu_put_be32(f, env->cp15.c5_data);
5726 for (i = 0; i < 8; i++) {
5727 qemu_put_be32(f, env->cp15.c6_region[i]);
5729 qemu_put_be32(f, env->cp15.c6_insn);
5730 qemu_put_be32(f, env->cp15.c6_data);
5731 qemu_put_be32(f, env->cp15.c9_insn);
5732 qemu_put_be32(f, env->cp15.c9_data);
5733 qemu_put_be32(f, env->cp15.c13_fcse);
5734 qemu_put_be32(f, env->cp15.c13_context);
5735 qemu_put_be32(f, env->cp15.c15_cpar);
5737 qemu_put_be32(f, env->features);
5739 if (arm_feature(env, ARM_FEATURE_VFP)) {
5740 for (i = 0; i < 16; i++) {
5742 u.d = env->vfp.regs[i];
5743 qemu_put_be32(f, u.l.upper);
5744 qemu_put_be32(f, u.l.lower);
5746 for (i = 0; i < 16; i++) {
5747 qemu_put_be32(f, env->vfp.xregs[i]);
5750 /* TODO: Should use proper FPSCR access functions. */
5751 qemu_put_be32(f, env->vfp.vec_len);
5752 qemu_put_be32(f, env->vfp.vec_stride);
5755 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5756 for (i = 0; i < 16; i++) {
5757 qemu_put_be64(f, env->iwmmxt.regs[i]);
5759 for (i = 0; i < 16; i++) {
5760 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5765 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5767 CPUARMState *env = (CPUARMState *)opaque;
5770 if (version_id != 0)
5773 for (i = 0; i < 16; i++) {
5774 env->regs[i] = qemu_get_be32(f);
5776 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5777 env->spsr = qemu_get_be32(f);
5778 for (i = 0; i < 6; i++) {
5779 env->banked_spsr[i] = qemu_get_be32(f);
5780 env->banked_r13[i] = qemu_get_be32(f);
5781 env->banked_r14[i] = qemu_get_be32(f);
5783 for (i = 0; i < 5; i++) {
5784 env->usr_regs[i] = qemu_get_be32(f);
5785 env->fiq_regs[i] = qemu_get_be32(f);
5787 env->cp15.c0_cpuid = qemu_get_be32(f);
5788 env->cp15.c0_cachetype = qemu_get_be32(f);
5789 env->cp15.c1_sys = qemu_get_be32(f);
5790 env->cp15.c1_coproc = qemu_get_be32(f);
5791 env->cp15.c2_base = qemu_get_be32(f);
5792 env->cp15.c2_data = qemu_get_be32(f);
5793 env->cp15.c2_insn = qemu_get_be32(f);
5794 env->cp15.c3 = qemu_get_be32(f);
5795 env->cp15.c5_insn = qemu_get_be32(f);
5796 env->cp15.c5_data = qemu_get_be32(f);
5797 for (i = 0; i < 8; i++) {
5798 env->cp15.c6_region[i] = qemu_get_be32(f);
5800 env->cp15.c6_insn = qemu_get_be32(f);
5801 env->cp15.c6_data = qemu_get_be32(f);
5802 env->cp15.c9_insn = qemu_get_be32(f);
5803 env->cp15.c9_data = qemu_get_be32(f);
5804 env->cp15.c13_fcse = qemu_get_be32(f);
5805 env->cp15.c13_context = qemu_get_be32(f);
5806 env->cp15.c15_cpar = qemu_get_be32(f);
5808 env->features = qemu_get_be32(f);
5810 if (arm_feature(env, ARM_FEATURE_VFP)) {
5811 for (i = 0; i < 16; i++) {
5813 u.l.upper = qemu_get_be32(f);
5814 u.l.lower = qemu_get_be32(f);
5815 env->vfp.regs[i] = u.d;
5817 for (i = 0; i < 16; i++) {
5818 env->vfp.xregs[i] = qemu_get_be32(f);
5821 /* TODO: Should use proper FPSCR access functions. */
5822 env->vfp.vec_len = qemu_get_be32(f);
5823 env->vfp.vec_stride = qemu_get_be32(f);
5826 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5827 for (i = 0; i < 16; i++) {
5828 env->iwmmxt.regs[i] = qemu_get_be64(f);
5830 for (i = 0; i < 16; i++) {
5831 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5840 #warning No CPU save/restore functions
5844 /***********************************************************/
5845 /* ram save/restore */
5847 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5851 v = qemu_get_byte(f);
5854 if (qemu_get_buffer(f, buf, len) != len)
5858 v = qemu_get_byte(f);
5859 memset(buf, v, len);
5867 static int ram_load_v1(QEMUFile *f, void *opaque)
5871 if (qemu_get_be32(f) != phys_ram_size)
5873 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5874 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5881 #define BDRV_HASH_BLOCK_SIZE 1024
5882 #define IOBUF_SIZE 4096
5883 #define RAM_CBLOCK_MAGIC 0xfabe
5885 typedef struct RamCompressState {
5888 uint8_t buf[IOBUF_SIZE];
5891 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5894 memset(s, 0, sizeof(*s));
5896 ret = deflateInit2(&s->zstream, 1,
5898 9, Z_DEFAULT_STRATEGY);
5901 s->zstream.avail_out = IOBUF_SIZE;
5902 s->zstream.next_out = s->buf;
5906 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5908 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5909 qemu_put_be16(s->f, len);
5910 qemu_put_buffer(s->f, buf, len);
5913 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5917 s->zstream.avail_in = len;
5918 s->zstream.next_in = (uint8_t *)buf;
5919 while (s->zstream.avail_in > 0) {
5920 ret = deflate(&s->zstream, Z_NO_FLUSH);
5923 if (s->zstream.avail_out == 0) {
5924 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5925 s->zstream.avail_out = IOBUF_SIZE;
5926 s->zstream.next_out = s->buf;
5932 static void ram_compress_close(RamCompressState *s)
5936 /* compress last bytes */
5938 ret = deflate(&s->zstream, Z_FINISH);
5939 if (ret == Z_OK || ret == Z_STREAM_END) {
5940 len = IOBUF_SIZE - s->zstream.avail_out;
5942 ram_put_cblock(s, s->buf, len);
5944 s->zstream.avail_out = IOBUF_SIZE;
5945 s->zstream.next_out = s->buf;
5946 if (ret == Z_STREAM_END)
5953 deflateEnd(&s->zstream);
5956 typedef struct RamDecompressState {
5959 uint8_t buf[IOBUF_SIZE];
5960 } RamDecompressState;
5962 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5965 memset(s, 0, sizeof(*s));
5967 ret = inflateInit(&s->zstream);
5973 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5977 s->zstream.avail_out = len;
5978 s->zstream.next_out = buf;
5979 while (s->zstream.avail_out > 0) {
5980 if (s->zstream.avail_in == 0) {
5981 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5983 clen = qemu_get_be16(s->f);
5984 if (clen > IOBUF_SIZE)
5986 qemu_get_buffer(s->f, s->buf, clen);
5987 s->zstream.avail_in = clen;
5988 s->zstream.next_in = s->buf;
5990 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5991 if (ret != Z_OK && ret != Z_STREAM_END) {
5998 static void ram_decompress_close(RamDecompressState *s)
6000 inflateEnd(&s->zstream);
6003 static void ram_save(QEMUFile *f, void *opaque)
6006 RamCompressState s1, *s = &s1;
6009 qemu_put_be32(f, phys_ram_size);
6010 if (ram_compress_open(s, f) < 0)
6012 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6014 if (tight_savevm_enabled) {
6018 /* find if the memory block is available on a virtual
6021 for(j = 0; j < MAX_DISKS; j++) {
6023 sector_num = bdrv_hash_find(bs_table[j],
6024 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6025 if (sector_num >= 0)
6030 goto normal_compress;
6033 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6034 ram_compress_buf(s, buf, 10);
6040 ram_compress_buf(s, buf, 1);
6041 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6044 ram_compress_close(s);
6047 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6049 RamDecompressState s1, *s = &s1;
6053 if (version_id == 1)
6054 return ram_load_v1(f, opaque);
6055 if (version_id != 2)
6057 if (qemu_get_be32(f) != phys_ram_size)
6059 if (ram_decompress_open(s, f) < 0)
6061 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6062 if (ram_decompress_buf(s, buf, 1) < 0) {
6063 fprintf(stderr, "Error while reading ram block header\n");
6067 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6068 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6077 ram_decompress_buf(s, buf + 1, 9);
6079 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6080 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6081 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6084 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6085 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6086 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6087 bs_index, sector_num);
6094 printf("Error block header\n");
6098 ram_decompress_close(s);
6102 /***********************************************************/
6103 /* bottom halves (can be seen as timers which expire ASAP) */
6112 static QEMUBH *first_bh = NULL;
6114 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6117 bh = qemu_mallocz(sizeof(QEMUBH));
6121 bh->opaque = opaque;
6125 int qemu_bh_poll(void)
6144 void qemu_bh_schedule(QEMUBH *bh)
6146 CPUState *env = cpu_single_env;
6150 bh->next = first_bh;
6153 /* stop the currently executing CPU to execute the BH ASAP */
6155 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6159 void qemu_bh_cancel(QEMUBH *bh)
6162 if (bh->scheduled) {
6165 pbh = &(*pbh)->next;
6171 void qemu_bh_delete(QEMUBH *bh)
6177 /***********************************************************/
6178 /* machine registration */
6180 QEMUMachine *first_machine = NULL;
6182 int qemu_register_machine(QEMUMachine *m)
6185 pm = &first_machine;
6193 QEMUMachine *find_machine(const char *name)
6197 for(m = first_machine; m != NULL; m = m->next) {
6198 if (!strcmp(m->name, name))
6204 /***********************************************************/
6205 /* main execution loop */
6207 void gui_update(void *opaque)
6209 DisplayState *ds = opaque;
6210 ds->dpy_refresh(ds);
6211 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6214 struct vm_change_state_entry {
6215 VMChangeStateHandler *cb;
6217 LIST_ENTRY (vm_change_state_entry) entries;
6220 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6222 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6225 VMChangeStateEntry *e;
6227 e = qemu_mallocz(sizeof (*e));
6233 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6237 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6239 LIST_REMOVE (e, entries);
6243 static void vm_state_notify(int running)
6245 VMChangeStateEntry *e;
6247 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6248 e->cb(e->opaque, running);
6252 /* XXX: support several handlers */
6253 static VMStopHandler *vm_stop_cb;
6254 static void *vm_stop_opaque;
6256 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6259 vm_stop_opaque = opaque;
6263 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6277 void vm_stop(int reason)
6280 cpu_disable_ticks();
6284 vm_stop_cb(vm_stop_opaque, reason);
6291 /* reset/shutdown handler */
6293 typedef struct QEMUResetEntry {
6294 QEMUResetHandler *func;
6296 struct QEMUResetEntry *next;
6299 static QEMUResetEntry *first_reset_entry;
6300 static int reset_requested;
6301 static int shutdown_requested;
6302 static int powerdown_requested;
6304 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6306 QEMUResetEntry **pre, *re;
6308 pre = &first_reset_entry;
6309 while (*pre != NULL)
6310 pre = &(*pre)->next;
6311 re = qemu_mallocz(sizeof(QEMUResetEntry));
6313 re->opaque = opaque;
6318 static void qemu_system_reset(void)
6322 /* reset all devices */
6323 for(re = first_reset_entry; re != NULL; re = re->next) {
6324 re->func(re->opaque);
6328 void qemu_system_reset_request(void)
6331 shutdown_requested = 1;
6333 reset_requested = 1;
6336 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6339 void qemu_system_shutdown_request(void)
6341 shutdown_requested = 1;
6343 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6346 void qemu_system_powerdown_request(void)
6348 powerdown_requested = 1;
6350 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6353 void main_loop_wait(int timeout)
6355 IOHandlerRecord *ioh;
6356 fd_set rfds, wfds, xfds;
6365 /* XXX: need to suppress polling by better using win32 events */
6367 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6368 ret |= pe->func(pe->opaque);
6373 WaitObjects *w = &wait_objects;
6375 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6376 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6377 if (w->func[ret - WAIT_OBJECT_0])
6378 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6380 /* Check for additional signaled events */
6381 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6383 /* Check if event is signaled */
6384 ret2 = WaitForSingleObject(w->events[i], 0);
6385 if(ret2 == WAIT_OBJECT_0) {
6387 w->func[i](w->opaque[i]);
6388 } else if (ret2 == WAIT_TIMEOUT) {
6390 err = GetLastError();
6391 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6394 } else if (ret == WAIT_TIMEOUT) {
6396 err = GetLastError();
6397 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6401 /* poll any events */
6402 /* XXX: separate device handlers from system ones */
6407 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6411 (!ioh->fd_read_poll ||
6412 ioh->fd_read_poll(ioh->opaque) != 0)) {
6413 FD_SET(ioh->fd, &rfds);
6417 if (ioh->fd_write) {
6418 FD_SET(ioh->fd, &wfds);
6428 tv.tv_usec = timeout * 1000;
6430 #if defined(CONFIG_SLIRP)
6432 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6435 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6437 IOHandlerRecord **pioh;
6439 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6442 if (FD_ISSET(ioh->fd, &rfds)) {
6443 ioh->fd_read(ioh->opaque);
6445 if (FD_ISSET(ioh->fd, &wfds)) {
6446 ioh->fd_write(ioh->opaque);
6450 /* remove deleted IO handlers */
6451 pioh = &first_io_handler;
6461 #if defined(CONFIG_SLIRP)
6468 slirp_select_poll(&rfds, &wfds, &xfds);
6474 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6475 qemu_get_clock(vm_clock));
6476 /* run dma transfers, if any */
6480 /* real time timers */
6481 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6482 qemu_get_clock(rt_clock));
6484 /* Check bottom-halves last in case any of the earlier events triggered
6490 static CPUState *cur_cpu;
6495 #ifdef CONFIG_PROFILER
6500 cur_cpu = first_cpu;
6507 env = env->next_cpu;
6510 #ifdef CONFIG_PROFILER
6511 ti = profile_getclock();
6513 ret = cpu_exec(env);
6514 #ifdef CONFIG_PROFILER
6515 qemu_time += profile_getclock() - ti;
6517 if (ret == EXCP_HLT) {
6518 /* Give the next CPU a chance to run. */
6522 if (ret != EXCP_HALTED)
6524 /* all CPUs are halted ? */
6530 if (shutdown_requested) {
6531 ret = EXCP_INTERRUPT;
6534 if (reset_requested) {
6535 reset_requested = 0;
6536 qemu_system_reset();
6537 ret = EXCP_INTERRUPT;
6539 if (powerdown_requested) {
6540 powerdown_requested = 0;
6541 qemu_system_powerdown();
6542 ret = EXCP_INTERRUPT;
6544 if (ret == EXCP_DEBUG) {
6545 vm_stop(EXCP_DEBUG);
6547 /* If all cpus are halted then wait until the next IRQ */
6548 /* XXX: use timeout computed from timers */
6549 if (ret == EXCP_HALTED)
6556 #ifdef CONFIG_PROFILER
6557 ti = profile_getclock();
6559 main_loop_wait(timeout);
6560 #ifdef CONFIG_PROFILER
6561 dev_time += profile_getclock() - ti;
6564 cpu_disable_ticks();
6570 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6571 "usage: %s [options] [disk_image]\n"
6573 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6575 "Standard options:\n"
6576 "-M machine select emulated machine (-M ? for list)\n"
6577 "-cpu cpu select CPU (-cpu ? for list)\n"
6578 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6579 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6580 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6581 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6582 "-mtdblock file use 'file' as on-board Flash memory image\n"
6583 "-sd file use 'file' as SecureDigital card image\n"
6584 "-pflash file use 'file' as a parallel flash image\n"
6585 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6586 "-snapshot write to temporary files instead of disk image files\n"
6588 "-no-frame open SDL window without a frame and window decorations\n"
6589 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6590 "-no-quit disable SDL window close capability\n"
6593 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6595 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6596 "-smp n set the number of CPUs to 'n' [default=1]\n"
6597 "-nographic disable graphical output and redirect serial I/Os to console\n"
6598 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6600 "-k language use keyboard layout (for example \"fr\" for French)\n"
6603 "-audio-help print list of audio drivers and their options\n"
6604 "-soundhw c1,... enable audio support\n"
6605 " and only specified sound cards (comma separated list)\n"
6606 " use -soundhw ? to get the list of supported cards\n"
6607 " use -soundhw all to enable all of them\n"
6609 "-localtime set the real time clock to local time [default=utc]\n"
6610 "-full-screen start in full screen\n"
6612 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6614 "-usb enable the USB driver (will be the default soon)\n"
6615 "-usbdevice name add the host or guest USB device 'name'\n"
6616 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6617 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6619 "-name string set the name of the guest\n"
6621 "Network options:\n"
6622 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6623 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6625 "-net user[,vlan=n][,hostname=host]\n"
6626 " connect the user mode network stack to VLAN 'n' and send\n"
6627 " hostname 'host' to DHCP clients\n"
6630 "-net tap[,vlan=n],ifname=name\n"
6631 " connect the host TAP network interface to VLAN 'n'\n"
6633 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6634 " connect the host TAP network interface to VLAN 'n' and use\n"
6635 " the network script 'file' (default=%s);\n"
6636 " use 'script=no' to disable script execution;\n"
6637 " use 'fd=h' to connect to an already opened TAP interface\n"
6639 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6640 " connect the vlan 'n' to another VLAN using a socket connection\n"
6641 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6642 " connect the vlan 'n' to multicast maddr and port\n"
6643 "-net none use it alone to have zero network devices; if no -net option\n"
6644 " is provided, the default is '-net nic -net user'\n"
6647 "-tftp dir allow tftp access to files in dir [-net user]\n"
6648 "-bootp file advertise file in BOOTP replies\n"
6650 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6652 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6653 " redirect TCP or UDP connections from host to guest [-net user]\n"
6656 "Linux boot specific:\n"
6657 "-kernel bzImage use 'bzImage' as kernel image\n"
6658 "-append cmdline use 'cmdline' as kernel command line\n"
6659 "-initrd file use 'file' as initial ram disk\n"
6661 "Debug/Expert options:\n"
6662 "-monitor dev redirect the monitor to char device 'dev'\n"
6663 "-serial dev redirect the serial port to char device 'dev'\n"
6664 "-parallel dev redirect the parallel port to char device 'dev'\n"
6665 "-pidfile file Write PID to 'file'\n"
6666 "-S freeze CPU at startup (use 'c' to start execution)\n"
6667 "-s wait gdb connection to port\n"
6668 "-p port set gdb connection port [default=%s]\n"
6669 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6670 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6671 " translation (t=none or lba) (usually qemu can guess them)\n"
6672 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6674 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6675 "-no-kqemu disable KQEMU kernel module usage\n"
6677 #ifdef USE_CODE_COPY
6678 "-no-code-copy disable code copy acceleration\n"
6681 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6682 " (default is CL-GD5446 PCI VGA)\n"
6683 "-no-acpi disable ACPI\n"
6685 "-no-reboot exit instead of rebooting\n"
6686 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6687 "-vnc display start a VNC server on display\n"
6689 "-daemonize daemonize QEMU after initializing\n"
6691 "-option-rom rom load a file, rom, into the option ROM space\n"
6693 "-prom-env variable=value set OpenBIOS nvram variables\n"
6696 "During emulation, the following keys are useful:\n"
6697 "ctrl-alt-f toggle full screen\n"
6698 "ctrl-alt-n switch to virtual console 'n'\n"
6699 "ctrl-alt toggle mouse and keyboard grab\n"
6701 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6706 DEFAULT_NETWORK_SCRIPT,
6708 DEFAULT_GDBSTUB_PORT,
6710 exit(strcmp(optarg, "?"));
6713 #define HAS_ARG 0x0001
6727 QEMU_OPTION_mtdblock,
6731 QEMU_OPTION_snapshot,
6733 QEMU_OPTION_no_fd_bootchk,
6736 QEMU_OPTION_nographic,
6737 QEMU_OPTION_portrait,
6739 QEMU_OPTION_audio_help,
6740 QEMU_OPTION_soundhw,
6759 QEMU_OPTION_no_code_copy,
6761 QEMU_OPTION_localtime,
6762 QEMU_OPTION_cirrusvga,
6765 QEMU_OPTION_std_vga,
6767 QEMU_OPTION_monitor,
6769 QEMU_OPTION_parallel,
6771 QEMU_OPTION_full_screen,
6772 QEMU_OPTION_no_frame,
6773 QEMU_OPTION_alt_grab,
6774 QEMU_OPTION_no_quit,
6775 QEMU_OPTION_pidfile,
6776 QEMU_OPTION_no_kqemu,
6777 QEMU_OPTION_kernel_kqemu,
6778 QEMU_OPTION_win2k_hack,
6780 QEMU_OPTION_usbdevice,
6783 QEMU_OPTION_no_acpi,
6784 QEMU_OPTION_no_reboot,
6785 QEMU_OPTION_show_cursor,
6786 QEMU_OPTION_daemonize,
6787 QEMU_OPTION_option_rom,
6788 QEMU_OPTION_semihosting,
6790 QEMU_OPTION_prom_env,
6793 typedef struct QEMUOption {
6799 const QEMUOption qemu_options[] = {
6800 { "h", 0, QEMU_OPTION_h },
6801 { "help", 0, QEMU_OPTION_h },
6803 { "M", HAS_ARG, QEMU_OPTION_M },
6804 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6805 { "fda", HAS_ARG, QEMU_OPTION_fda },
6806 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6807 { "hda", HAS_ARG, QEMU_OPTION_hda },
6808 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6809 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6810 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6811 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6812 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6813 { "sd", HAS_ARG, QEMU_OPTION_sd },
6814 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6815 { "boot", HAS_ARG, QEMU_OPTION_boot },
6816 { "snapshot", 0, QEMU_OPTION_snapshot },
6818 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6820 { "m", HAS_ARG, QEMU_OPTION_m },
6821 { "nographic", 0, QEMU_OPTION_nographic },
6822 { "portrait", 0, QEMU_OPTION_portrait },
6823 { "k", HAS_ARG, QEMU_OPTION_k },
6825 { "audio-help", 0, QEMU_OPTION_audio_help },
6826 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6829 { "net", HAS_ARG, QEMU_OPTION_net},
6831 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6832 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6834 { "smb", HAS_ARG, QEMU_OPTION_smb },
6836 { "redir", HAS_ARG, QEMU_OPTION_redir },
6839 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6840 { "append", HAS_ARG, QEMU_OPTION_append },
6841 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6843 { "S", 0, QEMU_OPTION_S },
6844 { "s", 0, QEMU_OPTION_s },
6845 { "p", HAS_ARG, QEMU_OPTION_p },
6846 { "d", HAS_ARG, QEMU_OPTION_d },
6847 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6848 { "L", HAS_ARG, QEMU_OPTION_L },
6849 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6851 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6852 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6854 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6855 { "g", 1, QEMU_OPTION_g },
6857 { "localtime", 0, QEMU_OPTION_localtime },
6858 { "std-vga", 0, QEMU_OPTION_std_vga },
6859 { "echr", HAS_ARG, QEMU_OPTION_echr },
6860 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6861 { "serial", HAS_ARG, QEMU_OPTION_serial },
6862 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6863 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6864 { "full-screen", 0, QEMU_OPTION_full_screen },
6866 { "no-frame", 0, QEMU_OPTION_no_frame },
6867 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6868 { "no-quit", 0, QEMU_OPTION_no_quit },
6870 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6871 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6872 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6873 { "smp", HAS_ARG, QEMU_OPTION_smp },
6874 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6876 /* temporary options */
6877 { "usb", 0, QEMU_OPTION_usb },
6878 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6879 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6880 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6881 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6882 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6883 { "daemonize", 0, QEMU_OPTION_daemonize },
6884 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6885 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6886 { "semihosting", 0, QEMU_OPTION_semihosting },
6888 { "name", HAS_ARG, QEMU_OPTION_name },
6889 #if defined(TARGET_SPARC)
6890 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6895 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6897 /* this stack is only used during signal handling */
6898 #define SIGNAL_STACK_SIZE 32768
6900 static uint8_t *signal_stack;
6904 /* password input */
6906 int qemu_key_check(BlockDriverState *bs, const char *name)
6911 if (!bdrv_is_encrypted(bs))
6914 term_printf("%s is encrypted.\n", name);
6915 for(i = 0; i < 3; i++) {
6916 monitor_readline("Password: ", 1, password, sizeof(password));
6917 if (bdrv_set_key(bs, password) == 0)
6919 term_printf("invalid password\n");
6924 static BlockDriverState *get_bdrv(int index)
6926 BlockDriverState *bs;
6929 bs = bs_table[index];
6930 } else if (index < 6) {
6931 bs = fd_table[index - 4];
6938 static void read_passwords(void)
6940 BlockDriverState *bs;
6943 for(i = 0; i < 6; i++) {
6946 qemu_key_check(bs, bdrv_get_device_name(bs));
6950 /* XXX: currently we cannot use simultaneously different CPUs */
6951 void register_machines(void)
6953 #if defined(TARGET_I386)
6954 qemu_register_machine(&pc_machine);
6955 qemu_register_machine(&isapc_machine);
6956 #elif defined(TARGET_PPC)
6957 qemu_register_machine(&heathrow_machine);
6958 qemu_register_machine(&core99_machine);
6959 qemu_register_machine(&prep_machine);
6960 qemu_register_machine(&ref405ep_machine);
6961 qemu_register_machine(&taihu_machine);
6962 #elif defined(TARGET_MIPS)
6963 qemu_register_machine(&mips_machine);
6964 qemu_register_machine(&mips_malta_machine);
6965 qemu_register_machine(&mips_pica61_machine);
6966 #elif defined(TARGET_SPARC)
6967 #ifdef TARGET_SPARC64
6968 qemu_register_machine(&sun4u_machine);
6970 qemu_register_machine(&ss5_machine);
6971 qemu_register_machine(&ss10_machine);
6973 #elif defined(TARGET_ARM)
6974 qemu_register_machine(&integratorcp_machine);
6975 qemu_register_machine(&versatilepb_machine);
6976 qemu_register_machine(&versatileab_machine);
6977 qemu_register_machine(&realview_machine);
6978 qemu_register_machine(&akitapda_machine);
6979 qemu_register_machine(&spitzpda_machine);
6980 qemu_register_machine(&borzoipda_machine);
6981 qemu_register_machine(&terrierpda_machine);
6982 #elif defined(TARGET_SH4)
6983 qemu_register_machine(&shix_machine);
6984 #elif defined(TARGET_ALPHA)
6986 #elif defined(TARGET_M68K)
6987 qemu_register_machine(&mcf5208evb_machine);
6988 qemu_register_machine(&an5206_machine);
6990 #error unsupported CPU
6995 struct soundhw soundhw[] = {
6996 #ifdef HAS_AUDIO_CHOICE
7003 { .init_isa = pcspk_audio_init }
7008 "Creative Sound Blaster 16",
7011 { .init_isa = SB16_init }
7018 "Yamaha YMF262 (OPL3)",
7020 "Yamaha YM3812 (OPL2)",
7024 { .init_isa = Adlib_init }
7031 "Gravis Ultrasound GF1",
7034 { .init_isa = GUS_init }
7040 "ENSONIQ AudioPCI ES1370",
7043 { .init_pci = es1370_init }
7047 { NULL, NULL, 0, 0, { NULL } }
7050 static void select_soundhw (const char *optarg)
7054 if (*optarg == '?') {
7057 printf ("Valid sound card names (comma separated):\n");
7058 for (c = soundhw; c->name; ++c) {
7059 printf ("%-11s %s\n", c->name, c->descr);
7061 printf ("\n-soundhw all will enable all of the above\n");
7062 exit (*optarg != '?');
7070 if (!strcmp (optarg, "all")) {
7071 for (c = soundhw; c->name; ++c) {
7079 e = strchr (p, ',');
7080 l = !e ? strlen (p) : (size_t) (e - p);
7082 for (c = soundhw; c->name; ++c) {
7083 if (!strncmp (c->name, p, l)) {
7092 "Unknown sound card name (too big to show)\n");
7095 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7100 p += l + (e != NULL);
7104 goto show_valid_cards;
7110 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7112 exit(STATUS_CONTROL_C_EXIT);
7117 #define MAX_NET_CLIENTS 32
7119 int main(int argc, char **argv)
7121 #ifdef CONFIG_GDBSTUB
7123 const char *gdbstub_port;
7125 int i, cdrom_index, pflash_index;
7126 int snapshot, linux_boot;
7127 const char *initrd_filename;
7128 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7129 const char *pflash_filename[MAX_PFLASH];
7130 const char *sd_filename;
7131 const char *mtd_filename;
7132 const char *kernel_filename, *kernel_cmdline;
7133 DisplayState *ds = &display_state;
7134 int cyls, heads, secs, translation;
7135 char net_clients[MAX_NET_CLIENTS][256];
7138 const char *r, *optarg;
7139 CharDriverState *monitor_hd;
7140 char monitor_device[128];
7141 char serial_devices[MAX_SERIAL_PORTS][128];
7142 int serial_device_index;
7143 char parallel_devices[MAX_PARALLEL_PORTS][128];
7144 int parallel_device_index;
7145 const char *loadvm = NULL;
7146 QEMUMachine *machine;
7147 const char *cpu_model;
7148 char usb_devices[MAX_USB_CMDLINE][128];
7149 int usb_devices_index;
7151 const char *pid_file = NULL;
7154 LIST_INIT (&vm_change_state_head);
7157 struct sigaction act;
7158 sigfillset(&act.sa_mask);
7160 act.sa_handler = SIG_IGN;
7161 sigaction(SIGPIPE, &act, NULL);
7164 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7165 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7166 QEMU to run on a single CPU */
7171 h = GetCurrentProcess();
7172 if (GetProcessAffinityMask(h, &mask, &smask)) {
7173 for(i = 0; i < 32; i++) {
7174 if (mask & (1 << i))
7179 SetProcessAffinityMask(h, mask);
7185 register_machines();
7186 machine = first_machine;
7188 initrd_filename = NULL;
7189 for(i = 0; i < MAX_FD; i++)
7190 fd_filename[i] = NULL;
7191 for(i = 0; i < MAX_DISKS; i++)
7192 hd_filename[i] = NULL;
7193 for(i = 0; i < MAX_PFLASH; i++)
7194 pflash_filename[i] = NULL;
7197 mtd_filename = NULL;
7198 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7199 vga_ram_size = VGA_RAM_SIZE;
7200 #ifdef CONFIG_GDBSTUB
7202 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7206 kernel_filename = NULL;
7207 kernel_cmdline = "";
7213 cyls = heads = secs = 0;
7214 translation = BIOS_ATA_TRANSLATION_AUTO;
7215 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7217 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7218 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7219 serial_devices[i][0] = '\0';
7220 serial_device_index = 0;
7222 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7223 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7224 parallel_devices[i][0] = '\0';
7225 parallel_device_index = 0;
7227 usb_devices_index = 0;
7232 /* default mac address of the first network interface */
7240 hd_filename[0] = argv[optind++];
7242 const QEMUOption *popt;
7245 /* Treat --foo the same as -foo. */
7248 popt = qemu_options;
7251 fprintf(stderr, "%s: invalid option -- '%s'\n",
7255 if (!strcmp(popt->name, r + 1))
7259 if (popt->flags & HAS_ARG) {
7260 if (optind >= argc) {
7261 fprintf(stderr, "%s: option '%s' requires an argument\n",
7265 optarg = argv[optind++];
7270 switch(popt->index) {
7272 machine = find_machine(optarg);
7275 printf("Supported machines are:\n");
7276 for(m = first_machine; m != NULL; m = m->next) {
7277 printf("%-10s %s%s\n",
7279 m == first_machine ? " (default)" : "");
7284 case QEMU_OPTION_cpu:
7285 /* hw initialization will check this */
7286 if (optarg[0] == '?') {
7287 #if defined(TARGET_PPC)
7288 ppc_cpu_list(stdout, &fprintf);
7289 #elif defined(TARGET_ARM)
7291 #elif defined(TARGET_MIPS)
7292 mips_cpu_list(stdout, &fprintf);
7293 #elif defined(TARGET_SPARC)
7294 sparc_cpu_list(stdout, &fprintf);
7301 case QEMU_OPTION_initrd:
7302 initrd_filename = optarg;
7304 case QEMU_OPTION_hda:
7305 case QEMU_OPTION_hdb:
7306 case QEMU_OPTION_hdc:
7307 case QEMU_OPTION_hdd:
7310 hd_index = popt->index - QEMU_OPTION_hda;
7311 hd_filename[hd_index] = optarg;
7312 if (hd_index == cdrom_index)
7316 case QEMU_OPTION_mtdblock:
7317 mtd_filename = optarg;
7319 case QEMU_OPTION_sd:
7320 sd_filename = optarg;
7322 case QEMU_OPTION_pflash:
7323 if (pflash_index >= MAX_PFLASH) {
7324 fprintf(stderr, "qemu: too many parallel flash images\n");
7327 pflash_filename[pflash_index++] = optarg;
7329 case QEMU_OPTION_snapshot:
7332 case QEMU_OPTION_hdachs:
7336 cyls = strtol(p, (char **)&p, 0);
7337 if (cyls < 1 || cyls > 16383)
7342 heads = strtol(p, (char **)&p, 0);
7343 if (heads < 1 || heads > 16)
7348 secs = strtol(p, (char **)&p, 0);
7349 if (secs < 1 || secs > 63)
7353 if (!strcmp(p, "none"))
7354 translation = BIOS_ATA_TRANSLATION_NONE;
7355 else if (!strcmp(p, "lba"))
7356 translation = BIOS_ATA_TRANSLATION_LBA;
7357 else if (!strcmp(p, "auto"))
7358 translation = BIOS_ATA_TRANSLATION_AUTO;
7361 } else if (*p != '\0') {
7363 fprintf(stderr, "qemu: invalid physical CHS format\n");
7368 case QEMU_OPTION_nographic:
7369 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7370 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7371 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7374 case QEMU_OPTION_portrait:
7377 case QEMU_OPTION_kernel:
7378 kernel_filename = optarg;
7380 case QEMU_OPTION_append:
7381 kernel_cmdline = optarg;
7383 case QEMU_OPTION_cdrom:
7384 if (cdrom_index >= 0) {
7385 hd_filename[cdrom_index] = optarg;
7388 case QEMU_OPTION_boot:
7389 boot_device = optarg[0];
7390 if (boot_device != 'a' &&
7391 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7393 boot_device != 'n' &&
7395 boot_device != 'c' && boot_device != 'd') {
7396 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7400 case QEMU_OPTION_fda:
7401 fd_filename[0] = optarg;
7403 case QEMU_OPTION_fdb:
7404 fd_filename[1] = optarg;
7407 case QEMU_OPTION_no_fd_bootchk:
7411 case QEMU_OPTION_no_code_copy:
7412 code_copy_enabled = 0;
7414 case QEMU_OPTION_net:
7415 if (nb_net_clients >= MAX_NET_CLIENTS) {
7416 fprintf(stderr, "qemu: too many network clients\n");
7419 pstrcpy(net_clients[nb_net_clients],
7420 sizeof(net_clients[0]),
7425 case QEMU_OPTION_tftp:
7426 tftp_prefix = optarg;
7428 case QEMU_OPTION_bootp:
7429 bootp_filename = optarg;
7432 case QEMU_OPTION_smb:
7433 net_slirp_smb(optarg);
7436 case QEMU_OPTION_redir:
7437 net_slirp_redir(optarg);
7441 case QEMU_OPTION_audio_help:
7445 case QEMU_OPTION_soundhw:
7446 select_soundhw (optarg);
7453 ram_size = atoi(optarg) * 1024 * 1024;
7456 if (ram_size > PHYS_RAM_MAX_SIZE) {
7457 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7458 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7467 mask = cpu_str_to_log_mask(optarg);
7469 printf("Log items (comma separated):\n");
7470 for(item = cpu_log_items; item->mask != 0; item++) {
7471 printf("%-10s %s\n", item->name, item->help);
7478 #ifdef CONFIG_GDBSTUB
7483 gdbstub_port = optarg;
7493 keyboard_layout = optarg;
7495 case QEMU_OPTION_localtime:
7498 case QEMU_OPTION_cirrusvga:
7499 cirrus_vga_enabled = 1;
7502 case QEMU_OPTION_vmsvga:
7503 cirrus_vga_enabled = 0;
7506 case QEMU_OPTION_std_vga:
7507 cirrus_vga_enabled = 0;
7515 w = strtol(p, (char **)&p, 10);
7518 fprintf(stderr, "qemu: invalid resolution or depth\n");
7524 h = strtol(p, (char **)&p, 10);
7529 depth = strtol(p, (char **)&p, 10);
7530 if (depth != 8 && depth != 15 && depth != 16 &&
7531 depth != 24 && depth != 32)
7533 } else if (*p == '\0') {
7534 depth = graphic_depth;
7541 graphic_depth = depth;
7544 case QEMU_OPTION_echr:
7547 term_escape_char = strtol(optarg, &r, 0);
7549 printf("Bad argument to echr\n");
7552 case QEMU_OPTION_monitor:
7553 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7555 case QEMU_OPTION_serial:
7556 if (serial_device_index >= MAX_SERIAL_PORTS) {
7557 fprintf(stderr, "qemu: too many serial ports\n");
7560 pstrcpy(serial_devices[serial_device_index],
7561 sizeof(serial_devices[0]), optarg);
7562 serial_device_index++;
7564 case QEMU_OPTION_parallel:
7565 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7566 fprintf(stderr, "qemu: too many parallel ports\n");
7569 pstrcpy(parallel_devices[parallel_device_index],
7570 sizeof(parallel_devices[0]), optarg);
7571 parallel_device_index++;
7573 case QEMU_OPTION_loadvm:
7576 case QEMU_OPTION_full_screen:
7580 case QEMU_OPTION_no_frame:
7583 case QEMU_OPTION_alt_grab:
7586 case QEMU_OPTION_no_quit:
7590 case QEMU_OPTION_pidfile:
7594 case QEMU_OPTION_win2k_hack:
7595 win2k_install_hack = 1;
7599 case QEMU_OPTION_no_kqemu:
7602 case QEMU_OPTION_kernel_kqemu:
7606 case QEMU_OPTION_usb:
7609 case QEMU_OPTION_usbdevice:
7611 if (usb_devices_index >= MAX_USB_CMDLINE) {
7612 fprintf(stderr, "Too many USB devices\n");
7615 pstrcpy(usb_devices[usb_devices_index],
7616 sizeof(usb_devices[usb_devices_index]),
7618 usb_devices_index++;
7620 case QEMU_OPTION_smp:
7621 smp_cpus = atoi(optarg);
7622 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7623 fprintf(stderr, "Invalid number of CPUs\n");
7627 case QEMU_OPTION_vnc:
7628 vnc_display = optarg;
7630 case QEMU_OPTION_no_acpi:
7633 case QEMU_OPTION_no_reboot:
7636 case QEMU_OPTION_show_cursor:
7639 case QEMU_OPTION_daemonize:
7642 case QEMU_OPTION_option_rom:
7643 if (nb_option_roms >= MAX_OPTION_ROMS) {
7644 fprintf(stderr, "Too many option ROMs\n");
7647 option_rom[nb_option_roms] = optarg;
7650 case QEMU_OPTION_semihosting:
7651 semihosting_enabled = 1;
7653 case QEMU_OPTION_name:
7657 case QEMU_OPTION_prom_env:
7658 if (nb_prom_envs >= MAX_PROM_ENVS) {
7659 fprintf(stderr, "Too many prom variables\n");
7662 prom_envs[nb_prom_envs] = optarg;
7671 if (daemonize && !nographic && vnc_display == NULL) {
7672 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7679 if (pipe(fds) == -1)
7690 len = read(fds[0], &status, 1);
7691 if (len == -1 && (errno == EINTR))
7696 else if (status == 1) {
7697 fprintf(stderr, "Could not acquire pidfile\n");
7715 signal(SIGTSTP, SIG_IGN);
7716 signal(SIGTTOU, SIG_IGN);
7717 signal(SIGTTIN, SIG_IGN);
7721 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7724 write(fds[1], &status, 1);
7726 fprintf(stderr, "Could not acquire pid file\n");
7734 linux_boot = (kernel_filename != NULL);
7737 boot_device != 'n' &&
7738 hd_filename[0] == '\0' &&
7739 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7740 fd_filename[0] == '\0')
7743 /* boot to floppy or the default cd if no hard disk defined yet */
7744 if (hd_filename[0] == '\0' && boot_device == 'c') {
7745 if (fd_filename[0] != '\0')
7751 setvbuf(stdout, NULL, _IOLBF, 0);
7761 /* init network clients */
7762 if (nb_net_clients == 0) {
7763 /* if no clients, we use a default config */
7764 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7766 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7771 for(i = 0;i < nb_net_clients; i++) {
7772 if (net_client_init(net_clients[i]) < 0)
7775 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7776 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7778 if (vlan->nb_guest_devs == 0) {
7779 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7782 if (vlan->nb_host_devs == 0)
7784 "Warning: vlan %d is not connected to host network\n",
7789 if (boot_device == 'n') {
7790 for (i = 0; i < nb_nics; i++) {
7791 const char *model = nd_table[i].model;
7795 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7796 if (get_image_size(buf) > 0) {
7797 option_rom[nb_option_roms] = strdup(buf);
7803 fprintf(stderr, "No valid PXE rom found for network device\n");
7806 boot_device = 'c'; /* to prevent confusion by the BIOS */
7810 /* init the memory */
7811 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7813 phys_ram_base = qemu_vmalloc(phys_ram_size);
7814 if (!phys_ram_base) {
7815 fprintf(stderr, "Could not allocate physical memory\n");
7819 /* we always create the cdrom drive, even if no disk is there */
7821 if (cdrom_index >= 0) {
7822 bs_table[cdrom_index] = bdrv_new("cdrom");
7823 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7826 /* open the virtual block devices */
7827 for(i = 0; i < MAX_DISKS; i++) {
7828 if (hd_filename[i]) {
7831 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7832 bs_table[i] = bdrv_new(buf);
7834 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7835 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7839 if (i == 0 && cyls != 0) {
7840 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7841 bdrv_set_translation_hint(bs_table[i], translation);
7846 /* we always create at least one floppy disk */
7847 fd_table[0] = bdrv_new("fda");
7848 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7850 for(i = 0; i < MAX_FD; i++) {
7851 if (fd_filename[i]) {
7854 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7855 fd_table[i] = bdrv_new(buf);
7856 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7858 if (fd_filename[i][0] != '\0') {
7859 if (bdrv_open(fd_table[i], fd_filename[i],
7860 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7861 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7869 /* Open the virtual parallel flash block devices */
7870 for(i = 0; i < MAX_PFLASH; i++) {
7871 if (pflash_filename[i]) {
7872 if (!pflash_table[i]) {
7874 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7875 pflash_table[i] = bdrv_new(buf);
7877 if (bdrv_open(pflash_table[i], pflash_filename[i],
7878 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7879 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7880 pflash_filename[i]);
7886 sd_bdrv = bdrv_new ("sd");
7887 /* FIXME: This isn't really a floppy, but it's a reasonable
7889 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7891 if (bdrv_open(sd_bdrv, sd_filename,
7892 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7893 fprintf(stderr, "qemu: could not open SD card image %s\n",
7896 qemu_key_check(sd_bdrv, sd_filename);
7900 mtd_bdrv = bdrv_new ("mtd");
7901 if (bdrv_open(mtd_bdrv, mtd_filename,
7902 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7903 qemu_key_check(mtd_bdrv, mtd_filename)) {
7904 fprintf(stderr, "qemu: could not open Flash image %s\n",
7906 bdrv_delete(mtd_bdrv);
7911 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7912 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7917 memset(&display_state, 0, sizeof(display_state));
7919 /* nearly nothing to do */
7920 dumb_display_init(ds);
7921 } else if (vnc_display != NULL) {
7922 vnc_display_init(ds, vnc_display);
7924 #if defined(CONFIG_SDL)
7925 sdl_display_init(ds, full_screen, no_frame);
7926 #elif defined(CONFIG_COCOA)
7927 cocoa_display_init(ds, full_screen);
7931 /* Maintain compatibility with multiple stdio monitors */
7932 if (!strcmp(monitor_device,"stdio")) {
7933 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7934 if (!strcmp(serial_devices[i],"mon:stdio")) {
7935 monitor_device[0] = '\0';
7937 } else if (!strcmp(serial_devices[i],"stdio")) {
7938 monitor_device[0] = '\0';
7939 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7944 if (monitor_device[0] != '\0') {
7945 monitor_hd = qemu_chr_open(monitor_device);
7947 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7950 monitor_init(monitor_hd, !nographic);
7953 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7954 const char *devname = serial_devices[i];
7955 if (devname[0] != '\0' && strcmp(devname, "none")) {
7956 serial_hds[i] = qemu_chr_open(devname);
7957 if (!serial_hds[i]) {
7958 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7962 if (!strcmp(devname, "vc"))
7963 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7967 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7968 const char *devname = parallel_devices[i];
7969 if (devname[0] != '\0' && strcmp(devname, "none")) {
7970 parallel_hds[i] = qemu_chr_open(devname);
7971 if (!parallel_hds[i]) {
7972 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7976 if (!strcmp(devname, "vc"))
7977 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7981 machine->init(ram_size, vga_ram_size, boot_device,
7982 ds, fd_filename, snapshot,
7983 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7985 /* init USB devices */
7987 for(i = 0; i < usb_devices_index; i++) {
7988 if (usb_device_add(usb_devices[i]) < 0) {
7989 fprintf(stderr, "Warning: could not add USB device %s\n",
7995 if (display_state.dpy_refresh) {
7996 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
7997 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8000 #ifdef CONFIG_GDBSTUB
8002 /* XXX: use standard host:port notation and modify options
8004 if (gdbserver_start(gdbstub_port) < 0) {
8005 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8015 /* XXX: simplify init */
8028 len = write(fds[1], &status, 1);
8029 if (len == -1 && (errno == EINTR))
8035 fd = open("/dev/null", O_RDWR);