4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
78 #if defined(CONFIG_SLIRP)
84 #include <sys/timeb.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
90 #include "qemu_socket.h"
96 #endif /* CONFIG_SDL */
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
111 #define SMBD_COMMAND "/usr/sbin/smbd"
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
120 #define DEFAULT_RAM_SIZE 144
122 #define DEFAULT_RAM_SIZE 128
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141 BlockDriverState *pflash_table[MAX_PFLASH];
142 BlockDriverState *sd_bdrv;
143 BlockDriverState *mtd_bdrv;
144 /* point to the block driver where the snapshots are managed */
145 BlockDriverState *bs_snapshots;
147 static DisplayState display_state;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 int boot_device = 'c';
153 int pit_min_timer_count = 0;
155 NICInfo nd_table[MAX_NICS];
156 QEMUTimer *gui_timer;
159 int cirrus_vga_enabled = 1;
160 int vmsvga_enabled = 0;
162 int graphic_width = 1024;
163 int graphic_height = 768;
164 int graphic_depth = 8;
166 int graphic_width = 800;
167 int graphic_height = 600;
168 int graphic_depth = 15;
173 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
174 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
176 int win2k_install_hack = 0;
179 static VLANState *first_vlan;
181 const char *vnc_display;
182 #if defined(TARGET_SPARC)
184 #elif defined(TARGET_I386)
189 int acpi_enabled = 1;
192 int graphic_rotate = 0;
194 const char *option_rom[MAX_OPTION_ROMS];
196 int semihosting_enabled = 0;
198 const char *qemu_name;
200 /***********************************************************/
201 /* x86 ISA bus support */
203 target_phys_addr_t isa_mem_base = 0;
206 uint32_t default_ioport_readb(void *opaque, uint32_t address)
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "unused inb: port=0x%04x\n", address);
214 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
216 #ifdef DEBUG_UNUSED_IOPORT
217 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
221 /* default is to make two byte accesses */
222 uint32_t default_ioport_readw(void *opaque, uint32_t address)
225 data = ioport_read_table[0][address](ioport_opaque[address], address);
226 address = (address + 1) & (MAX_IOPORTS - 1);
227 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
231 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
233 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
234 address = (address + 1) & (MAX_IOPORTS - 1);
235 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
238 uint32_t default_ioport_readl(void *opaque, uint32_t address)
240 #ifdef DEBUG_UNUSED_IOPORT
241 fprintf(stderr, "unused inl: port=0x%04x\n", address);
246 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
248 #ifdef DEBUG_UNUSED_IOPORT
249 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
253 void init_ioports(void)
257 for(i = 0; i < MAX_IOPORTS; i++) {
258 ioport_read_table[0][i] = default_ioport_readb;
259 ioport_write_table[0][i] = default_ioport_writeb;
260 ioport_read_table[1][i] = default_ioport_readw;
261 ioport_write_table[1][i] = default_ioport_writew;
262 ioport_read_table[2][i] = default_ioport_readl;
263 ioport_write_table[2][i] = default_ioport_writel;
267 /* size is the word size in byte */
268 int register_ioport_read(int start, int length, int size,
269 IOPortReadFunc *func, void *opaque)
275 } else if (size == 2) {
277 } else if (size == 4) {
280 hw_error("register_ioport_read: invalid size");
283 for(i = start; i < start + length; i += size) {
284 ioport_read_table[bsize][i] = func;
285 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
286 hw_error("register_ioport_read: invalid opaque");
287 ioport_opaque[i] = opaque;
292 /* size is the word size in byte */
293 int register_ioport_write(int start, int length, int size,
294 IOPortWriteFunc *func, void *opaque)
300 } else if (size == 2) {
302 } else if (size == 4) {
305 hw_error("register_ioport_write: invalid size");
308 for(i = start; i < start + length; i += size) {
309 ioport_write_table[bsize][i] = func;
310 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
311 hw_error("register_ioport_write: invalid opaque");
312 ioport_opaque[i] = opaque;
317 void isa_unassign_ioport(int start, int length)
321 for(i = start; i < start + length; i++) {
322 ioport_read_table[0][i] = default_ioport_readb;
323 ioport_read_table[1][i] = default_ioport_readw;
324 ioport_read_table[2][i] = default_ioport_readl;
326 ioport_write_table[0][i] = default_ioport_writeb;
327 ioport_write_table[1][i] = default_ioport_writew;
328 ioport_write_table[2][i] = default_ioport_writel;
332 /***********************************************************/
334 void cpu_outb(CPUState *env, int addr, int val)
337 if (loglevel & CPU_LOG_IOPORT)
338 fprintf(logfile, "outb: %04x %02x\n", addr, val);
340 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
343 env->last_io_time = cpu_get_time_fast();
347 void cpu_outw(CPUState *env, int addr, int val)
350 if (loglevel & CPU_LOG_IOPORT)
351 fprintf(logfile, "outw: %04x %04x\n", addr, val);
353 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
356 env->last_io_time = cpu_get_time_fast();
360 void cpu_outl(CPUState *env, int addr, int val)
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outl: %04x %08x\n", addr, val);
366 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
369 env->last_io_time = cpu_get_time_fast();
373 int cpu_inb(CPUState *env, int addr)
376 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
378 if (loglevel & CPU_LOG_IOPORT)
379 fprintf(logfile, "inb : %04x %02x\n", addr, val);
383 env->last_io_time = cpu_get_time_fast();
388 int cpu_inw(CPUState *env, int addr)
391 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
393 if (loglevel & CPU_LOG_IOPORT)
394 fprintf(logfile, "inw : %04x %04x\n", addr, val);
398 env->last_io_time = cpu_get_time_fast();
403 int cpu_inl(CPUState *env, int addr)
406 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "inl : %04x %08x\n", addr, val);
413 env->last_io_time = cpu_get_time_fast();
418 /***********************************************************/
419 void hw_error(const char *fmt, ...)
425 fprintf(stderr, "qemu: hardware error: ");
426 vfprintf(stderr, fmt, ap);
427 fprintf(stderr, "\n");
428 for(env = first_cpu; env != NULL; env = env->next_cpu) {
429 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
431 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
433 cpu_dump_state(env, stderr, fprintf, 0);
440 /***********************************************************/
443 static QEMUPutKBDEvent *qemu_put_kbd_event;
444 static void *qemu_put_kbd_event_opaque;
445 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
446 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
448 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
450 qemu_put_kbd_event_opaque = opaque;
451 qemu_put_kbd_event = func;
454 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
455 void *opaque, int absolute,
458 QEMUPutMouseEntry *s, *cursor;
460 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
464 s->qemu_put_mouse_event = func;
465 s->qemu_put_mouse_event_opaque = opaque;
466 s->qemu_put_mouse_event_absolute = absolute;
467 s->qemu_put_mouse_event_name = qemu_strdup(name);
470 if (!qemu_put_mouse_event_head) {
471 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
475 cursor = qemu_put_mouse_event_head;
476 while (cursor->next != NULL)
477 cursor = cursor->next;
480 qemu_put_mouse_event_current = s;
485 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
487 QEMUPutMouseEntry *prev = NULL, *cursor;
489 if (!qemu_put_mouse_event_head || entry == NULL)
492 cursor = qemu_put_mouse_event_head;
493 while (cursor != NULL && cursor != entry) {
495 cursor = cursor->next;
498 if (cursor == NULL) // does not exist or list empty
500 else if (prev == NULL) { // entry is head
501 qemu_put_mouse_event_head = cursor->next;
502 if (qemu_put_mouse_event_current == entry)
503 qemu_put_mouse_event_current = cursor->next;
504 qemu_free(entry->qemu_put_mouse_event_name);
509 prev->next = entry->next;
511 if (qemu_put_mouse_event_current == entry)
512 qemu_put_mouse_event_current = prev;
514 qemu_free(entry->qemu_put_mouse_event_name);
518 void kbd_put_keycode(int keycode)
520 if (qemu_put_kbd_event) {
521 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
525 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
527 QEMUPutMouseEvent *mouse_event;
528 void *mouse_event_opaque;
531 if (!qemu_put_mouse_event_current) {
536 qemu_put_mouse_event_current->qemu_put_mouse_event;
538 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
541 if (graphic_rotate) {
542 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
545 width = graphic_width;
546 mouse_event(mouse_event_opaque,
547 width - dy, dx, dz, buttons_state);
549 mouse_event(mouse_event_opaque,
550 dx, dy, dz, buttons_state);
554 int kbd_mouse_is_absolute(void)
556 if (!qemu_put_mouse_event_current)
559 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
562 void (*kbd_mouse_set)(int x, int y, int on) = NULL;
563 void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
564 uint8_t *image, uint8_t *mask) = NULL;
566 void do_info_mice(void)
568 QEMUPutMouseEntry *cursor;
571 if (!qemu_put_mouse_event_head) {
572 term_printf("No mouse devices connected\n");
576 term_printf("Mouse devices available:\n");
577 cursor = qemu_put_mouse_event_head;
578 while (cursor != NULL) {
579 term_printf("%c Mouse #%d: %s\n",
580 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
581 index, cursor->qemu_put_mouse_event_name);
583 cursor = cursor->next;
587 void do_mouse_set(int index)
589 QEMUPutMouseEntry *cursor;
592 if (!qemu_put_mouse_event_head) {
593 term_printf("No mouse devices connected\n");
597 cursor = qemu_put_mouse_event_head;
598 while (cursor != NULL && index != i) {
600 cursor = cursor->next;
604 qemu_put_mouse_event_current = cursor;
606 term_printf("Mouse at given index not found\n");
609 /* compute with 96 bit intermediate result: (a*b)/c */
610 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
615 #ifdef WORDS_BIGENDIAN
625 rl = (uint64_t)u.l.low * (uint64_t)b;
626 rh = (uint64_t)u.l.high * (uint64_t)b;
629 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
633 /***********************************************************/
634 /* real time host monotonic timer */
636 #define QEMU_TIMER_BASE 1000000000LL
640 static int64_t clock_freq;
642 static void init_get_clock(void)
646 ret = QueryPerformanceFrequency(&freq);
648 fprintf(stderr, "Could not calibrate ticks\n");
651 clock_freq = freq.QuadPart;
654 static int64_t get_clock(void)
657 QueryPerformanceCounter(&ti);
658 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
663 static int use_rt_clock;
665 static void init_get_clock(void)
668 #if defined(__linux__)
671 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
678 static int64_t get_clock(void)
680 #if defined(__linux__)
683 clock_gettime(CLOCK_MONOTONIC, &ts);
684 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
688 /* XXX: using gettimeofday leads to problems if the date
689 changes, so it should be avoided. */
691 gettimeofday(&tv, NULL);
692 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
698 /***********************************************************/
699 /* guest cycle counter */
701 static int64_t cpu_ticks_prev;
702 static int64_t cpu_ticks_offset;
703 static int64_t cpu_clock_offset;
704 static int cpu_ticks_enabled;
706 /* return the host CPU cycle counter and handle stop/restart */
707 int64_t cpu_get_ticks(void)
709 if (!cpu_ticks_enabled) {
710 return cpu_ticks_offset;
713 ticks = cpu_get_real_ticks();
714 if (cpu_ticks_prev > ticks) {
715 /* Note: non increasing ticks may happen if the host uses
717 cpu_ticks_offset += cpu_ticks_prev - ticks;
719 cpu_ticks_prev = ticks;
720 return ticks + cpu_ticks_offset;
724 /* return the host CPU monotonic timer and handle stop/restart */
725 static int64_t cpu_get_clock(void)
728 if (!cpu_ticks_enabled) {
729 return cpu_clock_offset;
732 return ti + cpu_clock_offset;
736 /* enable cpu_get_ticks() */
737 void cpu_enable_ticks(void)
739 if (!cpu_ticks_enabled) {
740 cpu_ticks_offset -= cpu_get_real_ticks();
741 cpu_clock_offset -= get_clock();
742 cpu_ticks_enabled = 1;
746 /* disable cpu_get_ticks() : the clock is stopped. You must not call
747 cpu_get_ticks() after that. */
748 void cpu_disable_ticks(void)
750 if (cpu_ticks_enabled) {
751 cpu_ticks_offset = cpu_get_ticks();
752 cpu_clock_offset = cpu_get_clock();
753 cpu_ticks_enabled = 0;
757 /***********************************************************/
760 #define QEMU_TIMER_REALTIME 0
761 #define QEMU_TIMER_VIRTUAL 1
765 /* XXX: add frequency */
773 struct QEMUTimer *next;
779 static QEMUTimer *active_timers[2];
781 static MMRESULT timerID;
782 static HANDLE host_alarm = NULL;
783 static unsigned int period = 1;
785 /* frequency of the times() clock tick */
786 static int timer_freq;
789 QEMUClock *qemu_new_clock(int type)
792 clock = qemu_mallocz(sizeof(QEMUClock));
799 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
803 ts = qemu_mallocz(sizeof(QEMUTimer));
810 void qemu_free_timer(QEMUTimer *ts)
815 /* stop a timer, but do not dealloc it */
816 void qemu_del_timer(QEMUTimer *ts)
820 /* NOTE: this code must be signal safe because
821 qemu_timer_expired() can be called from a signal. */
822 pt = &active_timers[ts->clock->type];
835 /* modify the current timer so that it will be fired when current_time
836 >= expire_time. The corresponding callback will be called. */
837 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
843 /* add the timer in the sorted list */
844 /* NOTE: this code must be signal safe because
845 qemu_timer_expired() can be called from a signal. */
846 pt = &active_timers[ts->clock->type];
851 if (t->expire_time > expire_time)
855 ts->expire_time = expire_time;
860 int qemu_timer_pending(QEMUTimer *ts)
863 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
870 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
874 return (timer_head->expire_time <= current_time);
877 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
883 if (!ts || ts->expire_time > current_time)
885 /* remove timer from the list before calling the callback */
886 *ptimer_head = ts->next;
889 /* run the callback (the timer list can be modified) */
894 int64_t qemu_get_clock(QEMUClock *clock)
896 switch(clock->type) {
897 case QEMU_TIMER_REALTIME:
898 return get_clock() / 1000000;
900 case QEMU_TIMER_VIRTUAL:
901 return cpu_get_clock();
905 static void init_timers(void)
908 ticks_per_sec = QEMU_TIMER_BASE;
909 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
910 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
914 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
916 uint64_t expire_time;
918 if (qemu_timer_pending(ts)) {
919 expire_time = ts->expire_time;
923 qemu_put_be64(f, expire_time);
926 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
928 uint64_t expire_time;
930 expire_time = qemu_get_be64(f);
931 if (expire_time != -1) {
932 qemu_mod_timer(ts, expire_time);
938 static void timer_save(QEMUFile *f, void *opaque)
940 if (cpu_ticks_enabled) {
941 hw_error("cannot save state if virtual timers are running");
943 qemu_put_be64s(f, &cpu_ticks_offset);
944 qemu_put_be64s(f, &ticks_per_sec);
945 qemu_put_be64s(f, &cpu_clock_offset);
948 static int timer_load(QEMUFile *f, void *opaque, int version_id)
950 if (version_id != 1 && version_id != 2)
952 if (cpu_ticks_enabled) {
955 qemu_get_be64s(f, &cpu_ticks_offset);
956 qemu_get_be64s(f, &ticks_per_sec);
957 if (version_id == 2) {
958 qemu_get_be64s(f, &cpu_clock_offset);
964 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
965 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
967 static void host_alarm_handler(int host_signum)
971 #define DISP_FREQ 1000
973 static int64_t delta_min = INT64_MAX;
974 static int64_t delta_max, delta_cum, last_clock, delta, ti;
976 ti = qemu_get_clock(vm_clock);
977 if (last_clock != 0) {
978 delta = ti - last_clock;
979 if (delta < delta_min)
981 if (delta > delta_max)
984 if (++count == DISP_FREQ) {
985 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
986 muldiv64(delta_min, 1000000, ticks_per_sec),
987 muldiv64(delta_max, 1000000, ticks_per_sec),
988 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
989 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
991 delta_min = INT64_MAX;
999 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1000 qemu_get_clock(vm_clock)) ||
1001 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1002 qemu_get_clock(rt_clock))) {
1004 SetEvent(host_alarm);
1006 CPUState *env = cpu_single_env;
1008 /* stop the currently executing cpu because a timer occured */
1009 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1011 if (env->kqemu_enabled) {
1012 kqemu_cpu_interrupt(env);
1021 #if defined(__linux__)
1023 #define RTC_FREQ 1024
1027 static int start_rtc_timer(void)
1029 rtc_fd = open("/dev/rtc", O_RDONLY);
1032 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1033 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1034 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1035 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1038 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1043 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1049 static int start_rtc_timer(void)
1054 #endif /* !defined(__linux__) */
1056 #endif /* !defined(_WIN32) */
1058 static void init_timer_alarm(void)
1065 ZeroMemory(&tc, sizeof(TIMECAPS));
1066 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1067 if (period < tc.wPeriodMin)
1068 period = tc.wPeriodMin;
1069 timeBeginPeriod(period);
1070 timerID = timeSetEvent(1, // interval (ms)
1071 period, // resolution
1072 host_alarm_handler, // function
1073 (DWORD)&count, // user parameter
1074 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1076 perror("failed timer alarm");
1079 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1081 perror("failed CreateEvent");
1084 qemu_add_wait_object(host_alarm, NULL, NULL);
1086 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1089 struct sigaction act;
1090 struct itimerval itv;
1092 /* get times() syscall frequency */
1093 timer_freq = sysconf(_SC_CLK_TCK);
1096 sigfillset(&act.sa_mask);
1098 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1099 act.sa_flags |= SA_ONSTACK;
1101 act.sa_handler = host_alarm_handler;
1102 sigaction(SIGALRM, &act, NULL);
1104 itv.it_interval.tv_sec = 0;
1105 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1106 itv.it_value.tv_sec = 0;
1107 itv.it_value.tv_usec = 10 * 1000;
1108 setitimer(ITIMER_REAL, &itv, NULL);
1109 /* we probe the tick duration of the kernel to inform the user if
1110 the emulated kernel requested a too high timer frequency */
1111 getitimer(ITIMER_REAL, &itv);
1113 #if defined(__linux__)
1114 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1115 have timers with 1 ms resolution. The correct solution will
1116 be to use the POSIX real time timers available in recent
1118 if (itv.it_interval.tv_usec > 1000 || 1) {
1119 /* try to use /dev/rtc to have a faster timer */
1120 if (start_rtc_timer() < 0)
1122 /* disable itimer */
1123 itv.it_interval.tv_sec = 0;
1124 itv.it_interval.tv_usec = 0;
1125 itv.it_value.tv_sec = 0;
1126 itv.it_value.tv_usec = 0;
1127 setitimer(ITIMER_REAL, &itv, NULL);
1130 sigaction(SIGIO, &act, NULL);
1131 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1132 fcntl(rtc_fd, F_SETOWN, getpid());
1134 #endif /* defined(__linux__) */
1137 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1138 PIT_FREQ) / 1000000;
1144 void quit_timers(void)
1147 timeKillEvent(timerID);
1148 timeEndPeriod(period);
1150 CloseHandle(host_alarm);
1156 /***********************************************************/
1157 /* character device */
1159 static void qemu_chr_event(CharDriverState *s, int event)
1163 s->chr_event(s->handler_opaque, event);
1166 static void qemu_chr_reset_bh(void *opaque)
1168 CharDriverState *s = opaque;
1169 qemu_chr_event(s, CHR_EVENT_RESET);
1170 qemu_bh_delete(s->bh);
1174 void qemu_chr_reset(CharDriverState *s)
1176 if (s->bh == NULL) {
1177 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1178 qemu_bh_schedule(s->bh);
1182 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1184 return s->chr_write(s, buf, len);
1187 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1191 return s->chr_ioctl(s, cmd, arg);
1194 int qemu_chr_can_read(CharDriverState *s)
1196 if (!s->chr_can_read)
1198 return s->chr_can_read(s->handler_opaque);
1201 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1203 s->chr_read(s->handler_opaque, buf, len);
1207 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1212 vsnprintf(buf, sizeof(buf), fmt, ap);
1213 qemu_chr_write(s, buf, strlen(buf));
1217 void qemu_chr_send_event(CharDriverState *s, int event)
1219 if (s->chr_send_event)
1220 s->chr_send_event(s, event);
1223 void qemu_chr_add_handlers(CharDriverState *s,
1224 IOCanRWHandler *fd_can_read,
1225 IOReadHandler *fd_read,
1226 IOEventHandler *fd_event,
1229 s->chr_can_read = fd_can_read;
1230 s->chr_read = fd_read;
1231 s->chr_event = fd_event;
1232 s->handler_opaque = opaque;
1233 if (s->chr_update_read_handler)
1234 s->chr_update_read_handler(s);
1237 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1242 static CharDriverState *qemu_chr_open_null(void)
1244 CharDriverState *chr;
1246 chr = qemu_mallocz(sizeof(CharDriverState));
1249 chr->chr_write = null_chr_write;
1253 /* MUX driver for serial I/O splitting */
1254 static int term_timestamps;
1255 static int64_t term_timestamps_start;
1258 IOCanRWHandler *chr_can_read[MAX_MUX];
1259 IOReadHandler *chr_read[MAX_MUX];
1260 IOEventHandler *chr_event[MAX_MUX];
1261 void *ext_opaque[MAX_MUX];
1262 CharDriverState *drv;
1264 int term_got_escape;
1269 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1271 MuxDriver *d = chr->opaque;
1273 if (!term_timestamps) {
1274 ret = d->drv->chr_write(d->drv, buf, len);
1279 for(i = 0; i < len; i++) {
1280 ret += d->drv->chr_write(d->drv, buf+i, 1);
1281 if (buf[i] == '\n') {
1287 if (term_timestamps_start == -1)
1288 term_timestamps_start = ti;
1289 ti -= term_timestamps_start;
1290 secs = ti / 1000000000;
1291 snprintf(buf1, sizeof(buf1),
1292 "[%02d:%02d:%02d.%03d] ",
1296 (int)((ti / 1000000) % 1000));
1297 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1304 static char *mux_help[] = {
1305 "% h print this help\n\r",
1306 "% x exit emulator\n\r",
1307 "% s save disk data back to file (if -snapshot)\n\r",
1308 "% t toggle console timestamps\n\r"
1309 "% b send break (magic sysrq)\n\r",
1310 "% c switch between console and monitor\n\r",
1315 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1316 static void mux_print_help(CharDriverState *chr)
1319 char ebuf[15] = "Escape-Char";
1320 char cbuf[50] = "\n\r";
1322 if (term_escape_char > 0 && term_escape_char < 26) {
1323 sprintf(cbuf,"\n\r");
1324 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1326 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1328 chr->chr_write(chr, cbuf, strlen(cbuf));
1329 for (i = 0; mux_help[i] != NULL; i++) {
1330 for (j=0; mux_help[i][j] != '\0'; j++) {
1331 if (mux_help[i][j] == '%')
1332 chr->chr_write(chr, ebuf, strlen(ebuf));
1334 chr->chr_write(chr, &mux_help[i][j], 1);
1339 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1341 if (d->term_got_escape) {
1342 d->term_got_escape = 0;
1343 if (ch == term_escape_char)
1348 mux_print_help(chr);
1352 char *term = "QEMU: Terminated\n\r";
1353 chr->chr_write(chr,term,strlen(term));
1360 for (i = 0; i < MAX_DISKS; i++) {
1362 bdrv_commit(bs_table[i]);
1368 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1371 /* Switch to the next registered device */
1373 if (chr->focus >= d->mux_cnt)
1377 term_timestamps = !term_timestamps;
1378 term_timestamps_start = -1;
1381 } else if (ch == term_escape_char) {
1382 d->term_got_escape = 1;
1390 static int mux_chr_can_read(void *opaque)
1392 CharDriverState *chr = opaque;
1393 MuxDriver *d = chr->opaque;
1394 if (d->chr_can_read[chr->focus])
1395 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1399 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1401 CharDriverState *chr = opaque;
1402 MuxDriver *d = chr->opaque;
1404 for(i = 0; i < size; i++)
1405 if (mux_proc_byte(chr, d, buf[i]))
1406 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1409 static void mux_chr_event(void *opaque, int event)
1411 CharDriverState *chr = opaque;
1412 MuxDriver *d = chr->opaque;
1415 /* Send the event to all registered listeners */
1416 for (i = 0; i < d->mux_cnt; i++)
1417 if (d->chr_event[i])
1418 d->chr_event[i](d->ext_opaque[i], event);
1421 static void mux_chr_update_read_handler(CharDriverState *chr)
1423 MuxDriver *d = chr->opaque;
1425 if (d->mux_cnt >= MAX_MUX) {
1426 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1429 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1430 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1431 d->chr_read[d->mux_cnt] = chr->chr_read;
1432 d->chr_event[d->mux_cnt] = chr->chr_event;
1433 /* Fix up the real driver with mux routines */
1434 if (d->mux_cnt == 0) {
1435 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1436 mux_chr_event, chr);
1438 chr->focus = d->mux_cnt;
1442 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1444 CharDriverState *chr;
1447 chr = qemu_mallocz(sizeof(CharDriverState));
1450 d = qemu_mallocz(sizeof(MuxDriver));
1459 chr->chr_write = mux_chr_write;
1460 chr->chr_update_read_handler = mux_chr_update_read_handler;
1467 static void socket_cleanup(void)
1472 static int socket_init(void)
1477 ret = WSAStartup(MAKEWORD(2,2), &Data);
1479 err = WSAGetLastError();
1480 fprintf(stderr, "WSAStartup: %d\n", err);
1483 atexit(socket_cleanup);
1487 static int send_all(int fd, const uint8_t *buf, int len1)
1493 ret = send(fd, buf, len, 0);
1496 errno = WSAGetLastError();
1497 if (errno != WSAEWOULDBLOCK) {
1500 } else if (ret == 0) {
1510 void socket_set_nonblock(int fd)
1512 unsigned long opt = 1;
1513 ioctlsocket(fd, FIONBIO, &opt);
1518 static int unix_write(int fd, const uint8_t *buf, int len1)
1524 ret = write(fd, buf, len);
1526 if (errno != EINTR && errno != EAGAIN)
1528 } else if (ret == 0) {
1538 static inline int send_all(int fd, const uint8_t *buf, int len1)
1540 return unix_write(fd, buf, len1);
1543 void socket_set_nonblock(int fd)
1545 fcntl(fd, F_SETFL, O_NONBLOCK);
1547 #endif /* !_WIN32 */
1556 #define STDIO_MAX_CLIENTS 1
1557 static int stdio_nb_clients = 0;
1559 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1561 FDCharDriver *s = chr->opaque;
1562 return unix_write(s->fd_out, buf, len);
1565 static int fd_chr_read_poll(void *opaque)
1567 CharDriverState *chr = opaque;
1568 FDCharDriver *s = chr->opaque;
1570 s->max_size = qemu_chr_can_read(chr);
1574 static void fd_chr_read(void *opaque)
1576 CharDriverState *chr = opaque;
1577 FDCharDriver *s = chr->opaque;
1582 if (len > s->max_size)
1586 size = read(s->fd_in, buf, len);
1588 /* FD has been closed. Remove it from the active list. */
1589 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1593 qemu_chr_read(chr, buf, size);
1597 static void fd_chr_update_read_handler(CharDriverState *chr)
1599 FDCharDriver *s = chr->opaque;
1601 if (s->fd_in >= 0) {
1602 if (nographic && s->fd_in == 0) {
1604 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1605 fd_chr_read, NULL, chr);
1610 /* open a character device to a unix fd */
1611 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1613 CharDriverState *chr;
1616 chr = qemu_mallocz(sizeof(CharDriverState));
1619 s = qemu_mallocz(sizeof(FDCharDriver));
1627 chr->chr_write = fd_chr_write;
1628 chr->chr_update_read_handler = fd_chr_update_read_handler;
1630 qemu_chr_reset(chr);
1635 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1639 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1642 return qemu_chr_open_fd(-1, fd_out);
1645 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1648 char filename_in[256], filename_out[256];
1650 snprintf(filename_in, 256, "%s.in", filename);
1651 snprintf(filename_out, 256, "%s.out", filename);
1652 fd_in = open(filename_in, O_RDWR | O_BINARY);
1653 fd_out = open(filename_out, O_RDWR | O_BINARY);
1654 if (fd_in < 0 || fd_out < 0) {
1659 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1663 return qemu_chr_open_fd(fd_in, fd_out);
1667 /* for STDIO, we handle the case where several clients use it
1670 #define TERM_FIFO_MAX_SIZE 1
1672 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1673 static int term_fifo_size;
1675 static int stdio_read_poll(void *opaque)
1677 CharDriverState *chr = opaque;
1679 /* try to flush the queue if needed */
1680 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1681 qemu_chr_read(chr, term_fifo, 1);
1684 /* see if we can absorb more chars */
1685 if (term_fifo_size == 0)
1691 static void stdio_read(void *opaque)
1695 CharDriverState *chr = opaque;
1697 size = read(0, buf, 1);
1699 /* stdin has been closed. Remove it from the active list. */
1700 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1704 if (qemu_chr_can_read(chr) > 0) {
1705 qemu_chr_read(chr, buf, 1);
1706 } else if (term_fifo_size == 0) {
1707 term_fifo[term_fifo_size++] = buf[0];
1712 /* init terminal so that we can grab keys */
1713 static struct termios oldtty;
1714 static int old_fd0_flags;
1716 static void term_exit(void)
1718 tcsetattr (0, TCSANOW, &oldtty);
1719 fcntl(0, F_SETFL, old_fd0_flags);
1722 static void term_init(void)
1726 tcgetattr (0, &tty);
1728 old_fd0_flags = fcntl(0, F_GETFL);
1730 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1731 |INLCR|IGNCR|ICRNL|IXON);
1732 tty.c_oflag |= OPOST;
1733 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1734 /* if graphical mode, we allow Ctrl-C handling */
1736 tty.c_lflag &= ~ISIG;
1737 tty.c_cflag &= ~(CSIZE|PARENB);
1740 tty.c_cc[VTIME] = 0;
1742 tcsetattr (0, TCSANOW, &tty);
1746 fcntl(0, F_SETFL, O_NONBLOCK);
1749 static CharDriverState *qemu_chr_open_stdio(void)
1751 CharDriverState *chr;
1753 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1755 chr = qemu_chr_open_fd(0, 1);
1756 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1763 #if defined(__linux__)
1764 static CharDriverState *qemu_chr_open_pty(void)
1767 char slave_name[1024];
1768 int master_fd, slave_fd;
1770 /* Not satisfying */
1771 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1775 /* Disabling local echo and line-buffered output */
1776 tcgetattr (master_fd, &tty);
1777 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1779 tty.c_cc[VTIME] = 0;
1780 tcsetattr (master_fd, TCSAFLUSH, &tty);
1782 fprintf(stderr, "char device redirected to %s\n", slave_name);
1783 return qemu_chr_open_fd(master_fd, master_fd);
1786 static void tty_serial_init(int fd, int speed,
1787 int parity, int data_bits, int stop_bits)
1793 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1794 speed, parity, data_bits, stop_bits);
1796 tcgetattr (fd, &tty);
1838 cfsetispeed(&tty, spd);
1839 cfsetospeed(&tty, spd);
1841 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1842 |INLCR|IGNCR|ICRNL|IXON);
1843 tty.c_oflag |= OPOST;
1844 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1845 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1866 tty.c_cflag |= PARENB;
1869 tty.c_cflag |= PARENB | PARODD;
1873 tty.c_cflag |= CSTOPB;
1875 tcsetattr (fd, TCSANOW, &tty);
1878 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1880 FDCharDriver *s = chr->opaque;
1883 case CHR_IOCTL_SERIAL_SET_PARAMS:
1885 QEMUSerialSetParams *ssp = arg;
1886 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1887 ssp->data_bits, ssp->stop_bits);
1890 case CHR_IOCTL_SERIAL_SET_BREAK:
1892 int enable = *(int *)arg;
1894 tcsendbreak(s->fd_in, 1);
1903 static CharDriverState *qemu_chr_open_tty(const char *filename)
1905 CharDriverState *chr;
1908 fd = open(filename, O_RDWR | O_NONBLOCK);
1911 fcntl(fd, F_SETFL, O_NONBLOCK);
1912 tty_serial_init(fd, 115200, 'N', 8, 1);
1913 chr = qemu_chr_open_fd(fd, fd);
1916 chr->chr_ioctl = tty_serial_ioctl;
1917 qemu_chr_reset(chr);
1924 } ParallelCharDriver;
1926 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1928 if (s->mode != mode) {
1930 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1937 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1939 ParallelCharDriver *drv = chr->opaque;
1944 case CHR_IOCTL_PP_READ_DATA:
1945 if (ioctl(fd, PPRDATA, &b) < 0)
1947 *(uint8_t *)arg = b;
1949 case CHR_IOCTL_PP_WRITE_DATA:
1950 b = *(uint8_t *)arg;
1951 if (ioctl(fd, PPWDATA, &b) < 0)
1954 case CHR_IOCTL_PP_READ_CONTROL:
1955 if (ioctl(fd, PPRCONTROL, &b) < 0)
1957 /* Linux gives only the lowest bits, and no way to know data
1958 direction! For better compatibility set the fixed upper
1960 *(uint8_t *)arg = b | 0xc0;
1962 case CHR_IOCTL_PP_WRITE_CONTROL:
1963 b = *(uint8_t *)arg;
1964 if (ioctl(fd, PPWCONTROL, &b) < 0)
1967 case CHR_IOCTL_PP_READ_STATUS:
1968 if (ioctl(fd, PPRSTATUS, &b) < 0)
1970 *(uint8_t *)arg = b;
1972 case CHR_IOCTL_PP_EPP_READ_ADDR:
1973 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1974 struct ParallelIOArg *parg = arg;
1975 int n = read(fd, parg->buffer, parg->count);
1976 if (n != parg->count) {
1981 case CHR_IOCTL_PP_EPP_READ:
1982 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1983 struct ParallelIOArg *parg = arg;
1984 int n = read(fd, parg->buffer, parg->count);
1985 if (n != parg->count) {
1990 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1991 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1992 struct ParallelIOArg *parg = arg;
1993 int n = write(fd, parg->buffer, parg->count);
1994 if (n != parg->count) {
1999 case CHR_IOCTL_PP_EPP_WRITE:
2000 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2001 struct ParallelIOArg *parg = arg;
2002 int n = write(fd, parg->buffer, parg->count);
2003 if (n != parg->count) {
2014 static void pp_close(CharDriverState *chr)
2016 ParallelCharDriver *drv = chr->opaque;
2019 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2020 ioctl(fd, PPRELEASE);
2025 static CharDriverState *qemu_chr_open_pp(const char *filename)
2027 CharDriverState *chr;
2028 ParallelCharDriver *drv;
2031 fd = open(filename, O_RDWR);
2035 if (ioctl(fd, PPCLAIM) < 0) {
2040 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2046 drv->mode = IEEE1284_MODE_COMPAT;
2048 chr = qemu_mallocz(sizeof(CharDriverState));
2054 chr->chr_write = null_chr_write;
2055 chr->chr_ioctl = pp_ioctl;
2056 chr->chr_close = pp_close;
2059 qemu_chr_reset(chr);
2065 static CharDriverState *qemu_chr_open_pty(void)
2071 #endif /* !defined(_WIN32) */
2076 HANDLE hcom, hrecv, hsend;
2077 OVERLAPPED orecv, osend;
2082 #define NSENDBUF 2048
2083 #define NRECVBUF 2048
2084 #define MAXCONNECT 1
2085 #define NTIMEOUT 5000
2087 static int win_chr_poll(void *opaque);
2088 static int win_chr_pipe_poll(void *opaque);
2090 static void win_chr_close(CharDriverState *chr)
2092 WinCharState *s = chr->opaque;
2095 CloseHandle(s->hsend);
2099 CloseHandle(s->hrecv);
2103 CloseHandle(s->hcom);
2107 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2109 qemu_del_polling_cb(win_chr_poll, chr);
2112 static int win_chr_init(CharDriverState *chr, const char *filename)
2114 WinCharState *s = chr->opaque;
2116 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2121 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2123 fprintf(stderr, "Failed CreateEvent\n");
2126 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 fprintf(stderr, "Failed CreateEvent\n");
2132 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2133 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2134 if (s->hcom == INVALID_HANDLE_VALUE) {
2135 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2140 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2141 fprintf(stderr, "Failed SetupComm\n");
2145 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2146 size = sizeof(COMMCONFIG);
2147 GetDefaultCommConfig(filename, &comcfg, &size);
2148 comcfg.dcb.DCBlength = sizeof(DCB);
2149 CommConfigDialog(filename, NULL, &comcfg);
2151 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2152 fprintf(stderr, "Failed SetCommState\n");
2156 if (!SetCommMask(s->hcom, EV_ERR)) {
2157 fprintf(stderr, "Failed SetCommMask\n");
2161 cto.ReadIntervalTimeout = MAXDWORD;
2162 if (!SetCommTimeouts(s->hcom, &cto)) {
2163 fprintf(stderr, "Failed SetCommTimeouts\n");
2167 if (!ClearCommError(s->hcom, &err, &comstat)) {
2168 fprintf(stderr, "Failed ClearCommError\n");
2171 qemu_add_polling_cb(win_chr_poll, chr);
2179 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2181 WinCharState *s = chr->opaque;
2182 DWORD len, ret, size, err;
2185 ZeroMemory(&s->osend, sizeof(s->osend));
2186 s->osend.hEvent = s->hsend;
2189 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2191 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2193 err = GetLastError();
2194 if (err == ERROR_IO_PENDING) {
2195 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2213 static int win_chr_read_poll(CharDriverState *chr)
2215 WinCharState *s = chr->opaque;
2217 s->max_size = qemu_chr_can_read(chr);
2221 static void win_chr_readfile(CharDriverState *chr)
2223 WinCharState *s = chr->opaque;
2228 ZeroMemory(&s->orecv, sizeof(s->orecv));
2229 s->orecv.hEvent = s->hrecv;
2230 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2232 err = GetLastError();
2233 if (err == ERROR_IO_PENDING) {
2234 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2239 qemu_chr_read(chr, buf, size);
2243 static void win_chr_read(CharDriverState *chr)
2245 WinCharState *s = chr->opaque;
2247 if (s->len > s->max_size)
2248 s->len = s->max_size;
2252 win_chr_readfile(chr);
2255 static int win_chr_poll(void *opaque)
2257 CharDriverState *chr = opaque;
2258 WinCharState *s = chr->opaque;
2262 ClearCommError(s->hcom, &comerr, &status);
2263 if (status.cbInQue > 0) {
2264 s->len = status.cbInQue;
2265 win_chr_read_poll(chr);
2272 static CharDriverState *qemu_chr_open_win(const char *filename)
2274 CharDriverState *chr;
2277 chr = qemu_mallocz(sizeof(CharDriverState));
2280 s = qemu_mallocz(sizeof(WinCharState));
2286 chr->chr_write = win_chr_write;
2287 chr->chr_close = win_chr_close;
2289 if (win_chr_init(chr, filename) < 0) {
2294 qemu_chr_reset(chr);
2298 static int win_chr_pipe_poll(void *opaque)
2300 CharDriverState *chr = opaque;
2301 WinCharState *s = chr->opaque;
2304 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2307 win_chr_read_poll(chr);
2314 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2316 WinCharState *s = chr->opaque;
2324 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2326 fprintf(stderr, "Failed CreateEvent\n");
2329 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2331 fprintf(stderr, "Failed CreateEvent\n");
2335 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2336 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2337 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2339 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2340 if (s->hcom == INVALID_HANDLE_VALUE) {
2341 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2346 ZeroMemory(&ov, sizeof(ov));
2347 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2348 ret = ConnectNamedPipe(s->hcom, &ov);
2350 fprintf(stderr, "Failed ConnectNamedPipe\n");
2354 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2356 fprintf(stderr, "Failed GetOverlappedResult\n");
2358 CloseHandle(ov.hEvent);
2365 CloseHandle(ov.hEvent);
2368 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2377 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2379 CharDriverState *chr;
2382 chr = qemu_mallocz(sizeof(CharDriverState));
2385 s = qemu_mallocz(sizeof(WinCharState));
2391 chr->chr_write = win_chr_write;
2392 chr->chr_close = win_chr_close;
2394 if (win_chr_pipe_init(chr, filename) < 0) {
2399 qemu_chr_reset(chr);
2403 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2405 CharDriverState *chr;
2408 chr = qemu_mallocz(sizeof(CharDriverState));
2411 s = qemu_mallocz(sizeof(WinCharState));
2418 chr->chr_write = win_chr_write;
2419 qemu_chr_reset(chr);
2423 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2427 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2428 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2429 if (fd_out == INVALID_HANDLE_VALUE)
2432 return qemu_chr_open_win_file(fd_out);
2436 /***********************************************************/
2437 /* UDP Net console */
2441 struct sockaddr_in daddr;
2448 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2450 NetCharDriver *s = chr->opaque;
2452 return sendto(s->fd, buf, len, 0,
2453 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2456 static int udp_chr_read_poll(void *opaque)
2458 CharDriverState *chr = opaque;
2459 NetCharDriver *s = chr->opaque;
2461 s->max_size = qemu_chr_can_read(chr);
2463 /* If there were any stray characters in the queue process them
2466 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2467 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2469 s->max_size = qemu_chr_can_read(chr);
2474 static void udp_chr_read(void *opaque)
2476 CharDriverState *chr = opaque;
2477 NetCharDriver *s = chr->opaque;
2479 if (s->max_size == 0)
2481 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2482 s->bufptr = s->bufcnt;
2487 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2488 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2490 s->max_size = qemu_chr_can_read(chr);
2494 static void udp_chr_update_read_handler(CharDriverState *chr)
2496 NetCharDriver *s = chr->opaque;
2499 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2500 udp_chr_read, NULL, chr);
2504 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2506 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2508 int parse_host_src_port(struct sockaddr_in *haddr,
2509 struct sockaddr_in *saddr,
2512 static CharDriverState *qemu_chr_open_udp(const char *def)
2514 CharDriverState *chr = NULL;
2515 NetCharDriver *s = NULL;
2517 struct sockaddr_in saddr;
2519 chr = qemu_mallocz(sizeof(CharDriverState));
2522 s = qemu_mallocz(sizeof(NetCharDriver));
2526 fd = socket(PF_INET, SOCK_DGRAM, 0);
2528 perror("socket(PF_INET, SOCK_DGRAM)");
2532 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2533 printf("Could not parse: %s\n", def);
2537 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2547 chr->chr_write = udp_chr_write;
2548 chr->chr_update_read_handler = udp_chr_update_read_handler;
2561 /***********************************************************/
2562 /* TCP Net console */
2573 static void tcp_chr_accept(void *opaque);
2575 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2577 TCPCharDriver *s = chr->opaque;
2579 return send_all(s->fd, buf, len);
2581 /* XXX: indicate an error ? */
2586 static int tcp_chr_read_poll(void *opaque)
2588 CharDriverState *chr = opaque;
2589 TCPCharDriver *s = chr->opaque;
2592 s->max_size = qemu_chr_can_read(chr);
2597 #define IAC_BREAK 243
2598 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2600 char *buf, int *size)
2602 /* Handle any telnet client's basic IAC options to satisfy char by
2603 * char mode with no echo. All IAC options will be removed from
2604 * the buf and the do_telnetopt variable will be used to track the
2605 * state of the width of the IAC information.
2607 * IAC commands come in sets of 3 bytes with the exception of the
2608 * "IAC BREAK" command and the double IAC.
2614 for (i = 0; i < *size; i++) {
2615 if (s->do_telnetopt > 1) {
2616 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2617 /* Double IAC means send an IAC */
2621 s->do_telnetopt = 1;
2623 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2624 /* Handle IAC break commands by sending a serial break */
2625 qemu_chr_event(chr, CHR_EVENT_BREAK);
2630 if (s->do_telnetopt >= 4) {
2631 s->do_telnetopt = 1;
2634 if ((unsigned char)buf[i] == IAC) {
2635 s->do_telnetopt = 2;
2646 static void tcp_chr_read(void *opaque)
2648 CharDriverState *chr = opaque;
2649 TCPCharDriver *s = chr->opaque;
2653 if (!s->connected || s->max_size <= 0)
2656 if (len > s->max_size)
2658 size = recv(s->fd, buf, len, 0);
2660 /* connection closed */
2662 if (s->listen_fd >= 0) {
2663 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2665 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2668 } else if (size > 0) {
2669 if (s->do_telnetopt)
2670 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2672 qemu_chr_read(chr, buf, size);
2676 static void tcp_chr_connect(void *opaque)
2678 CharDriverState *chr = opaque;
2679 TCPCharDriver *s = chr->opaque;
2682 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2683 tcp_chr_read, NULL, chr);
2684 qemu_chr_reset(chr);
2687 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2688 static void tcp_chr_telnet_init(int fd)
2691 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2692 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2693 send(fd, (char *)buf, 3, 0);
2694 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2695 send(fd, (char *)buf, 3, 0);
2696 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2697 send(fd, (char *)buf, 3, 0);
2698 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2699 send(fd, (char *)buf, 3, 0);
2702 static void socket_set_nodelay(int fd)
2705 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2708 static void tcp_chr_accept(void *opaque)
2710 CharDriverState *chr = opaque;
2711 TCPCharDriver *s = chr->opaque;
2712 struct sockaddr_in saddr;
2714 struct sockaddr_un uaddr;
2716 struct sockaddr *addr;
2723 len = sizeof(uaddr);
2724 addr = (struct sockaddr *)&uaddr;
2728 len = sizeof(saddr);
2729 addr = (struct sockaddr *)&saddr;
2731 fd = accept(s->listen_fd, addr, &len);
2732 if (fd < 0 && errno != EINTR) {
2734 } else if (fd >= 0) {
2735 if (s->do_telnetopt)
2736 tcp_chr_telnet_init(fd);
2740 socket_set_nonblock(fd);
2742 socket_set_nodelay(fd);
2744 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2745 tcp_chr_connect(chr);
2748 static void tcp_chr_close(CharDriverState *chr)
2750 TCPCharDriver *s = chr->opaque;
2753 if (s->listen_fd >= 0)
2754 closesocket(s->listen_fd);
2758 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2762 CharDriverState *chr = NULL;
2763 TCPCharDriver *s = NULL;
2764 int fd = -1, ret, err, val;
2766 int is_waitconnect = 1;
2769 struct sockaddr_in saddr;
2771 struct sockaddr_un uaddr;
2773 struct sockaddr *addr;
2778 addr = (struct sockaddr *)&uaddr;
2779 addrlen = sizeof(uaddr);
2780 if (parse_unix_path(&uaddr, host_str) < 0)
2785 addr = (struct sockaddr *)&saddr;
2786 addrlen = sizeof(saddr);
2787 if (parse_host_port(&saddr, host_str) < 0)
2792 while((ptr = strchr(ptr,','))) {
2794 if (!strncmp(ptr,"server",6)) {
2796 } else if (!strncmp(ptr,"nowait",6)) {
2798 } else if (!strncmp(ptr,"nodelay",6)) {
2801 printf("Unknown option: %s\n", ptr);
2808 chr = qemu_mallocz(sizeof(CharDriverState));
2811 s = qemu_mallocz(sizeof(TCPCharDriver));
2817 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2820 fd = socket(PF_INET, SOCK_STREAM, 0);
2825 if (!is_waitconnect)
2826 socket_set_nonblock(fd);
2831 s->is_unix = is_unix;
2832 s->do_nodelay = do_nodelay && !is_unix;
2835 chr->chr_write = tcp_chr_write;
2836 chr->chr_close = tcp_chr_close;
2839 /* allow fast reuse */
2843 strncpy(path, uaddr.sun_path, 108);
2850 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2853 ret = bind(fd, addr, addrlen);
2857 ret = listen(fd, 0);
2862 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2864 s->do_telnetopt = 1;
2867 ret = connect(fd, addr, addrlen);
2869 err = socket_error();
2870 if (err == EINTR || err == EWOULDBLOCK) {
2871 } else if (err == EINPROGRESS) {
2874 } else if (err == WSAEALREADY) {
2886 socket_set_nodelay(fd);
2888 tcp_chr_connect(chr);
2890 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2893 if (is_listen && is_waitconnect) {
2894 printf("QEMU waiting for connection on: %s\n", host_str);
2895 tcp_chr_accept(chr);
2896 socket_set_nonblock(s->listen_fd);
2908 CharDriverState *qemu_chr_open(const char *filename)
2912 if (!strcmp(filename, "vc")) {
2913 return text_console_init(&display_state);
2914 } else if (!strcmp(filename, "null")) {
2915 return qemu_chr_open_null();
2917 if (strstart(filename, "tcp:", &p)) {
2918 return qemu_chr_open_tcp(p, 0, 0);
2920 if (strstart(filename, "telnet:", &p)) {
2921 return qemu_chr_open_tcp(p, 1, 0);
2923 if (strstart(filename, "udp:", &p)) {
2924 return qemu_chr_open_udp(p);
2926 if (strstart(filename, "mon:", &p)) {
2927 CharDriverState *drv = qemu_chr_open(p);
2929 drv = qemu_chr_open_mux(drv);
2930 monitor_init(drv, !nographic);
2933 printf("Unable to open driver: %s\n", p);
2937 if (strstart(filename, "unix:", &p)) {
2938 return qemu_chr_open_tcp(p, 0, 1);
2939 } else if (strstart(filename, "file:", &p)) {
2940 return qemu_chr_open_file_out(p);
2941 } else if (strstart(filename, "pipe:", &p)) {
2942 return qemu_chr_open_pipe(p);
2943 } else if (!strcmp(filename, "pty")) {
2944 return qemu_chr_open_pty();
2945 } else if (!strcmp(filename, "stdio")) {
2946 return qemu_chr_open_stdio();
2949 #if defined(__linux__)
2950 if (strstart(filename, "/dev/parport", NULL)) {
2951 return qemu_chr_open_pp(filename);
2953 if (strstart(filename, "/dev/", NULL)) {
2954 return qemu_chr_open_tty(filename);
2958 if (strstart(filename, "COM", NULL)) {
2959 return qemu_chr_open_win(filename);
2961 if (strstart(filename, "pipe:", &p)) {
2962 return qemu_chr_open_win_pipe(p);
2964 if (strstart(filename, "file:", &p)) {
2965 return qemu_chr_open_win_file_out(p);
2973 void qemu_chr_close(CharDriverState *chr)
2976 chr->chr_close(chr);
2979 /***********************************************************/
2980 /* network device redirectors */
2982 void hex_dump(FILE *f, const uint8_t *buf, int size)
2986 for(i=0;i<size;i+=16) {
2990 fprintf(f, "%08x ", i);
2993 fprintf(f, " %02x", buf[i+j]);
2998 for(j=0;j<len;j++) {
3000 if (c < ' ' || c > '~')
3002 fprintf(f, "%c", c);
3008 static int parse_macaddr(uint8_t *macaddr, const char *p)
3011 for(i = 0; i < 6; i++) {
3012 macaddr[i] = strtol(p, (char **)&p, 16);
3025 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3030 p1 = strchr(p, sep);
3036 if (len > buf_size - 1)
3038 memcpy(buf, p, len);
3045 int parse_host_src_port(struct sockaddr_in *haddr,
3046 struct sockaddr_in *saddr,
3047 const char *input_str)
3049 char *str = strdup(input_str);
3050 char *host_str = str;
3055 * Chop off any extra arguments at the end of the string which
3056 * would start with a comma, then fill in the src port information
3057 * if it was provided else use the "any address" and "any port".
3059 if ((ptr = strchr(str,',')))
3062 if ((src_str = strchr(input_str,'@'))) {
3067 if (parse_host_port(haddr, host_str) < 0)
3070 if (!src_str || *src_str == '\0')
3073 if (parse_host_port(saddr, src_str) < 0)
3084 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3092 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3094 saddr->sin_family = AF_INET;
3095 if (buf[0] == '\0') {
3096 saddr->sin_addr.s_addr = 0;
3098 if (isdigit(buf[0])) {
3099 if (!inet_aton(buf, &saddr->sin_addr))
3102 if ((he = gethostbyname(buf)) == NULL)
3104 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3107 port = strtol(p, (char **)&r, 0);
3110 saddr->sin_port = htons(port);
3115 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3120 len = MIN(108, strlen(str));
3121 p = strchr(str, ',');
3123 len = MIN(len, p - str);
3125 memset(uaddr, 0, sizeof(*uaddr));
3127 uaddr->sun_family = AF_UNIX;
3128 memcpy(uaddr->sun_path, str, len);
3134 /* find or alloc a new VLAN */
3135 VLANState *qemu_find_vlan(int id)
3137 VLANState **pvlan, *vlan;
3138 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3142 vlan = qemu_mallocz(sizeof(VLANState));
3147 pvlan = &first_vlan;
3148 while (*pvlan != NULL)
3149 pvlan = &(*pvlan)->next;
3154 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3155 IOReadHandler *fd_read,
3156 IOCanRWHandler *fd_can_read,
3159 VLANClientState *vc, **pvc;
3160 vc = qemu_mallocz(sizeof(VLANClientState));
3163 vc->fd_read = fd_read;
3164 vc->fd_can_read = fd_can_read;
3165 vc->opaque = opaque;
3169 pvc = &vlan->first_client;
3170 while (*pvc != NULL)
3171 pvc = &(*pvc)->next;
3176 int qemu_can_send_packet(VLANClientState *vc1)
3178 VLANState *vlan = vc1->vlan;
3179 VLANClientState *vc;
3181 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3183 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3190 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3192 VLANState *vlan = vc1->vlan;
3193 VLANClientState *vc;
3196 printf("vlan %d send:\n", vlan->id);
3197 hex_dump(stdout, buf, size);
3199 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3201 vc->fd_read(vc->opaque, buf, size);
3206 #if defined(CONFIG_SLIRP)
3208 /* slirp network adapter */
3210 static int slirp_inited;
3211 static VLANClientState *slirp_vc;
3213 int slirp_can_output(void)
3215 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3218 void slirp_output(const uint8_t *pkt, int pkt_len)
3221 printf("slirp output:\n");
3222 hex_dump(stdout, pkt, pkt_len);
3226 qemu_send_packet(slirp_vc, pkt, pkt_len);
3229 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3232 printf("slirp input:\n");
3233 hex_dump(stdout, buf, size);
3235 slirp_input(buf, size);
3238 static int net_slirp_init(VLANState *vlan)
3240 if (!slirp_inited) {
3244 slirp_vc = qemu_new_vlan_client(vlan,
3245 slirp_receive, NULL, NULL);
3246 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3250 static void net_slirp_redir(const char *redir_str)
3255 struct in_addr guest_addr;
3256 int host_port, guest_port;
3258 if (!slirp_inited) {
3264 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3266 if (!strcmp(buf, "tcp")) {
3268 } else if (!strcmp(buf, "udp")) {
3274 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3276 host_port = strtol(buf, &r, 0);
3280 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3282 if (buf[0] == '\0') {
3283 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3285 if (!inet_aton(buf, &guest_addr))
3288 guest_port = strtol(p, &r, 0);
3292 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3293 fprintf(stderr, "qemu: could not set up redirection\n");
3298 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3306 static void smb_exit(void)
3310 char filename[1024];
3312 /* erase all the files in the directory */
3313 d = opendir(smb_dir);
3318 if (strcmp(de->d_name, ".") != 0 &&
3319 strcmp(de->d_name, "..") != 0) {
3320 snprintf(filename, sizeof(filename), "%s/%s",
3321 smb_dir, de->d_name);
3329 /* automatic user mode samba server configuration */
3330 void net_slirp_smb(const char *exported_dir)
3332 char smb_conf[1024];
3333 char smb_cmdline[1024];
3336 if (!slirp_inited) {
3341 /* XXX: better tmp dir construction */
3342 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3343 if (mkdir(smb_dir, 0700) < 0) {
3344 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3347 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3349 f = fopen(smb_conf, "w");
3351 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3358 "socket address=127.0.0.1\n"
3359 "pid directory=%s\n"
3360 "lock directory=%s\n"
3361 "log file=%s/log.smbd\n"
3362 "smb passwd file=%s/smbpasswd\n"
3363 "security = share\n"
3378 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3379 SMBD_COMMAND, smb_conf);
3381 slirp_add_exec(0, smb_cmdline, 4, 139);
3384 #endif /* !defined(_WIN32) */
3386 #endif /* CONFIG_SLIRP */
3388 #if !defined(_WIN32)
3390 typedef struct TAPState {
3391 VLANClientState *vc;
3395 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3397 TAPState *s = opaque;
3400 ret = write(s->fd, buf, size);
3401 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3408 static void tap_send(void *opaque)
3410 TAPState *s = opaque;
3417 sbuf.maxlen = sizeof(buf);
3419 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3421 size = read(s->fd, buf, sizeof(buf));
3424 qemu_send_packet(s->vc, buf, size);
3430 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3434 s = qemu_mallocz(sizeof(TAPState));
3438 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3439 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3440 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3445 static int tap_open(char *ifname, int ifname_size)
3451 fd = open("/dev/tap", O_RDWR);
3453 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3458 dev = devname(s.st_rdev, S_IFCHR);
3459 pstrcpy(ifname, ifname_size, dev);
3461 fcntl(fd, F_SETFL, O_NONBLOCK);
3464 #elif defined(__sun__)
3465 #define TUNNEWPPA (('T'<<16) | 0x0001)
3467 * Allocate TAP device, returns opened fd.
3468 * Stores dev name in the first arg(must be large enough).
3470 int tap_alloc(char *dev)
3472 int tap_fd, if_fd, ppa = -1;
3473 static int ip_fd = 0;
3476 static int arp_fd = 0;
3477 int ip_muxid, arp_muxid;
3478 struct strioctl strioc_if, strioc_ppa;
3479 int link_type = I_PLINK;;
3481 char actual_name[32] = "";
3483 memset(&ifr, 0x0, sizeof(ifr));
3487 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3491 /* Check if IP device was opened */
3495 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3496 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3500 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3501 syslog(LOG_ERR, "Can't open /dev/tap");
3505 /* Assign a new PPA and get its unit number. */
3506 strioc_ppa.ic_cmd = TUNNEWPPA;
3507 strioc_ppa.ic_timout = 0;
3508 strioc_ppa.ic_len = sizeof(ppa);
3509 strioc_ppa.ic_dp = (char *)&ppa;
3510 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3511 syslog (LOG_ERR, "Can't assign new interface");
3513 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3514 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3517 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3518 syslog(LOG_ERR, "Can't push IP module");
3522 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3523 syslog(LOG_ERR, "Can't get flags\n");
3525 snprintf (actual_name, 32, "tap%d", ppa);
3526 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3529 /* Assign ppa according to the unit number returned by tun device */
3531 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3532 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3533 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3534 syslog (LOG_ERR, "Can't get flags\n");
3535 /* Push arp module to if_fd */
3536 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3537 syslog (LOG_ERR, "Can't push ARP module (2)");
3539 /* Push arp module to ip_fd */
3540 if (ioctl (ip_fd, I_POP, NULL) < 0)
3541 syslog (LOG_ERR, "I_POP failed\n");
3542 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3543 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3545 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3546 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3548 /* Set ifname to arp */
3549 strioc_if.ic_cmd = SIOCSLIFNAME;
3550 strioc_if.ic_timout = 0;
3551 strioc_if.ic_len = sizeof(ifr);
3552 strioc_if.ic_dp = (char *)𝔦
3553 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3554 syslog (LOG_ERR, "Can't set ifname to arp\n");
3557 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3558 syslog(LOG_ERR, "Can't link TAP device to IP");
3562 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3563 syslog (LOG_ERR, "Can't link TAP device to ARP");
3567 memset(&ifr, 0x0, sizeof(ifr));
3568 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3569 ifr.lifr_ip_muxid = ip_muxid;
3570 ifr.lifr_arp_muxid = arp_muxid;
3572 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3574 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3575 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3576 syslog (LOG_ERR, "Can't set multiplexor id");
3579 sprintf(dev, "tap%d", ppa);
3583 static int tap_open(char *ifname, int ifname_size)
3587 if( (fd = tap_alloc(dev)) < 0 ){
3588 fprintf(stderr, "Cannot allocate TAP device\n");
3591 pstrcpy(ifname, ifname_size, dev);
3592 fcntl(fd, F_SETFL, O_NONBLOCK);
3596 static int tap_open(char *ifname, int ifname_size)
3601 fd = open("/dev/net/tun", O_RDWR);
3603 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3606 memset(&ifr, 0, sizeof(ifr));
3607 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3608 if (ifname[0] != '\0')
3609 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3611 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3612 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3614 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3618 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3619 fcntl(fd, F_SETFL, O_NONBLOCK);
3624 static int net_tap_init(VLANState *vlan, const char *ifname1,
3625 const char *setup_script)
3628 int pid, status, fd;
3633 if (ifname1 != NULL)
3634 pstrcpy(ifname, sizeof(ifname), ifname1);
3637 fd = tap_open(ifname, sizeof(ifname));
3641 if (!setup_script || !strcmp(setup_script, "no"))
3643 if (setup_script[0] != '\0') {
3644 /* try to launch network init script */
3648 int open_max = sysconf (_SC_OPEN_MAX), i;
3649 for (i = 0; i < open_max; i++)
3650 if (i != STDIN_FILENO &&
3651 i != STDOUT_FILENO &&
3652 i != STDERR_FILENO &&
3657 *parg++ = (char *)setup_script;
3660 execv(setup_script, args);
3663 while (waitpid(pid, &status, 0) != pid);
3664 if (!WIFEXITED(status) ||
3665 WEXITSTATUS(status) != 0) {
3666 fprintf(stderr, "%s: could not launch network script\n",
3672 s = net_tap_fd_init(vlan, fd);
3675 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3676 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3680 #endif /* !_WIN32 */
3682 /* network connection */
3683 typedef struct NetSocketState {
3684 VLANClientState *vc;
3686 int state; /* 0 = getting length, 1 = getting data */
3690 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3693 typedef struct NetSocketListenState {
3696 } NetSocketListenState;
3698 /* XXX: we consider we can send the whole packet without blocking */
3699 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3701 NetSocketState *s = opaque;
3705 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3706 send_all(s->fd, buf, size);
3709 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3711 NetSocketState *s = opaque;
3712 sendto(s->fd, buf, size, 0,
3713 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3716 static void net_socket_send(void *opaque)
3718 NetSocketState *s = opaque;
3723 size = recv(s->fd, buf1, sizeof(buf1), 0);
3725 err = socket_error();
3726 if (err != EWOULDBLOCK)
3728 } else if (size == 0) {
3729 /* end of connection */
3731 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3737 /* reassemble a packet from the network */
3743 memcpy(s->buf + s->index, buf, l);
3747 if (s->index == 4) {
3749 s->packet_len = ntohl(*(uint32_t *)s->buf);
3755 l = s->packet_len - s->index;
3758 memcpy(s->buf + s->index, buf, l);
3762 if (s->index >= s->packet_len) {
3763 qemu_send_packet(s->vc, s->buf, s->packet_len);
3772 static void net_socket_send_dgram(void *opaque)
3774 NetSocketState *s = opaque;
3777 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3781 /* end of connection */
3782 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3785 qemu_send_packet(s->vc, s->buf, size);
3788 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3793 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3794 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3795 inet_ntoa(mcastaddr->sin_addr),
3796 (int)ntohl(mcastaddr->sin_addr.s_addr));
3800 fd = socket(PF_INET, SOCK_DGRAM, 0);
3802 perror("socket(PF_INET, SOCK_DGRAM)");
3807 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3808 (const char *)&val, sizeof(val));
3810 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3814 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3820 /* Add host to multicast group */
3821 imr.imr_multiaddr = mcastaddr->sin_addr;
3822 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3824 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3825 (const char *)&imr, sizeof(struct ip_mreq));
3827 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3831 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3833 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3834 (const char *)&val, sizeof(val));
3836 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3840 socket_set_nonblock(fd);
3848 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3851 struct sockaddr_in saddr;
3853 socklen_t saddr_len;
3856 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3857 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3858 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3862 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3864 if (saddr.sin_addr.s_addr==0) {
3865 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3869 /* clone dgram socket */
3870 newfd = net_socket_mcast_create(&saddr);
3872 /* error already reported by net_socket_mcast_create() */
3876 /* clone newfd to fd, close newfd */
3881 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3882 fd, strerror(errno));
3887 s = qemu_mallocz(sizeof(NetSocketState));
3892 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3893 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3895 /* mcast: save bound address as dst */
3896 if (is_connected) s->dgram_dst=saddr;
3898 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3899 "socket: fd=%d (%s mcast=%s:%d)",
3900 fd, is_connected? "cloned" : "",
3901 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3905 static void net_socket_connect(void *opaque)
3907 NetSocketState *s = opaque;
3908 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3911 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3915 s = qemu_mallocz(sizeof(NetSocketState));
3919 s->vc = qemu_new_vlan_client(vlan,
3920 net_socket_receive, NULL, s);
3921 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3922 "socket: fd=%d", fd);
3924 net_socket_connect(s);
3926 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3931 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3934 int so_type=-1, optlen=sizeof(so_type);
3936 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3937 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3942 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3944 return net_socket_fd_init_stream(vlan, fd, is_connected);
3946 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3947 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3948 return net_socket_fd_init_stream(vlan, fd, is_connected);
3953 static void net_socket_accept(void *opaque)
3955 NetSocketListenState *s = opaque;
3957 struct sockaddr_in saddr;
3962 len = sizeof(saddr);
3963 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3964 if (fd < 0 && errno != EINTR) {
3966 } else if (fd >= 0) {
3970 s1 = net_socket_fd_init(s->vlan, fd, 1);
3974 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3975 "socket: connection from %s:%d",
3976 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3980 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3982 NetSocketListenState *s;
3984 struct sockaddr_in saddr;
3986 if (parse_host_port(&saddr, host_str) < 0)
3989 s = qemu_mallocz(sizeof(NetSocketListenState));
3993 fd = socket(PF_INET, SOCK_STREAM, 0);
3998 socket_set_nonblock(fd);
4000 /* allow fast reuse */
4002 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4004 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4009 ret = listen(fd, 0);
4016 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4020 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4023 int fd, connected, ret, err;
4024 struct sockaddr_in saddr;
4026 if (parse_host_port(&saddr, host_str) < 0)
4029 fd = socket(PF_INET, SOCK_STREAM, 0);
4034 socket_set_nonblock(fd);
4038 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4040 err = socket_error();
4041 if (err == EINTR || err == EWOULDBLOCK) {
4042 } else if (err == EINPROGRESS) {
4045 } else if (err == WSAEALREADY) {
4058 s = net_socket_fd_init(vlan, fd, connected);
4061 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4062 "socket: connect to %s:%d",
4063 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4067 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4071 struct sockaddr_in saddr;
4073 if (parse_host_port(&saddr, host_str) < 0)
4077 fd = net_socket_mcast_create(&saddr);
4081 s = net_socket_fd_init(vlan, fd, 0);
4085 s->dgram_dst = saddr;
4087 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4088 "socket: mcast=%s:%d",
4089 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4094 static int get_param_value(char *buf, int buf_size,
4095 const char *tag, const char *str)
4104 while (*p != '\0' && *p != '=') {
4105 if ((q - option) < sizeof(option) - 1)
4113 if (!strcmp(tag, option)) {
4115 while (*p != '\0' && *p != ',') {
4116 if ((q - buf) < buf_size - 1)
4123 while (*p != '\0' && *p != ',') {
4134 static int net_client_init(const char *str)
4145 while (*p != '\0' && *p != ',') {
4146 if ((q - device) < sizeof(device) - 1)
4154 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4155 vlan_id = strtol(buf, NULL, 0);
4157 vlan = qemu_find_vlan(vlan_id);
4159 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4162 if (!strcmp(device, "nic")) {
4166 if (nb_nics >= MAX_NICS) {
4167 fprintf(stderr, "Too Many NICs\n");
4170 nd = &nd_table[nb_nics];
4171 macaddr = nd->macaddr;
4177 macaddr[5] = 0x56 + nb_nics;
4179 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4180 if (parse_macaddr(macaddr, buf) < 0) {
4181 fprintf(stderr, "invalid syntax for ethernet address\n");
4185 if (get_param_value(buf, sizeof(buf), "model", p)) {
4186 nd->model = strdup(buf);
4192 if (!strcmp(device, "none")) {
4193 /* does nothing. It is needed to signal that no network cards
4198 if (!strcmp(device, "user")) {
4199 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4200 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4202 ret = net_slirp_init(vlan);
4206 if (!strcmp(device, "tap")) {
4208 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4209 fprintf(stderr, "tap: no interface name\n");
4212 ret = tap_win32_init(vlan, ifname);
4215 if (!strcmp(device, "tap")) {
4217 char setup_script[1024];
4219 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4220 fd = strtol(buf, NULL, 0);
4222 if (net_tap_fd_init(vlan, fd))
4225 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4228 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4229 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4231 ret = net_tap_init(vlan, ifname, setup_script);
4235 if (!strcmp(device, "socket")) {
4236 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4238 fd = strtol(buf, NULL, 0);
4240 if (net_socket_fd_init(vlan, fd, 1))
4242 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4243 ret = net_socket_listen_init(vlan, buf);
4244 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4245 ret = net_socket_connect_init(vlan, buf);
4246 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4247 ret = net_socket_mcast_init(vlan, buf);
4249 fprintf(stderr, "Unknown socket options: %s\n", p);
4254 fprintf(stderr, "Unknown network device: %s\n", device);
4258 fprintf(stderr, "Could not initialize device '%s'\n", device);
4264 void do_info_network(void)
4267 VLANClientState *vc;
4269 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4270 term_printf("VLAN %d devices:\n", vlan->id);
4271 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4272 term_printf(" %s\n", vc->info_str);
4276 /***********************************************************/
4279 static USBPort *used_usb_ports;
4280 static USBPort *free_usb_ports;
4282 /* ??? Maybe change this to register a hub to keep track of the topology. */
4283 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4284 usb_attachfn attach)
4286 port->opaque = opaque;
4287 port->index = index;
4288 port->attach = attach;
4289 port->next = free_usb_ports;
4290 free_usb_ports = port;
4293 static int usb_device_add(const char *devname)
4299 if (!free_usb_ports)
4302 if (strstart(devname, "host:", &p)) {
4303 dev = usb_host_device_open(p);
4304 } else if (!strcmp(devname, "mouse")) {
4305 dev = usb_mouse_init();
4306 } else if (!strcmp(devname, "tablet")) {
4307 dev = usb_tablet_init();
4308 } else if (strstart(devname, "disk:", &p)) {
4309 dev = usb_msd_init(p);
4316 /* Find a USB port to add the device to. */
4317 port = free_usb_ports;
4321 /* Create a new hub and chain it on. */
4322 free_usb_ports = NULL;
4323 port->next = used_usb_ports;
4324 used_usb_ports = port;
4326 hub = usb_hub_init(VM_USB_HUB_SIZE);
4327 usb_attach(port, hub);
4328 port = free_usb_ports;
4331 free_usb_ports = port->next;
4332 port->next = used_usb_ports;
4333 used_usb_ports = port;
4334 usb_attach(port, dev);
4338 static int usb_device_del(const char *devname)
4346 if (!used_usb_ports)
4349 p = strchr(devname, '.');
4352 bus_num = strtoul(devname, NULL, 0);
4353 addr = strtoul(p + 1, NULL, 0);
4357 lastp = &used_usb_ports;
4358 port = used_usb_ports;
4359 while (port && port->dev->addr != addr) {
4360 lastp = &port->next;
4368 *lastp = port->next;
4369 usb_attach(port, NULL);
4370 dev->handle_destroy(dev);
4371 port->next = free_usb_ports;
4372 free_usb_ports = port;
4376 void do_usb_add(const char *devname)
4379 ret = usb_device_add(devname);
4381 term_printf("Could not add USB device '%s'\n", devname);
4384 void do_usb_del(const char *devname)
4387 ret = usb_device_del(devname);
4389 term_printf("Could not remove USB device '%s'\n", devname);
4396 const char *speed_str;
4399 term_printf("USB support not enabled\n");
4403 for (port = used_usb_ports; port; port = port->next) {
4407 switch(dev->speed) {
4411 case USB_SPEED_FULL:
4414 case USB_SPEED_HIGH:
4421 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4422 0, dev->addr, speed_str, dev->devname);
4426 /***********************************************************/
4427 /* PCMCIA/Cardbus */
4429 static struct pcmcia_socket_entry_s {
4430 struct pcmcia_socket_s *socket;
4431 struct pcmcia_socket_entry_s *next;
4432 } *pcmcia_sockets = 0;
4434 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4436 struct pcmcia_socket_entry_s *entry;
4438 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4439 entry->socket = socket;
4440 entry->next = pcmcia_sockets;
4441 pcmcia_sockets = entry;
4444 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4446 struct pcmcia_socket_entry_s *entry, **ptr;
4448 ptr = &pcmcia_sockets;
4449 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4450 if (entry->socket == socket) {
4456 void pcmcia_info(void)
4458 struct pcmcia_socket_entry_s *iter;
4459 if (!pcmcia_sockets)
4460 term_printf("No PCMCIA sockets\n");
4462 for (iter = pcmcia_sockets; iter; iter = iter->next)
4463 term_printf("%s: %s\n", iter->socket->slot_string,
4464 iter->socket->attached ? iter->socket->card_string :
4468 /***********************************************************/
4471 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4475 static void dumb_resize(DisplayState *ds, int w, int h)
4479 static void dumb_refresh(DisplayState *ds)
4484 void dumb_display_init(DisplayState *ds)
4489 ds->dpy_update = dumb_update;
4490 ds->dpy_resize = dumb_resize;
4491 ds->dpy_refresh = dumb_refresh;
4494 /***********************************************************/
4497 #define MAX_IO_HANDLERS 64
4499 typedef struct IOHandlerRecord {
4501 IOCanRWHandler *fd_read_poll;
4503 IOHandler *fd_write;
4506 /* temporary data */
4508 struct IOHandlerRecord *next;
4511 static IOHandlerRecord *first_io_handler;
4513 /* XXX: fd_read_poll should be suppressed, but an API change is
4514 necessary in the character devices to suppress fd_can_read(). */
4515 int qemu_set_fd_handler2(int fd,
4516 IOCanRWHandler *fd_read_poll,
4518 IOHandler *fd_write,
4521 IOHandlerRecord **pioh, *ioh;
4523 if (!fd_read && !fd_write) {
4524 pioh = &first_io_handler;
4529 if (ioh->fd == fd) {
4536 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4540 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4543 ioh->next = first_io_handler;
4544 first_io_handler = ioh;
4547 ioh->fd_read_poll = fd_read_poll;
4548 ioh->fd_read = fd_read;
4549 ioh->fd_write = fd_write;
4550 ioh->opaque = opaque;
4556 int qemu_set_fd_handler(int fd,
4558 IOHandler *fd_write,
4561 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4564 /***********************************************************/
4565 /* Polling handling */
4567 typedef struct PollingEntry {
4570 struct PollingEntry *next;
4573 static PollingEntry *first_polling_entry;
4575 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4577 PollingEntry **ppe, *pe;
4578 pe = qemu_mallocz(sizeof(PollingEntry));
4582 pe->opaque = opaque;
4583 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4588 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4590 PollingEntry **ppe, *pe;
4591 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4593 if (pe->func == func && pe->opaque == opaque) {
4602 /***********************************************************/
4603 /* Wait objects support */
4604 typedef struct WaitObjects {
4606 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4607 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4608 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4611 static WaitObjects wait_objects = {0};
4613 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4615 WaitObjects *w = &wait_objects;
4617 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4619 w->events[w->num] = handle;
4620 w->func[w->num] = func;
4621 w->opaque[w->num] = opaque;
4626 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4629 WaitObjects *w = &wait_objects;
4632 for (i = 0; i < w->num; i++) {
4633 if (w->events[i] == handle)
4636 w->events[i] = w->events[i + 1];
4637 w->func[i] = w->func[i + 1];
4638 w->opaque[i] = w->opaque[i + 1];
4646 /***********************************************************/
4647 /* savevm/loadvm support */
4649 #define IO_BUF_SIZE 32768
4653 BlockDriverState *bs;
4656 int64_t base_offset;
4657 int64_t buf_offset; /* start of buffer when writing, end of buffer
4660 int buf_size; /* 0 when writing */
4661 uint8_t buf[IO_BUF_SIZE];
4664 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4668 f = qemu_mallocz(sizeof(QEMUFile));
4671 if (!strcmp(mode, "wb")) {
4673 } else if (!strcmp(mode, "rb")) {
4678 f->outfile = fopen(filename, mode);
4690 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4694 f = qemu_mallocz(sizeof(QEMUFile));
4699 f->is_writable = is_writable;
4700 f->base_offset = offset;
4704 void qemu_fflush(QEMUFile *f)
4706 if (!f->is_writable)
4708 if (f->buf_index > 0) {
4710 fseek(f->outfile, f->buf_offset, SEEK_SET);
4711 fwrite(f->buf, 1, f->buf_index, f->outfile);
4713 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4714 f->buf, f->buf_index);
4716 f->buf_offset += f->buf_index;
4721 static void qemu_fill_buffer(QEMUFile *f)
4728 fseek(f->outfile, f->buf_offset, SEEK_SET);
4729 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4733 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4734 f->buf, IO_BUF_SIZE);
4740 f->buf_offset += len;
4743 void qemu_fclose(QEMUFile *f)
4753 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4757 l = IO_BUF_SIZE - f->buf_index;
4760 memcpy(f->buf + f->buf_index, buf, l);
4764 if (f->buf_index >= IO_BUF_SIZE)
4769 void qemu_put_byte(QEMUFile *f, int v)
4771 f->buf[f->buf_index++] = v;
4772 if (f->buf_index >= IO_BUF_SIZE)
4776 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4782 l = f->buf_size - f->buf_index;
4784 qemu_fill_buffer(f);
4785 l = f->buf_size - f->buf_index;
4791 memcpy(buf, f->buf + f->buf_index, l);
4796 return size1 - size;
4799 int qemu_get_byte(QEMUFile *f)
4801 if (f->buf_index >= f->buf_size) {
4802 qemu_fill_buffer(f);
4803 if (f->buf_index >= f->buf_size)
4806 return f->buf[f->buf_index++];
4809 int64_t qemu_ftell(QEMUFile *f)
4811 return f->buf_offset - f->buf_size + f->buf_index;
4814 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4816 if (whence == SEEK_SET) {
4818 } else if (whence == SEEK_CUR) {
4819 pos += qemu_ftell(f);
4821 /* SEEK_END not supported */
4824 if (f->is_writable) {
4826 f->buf_offset = pos;
4828 f->buf_offset = pos;
4835 void qemu_put_be16(QEMUFile *f, unsigned int v)
4837 qemu_put_byte(f, v >> 8);
4838 qemu_put_byte(f, v);
4841 void qemu_put_be32(QEMUFile *f, unsigned int v)
4843 qemu_put_byte(f, v >> 24);
4844 qemu_put_byte(f, v >> 16);
4845 qemu_put_byte(f, v >> 8);
4846 qemu_put_byte(f, v);
4849 void qemu_put_be64(QEMUFile *f, uint64_t v)
4851 qemu_put_be32(f, v >> 32);
4852 qemu_put_be32(f, v);
4855 unsigned int qemu_get_be16(QEMUFile *f)
4858 v = qemu_get_byte(f) << 8;
4859 v |= qemu_get_byte(f);
4863 unsigned int qemu_get_be32(QEMUFile *f)
4866 v = qemu_get_byte(f) << 24;
4867 v |= qemu_get_byte(f) << 16;
4868 v |= qemu_get_byte(f) << 8;
4869 v |= qemu_get_byte(f);
4873 uint64_t qemu_get_be64(QEMUFile *f)
4876 v = (uint64_t)qemu_get_be32(f) << 32;
4877 v |= qemu_get_be32(f);
4881 typedef struct SaveStateEntry {
4885 SaveStateHandler *save_state;
4886 LoadStateHandler *load_state;
4888 struct SaveStateEntry *next;
4891 static SaveStateEntry *first_se;
4893 int register_savevm(const char *idstr,
4896 SaveStateHandler *save_state,
4897 LoadStateHandler *load_state,
4900 SaveStateEntry *se, **pse;
4902 se = qemu_malloc(sizeof(SaveStateEntry));
4905 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4906 se->instance_id = instance_id;
4907 se->version_id = version_id;
4908 se->save_state = save_state;
4909 se->load_state = load_state;
4910 se->opaque = opaque;
4913 /* add at the end of list */
4915 while (*pse != NULL)
4916 pse = &(*pse)->next;
4921 #define QEMU_VM_FILE_MAGIC 0x5145564d
4922 #define QEMU_VM_FILE_VERSION 0x00000002
4924 int qemu_savevm_state(QEMUFile *f)
4928 int64_t cur_pos, len_pos, total_len_pos;
4930 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4931 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4932 total_len_pos = qemu_ftell(f);
4933 qemu_put_be64(f, 0); /* total size */
4935 for(se = first_se; se != NULL; se = se->next) {
4937 len = strlen(se->idstr);
4938 qemu_put_byte(f, len);
4939 qemu_put_buffer(f, se->idstr, len);
4941 qemu_put_be32(f, se->instance_id);
4942 qemu_put_be32(f, se->version_id);
4944 /* record size: filled later */
4945 len_pos = qemu_ftell(f);
4946 qemu_put_be32(f, 0);
4948 se->save_state(f, se->opaque);
4950 /* fill record size */
4951 cur_pos = qemu_ftell(f);
4952 len = cur_pos - len_pos - 4;
4953 qemu_fseek(f, len_pos, SEEK_SET);
4954 qemu_put_be32(f, len);
4955 qemu_fseek(f, cur_pos, SEEK_SET);
4957 cur_pos = qemu_ftell(f);
4958 qemu_fseek(f, total_len_pos, SEEK_SET);
4959 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4960 qemu_fseek(f, cur_pos, SEEK_SET);
4966 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4970 for(se = first_se; se != NULL; se = se->next) {
4971 if (!strcmp(se->idstr, idstr) &&
4972 instance_id == se->instance_id)
4978 int qemu_loadvm_state(QEMUFile *f)
4981 int len, ret, instance_id, record_len, version_id;
4982 int64_t total_len, end_pos, cur_pos;
4986 v = qemu_get_be32(f);
4987 if (v != QEMU_VM_FILE_MAGIC)
4989 v = qemu_get_be32(f);
4990 if (v != QEMU_VM_FILE_VERSION) {
4995 total_len = qemu_get_be64(f);
4996 end_pos = total_len + qemu_ftell(f);
4998 if (qemu_ftell(f) >= end_pos)
5000 len = qemu_get_byte(f);
5001 qemu_get_buffer(f, idstr, len);
5003 instance_id = qemu_get_be32(f);
5004 version_id = qemu_get_be32(f);
5005 record_len = qemu_get_be32(f);
5007 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5008 idstr, instance_id, version_id, record_len);
5010 cur_pos = qemu_ftell(f);
5011 se = find_se(idstr, instance_id);
5013 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5014 instance_id, idstr);
5016 ret = se->load_state(f, se->opaque, version_id);
5018 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5019 instance_id, idstr);
5022 /* always seek to exact end of record */
5023 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5030 /* device can contain snapshots */
5031 static int bdrv_can_snapshot(BlockDriverState *bs)
5034 !bdrv_is_removable(bs) &&
5035 !bdrv_is_read_only(bs));
5038 /* device must be snapshots in order to have a reliable snapshot */
5039 static int bdrv_has_snapshot(BlockDriverState *bs)
5042 !bdrv_is_removable(bs) &&
5043 !bdrv_is_read_only(bs));
5046 static BlockDriverState *get_bs_snapshots(void)
5048 BlockDriverState *bs;
5052 return bs_snapshots;
5053 for(i = 0; i <= MAX_DISKS; i++) {
5055 if (bdrv_can_snapshot(bs))
5064 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5067 QEMUSnapshotInfo *sn_tab, *sn;
5071 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5074 for(i = 0; i < nb_sns; i++) {
5076 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5086 void do_savevm(const char *name)
5088 BlockDriverState *bs, *bs1;
5089 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5090 int must_delete, ret, i;
5091 BlockDriverInfo bdi1, *bdi = &bdi1;
5093 int saved_vm_running;
5100 bs = get_bs_snapshots();
5102 term_printf("No block device can accept snapshots\n");
5106 /* ??? Should this occur after vm_stop? */
5109 saved_vm_running = vm_running;
5114 ret = bdrv_snapshot_find(bs, old_sn, name);
5119 memset(sn, 0, sizeof(*sn));
5121 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5122 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5125 pstrcpy(sn->name, sizeof(sn->name), name);
5128 /* fill auxiliary fields */
5131 sn->date_sec = tb.time;
5132 sn->date_nsec = tb.millitm * 1000000;
5134 gettimeofday(&tv, NULL);
5135 sn->date_sec = tv.tv_sec;
5136 sn->date_nsec = tv.tv_usec * 1000;
5138 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5140 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5141 term_printf("Device %s does not support VM state snapshots\n",
5142 bdrv_get_device_name(bs));
5146 /* save the VM state */
5147 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5149 term_printf("Could not open VM state file\n");
5152 ret = qemu_savevm_state(f);
5153 sn->vm_state_size = qemu_ftell(f);
5156 term_printf("Error %d while writing VM\n", ret);
5160 /* create the snapshots */
5162 for(i = 0; i < MAX_DISKS; i++) {
5164 if (bdrv_has_snapshot(bs1)) {
5166 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5168 term_printf("Error while deleting snapshot on '%s'\n",
5169 bdrv_get_device_name(bs1));
5172 ret = bdrv_snapshot_create(bs1, sn);
5174 term_printf("Error while creating snapshot on '%s'\n",
5175 bdrv_get_device_name(bs1));
5181 if (saved_vm_running)
5185 void do_loadvm(const char *name)
5187 BlockDriverState *bs, *bs1;
5188 BlockDriverInfo bdi1, *bdi = &bdi1;
5191 int saved_vm_running;
5193 bs = get_bs_snapshots();
5195 term_printf("No block device supports snapshots\n");
5199 /* Flush all IO requests so they don't interfere with the new state. */
5202 saved_vm_running = vm_running;
5205 for(i = 0; i <= MAX_DISKS; i++) {
5207 if (bdrv_has_snapshot(bs1)) {
5208 ret = bdrv_snapshot_goto(bs1, name);
5211 term_printf("Warning: ");
5214 term_printf("Snapshots not supported on device '%s'\n",
5215 bdrv_get_device_name(bs1));
5218 term_printf("Could not find snapshot '%s' on device '%s'\n",
5219 name, bdrv_get_device_name(bs1));
5222 term_printf("Error %d while activating snapshot on '%s'\n",
5223 ret, bdrv_get_device_name(bs1));
5226 /* fatal on snapshot block device */
5233 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5234 term_printf("Device %s does not support VM state snapshots\n",
5235 bdrv_get_device_name(bs));
5239 /* restore the VM state */
5240 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5242 term_printf("Could not open VM state file\n");
5245 ret = qemu_loadvm_state(f);
5248 term_printf("Error %d while loading VM state\n", ret);
5251 if (saved_vm_running)
5255 void do_delvm(const char *name)
5257 BlockDriverState *bs, *bs1;
5260 bs = get_bs_snapshots();
5262 term_printf("No block device supports snapshots\n");
5266 for(i = 0; i <= MAX_DISKS; i++) {
5268 if (bdrv_has_snapshot(bs1)) {
5269 ret = bdrv_snapshot_delete(bs1, name);
5271 if (ret == -ENOTSUP)
5272 term_printf("Snapshots not supported on device '%s'\n",
5273 bdrv_get_device_name(bs1));
5275 term_printf("Error %d while deleting snapshot on '%s'\n",
5276 ret, bdrv_get_device_name(bs1));
5282 void do_info_snapshots(void)
5284 BlockDriverState *bs, *bs1;
5285 QEMUSnapshotInfo *sn_tab, *sn;
5289 bs = get_bs_snapshots();
5291 term_printf("No available block device supports snapshots\n");
5294 term_printf("Snapshot devices:");
5295 for(i = 0; i <= MAX_DISKS; i++) {
5297 if (bdrv_has_snapshot(bs1)) {
5299 term_printf(" %s", bdrv_get_device_name(bs1));
5304 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5306 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5309 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5310 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5311 for(i = 0; i < nb_sns; i++) {
5313 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5318 /***********************************************************/
5319 /* cpu save/restore */
5321 #if defined(TARGET_I386)
5323 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5325 qemu_put_be32(f, dt->selector);
5326 qemu_put_betl(f, dt->base);
5327 qemu_put_be32(f, dt->limit);
5328 qemu_put_be32(f, dt->flags);
5331 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5333 dt->selector = qemu_get_be32(f);
5334 dt->base = qemu_get_betl(f);
5335 dt->limit = qemu_get_be32(f);
5336 dt->flags = qemu_get_be32(f);
5339 void cpu_save(QEMUFile *f, void *opaque)
5341 CPUState *env = opaque;
5342 uint16_t fptag, fpus, fpuc, fpregs_format;
5346 for(i = 0; i < CPU_NB_REGS; i++)
5347 qemu_put_betls(f, &env->regs[i]);
5348 qemu_put_betls(f, &env->eip);
5349 qemu_put_betls(f, &env->eflags);
5350 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5351 qemu_put_be32s(f, &hflags);
5355 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5357 for(i = 0; i < 8; i++) {
5358 fptag |= ((!env->fptags[i]) << i);
5361 qemu_put_be16s(f, &fpuc);
5362 qemu_put_be16s(f, &fpus);
5363 qemu_put_be16s(f, &fptag);
5365 #ifdef USE_X86LDOUBLE
5370 qemu_put_be16s(f, &fpregs_format);
5372 for(i = 0; i < 8; i++) {
5373 #ifdef USE_X86LDOUBLE
5377 /* we save the real CPU data (in case of MMX usage only 'mant'
5378 contains the MMX register */
5379 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5380 qemu_put_be64(f, mant);
5381 qemu_put_be16(f, exp);
5384 /* if we use doubles for float emulation, we save the doubles to
5385 avoid losing information in case of MMX usage. It can give
5386 problems if the image is restored on a CPU where long
5387 doubles are used instead. */
5388 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5392 for(i = 0; i < 6; i++)
5393 cpu_put_seg(f, &env->segs[i]);
5394 cpu_put_seg(f, &env->ldt);
5395 cpu_put_seg(f, &env->tr);
5396 cpu_put_seg(f, &env->gdt);
5397 cpu_put_seg(f, &env->idt);
5399 qemu_put_be32s(f, &env->sysenter_cs);
5400 qemu_put_be32s(f, &env->sysenter_esp);
5401 qemu_put_be32s(f, &env->sysenter_eip);
5403 qemu_put_betls(f, &env->cr[0]);
5404 qemu_put_betls(f, &env->cr[2]);
5405 qemu_put_betls(f, &env->cr[3]);
5406 qemu_put_betls(f, &env->cr[4]);
5408 for(i = 0; i < 8; i++)
5409 qemu_put_betls(f, &env->dr[i]);
5412 qemu_put_be32s(f, &env->a20_mask);
5415 qemu_put_be32s(f, &env->mxcsr);
5416 for(i = 0; i < CPU_NB_REGS; i++) {
5417 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5418 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5421 #ifdef TARGET_X86_64
5422 qemu_put_be64s(f, &env->efer);
5423 qemu_put_be64s(f, &env->star);
5424 qemu_put_be64s(f, &env->lstar);
5425 qemu_put_be64s(f, &env->cstar);
5426 qemu_put_be64s(f, &env->fmask);
5427 qemu_put_be64s(f, &env->kernelgsbase);
5429 qemu_put_be32s(f, &env->smbase);
5432 #ifdef USE_X86LDOUBLE
5433 /* XXX: add that in a FPU generic layer */
5434 union x86_longdouble {
5439 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5440 #define EXPBIAS1 1023
5441 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5442 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5444 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5448 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5449 /* exponent + sign */
5450 e = EXPD1(temp) - EXPBIAS1 + 16383;
5451 e |= SIGND1(temp) >> 16;
5456 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5458 CPUState *env = opaque;
5461 uint16_t fpus, fpuc, fptag, fpregs_format;
5463 if (version_id != 3 && version_id != 4)
5465 for(i = 0; i < CPU_NB_REGS; i++)
5466 qemu_get_betls(f, &env->regs[i]);
5467 qemu_get_betls(f, &env->eip);
5468 qemu_get_betls(f, &env->eflags);
5469 qemu_get_be32s(f, &hflags);
5471 qemu_get_be16s(f, &fpuc);
5472 qemu_get_be16s(f, &fpus);
5473 qemu_get_be16s(f, &fptag);
5474 qemu_get_be16s(f, &fpregs_format);
5476 /* NOTE: we cannot always restore the FPU state if the image come
5477 from a host with a different 'USE_X86LDOUBLE' define. We guess
5478 if we are in an MMX state to restore correctly in that case. */
5479 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5480 for(i = 0; i < 8; i++) {
5484 switch(fpregs_format) {
5486 mant = qemu_get_be64(f);
5487 exp = qemu_get_be16(f);
5488 #ifdef USE_X86LDOUBLE
5489 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5491 /* difficult case */
5493 env->fpregs[i].mmx.MMX_Q(0) = mant;
5495 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5499 mant = qemu_get_be64(f);
5500 #ifdef USE_X86LDOUBLE
5502 union x86_longdouble *p;
5503 /* difficult case */
5504 p = (void *)&env->fpregs[i];
5509 fp64_to_fp80(p, mant);
5513 env->fpregs[i].mmx.MMX_Q(0) = mant;
5522 /* XXX: restore FPU round state */
5523 env->fpstt = (fpus >> 11) & 7;
5524 env->fpus = fpus & ~0x3800;
5526 for(i = 0; i < 8; i++) {
5527 env->fptags[i] = (fptag >> i) & 1;
5530 for(i = 0; i < 6; i++)
5531 cpu_get_seg(f, &env->segs[i]);
5532 cpu_get_seg(f, &env->ldt);
5533 cpu_get_seg(f, &env->tr);
5534 cpu_get_seg(f, &env->gdt);
5535 cpu_get_seg(f, &env->idt);
5537 qemu_get_be32s(f, &env->sysenter_cs);
5538 qemu_get_be32s(f, &env->sysenter_esp);
5539 qemu_get_be32s(f, &env->sysenter_eip);
5541 qemu_get_betls(f, &env->cr[0]);
5542 qemu_get_betls(f, &env->cr[2]);
5543 qemu_get_betls(f, &env->cr[3]);
5544 qemu_get_betls(f, &env->cr[4]);
5546 for(i = 0; i < 8; i++)
5547 qemu_get_betls(f, &env->dr[i]);
5550 qemu_get_be32s(f, &env->a20_mask);
5552 qemu_get_be32s(f, &env->mxcsr);
5553 for(i = 0; i < CPU_NB_REGS; i++) {
5554 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5555 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5558 #ifdef TARGET_X86_64
5559 qemu_get_be64s(f, &env->efer);
5560 qemu_get_be64s(f, &env->star);
5561 qemu_get_be64s(f, &env->lstar);
5562 qemu_get_be64s(f, &env->cstar);
5563 qemu_get_be64s(f, &env->fmask);
5564 qemu_get_be64s(f, &env->kernelgsbase);
5566 if (version_id >= 4)
5567 qemu_get_be32s(f, &env->smbase);
5569 /* XXX: compute hflags from scratch, except for CPL and IIF */
5570 env->hflags = hflags;
5575 #elif defined(TARGET_PPC)
5576 void cpu_save(QEMUFile *f, void *opaque)
5580 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5585 #elif defined(TARGET_MIPS)
5586 void cpu_save(QEMUFile *f, void *opaque)
5590 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5595 #elif defined(TARGET_SPARC)
5596 void cpu_save(QEMUFile *f, void *opaque)
5598 CPUState *env = opaque;
5602 for(i = 0; i < 8; i++)
5603 qemu_put_betls(f, &env->gregs[i]);
5604 for(i = 0; i < NWINDOWS * 16; i++)
5605 qemu_put_betls(f, &env->regbase[i]);
5608 for(i = 0; i < TARGET_FPREGS; i++) {
5614 qemu_put_be32(f, u.i);
5617 qemu_put_betls(f, &env->pc);
5618 qemu_put_betls(f, &env->npc);
5619 qemu_put_betls(f, &env->y);
5621 qemu_put_be32(f, tmp);
5622 qemu_put_betls(f, &env->fsr);
5623 qemu_put_betls(f, &env->tbr);
5624 #ifndef TARGET_SPARC64
5625 qemu_put_be32s(f, &env->wim);
5627 for(i = 0; i < 16; i++)
5628 qemu_put_be32s(f, &env->mmuregs[i]);
5632 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5634 CPUState *env = opaque;
5638 for(i = 0; i < 8; i++)
5639 qemu_get_betls(f, &env->gregs[i]);
5640 for(i = 0; i < NWINDOWS * 16; i++)
5641 qemu_get_betls(f, &env->regbase[i]);
5644 for(i = 0; i < TARGET_FPREGS; i++) {
5649 u.i = qemu_get_be32(f);
5653 qemu_get_betls(f, &env->pc);
5654 qemu_get_betls(f, &env->npc);
5655 qemu_get_betls(f, &env->y);
5656 tmp = qemu_get_be32(f);
5657 env->cwp = 0; /* needed to ensure that the wrapping registers are
5658 correctly updated */
5660 qemu_get_betls(f, &env->fsr);
5661 qemu_get_betls(f, &env->tbr);
5662 #ifndef TARGET_SPARC64
5663 qemu_get_be32s(f, &env->wim);
5665 for(i = 0; i < 16; i++)
5666 qemu_get_be32s(f, &env->mmuregs[i]);
5672 #elif defined(TARGET_ARM)
5674 /* ??? Need to implement these. */
5675 void cpu_save(QEMUFile *f, void *opaque)
5679 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5686 #warning No CPU save/restore functions
5690 /***********************************************************/
5691 /* ram save/restore */
5693 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5697 v = qemu_get_byte(f);
5700 if (qemu_get_buffer(f, buf, len) != len)
5704 v = qemu_get_byte(f);
5705 memset(buf, v, len);
5713 static int ram_load_v1(QEMUFile *f, void *opaque)
5717 if (qemu_get_be32(f) != phys_ram_size)
5719 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5720 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5727 #define BDRV_HASH_BLOCK_SIZE 1024
5728 #define IOBUF_SIZE 4096
5729 #define RAM_CBLOCK_MAGIC 0xfabe
5731 typedef struct RamCompressState {
5734 uint8_t buf[IOBUF_SIZE];
5737 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5740 memset(s, 0, sizeof(*s));
5742 ret = deflateInit2(&s->zstream, 1,
5744 9, Z_DEFAULT_STRATEGY);
5747 s->zstream.avail_out = IOBUF_SIZE;
5748 s->zstream.next_out = s->buf;
5752 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5754 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5755 qemu_put_be16(s->f, len);
5756 qemu_put_buffer(s->f, buf, len);
5759 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5763 s->zstream.avail_in = len;
5764 s->zstream.next_in = (uint8_t *)buf;
5765 while (s->zstream.avail_in > 0) {
5766 ret = deflate(&s->zstream, Z_NO_FLUSH);
5769 if (s->zstream.avail_out == 0) {
5770 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5771 s->zstream.avail_out = IOBUF_SIZE;
5772 s->zstream.next_out = s->buf;
5778 static void ram_compress_close(RamCompressState *s)
5782 /* compress last bytes */
5784 ret = deflate(&s->zstream, Z_FINISH);
5785 if (ret == Z_OK || ret == Z_STREAM_END) {
5786 len = IOBUF_SIZE - s->zstream.avail_out;
5788 ram_put_cblock(s, s->buf, len);
5790 s->zstream.avail_out = IOBUF_SIZE;
5791 s->zstream.next_out = s->buf;
5792 if (ret == Z_STREAM_END)
5799 deflateEnd(&s->zstream);
5802 typedef struct RamDecompressState {
5805 uint8_t buf[IOBUF_SIZE];
5806 } RamDecompressState;
5808 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5811 memset(s, 0, sizeof(*s));
5813 ret = inflateInit(&s->zstream);
5819 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5823 s->zstream.avail_out = len;
5824 s->zstream.next_out = buf;
5825 while (s->zstream.avail_out > 0) {
5826 if (s->zstream.avail_in == 0) {
5827 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5829 clen = qemu_get_be16(s->f);
5830 if (clen > IOBUF_SIZE)
5832 qemu_get_buffer(s->f, s->buf, clen);
5833 s->zstream.avail_in = clen;
5834 s->zstream.next_in = s->buf;
5836 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5837 if (ret != Z_OK && ret != Z_STREAM_END) {
5844 static void ram_decompress_close(RamDecompressState *s)
5846 inflateEnd(&s->zstream);
5849 static void ram_save(QEMUFile *f, void *opaque)
5852 RamCompressState s1, *s = &s1;
5855 qemu_put_be32(f, phys_ram_size);
5856 if (ram_compress_open(s, f) < 0)
5858 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5860 if (tight_savevm_enabled) {
5864 /* find if the memory block is available on a virtual
5867 for(j = 0; j < MAX_DISKS; j++) {
5869 sector_num = bdrv_hash_find(bs_table[j],
5870 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5871 if (sector_num >= 0)
5876 goto normal_compress;
5879 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5880 ram_compress_buf(s, buf, 10);
5886 ram_compress_buf(s, buf, 1);
5887 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5890 ram_compress_close(s);
5893 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5895 RamDecompressState s1, *s = &s1;
5899 if (version_id == 1)
5900 return ram_load_v1(f, opaque);
5901 if (version_id != 2)
5903 if (qemu_get_be32(f) != phys_ram_size)
5905 if (ram_decompress_open(s, f) < 0)
5907 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5908 if (ram_decompress_buf(s, buf, 1) < 0) {
5909 fprintf(stderr, "Error while reading ram block header\n");
5913 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5914 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5923 ram_decompress_buf(s, buf + 1, 9);
5925 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5926 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5927 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5930 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5931 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5932 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5933 bs_index, sector_num);
5940 printf("Error block header\n");
5944 ram_decompress_close(s);
5948 /***********************************************************/
5949 /* bottom halves (can be seen as timers which expire ASAP) */
5958 static QEMUBH *first_bh = NULL;
5960 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5963 bh = qemu_mallocz(sizeof(QEMUBH));
5967 bh->opaque = opaque;
5971 int qemu_bh_poll(void)
5990 void qemu_bh_schedule(QEMUBH *bh)
5992 CPUState *env = cpu_single_env;
5996 bh->next = first_bh;
5999 /* stop the currently executing CPU to execute the BH ASAP */
6001 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6005 void qemu_bh_cancel(QEMUBH *bh)
6008 if (bh->scheduled) {
6011 pbh = &(*pbh)->next;
6017 void qemu_bh_delete(QEMUBH *bh)
6023 /***********************************************************/
6024 /* machine registration */
6026 QEMUMachine *first_machine = NULL;
6028 int qemu_register_machine(QEMUMachine *m)
6031 pm = &first_machine;
6039 QEMUMachine *find_machine(const char *name)
6043 for(m = first_machine; m != NULL; m = m->next) {
6044 if (!strcmp(m->name, name))
6050 /***********************************************************/
6051 /* main execution loop */
6053 void gui_update(void *opaque)
6055 display_state.dpy_refresh(&display_state);
6056 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6059 struct vm_change_state_entry {
6060 VMChangeStateHandler *cb;
6062 LIST_ENTRY (vm_change_state_entry) entries;
6065 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6067 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6070 VMChangeStateEntry *e;
6072 e = qemu_mallocz(sizeof (*e));
6078 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6082 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6084 LIST_REMOVE (e, entries);
6088 static void vm_state_notify(int running)
6090 VMChangeStateEntry *e;
6092 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6093 e->cb(e->opaque, running);
6097 /* XXX: support several handlers */
6098 static VMStopHandler *vm_stop_cb;
6099 static void *vm_stop_opaque;
6101 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6104 vm_stop_opaque = opaque;
6108 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6122 void vm_stop(int reason)
6125 cpu_disable_ticks();
6129 vm_stop_cb(vm_stop_opaque, reason);
6136 /* reset/shutdown handler */
6138 typedef struct QEMUResetEntry {
6139 QEMUResetHandler *func;
6141 struct QEMUResetEntry *next;
6144 static QEMUResetEntry *first_reset_entry;
6145 static int reset_requested;
6146 static int shutdown_requested;
6147 static int powerdown_requested;
6149 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6151 QEMUResetEntry **pre, *re;
6153 pre = &first_reset_entry;
6154 while (*pre != NULL)
6155 pre = &(*pre)->next;
6156 re = qemu_mallocz(sizeof(QEMUResetEntry));
6158 re->opaque = opaque;
6163 static void qemu_system_reset(void)
6167 /* reset all devices */
6168 for(re = first_reset_entry; re != NULL; re = re->next) {
6169 re->func(re->opaque);
6173 void qemu_system_reset_request(void)
6176 shutdown_requested = 1;
6178 reset_requested = 1;
6181 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6184 void qemu_system_shutdown_request(void)
6186 shutdown_requested = 1;
6188 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6191 void qemu_system_powerdown_request(void)
6193 powerdown_requested = 1;
6195 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6198 void main_loop_wait(int timeout)
6200 IOHandlerRecord *ioh;
6201 fd_set rfds, wfds, xfds;
6210 /* XXX: need to suppress polling by better using win32 events */
6212 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6213 ret |= pe->func(pe->opaque);
6218 WaitObjects *w = &wait_objects;
6220 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6221 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6222 if (w->func[ret - WAIT_OBJECT_0])
6223 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6225 /* Check for additional signaled events */
6226 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6228 /* Check if event is signaled */
6229 ret2 = WaitForSingleObject(w->events[i], 0);
6230 if(ret2 == WAIT_OBJECT_0) {
6232 w->func[i](w->opaque[i]);
6233 } else if (ret2 == WAIT_TIMEOUT) {
6235 err = GetLastError();
6236 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6239 } else if (ret == WAIT_TIMEOUT) {
6241 err = GetLastError();
6242 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6246 /* poll any events */
6247 /* XXX: separate device handlers from system ones */
6252 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6256 (!ioh->fd_read_poll ||
6257 ioh->fd_read_poll(ioh->opaque) != 0)) {
6258 FD_SET(ioh->fd, &rfds);
6262 if (ioh->fd_write) {
6263 FD_SET(ioh->fd, &wfds);
6273 tv.tv_usec = timeout * 1000;
6275 #if defined(CONFIG_SLIRP)
6277 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6280 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6282 IOHandlerRecord **pioh;
6284 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6287 if (FD_ISSET(ioh->fd, &rfds)) {
6288 ioh->fd_read(ioh->opaque);
6290 if (FD_ISSET(ioh->fd, &wfds)) {
6291 ioh->fd_write(ioh->opaque);
6295 /* remove deleted IO handlers */
6296 pioh = &first_io_handler;
6306 #if defined(CONFIG_SLIRP)
6313 slirp_select_poll(&rfds, &wfds, &xfds);
6320 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6321 qemu_get_clock(vm_clock));
6322 /* run dma transfers, if any */
6326 /* real time timers */
6327 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6328 qemu_get_clock(rt_clock));
6331 static CPUState *cur_cpu;
6336 #ifdef CONFIG_PROFILER
6341 cur_cpu = first_cpu;
6348 env = env->next_cpu;
6351 #ifdef CONFIG_PROFILER
6352 ti = profile_getclock();
6354 ret = cpu_exec(env);
6355 #ifdef CONFIG_PROFILER
6356 qemu_time += profile_getclock() - ti;
6358 if (ret == EXCP_HLT) {
6359 /* Give the next CPU a chance to run. */
6363 if (ret != EXCP_HALTED)
6365 /* all CPUs are halted ? */
6371 if (shutdown_requested) {
6372 ret = EXCP_INTERRUPT;
6375 if (reset_requested) {
6376 reset_requested = 0;
6377 qemu_system_reset();
6378 ret = EXCP_INTERRUPT;
6380 if (powerdown_requested) {
6381 powerdown_requested = 0;
6382 qemu_system_powerdown();
6383 ret = EXCP_INTERRUPT;
6385 if (ret == EXCP_DEBUG) {
6386 vm_stop(EXCP_DEBUG);
6388 /* If all cpus are halted then wait until the next IRQ */
6389 /* XXX: use timeout computed from timers */
6390 if (ret == EXCP_HALTED)
6397 #ifdef CONFIG_PROFILER
6398 ti = profile_getclock();
6400 main_loop_wait(timeout);
6401 #ifdef CONFIG_PROFILER
6402 dev_time += profile_getclock() - ti;
6405 cpu_disable_ticks();
6411 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6412 "usage: %s [options] [disk_image]\n"
6414 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6416 "Standard options:\n"
6417 "-M machine select emulated machine (-M ? for list)\n"
6418 "-cpu cpu select CPU (-cpu ? for list)\n"
6419 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6420 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6421 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6422 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6423 "-mtdblock file use 'file' as on-board Flash memory image\n"
6424 "-sd file use 'file' as SecureDigital card image\n"
6425 "-pflash file use 'file' as a parallel flash image\n"
6426 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6427 "-snapshot write to temporary files instead of disk image files\n"
6429 "-no-frame open SDL window without a frame and window decorations\n"
6430 "-no-quit disable SDL window close capability\n"
6433 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6435 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6436 "-smp n set the number of CPUs to 'n' [default=1]\n"
6437 "-nographic disable graphical output and redirect serial I/Os to console\n"
6438 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6440 "-k language use keyboard layout (for example \"fr\" for French)\n"
6443 "-audio-help print list of audio drivers and their options\n"
6444 "-soundhw c1,... enable audio support\n"
6445 " and only specified sound cards (comma separated list)\n"
6446 " use -soundhw ? to get the list of supported cards\n"
6447 " use -soundhw all to enable all of them\n"
6449 "-localtime set the real time clock to local time [default=utc]\n"
6450 "-full-screen start in full screen\n"
6452 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6454 "-usb enable the USB driver (will be the default soon)\n"
6455 "-usbdevice name add the host or guest USB device 'name'\n"
6456 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6457 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6459 "-name string set the name of the guest\n"
6461 "Network options:\n"
6462 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6463 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6465 "-net user[,vlan=n][,hostname=host]\n"
6466 " connect the user mode network stack to VLAN 'n' and send\n"
6467 " hostname 'host' to DHCP clients\n"
6470 "-net tap[,vlan=n],ifname=name\n"
6471 " connect the host TAP network interface to VLAN 'n'\n"
6473 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6474 " connect the host TAP network interface to VLAN 'n' and use\n"
6475 " the network script 'file' (default=%s);\n"
6476 " use 'script=no' to disable script execution;\n"
6477 " use 'fd=h' to connect to an already opened TAP interface\n"
6479 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6480 " connect the vlan 'n' to another VLAN using a socket connection\n"
6481 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6482 " connect the vlan 'n' to multicast maddr and port\n"
6483 "-net none use it alone to have zero network devices; if no -net option\n"
6484 " is provided, the default is '-net nic -net user'\n"
6487 "-tftp dir allow tftp access to files in dir [-net user]\n"
6488 "-bootp file advertise file in BOOTP replies\n"
6490 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6492 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6493 " redirect TCP or UDP connections from host to guest [-net user]\n"
6496 "Linux boot specific:\n"
6497 "-kernel bzImage use 'bzImage' as kernel image\n"
6498 "-append cmdline use 'cmdline' as kernel command line\n"
6499 "-initrd file use 'file' as initial ram disk\n"
6501 "Debug/Expert options:\n"
6502 "-monitor dev redirect the monitor to char device 'dev'\n"
6503 "-serial dev redirect the serial port to char device 'dev'\n"
6504 "-parallel dev redirect the parallel port to char device 'dev'\n"
6505 "-pidfile file Write PID to 'file'\n"
6506 "-S freeze CPU at startup (use 'c' to start execution)\n"
6507 "-s wait gdb connection to port\n"
6508 "-p port set gdb connection port [default=%s]\n"
6509 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6510 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6511 " translation (t=none or lba) (usually qemu can guess them)\n"
6512 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6514 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6515 "-no-kqemu disable KQEMU kernel module usage\n"
6517 #ifdef USE_CODE_COPY
6518 "-no-code-copy disable code copy acceleration\n"
6521 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6522 " (default is CL-GD5446 PCI VGA)\n"
6523 "-no-acpi disable ACPI\n"
6525 "-no-reboot exit instead of rebooting\n"
6526 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6527 "-vnc display start a VNC server on display\n"
6529 "-daemonize daemonize QEMU after initializing\n"
6531 "-option-rom rom load a file, rom, into the option ROM space\n"
6533 "During emulation, the following keys are useful:\n"
6534 "ctrl-alt-f toggle full screen\n"
6535 "ctrl-alt-n switch to virtual console 'n'\n"
6536 "ctrl-alt toggle mouse and keyboard grab\n"
6538 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6543 DEFAULT_NETWORK_SCRIPT,
6545 DEFAULT_GDBSTUB_PORT,
6550 #define HAS_ARG 0x0001
6564 QEMU_OPTION_mtdblock,
6568 QEMU_OPTION_snapshot,
6570 QEMU_OPTION_no_fd_bootchk,
6573 QEMU_OPTION_nographic,
6574 QEMU_OPTION_portrait,
6576 QEMU_OPTION_audio_help,
6577 QEMU_OPTION_soundhw,
6596 QEMU_OPTION_no_code_copy,
6598 QEMU_OPTION_localtime,
6599 QEMU_OPTION_cirrusvga,
6602 QEMU_OPTION_std_vga,
6604 QEMU_OPTION_monitor,
6606 QEMU_OPTION_parallel,
6608 QEMU_OPTION_full_screen,
6609 QEMU_OPTION_no_frame,
6610 QEMU_OPTION_no_quit,
6611 QEMU_OPTION_pidfile,
6612 QEMU_OPTION_no_kqemu,
6613 QEMU_OPTION_kernel_kqemu,
6614 QEMU_OPTION_win2k_hack,
6616 QEMU_OPTION_usbdevice,
6619 QEMU_OPTION_no_acpi,
6620 QEMU_OPTION_no_reboot,
6621 QEMU_OPTION_daemonize,
6622 QEMU_OPTION_option_rom,
6623 QEMU_OPTION_semihosting,
6627 typedef struct QEMUOption {
6633 const QEMUOption qemu_options[] = {
6634 { "h", 0, QEMU_OPTION_h },
6635 { "help", 0, QEMU_OPTION_h },
6637 { "M", HAS_ARG, QEMU_OPTION_M },
6638 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6639 { "fda", HAS_ARG, QEMU_OPTION_fda },
6640 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6641 { "hda", HAS_ARG, QEMU_OPTION_hda },
6642 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6643 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6644 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6645 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6646 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6647 { "sd", HAS_ARG, QEMU_OPTION_sd },
6648 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6649 { "boot", HAS_ARG, QEMU_OPTION_boot },
6650 { "snapshot", 0, QEMU_OPTION_snapshot },
6652 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6654 { "m", HAS_ARG, QEMU_OPTION_m },
6655 { "nographic", 0, QEMU_OPTION_nographic },
6656 { "portrait", 0, QEMU_OPTION_portrait },
6657 { "k", HAS_ARG, QEMU_OPTION_k },
6659 { "audio-help", 0, QEMU_OPTION_audio_help },
6660 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6663 { "net", HAS_ARG, QEMU_OPTION_net},
6665 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6666 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6668 { "smb", HAS_ARG, QEMU_OPTION_smb },
6670 { "redir", HAS_ARG, QEMU_OPTION_redir },
6673 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6674 { "append", HAS_ARG, QEMU_OPTION_append },
6675 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6677 { "S", 0, QEMU_OPTION_S },
6678 { "s", 0, QEMU_OPTION_s },
6679 { "p", HAS_ARG, QEMU_OPTION_p },
6680 { "d", HAS_ARG, QEMU_OPTION_d },
6681 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6682 { "L", HAS_ARG, QEMU_OPTION_L },
6683 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6685 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6686 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6688 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6689 { "g", 1, QEMU_OPTION_g },
6691 { "localtime", 0, QEMU_OPTION_localtime },
6692 { "std-vga", 0, QEMU_OPTION_std_vga },
6693 { "echr", 1, QEMU_OPTION_echr },
6694 { "monitor", 1, QEMU_OPTION_monitor },
6695 { "serial", 1, QEMU_OPTION_serial },
6696 { "parallel", 1, QEMU_OPTION_parallel },
6697 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6698 { "full-screen", 0, QEMU_OPTION_full_screen },
6700 { "no-frame", 0, QEMU_OPTION_no_frame },
6701 { "no-quit", 0, QEMU_OPTION_no_quit },
6703 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6704 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6705 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6706 { "smp", HAS_ARG, QEMU_OPTION_smp },
6707 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6709 /* temporary options */
6710 { "usb", 0, QEMU_OPTION_usb },
6711 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6712 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6713 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6714 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6715 { "daemonize", 0, QEMU_OPTION_daemonize },
6716 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6717 #if defined(TARGET_ARM)
6718 { "semihosting", 0, QEMU_OPTION_semihosting },
6720 { "name", HAS_ARG, QEMU_OPTION_name },
6724 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6726 /* this stack is only used during signal handling */
6727 #define SIGNAL_STACK_SIZE 32768
6729 static uint8_t *signal_stack;
6733 /* password input */
6735 int qemu_key_check(BlockDriverState *bs, const char *name)
6740 if (!bdrv_is_encrypted(bs))
6743 term_printf("%s is encrypted.\n", name);
6744 for(i = 0; i < 3; i++) {
6745 monitor_readline("Password: ", 1, password, sizeof(password));
6746 if (bdrv_set_key(bs, password) == 0)
6748 term_printf("invalid password\n");
6753 static BlockDriverState *get_bdrv(int index)
6755 BlockDriverState *bs;
6758 bs = bs_table[index];
6759 } else if (index < 6) {
6760 bs = fd_table[index - 4];
6767 static void read_passwords(void)
6769 BlockDriverState *bs;
6772 for(i = 0; i < 6; i++) {
6775 qemu_key_check(bs, bdrv_get_device_name(bs));
6779 /* XXX: currently we cannot use simultaneously different CPUs */
6780 void register_machines(void)
6782 #if defined(TARGET_I386)
6783 qemu_register_machine(&pc_machine);
6784 qemu_register_machine(&isapc_machine);
6785 #elif defined(TARGET_PPC)
6786 qemu_register_machine(&heathrow_machine);
6787 qemu_register_machine(&core99_machine);
6788 qemu_register_machine(&prep_machine);
6789 qemu_register_machine(&ref405ep_machine);
6790 qemu_register_machine(&taihu_machine);
6791 #elif defined(TARGET_MIPS)
6792 qemu_register_machine(&mips_machine);
6793 qemu_register_machine(&mips_malta_machine);
6794 qemu_register_machine(&mips_pica61_machine);
6795 #elif defined(TARGET_SPARC)
6796 #ifdef TARGET_SPARC64
6797 qemu_register_machine(&sun4u_machine);
6799 qemu_register_machine(&ss5_machine);
6800 qemu_register_machine(&ss10_machine);
6802 #elif defined(TARGET_ARM)
6803 qemu_register_machine(&integratorcp_machine);
6804 qemu_register_machine(&versatilepb_machine);
6805 qemu_register_machine(&versatileab_machine);
6806 qemu_register_machine(&realview_machine);
6807 #elif defined(TARGET_SH4)
6808 qemu_register_machine(&shix_machine);
6809 #elif defined(TARGET_ALPHA)
6812 #error unsupported CPU
6817 struct soundhw soundhw[] = {
6824 { .init_isa = pcspk_audio_init }
6829 "Creative Sound Blaster 16",
6832 { .init_isa = SB16_init }
6839 "Yamaha YMF262 (OPL3)",
6841 "Yamaha YM3812 (OPL2)",
6845 { .init_isa = Adlib_init }
6852 "Gravis Ultrasound GF1",
6855 { .init_isa = GUS_init }
6861 "ENSONIQ AudioPCI ES1370",
6864 { .init_pci = es1370_init }
6867 { NULL, NULL, 0, 0, { NULL } }
6870 static void select_soundhw (const char *optarg)
6874 if (*optarg == '?') {
6877 printf ("Valid sound card names (comma separated):\n");
6878 for (c = soundhw; c->name; ++c) {
6879 printf ("%-11s %s\n", c->name, c->descr);
6881 printf ("\n-soundhw all will enable all of the above\n");
6882 exit (*optarg != '?');
6890 if (!strcmp (optarg, "all")) {
6891 for (c = soundhw; c->name; ++c) {
6899 e = strchr (p, ',');
6900 l = !e ? strlen (p) : (size_t) (e - p);
6902 for (c = soundhw; c->name; ++c) {
6903 if (!strncmp (c->name, p, l)) {
6912 "Unknown sound card name (too big to show)\n");
6915 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6920 p += l + (e != NULL);
6924 goto show_valid_cards;
6930 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6932 exit(STATUS_CONTROL_C_EXIT);
6937 #define MAX_NET_CLIENTS 32
6939 int main(int argc, char **argv)
6941 #ifdef CONFIG_GDBSTUB
6943 const char *gdbstub_port;
6945 int i, cdrom_index, pflash_index;
6946 int snapshot, linux_boot;
6947 const char *initrd_filename;
6948 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6949 const char *pflash_filename[MAX_PFLASH];
6950 const char *sd_filename;
6951 const char *mtd_filename;
6952 const char *kernel_filename, *kernel_cmdline;
6953 DisplayState *ds = &display_state;
6954 int cyls, heads, secs, translation;
6955 char net_clients[MAX_NET_CLIENTS][256];
6958 const char *r, *optarg;
6959 CharDriverState *monitor_hd;
6960 char monitor_device[128];
6961 char serial_devices[MAX_SERIAL_PORTS][128];
6962 int serial_device_index;
6963 char parallel_devices[MAX_PARALLEL_PORTS][128];
6964 int parallel_device_index;
6965 const char *loadvm = NULL;
6966 QEMUMachine *machine;
6967 const char *cpu_model;
6968 char usb_devices[MAX_USB_CMDLINE][128];
6969 int usb_devices_index;
6971 const char *pid_file = NULL;
6973 LIST_INIT (&vm_change_state_head);
6976 struct sigaction act;
6977 sigfillset(&act.sa_mask);
6979 act.sa_handler = SIG_IGN;
6980 sigaction(SIGPIPE, &act, NULL);
6983 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6984 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6985 QEMU to run on a single CPU */
6990 h = GetCurrentProcess();
6991 if (GetProcessAffinityMask(h, &mask, &smask)) {
6992 for(i = 0; i < 32; i++) {
6993 if (mask & (1 << i))
6998 SetProcessAffinityMask(h, mask);
7004 register_machines();
7005 machine = first_machine;
7007 initrd_filename = NULL;
7008 for(i = 0; i < MAX_FD; i++)
7009 fd_filename[i] = NULL;
7010 for(i = 0; i < MAX_DISKS; i++)
7011 hd_filename[i] = NULL;
7012 for(i = 0; i < MAX_PFLASH; i++)
7013 pflash_filename[i] = NULL;
7016 mtd_filename = NULL;
7017 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7018 vga_ram_size = VGA_RAM_SIZE;
7019 #ifdef CONFIG_GDBSTUB
7021 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7025 kernel_filename = NULL;
7026 kernel_cmdline = "";
7032 cyls = heads = secs = 0;
7033 translation = BIOS_ATA_TRANSLATION_AUTO;
7034 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7036 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7037 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7038 serial_devices[i][0] = '\0';
7039 serial_device_index = 0;
7041 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7042 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7043 parallel_devices[i][0] = '\0';
7044 parallel_device_index = 0;
7046 usb_devices_index = 0;
7051 /* default mac address of the first network interface */
7059 hd_filename[0] = argv[optind++];
7061 const QEMUOption *popt;
7064 /* Treat --foo the same as -foo. */
7067 popt = qemu_options;
7070 fprintf(stderr, "%s: invalid option -- '%s'\n",
7074 if (!strcmp(popt->name, r + 1))
7078 if (popt->flags & HAS_ARG) {
7079 if (optind >= argc) {
7080 fprintf(stderr, "%s: option '%s' requires an argument\n",
7084 optarg = argv[optind++];
7089 switch(popt->index) {
7091 machine = find_machine(optarg);
7094 printf("Supported machines are:\n");
7095 for(m = first_machine; m != NULL; m = m->next) {
7096 printf("%-10s %s%s\n",
7098 m == first_machine ? " (default)" : "");
7103 case QEMU_OPTION_cpu:
7104 /* hw initialization will check this */
7105 if (optarg[0] == '?') {
7106 #if defined(TARGET_PPC)
7107 ppc_cpu_list(stdout, &fprintf);
7108 #elif defined(TARGET_ARM)
7110 #elif defined(TARGET_MIPS)
7111 mips_cpu_list(stdout, &fprintf);
7112 #elif defined(TARGET_SPARC)
7113 sparc_cpu_list(stdout, &fprintf);
7120 case QEMU_OPTION_initrd:
7121 initrd_filename = optarg;
7123 case QEMU_OPTION_hda:
7124 case QEMU_OPTION_hdb:
7125 case QEMU_OPTION_hdc:
7126 case QEMU_OPTION_hdd:
7129 hd_index = popt->index - QEMU_OPTION_hda;
7130 hd_filename[hd_index] = optarg;
7131 if (hd_index == cdrom_index)
7135 case QEMU_OPTION_mtdblock:
7136 mtd_filename = optarg;
7138 case QEMU_OPTION_sd:
7139 sd_filename = optarg;
7141 case QEMU_OPTION_pflash:
7142 if (pflash_index >= MAX_PFLASH) {
7143 fprintf(stderr, "qemu: too many parallel flash images\n");
7146 pflash_filename[pflash_index++] = optarg;
7148 case QEMU_OPTION_snapshot:
7151 case QEMU_OPTION_hdachs:
7155 cyls = strtol(p, (char **)&p, 0);
7156 if (cyls < 1 || cyls > 16383)
7161 heads = strtol(p, (char **)&p, 0);
7162 if (heads < 1 || heads > 16)
7167 secs = strtol(p, (char **)&p, 0);
7168 if (secs < 1 || secs > 63)
7172 if (!strcmp(p, "none"))
7173 translation = BIOS_ATA_TRANSLATION_NONE;
7174 else if (!strcmp(p, "lba"))
7175 translation = BIOS_ATA_TRANSLATION_LBA;
7176 else if (!strcmp(p, "auto"))
7177 translation = BIOS_ATA_TRANSLATION_AUTO;
7180 } else if (*p != '\0') {
7182 fprintf(stderr, "qemu: invalid physical CHS format\n");
7187 case QEMU_OPTION_nographic:
7188 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7189 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7190 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7193 case QEMU_OPTION_portrait:
7196 case QEMU_OPTION_kernel:
7197 kernel_filename = optarg;
7199 case QEMU_OPTION_append:
7200 kernel_cmdline = optarg;
7202 case QEMU_OPTION_cdrom:
7203 if (cdrom_index >= 0) {
7204 hd_filename[cdrom_index] = optarg;
7207 case QEMU_OPTION_boot:
7208 boot_device = optarg[0];
7209 if (boot_device != 'a' &&
7210 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7212 boot_device != 'n' &&
7214 boot_device != 'c' && boot_device != 'd') {
7215 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7219 case QEMU_OPTION_fda:
7220 fd_filename[0] = optarg;
7222 case QEMU_OPTION_fdb:
7223 fd_filename[1] = optarg;
7226 case QEMU_OPTION_no_fd_bootchk:
7230 case QEMU_OPTION_no_code_copy:
7231 code_copy_enabled = 0;
7233 case QEMU_OPTION_net:
7234 if (nb_net_clients >= MAX_NET_CLIENTS) {
7235 fprintf(stderr, "qemu: too many network clients\n");
7238 pstrcpy(net_clients[nb_net_clients],
7239 sizeof(net_clients[0]),
7244 case QEMU_OPTION_tftp:
7245 tftp_prefix = optarg;
7247 case QEMU_OPTION_bootp:
7248 bootp_filename = optarg;
7251 case QEMU_OPTION_smb:
7252 net_slirp_smb(optarg);
7255 case QEMU_OPTION_redir:
7256 net_slirp_redir(optarg);
7260 case QEMU_OPTION_audio_help:
7264 case QEMU_OPTION_soundhw:
7265 select_soundhw (optarg);
7272 ram_size = atoi(optarg) * 1024 * 1024;
7275 if (ram_size > PHYS_RAM_MAX_SIZE) {
7276 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7277 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7286 mask = cpu_str_to_log_mask(optarg);
7288 printf("Log items (comma separated):\n");
7289 for(item = cpu_log_items; item->mask != 0; item++) {
7290 printf("%-10s %s\n", item->name, item->help);
7297 #ifdef CONFIG_GDBSTUB
7302 gdbstub_port = optarg;
7312 keyboard_layout = optarg;
7314 case QEMU_OPTION_localtime:
7317 case QEMU_OPTION_cirrusvga:
7318 cirrus_vga_enabled = 1;
7321 case QEMU_OPTION_vmsvga:
7322 cirrus_vga_enabled = 0;
7325 case QEMU_OPTION_std_vga:
7326 cirrus_vga_enabled = 0;
7334 w = strtol(p, (char **)&p, 10);
7337 fprintf(stderr, "qemu: invalid resolution or depth\n");
7343 h = strtol(p, (char **)&p, 10);
7348 depth = strtol(p, (char **)&p, 10);
7349 if (depth != 8 && depth != 15 && depth != 16 &&
7350 depth != 24 && depth != 32)
7352 } else if (*p == '\0') {
7353 depth = graphic_depth;
7360 graphic_depth = depth;
7363 case QEMU_OPTION_echr:
7366 term_escape_char = strtol(optarg, &r, 0);
7368 printf("Bad argument to echr\n");
7371 case QEMU_OPTION_monitor:
7372 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7374 case QEMU_OPTION_serial:
7375 if (serial_device_index >= MAX_SERIAL_PORTS) {
7376 fprintf(stderr, "qemu: too many serial ports\n");
7379 pstrcpy(serial_devices[serial_device_index],
7380 sizeof(serial_devices[0]), optarg);
7381 serial_device_index++;
7383 case QEMU_OPTION_parallel:
7384 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7385 fprintf(stderr, "qemu: too many parallel ports\n");
7388 pstrcpy(parallel_devices[parallel_device_index],
7389 sizeof(parallel_devices[0]), optarg);
7390 parallel_device_index++;
7392 case QEMU_OPTION_loadvm:
7395 case QEMU_OPTION_full_screen:
7399 case QEMU_OPTION_no_frame:
7402 case QEMU_OPTION_no_quit:
7406 case QEMU_OPTION_pidfile:
7410 case QEMU_OPTION_win2k_hack:
7411 win2k_install_hack = 1;
7415 case QEMU_OPTION_no_kqemu:
7418 case QEMU_OPTION_kernel_kqemu:
7422 case QEMU_OPTION_usb:
7425 case QEMU_OPTION_usbdevice:
7427 if (usb_devices_index >= MAX_USB_CMDLINE) {
7428 fprintf(stderr, "Too many USB devices\n");
7431 pstrcpy(usb_devices[usb_devices_index],
7432 sizeof(usb_devices[usb_devices_index]),
7434 usb_devices_index++;
7436 case QEMU_OPTION_smp:
7437 smp_cpus = atoi(optarg);
7438 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7439 fprintf(stderr, "Invalid number of CPUs\n");
7443 case QEMU_OPTION_vnc:
7444 vnc_display = optarg;
7446 case QEMU_OPTION_no_acpi:
7449 case QEMU_OPTION_no_reboot:
7452 case QEMU_OPTION_daemonize:
7455 case QEMU_OPTION_option_rom:
7456 if (nb_option_roms >= MAX_OPTION_ROMS) {
7457 fprintf(stderr, "Too many option ROMs\n");
7460 option_rom[nb_option_roms] = optarg;
7463 case QEMU_OPTION_semihosting:
7464 semihosting_enabled = 1;
7466 case QEMU_OPTION_name:
7474 if (daemonize && !nographic && vnc_display == NULL) {
7475 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7482 if (pipe(fds) == -1)
7493 len = read(fds[0], &status, 1);
7494 if (len == -1 && (errno == EINTR))
7499 else if (status == 1) {
7500 fprintf(stderr, "Could not acquire pidfile\n");
7518 signal(SIGTSTP, SIG_IGN);
7519 signal(SIGTTOU, SIG_IGN);
7520 signal(SIGTTIN, SIG_IGN);
7524 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7527 write(fds[1], &status, 1);
7529 fprintf(stderr, "Could not acquire pid file\n");
7537 linux_boot = (kernel_filename != NULL);
7540 boot_device != 'n' &&
7541 hd_filename[0] == '\0' &&
7542 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7543 fd_filename[0] == '\0')
7546 /* boot to floppy or the default cd if no hard disk defined yet */
7547 if (hd_filename[0] == '\0' && boot_device == 'c') {
7548 if (fd_filename[0] != '\0')
7554 setvbuf(stdout, NULL, _IOLBF, 0);
7564 /* init network clients */
7565 if (nb_net_clients == 0) {
7566 /* if no clients, we use a default config */
7567 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7569 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7574 for(i = 0;i < nb_net_clients; i++) {
7575 if (net_client_init(net_clients[i]) < 0)
7580 if (boot_device == 'n') {
7581 for (i = 0; i < nb_nics; i++) {
7582 const char *model = nd_table[i].model;
7586 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7587 if (get_image_size(buf) > 0) {
7588 option_rom[nb_option_roms] = strdup(buf);
7594 fprintf(stderr, "No valid PXE rom found for network device\n");
7597 boot_device = 'c'; /* to prevent confusion by the BIOS */
7601 /* init the memory */
7602 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7604 phys_ram_base = qemu_vmalloc(phys_ram_size);
7605 if (!phys_ram_base) {
7606 fprintf(stderr, "Could not allocate physical memory\n");
7610 /* we always create the cdrom drive, even if no disk is there */
7612 if (cdrom_index >= 0) {
7613 bs_table[cdrom_index] = bdrv_new("cdrom");
7614 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7617 /* open the virtual block devices */
7618 for(i = 0; i < MAX_DISKS; i++) {
7619 if (hd_filename[i]) {
7622 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7623 bs_table[i] = bdrv_new(buf);
7625 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7626 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7630 if (i == 0 && cyls != 0) {
7631 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7632 bdrv_set_translation_hint(bs_table[i], translation);
7637 /* we always create at least one floppy disk */
7638 fd_table[0] = bdrv_new("fda");
7639 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7641 for(i = 0; i < MAX_FD; i++) {
7642 if (fd_filename[i]) {
7645 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7646 fd_table[i] = bdrv_new(buf);
7647 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7649 if (fd_filename[i][0] != '\0') {
7650 if (bdrv_open(fd_table[i], fd_filename[i],
7651 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7652 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7660 /* Open the virtual parallel flash block devices */
7661 for(i = 0; i < MAX_PFLASH; i++) {
7662 if (pflash_filename[i]) {
7663 if (!pflash_table[i]) {
7665 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7666 pflash_table[i] = bdrv_new(buf);
7668 if (bdrv_open(pflash_table[i], pflash_filename[i],
7669 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7670 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7671 pflash_filename[i]);
7677 sd_bdrv = bdrv_new ("sd");
7678 /* FIXME: This isn't really a floppy, but it's a reasonable
7680 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7682 if (bdrv_open(sd_bdrv, sd_filename,
7683 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7684 fprintf(stderr, "qemu: could not open SD card image %s\n",
7687 qemu_key_check(sd_bdrv, sd_filename);
7691 mtd_bdrv = bdrv_new ("mtd");
7692 if (bdrv_open(mtd_bdrv, mtd_filename,
7693 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7694 qemu_key_check(mtd_bdrv, mtd_filename)) {
7695 fprintf(stderr, "qemu: could not open Flash image %s\n",
7697 bdrv_delete(mtd_bdrv);
7702 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7703 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7709 dumb_display_init(ds);
7710 } else if (vnc_display != NULL) {
7711 vnc_display_init(ds, vnc_display);
7713 #if defined(CONFIG_SDL)
7714 sdl_display_init(ds, full_screen, no_frame);
7715 #elif defined(CONFIG_COCOA)
7716 cocoa_display_init(ds, full_screen);
7718 dumb_display_init(ds);
7722 /* Maintain compatibility with multiple stdio monitors */
7723 if (!strcmp(monitor_device,"stdio")) {
7724 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7725 if (!strcmp(serial_devices[i],"mon:stdio")) {
7726 monitor_device[0] = '\0';
7728 } else if (!strcmp(serial_devices[i],"stdio")) {
7729 monitor_device[0] = '\0';
7730 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7735 if (monitor_device[0] != '\0') {
7736 monitor_hd = qemu_chr_open(monitor_device);
7738 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7741 monitor_init(monitor_hd, !nographic);
7744 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7745 const char *devname = serial_devices[i];
7746 if (devname[0] != '\0' && strcmp(devname, "none")) {
7747 serial_hds[i] = qemu_chr_open(devname);
7748 if (!serial_hds[i]) {
7749 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7753 if (!strcmp(devname, "vc"))
7754 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7758 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7759 const char *devname = parallel_devices[i];
7760 if (devname[0] != '\0' && strcmp(devname, "none")) {
7761 parallel_hds[i] = qemu_chr_open(devname);
7762 if (!parallel_hds[i]) {
7763 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7767 if (!strcmp(devname, "vc"))
7768 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7772 machine->init(ram_size, vga_ram_size, boot_device,
7773 ds, fd_filename, snapshot,
7774 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7776 /* init USB devices */
7778 for(i = 0; i < usb_devices_index; i++) {
7779 if (usb_device_add(usb_devices[i]) < 0) {
7780 fprintf(stderr, "Warning: could not add USB device %s\n",
7786 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7787 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7789 #ifdef CONFIG_GDBSTUB
7791 /* XXX: use standard host:port notation and modify options
7793 if (gdbserver_start(gdbstub_port) < 0) {
7794 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7804 /* XXX: simplify init */
7817 len = write(fds[1], &status, 1);
7818 if (len == -1 && (errno == EINTR))
7824 fd = open("/dev/null", O_RDWR);