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];
158 int cirrus_vga_enabled = 1;
159 int vmsvga_enabled = 0;
161 int graphic_width = 1024;
162 int graphic_height = 768;
163 int graphic_depth = 8;
165 int graphic_width = 800;
166 int graphic_height = 600;
167 int graphic_depth = 15;
172 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
173 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
175 int win2k_install_hack = 0;
178 static VLANState *first_vlan;
180 const char *vnc_display;
181 #if defined(TARGET_SPARC)
183 #elif defined(TARGET_I386)
188 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 unsigned int nb_prom_envs = 0;
201 const char *prom_envs[MAX_PROM_ENVS];
204 /***********************************************************/
205 /* x86 ISA bus support */
207 target_phys_addr_t isa_mem_base = 0;
210 uint32_t default_ioport_readb(void *opaque, uint32_t address)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "unused inb: port=0x%04x\n", address);
218 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
220 #ifdef DEBUG_UNUSED_IOPORT
221 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
225 /* default is to make two byte accesses */
226 uint32_t default_ioport_readw(void *opaque, uint32_t address)
229 data = ioport_read_table[0][address](ioport_opaque[address], address);
230 address = (address + 1) & (MAX_IOPORTS - 1);
231 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
235 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
237 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
238 address = (address + 1) & (MAX_IOPORTS - 1);
239 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
242 uint32_t default_ioport_readl(void *opaque, uint32_t address)
244 #ifdef DEBUG_UNUSED_IOPORT
245 fprintf(stderr, "unused inl: port=0x%04x\n", address);
250 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
252 #ifdef DEBUG_UNUSED_IOPORT
253 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
257 void init_ioports(void)
261 for(i = 0; i < MAX_IOPORTS; i++) {
262 ioport_read_table[0][i] = default_ioport_readb;
263 ioport_write_table[0][i] = default_ioport_writeb;
264 ioport_read_table[1][i] = default_ioport_readw;
265 ioport_write_table[1][i] = default_ioport_writew;
266 ioport_read_table[2][i] = default_ioport_readl;
267 ioport_write_table[2][i] = default_ioport_writel;
271 /* size is the word size in byte */
272 int register_ioport_read(int start, int length, int size,
273 IOPortReadFunc *func, void *opaque)
279 } else if (size == 2) {
281 } else if (size == 4) {
284 hw_error("register_ioport_read: invalid size");
287 for(i = start; i < start + length; i += size) {
288 ioport_read_table[bsize][i] = func;
289 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
290 hw_error("register_ioport_read: invalid opaque");
291 ioport_opaque[i] = opaque;
296 /* size is the word size in byte */
297 int register_ioport_write(int start, int length, int size,
298 IOPortWriteFunc *func, void *opaque)
304 } else if (size == 2) {
306 } else if (size == 4) {
309 hw_error("register_ioport_write: invalid size");
312 for(i = start; i < start + length; i += size) {
313 ioport_write_table[bsize][i] = func;
314 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
315 hw_error("register_ioport_write: invalid opaque");
316 ioport_opaque[i] = opaque;
321 void isa_unassign_ioport(int start, int length)
325 for(i = start; i < start + length; i++) {
326 ioport_read_table[0][i] = default_ioport_readb;
327 ioport_read_table[1][i] = default_ioport_readw;
328 ioport_read_table[2][i] = default_ioport_readl;
330 ioport_write_table[0][i] = default_ioport_writeb;
331 ioport_write_table[1][i] = default_ioport_writew;
332 ioport_write_table[2][i] = default_ioport_writel;
336 /***********************************************************/
338 void cpu_outb(CPUState *env, int addr, int val)
341 if (loglevel & CPU_LOG_IOPORT)
342 fprintf(logfile, "outb: %04x %02x\n", addr, val);
344 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
347 env->last_io_time = cpu_get_time_fast();
351 void cpu_outw(CPUState *env, int addr, int val)
354 if (loglevel & CPU_LOG_IOPORT)
355 fprintf(logfile, "outw: %04x %04x\n", addr, val);
357 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
360 env->last_io_time = cpu_get_time_fast();
364 void cpu_outl(CPUState *env, int addr, int val)
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outl: %04x %08x\n", addr, val);
370 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
373 env->last_io_time = cpu_get_time_fast();
377 int cpu_inb(CPUState *env, int addr)
380 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
382 if (loglevel & CPU_LOG_IOPORT)
383 fprintf(logfile, "inb : %04x %02x\n", addr, val);
387 env->last_io_time = cpu_get_time_fast();
392 int cpu_inw(CPUState *env, int addr)
395 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "inw : %04x %04x\n", addr, val);
402 env->last_io_time = cpu_get_time_fast();
407 int cpu_inl(CPUState *env, int addr)
410 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
412 if (loglevel & CPU_LOG_IOPORT)
413 fprintf(logfile, "inl : %04x %08x\n", addr, val);
417 env->last_io_time = cpu_get_time_fast();
422 /***********************************************************/
423 void hw_error(const char *fmt, ...)
429 fprintf(stderr, "qemu: hardware error: ");
430 vfprintf(stderr, fmt, ap);
431 fprintf(stderr, "\n");
432 for(env = first_cpu; env != NULL; env = env->next_cpu) {
433 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
435 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
437 cpu_dump_state(env, stderr, fprintf, 0);
444 /***********************************************************/
447 static QEMUPutKBDEvent *qemu_put_kbd_event;
448 static void *qemu_put_kbd_event_opaque;
449 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
450 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
459 void *opaque, int absolute,
462 QEMUPutMouseEntry *s, *cursor;
464 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
468 s->qemu_put_mouse_event = func;
469 s->qemu_put_mouse_event_opaque = opaque;
470 s->qemu_put_mouse_event_absolute = absolute;
471 s->qemu_put_mouse_event_name = qemu_strdup(name);
474 if (!qemu_put_mouse_event_head) {
475 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
479 cursor = qemu_put_mouse_event_head;
480 while (cursor->next != NULL)
481 cursor = cursor->next;
484 qemu_put_mouse_event_current = s;
489 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
491 QEMUPutMouseEntry *prev = NULL, *cursor;
493 if (!qemu_put_mouse_event_head || entry == NULL)
496 cursor = qemu_put_mouse_event_head;
497 while (cursor != NULL && cursor != entry) {
499 cursor = cursor->next;
502 if (cursor == NULL) // does not exist or list empty
504 else if (prev == NULL) { // entry is head
505 qemu_put_mouse_event_head = cursor->next;
506 if (qemu_put_mouse_event_current == entry)
507 qemu_put_mouse_event_current = cursor->next;
508 qemu_free(entry->qemu_put_mouse_event_name);
513 prev->next = entry->next;
515 if (qemu_put_mouse_event_current == entry)
516 qemu_put_mouse_event_current = prev;
518 qemu_free(entry->qemu_put_mouse_event_name);
522 void kbd_put_keycode(int keycode)
524 if (qemu_put_kbd_event) {
525 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
529 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
531 QEMUPutMouseEvent *mouse_event;
532 void *mouse_event_opaque;
535 if (!qemu_put_mouse_event_current) {
540 qemu_put_mouse_event_current->qemu_put_mouse_event;
542 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
545 if (graphic_rotate) {
546 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
549 width = graphic_width;
550 mouse_event(mouse_event_opaque,
551 width - dy, dx, dz, buttons_state);
553 mouse_event(mouse_event_opaque,
554 dx, dy, dz, buttons_state);
558 int kbd_mouse_is_absolute(void)
560 if (!qemu_put_mouse_event_current)
563 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
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]);
1365 bdrv_commit(mtd_bdrv);
1369 qemu_chr_event(chr, CHR_EVENT_BREAK);
1372 /* Switch to the next registered device */
1374 if (chr->focus >= d->mux_cnt)
1378 term_timestamps = !term_timestamps;
1379 term_timestamps_start = -1;
1382 } else if (ch == term_escape_char) {
1383 d->term_got_escape = 1;
1391 static int mux_chr_can_read(void *opaque)
1393 CharDriverState *chr = opaque;
1394 MuxDriver *d = chr->opaque;
1395 if (d->chr_can_read[chr->focus])
1396 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1400 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1402 CharDriverState *chr = opaque;
1403 MuxDriver *d = chr->opaque;
1405 for(i = 0; i < size; i++)
1406 if (mux_proc_byte(chr, d, buf[i]))
1407 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1410 static void mux_chr_event(void *opaque, int event)
1412 CharDriverState *chr = opaque;
1413 MuxDriver *d = chr->opaque;
1416 /* Send the event to all registered listeners */
1417 for (i = 0; i < d->mux_cnt; i++)
1418 if (d->chr_event[i])
1419 d->chr_event[i](d->ext_opaque[i], event);
1422 static void mux_chr_update_read_handler(CharDriverState *chr)
1424 MuxDriver *d = chr->opaque;
1426 if (d->mux_cnt >= MAX_MUX) {
1427 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1430 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1431 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1432 d->chr_read[d->mux_cnt] = chr->chr_read;
1433 d->chr_event[d->mux_cnt] = chr->chr_event;
1434 /* Fix up the real driver with mux routines */
1435 if (d->mux_cnt == 0) {
1436 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1437 mux_chr_event, chr);
1439 chr->focus = d->mux_cnt;
1443 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1445 CharDriverState *chr;
1448 chr = qemu_mallocz(sizeof(CharDriverState));
1451 d = qemu_mallocz(sizeof(MuxDriver));
1460 chr->chr_write = mux_chr_write;
1461 chr->chr_update_read_handler = mux_chr_update_read_handler;
1468 static void socket_cleanup(void)
1473 static int socket_init(void)
1478 ret = WSAStartup(MAKEWORD(2,2), &Data);
1480 err = WSAGetLastError();
1481 fprintf(stderr, "WSAStartup: %d\n", err);
1484 atexit(socket_cleanup);
1488 static int send_all(int fd, const uint8_t *buf, int len1)
1494 ret = send(fd, buf, len, 0);
1497 errno = WSAGetLastError();
1498 if (errno != WSAEWOULDBLOCK) {
1501 } else if (ret == 0) {
1511 void socket_set_nonblock(int fd)
1513 unsigned long opt = 1;
1514 ioctlsocket(fd, FIONBIO, &opt);
1519 static int unix_write(int fd, const uint8_t *buf, int len1)
1525 ret = write(fd, buf, len);
1527 if (errno != EINTR && errno != EAGAIN)
1529 } else if (ret == 0) {
1539 static inline int send_all(int fd, const uint8_t *buf, int len1)
1541 return unix_write(fd, buf, len1);
1544 void socket_set_nonblock(int fd)
1546 fcntl(fd, F_SETFL, O_NONBLOCK);
1548 #endif /* !_WIN32 */
1557 #define STDIO_MAX_CLIENTS 1
1558 static int stdio_nb_clients = 0;
1560 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1562 FDCharDriver *s = chr->opaque;
1563 return unix_write(s->fd_out, buf, len);
1566 static int fd_chr_read_poll(void *opaque)
1568 CharDriverState *chr = opaque;
1569 FDCharDriver *s = chr->opaque;
1571 s->max_size = qemu_chr_can_read(chr);
1575 static void fd_chr_read(void *opaque)
1577 CharDriverState *chr = opaque;
1578 FDCharDriver *s = chr->opaque;
1583 if (len > s->max_size)
1587 size = read(s->fd_in, buf, len);
1589 /* FD has been closed. Remove it from the active list. */
1590 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1594 qemu_chr_read(chr, buf, size);
1598 static void fd_chr_update_read_handler(CharDriverState *chr)
1600 FDCharDriver *s = chr->opaque;
1602 if (s->fd_in >= 0) {
1603 if (nographic && s->fd_in == 0) {
1605 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1606 fd_chr_read, NULL, chr);
1611 /* open a character device to a unix fd */
1612 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1614 CharDriverState *chr;
1617 chr = qemu_mallocz(sizeof(CharDriverState));
1620 s = qemu_mallocz(sizeof(FDCharDriver));
1628 chr->chr_write = fd_chr_write;
1629 chr->chr_update_read_handler = fd_chr_update_read_handler;
1631 qemu_chr_reset(chr);
1636 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1640 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1643 return qemu_chr_open_fd(-1, fd_out);
1646 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1649 char filename_in[256], filename_out[256];
1651 snprintf(filename_in, 256, "%s.in", filename);
1652 snprintf(filename_out, 256, "%s.out", filename);
1653 fd_in = open(filename_in, O_RDWR | O_BINARY);
1654 fd_out = open(filename_out, O_RDWR | O_BINARY);
1655 if (fd_in < 0 || fd_out < 0) {
1660 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1664 return qemu_chr_open_fd(fd_in, fd_out);
1668 /* for STDIO, we handle the case where several clients use it
1671 #define TERM_FIFO_MAX_SIZE 1
1673 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1674 static int term_fifo_size;
1676 static int stdio_read_poll(void *opaque)
1678 CharDriverState *chr = opaque;
1680 /* try to flush the queue if needed */
1681 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1682 qemu_chr_read(chr, term_fifo, 1);
1685 /* see if we can absorb more chars */
1686 if (term_fifo_size == 0)
1692 static void stdio_read(void *opaque)
1696 CharDriverState *chr = opaque;
1698 size = read(0, buf, 1);
1700 /* stdin has been closed. Remove it from the active list. */
1701 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1705 if (qemu_chr_can_read(chr) > 0) {
1706 qemu_chr_read(chr, buf, 1);
1707 } else if (term_fifo_size == 0) {
1708 term_fifo[term_fifo_size++] = buf[0];
1713 /* init terminal so that we can grab keys */
1714 static struct termios oldtty;
1715 static int old_fd0_flags;
1717 static void term_exit(void)
1719 tcsetattr (0, TCSANOW, &oldtty);
1720 fcntl(0, F_SETFL, old_fd0_flags);
1723 static void term_init(void)
1727 tcgetattr (0, &tty);
1729 old_fd0_flags = fcntl(0, F_GETFL);
1731 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1732 |INLCR|IGNCR|ICRNL|IXON);
1733 tty.c_oflag |= OPOST;
1734 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1735 /* if graphical mode, we allow Ctrl-C handling */
1737 tty.c_lflag &= ~ISIG;
1738 tty.c_cflag &= ~(CSIZE|PARENB);
1741 tty.c_cc[VTIME] = 0;
1743 tcsetattr (0, TCSANOW, &tty);
1747 fcntl(0, F_SETFL, O_NONBLOCK);
1750 static CharDriverState *qemu_chr_open_stdio(void)
1752 CharDriverState *chr;
1754 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1756 chr = qemu_chr_open_fd(0, 1);
1757 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1764 #if defined(__linux__)
1765 static CharDriverState *qemu_chr_open_pty(void)
1768 char slave_name[1024];
1769 int master_fd, slave_fd;
1771 /* Not satisfying */
1772 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1776 /* Disabling local echo and line-buffered output */
1777 tcgetattr (master_fd, &tty);
1778 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1780 tty.c_cc[VTIME] = 0;
1781 tcsetattr (master_fd, TCSAFLUSH, &tty);
1783 fprintf(stderr, "char device redirected to %s\n", slave_name);
1784 return qemu_chr_open_fd(master_fd, master_fd);
1787 static void tty_serial_init(int fd, int speed,
1788 int parity, int data_bits, int stop_bits)
1794 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1795 speed, parity, data_bits, stop_bits);
1797 tcgetattr (fd, &tty);
1839 cfsetispeed(&tty, spd);
1840 cfsetospeed(&tty, spd);
1842 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1843 |INLCR|IGNCR|ICRNL|IXON);
1844 tty.c_oflag |= OPOST;
1845 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1846 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1867 tty.c_cflag |= PARENB;
1870 tty.c_cflag |= PARENB | PARODD;
1874 tty.c_cflag |= CSTOPB;
1876 tcsetattr (fd, TCSANOW, &tty);
1879 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1881 FDCharDriver *s = chr->opaque;
1884 case CHR_IOCTL_SERIAL_SET_PARAMS:
1886 QEMUSerialSetParams *ssp = arg;
1887 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1888 ssp->data_bits, ssp->stop_bits);
1891 case CHR_IOCTL_SERIAL_SET_BREAK:
1893 int enable = *(int *)arg;
1895 tcsendbreak(s->fd_in, 1);
1904 static CharDriverState *qemu_chr_open_tty(const char *filename)
1906 CharDriverState *chr;
1909 fd = open(filename, O_RDWR | O_NONBLOCK);
1912 fcntl(fd, F_SETFL, O_NONBLOCK);
1913 tty_serial_init(fd, 115200, 'N', 8, 1);
1914 chr = qemu_chr_open_fd(fd, fd);
1917 chr->chr_ioctl = tty_serial_ioctl;
1918 qemu_chr_reset(chr);
1925 } ParallelCharDriver;
1927 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1929 if (s->mode != mode) {
1931 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1938 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1940 ParallelCharDriver *drv = chr->opaque;
1945 case CHR_IOCTL_PP_READ_DATA:
1946 if (ioctl(fd, PPRDATA, &b) < 0)
1948 *(uint8_t *)arg = b;
1950 case CHR_IOCTL_PP_WRITE_DATA:
1951 b = *(uint8_t *)arg;
1952 if (ioctl(fd, PPWDATA, &b) < 0)
1955 case CHR_IOCTL_PP_READ_CONTROL:
1956 if (ioctl(fd, PPRCONTROL, &b) < 0)
1958 /* Linux gives only the lowest bits, and no way to know data
1959 direction! For better compatibility set the fixed upper
1961 *(uint8_t *)arg = b | 0xc0;
1963 case CHR_IOCTL_PP_WRITE_CONTROL:
1964 b = *(uint8_t *)arg;
1965 if (ioctl(fd, PPWCONTROL, &b) < 0)
1968 case CHR_IOCTL_PP_READ_STATUS:
1969 if (ioctl(fd, PPRSTATUS, &b) < 0)
1971 *(uint8_t *)arg = b;
1973 case CHR_IOCTL_PP_EPP_READ_ADDR:
1974 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1975 struct ParallelIOArg *parg = arg;
1976 int n = read(fd, parg->buffer, parg->count);
1977 if (n != parg->count) {
1982 case CHR_IOCTL_PP_EPP_READ:
1983 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1984 struct ParallelIOArg *parg = arg;
1985 int n = read(fd, parg->buffer, parg->count);
1986 if (n != parg->count) {
1991 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1992 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1993 struct ParallelIOArg *parg = arg;
1994 int n = write(fd, parg->buffer, parg->count);
1995 if (n != parg->count) {
2000 case CHR_IOCTL_PP_EPP_WRITE:
2001 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2002 struct ParallelIOArg *parg = arg;
2003 int n = write(fd, parg->buffer, parg->count);
2004 if (n != parg->count) {
2015 static void pp_close(CharDriverState *chr)
2017 ParallelCharDriver *drv = chr->opaque;
2020 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2021 ioctl(fd, PPRELEASE);
2026 static CharDriverState *qemu_chr_open_pp(const char *filename)
2028 CharDriverState *chr;
2029 ParallelCharDriver *drv;
2032 fd = open(filename, O_RDWR);
2036 if (ioctl(fd, PPCLAIM) < 0) {
2041 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2047 drv->mode = IEEE1284_MODE_COMPAT;
2049 chr = qemu_mallocz(sizeof(CharDriverState));
2055 chr->chr_write = null_chr_write;
2056 chr->chr_ioctl = pp_ioctl;
2057 chr->chr_close = pp_close;
2060 qemu_chr_reset(chr);
2066 static CharDriverState *qemu_chr_open_pty(void)
2072 #endif /* !defined(_WIN32) */
2077 HANDLE hcom, hrecv, hsend;
2078 OVERLAPPED orecv, osend;
2083 #define NSENDBUF 2048
2084 #define NRECVBUF 2048
2085 #define MAXCONNECT 1
2086 #define NTIMEOUT 5000
2088 static int win_chr_poll(void *opaque);
2089 static int win_chr_pipe_poll(void *opaque);
2091 static void win_chr_close(CharDriverState *chr)
2093 WinCharState *s = chr->opaque;
2096 CloseHandle(s->hsend);
2100 CloseHandle(s->hrecv);
2104 CloseHandle(s->hcom);
2108 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2110 qemu_del_polling_cb(win_chr_poll, chr);
2113 static int win_chr_init(CharDriverState *chr, const char *filename)
2115 WinCharState *s = chr->opaque;
2117 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2122 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2124 fprintf(stderr, "Failed CreateEvent\n");
2127 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2129 fprintf(stderr, "Failed CreateEvent\n");
2133 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2134 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2135 if (s->hcom == INVALID_HANDLE_VALUE) {
2136 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2141 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2142 fprintf(stderr, "Failed SetupComm\n");
2146 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2147 size = sizeof(COMMCONFIG);
2148 GetDefaultCommConfig(filename, &comcfg, &size);
2149 comcfg.dcb.DCBlength = sizeof(DCB);
2150 CommConfigDialog(filename, NULL, &comcfg);
2152 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2153 fprintf(stderr, "Failed SetCommState\n");
2157 if (!SetCommMask(s->hcom, EV_ERR)) {
2158 fprintf(stderr, "Failed SetCommMask\n");
2162 cto.ReadIntervalTimeout = MAXDWORD;
2163 if (!SetCommTimeouts(s->hcom, &cto)) {
2164 fprintf(stderr, "Failed SetCommTimeouts\n");
2168 if (!ClearCommError(s->hcom, &err, &comstat)) {
2169 fprintf(stderr, "Failed ClearCommError\n");
2172 qemu_add_polling_cb(win_chr_poll, chr);
2180 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2182 WinCharState *s = chr->opaque;
2183 DWORD len, ret, size, err;
2186 ZeroMemory(&s->osend, sizeof(s->osend));
2187 s->osend.hEvent = s->hsend;
2190 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2192 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2194 err = GetLastError();
2195 if (err == ERROR_IO_PENDING) {
2196 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2214 static int win_chr_read_poll(CharDriverState *chr)
2216 WinCharState *s = chr->opaque;
2218 s->max_size = qemu_chr_can_read(chr);
2222 static void win_chr_readfile(CharDriverState *chr)
2224 WinCharState *s = chr->opaque;
2229 ZeroMemory(&s->orecv, sizeof(s->orecv));
2230 s->orecv.hEvent = s->hrecv;
2231 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2233 err = GetLastError();
2234 if (err == ERROR_IO_PENDING) {
2235 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2240 qemu_chr_read(chr, buf, size);
2244 static void win_chr_read(CharDriverState *chr)
2246 WinCharState *s = chr->opaque;
2248 if (s->len > s->max_size)
2249 s->len = s->max_size;
2253 win_chr_readfile(chr);
2256 static int win_chr_poll(void *opaque)
2258 CharDriverState *chr = opaque;
2259 WinCharState *s = chr->opaque;
2263 ClearCommError(s->hcom, &comerr, &status);
2264 if (status.cbInQue > 0) {
2265 s->len = status.cbInQue;
2266 win_chr_read_poll(chr);
2273 static CharDriverState *qemu_chr_open_win(const char *filename)
2275 CharDriverState *chr;
2278 chr = qemu_mallocz(sizeof(CharDriverState));
2281 s = qemu_mallocz(sizeof(WinCharState));
2287 chr->chr_write = win_chr_write;
2288 chr->chr_close = win_chr_close;
2290 if (win_chr_init(chr, filename) < 0) {
2295 qemu_chr_reset(chr);
2299 static int win_chr_pipe_poll(void *opaque)
2301 CharDriverState *chr = opaque;
2302 WinCharState *s = chr->opaque;
2305 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2308 win_chr_read_poll(chr);
2315 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2317 WinCharState *s = chr->opaque;
2325 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2327 fprintf(stderr, "Failed CreateEvent\n");
2330 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2332 fprintf(stderr, "Failed CreateEvent\n");
2336 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2337 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2338 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2340 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2341 if (s->hcom == INVALID_HANDLE_VALUE) {
2342 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2347 ZeroMemory(&ov, sizeof(ov));
2348 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2349 ret = ConnectNamedPipe(s->hcom, &ov);
2351 fprintf(stderr, "Failed ConnectNamedPipe\n");
2355 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2357 fprintf(stderr, "Failed GetOverlappedResult\n");
2359 CloseHandle(ov.hEvent);
2366 CloseHandle(ov.hEvent);
2369 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2378 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2380 CharDriverState *chr;
2383 chr = qemu_mallocz(sizeof(CharDriverState));
2386 s = qemu_mallocz(sizeof(WinCharState));
2392 chr->chr_write = win_chr_write;
2393 chr->chr_close = win_chr_close;
2395 if (win_chr_pipe_init(chr, filename) < 0) {
2400 qemu_chr_reset(chr);
2404 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2406 CharDriverState *chr;
2409 chr = qemu_mallocz(sizeof(CharDriverState));
2412 s = qemu_mallocz(sizeof(WinCharState));
2419 chr->chr_write = win_chr_write;
2420 qemu_chr_reset(chr);
2424 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2426 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2429 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2433 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2434 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2435 if (fd_out == INVALID_HANDLE_VALUE)
2438 return qemu_chr_open_win_file(fd_out);
2442 /***********************************************************/
2443 /* UDP Net console */
2447 struct sockaddr_in daddr;
2454 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2456 NetCharDriver *s = chr->opaque;
2458 return sendto(s->fd, buf, len, 0,
2459 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2462 static int udp_chr_read_poll(void *opaque)
2464 CharDriverState *chr = opaque;
2465 NetCharDriver *s = chr->opaque;
2467 s->max_size = qemu_chr_can_read(chr);
2469 /* If there were any stray characters in the queue process them
2472 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2473 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2475 s->max_size = qemu_chr_can_read(chr);
2480 static void udp_chr_read(void *opaque)
2482 CharDriverState *chr = opaque;
2483 NetCharDriver *s = chr->opaque;
2485 if (s->max_size == 0)
2487 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2488 s->bufptr = s->bufcnt;
2493 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2494 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2496 s->max_size = qemu_chr_can_read(chr);
2500 static void udp_chr_update_read_handler(CharDriverState *chr)
2502 NetCharDriver *s = chr->opaque;
2505 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2506 udp_chr_read, NULL, chr);
2510 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2512 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2514 int parse_host_src_port(struct sockaddr_in *haddr,
2515 struct sockaddr_in *saddr,
2518 static CharDriverState *qemu_chr_open_udp(const char *def)
2520 CharDriverState *chr = NULL;
2521 NetCharDriver *s = NULL;
2523 struct sockaddr_in saddr;
2525 chr = qemu_mallocz(sizeof(CharDriverState));
2528 s = qemu_mallocz(sizeof(NetCharDriver));
2532 fd = socket(PF_INET, SOCK_DGRAM, 0);
2534 perror("socket(PF_INET, SOCK_DGRAM)");
2538 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2539 printf("Could not parse: %s\n", def);
2543 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2553 chr->chr_write = udp_chr_write;
2554 chr->chr_update_read_handler = udp_chr_update_read_handler;
2567 /***********************************************************/
2568 /* TCP Net console */
2579 static void tcp_chr_accept(void *opaque);
2581 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2583 TCPCharDriver *s = chr->opaque;
2585 return send_all(s->fd, buf, len);
2587 /* XXX: indicate an error ? */
2592 static int tcp_chr_read_poll(void *opaque)
2594 CharDriverState *chr = opaque;
2595 TCPCharDriver *s = chr->opaque;
2598 s->max_size = qemu_chr_can_read(chr);
2603 #define IAC_BREAK 243
2604 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2606 char *buf, int *size)
2608 /* Handle any telnet client's basic IAC options to satisfy char by
2609 * char mode with no echo. All IAC options will be removed from
2610 * the buf and the do_telnetopt variable will be used to track the
2611 * state of the width of the IAC information.
2613 * IAC commands come in sets of 3 bytes with the exception of the
2614 * "IAC BREAK" command and the double IAC.
2620 for (i = 0; i < *size; i++) {
2621 if (s->do_telnetopt > 1) {
2622 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2623 /* Double IAC means send an IAC */
2627 s->do_telnetopt = 1;
2629 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2630 /* Handle IAC break commands by sending a serial break */
2631 qemu_chr_event(chr, CHR_EVENT_BREAK);
2636 if (s->do_telnetopt >= 4) {
2637 s->do_telnetopt = 1;
2640 if ((unsigned char)buf[i] == IAC) {
2641 s->do_telnetopt = 2;
2652 static void tcp_chr_read(void *opaque)
2654 CharDriverState *chr = opaque;
2655 TCPCharDriver *s = chr->opaque;
2659 if (!s->connected || s->max_size <= 0)
2662 if (len > s->max_size)
2664 size = recv(s->fd, buf, len, 0);
2666 /* connection closed */
2668 if (s->listen_fd >= 0) {
2669 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2671 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2674 } else if (size > 0) {
2675 if (s->do_telnetopt)
2676 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2678 qemu_chr_read(chr, buf, size);
2682 static void tcp_chr_connect(void *opaque)
2684 CharDriverState *chr = opaque;
2685 TCPCharDriver *s = chr->opaque;
2688 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2689 tcp_chr_read, NULL, chr);
2690 qemu_chr_reset(chr);
2693 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2694 static void tcp_chr_telnet_init(int fd)
2697 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2698 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2699 send(fd, (char *)buf, 3, 0);
2700 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2701 send(fd, (char *)buf, 3, 0);
2702 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2703 send(fd, (char *)buf, 3, 0);
2704 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2705 send(fd, (char *)buf, 3, 0);
2708 static void socket_set_nodelay(int fd)
2711 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2714 static void tcp_chr_accept(void *opaque)
2716 CharDriverState *chr = opaque;
2717 TCPCharDriver *s = chr->opaque;
2718 struct sockaddr_in saddr;
2720 struct sockaddr_un uaddr;
2722 struct sockaddr *addr;
2729 len = sizeof(uaddr);
2730 addr = (struct sockaddr *)&uaddr;
2734 len = sizeof(saddr);
2735 addr = (struct sockaddr *)&saddr;
2737 fd = accept(s->listen_fd, addr, &len);
2738 if (fd < 0 && errno != EINTR) {
2740 } else if (fd >= 0) {
2741 if (s->do_telnetopt)
2742 tcp_chr_telnet_init(fd);
2746 socket_set_nonblock(fd);
2748 socket_set_nodelay(fd);
2750 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2751 tcp_chr_connect(chr);
2754 static void tcp_chr_close(CharDriverState *chr)
2756 TCPCharDriver *s = chr->opaque;
2759 if (s->listen_fd >= 0)
2760 closesocket(s->listen_fd);
2764 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2768 CharDriverState *chr = NULL;
2769 TCPCharDriver *s = NULL;
2770 int fd = -1, ret, err, val;
2772 int is_waitconnect = 1;
2775 struct sockaddr_in saddr;
2777 struct sockaddr_un uaddr;
2779 struct sockaddr *addr;
2784 addr = (struct sockaddr *)&uaddr;
2785 addrlen = sizeof(uaddr);
2786 if (parse_unix_path(&uaddr, host_str) < 0)
2791 addr = (struct sockaddr *)&saddr;
2792 addrlen = sizeof(saddr);
2793 if (parse_host_port(&saddr, host_str) < 0)
2798 while((ptr = strchr(ptr,','))) {
2800 if (!strncmp(ptr,"server",6)) {
2802 } else if (!strncmp(ptr,"nowait",6)) {
2804 } else if (!strncmp(ptr,"nodelay",6)) {
2807 printf("Unknown option: %s\n", ptr);
2814 chr = qemu_mallocz(sizeof(CharDriverState));
2817 s = qemu_mallocz(sizeof(TCPCharDriver));
2823 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2826 fd = socket(PF_INET, SOCK_STREAM, 0);
2831 if (!is_waitconnect)
2832 socket_set_nonblock(fd);
2837 s->is_unix = is_unix;
2838 s->do_nodelay = do_nodelay && !is_unix;
2841 chr->chr_write = tcp_chr_write;
2842 chr->chr_close = tcp_chr_close;
2845 /* allow fast reuse */
2849 strncpy(path, uaddr.sun_path, 108);
2856 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2859 ret = bind(fd, addr, addrlen);
2863 ret = listen(fd, 0);
2868 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2870 s->do_telnetopt = 1;
2873 ret = connect(fd, addr, addrlen);
2875 err = socket_error();
2876 if (err == EINTR || err == EWOULDBLOCK) {
2877 } else if (err == EINPROGRESS) {
2880 } else if (err == WSAEALREADY) {
2892 socket_set_nodelay(fd);
2894 tcp_chr_connect(chr);
2896 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2899 if (is_listen && is_waitconnect) {
2900 printf("QEMU waiting for connection on: %s\n", host_str);
2901 tcp_chr_accept(chr);
2902 socket_set_nonblock(s->listen_fd);
2914 CharDriverState *qemu_chr_open(const char *filename)
2918 if (!strcmp(filename, "vc")) {
2919 return text_console_init(&display_state);
2920 } else if (!strcmp(filename, "null")) {
2921 return qemu_chr_open_null();
2923 if (strstart(filename, "tcp:", &p)) {
2924 return qemu_chr_open_tcp(p, 0, 0);
2926 if (strstart(filename, "telnet:", &p)) {
2927 return qemu_chr_open_tcp(p, 1, 0);
2929 if (strstart(filename, "udp:", &p)) {
2930 return qemu_chr_open_udp(p);
2932 if (strstart(filename, "mon:", &p)) {
2933 CharDriverState *drv = qemu_chr_open(p);
2935 drv = qemu_chr_open_mux(drv);
2936 monitor_init(drv, !nographic);
2939 printf("Unable to open driver: %s\n", p);
2943 if (strstart(filename, "unix:", &p)) {
2944 return qemu_chr_open_tcp(p, 0, 1);
2945 } else if (strstart(filename, "file:", &p)) {
2946 return qemu_chr_open_file_out(p);
2947 } else if (strstart(filename, "pipe:", &p)) {
2948 return qemu_chr_open_pipe(p);
2949 } else if (!strcmp(filename, "pty")) {
2950 return qemu_chr_open_pty();
2951 } else if (!strcmp(filename, "stdio")) {
2952 return qemu_chr_open_stdio();
2955 #if defined(__linux__)
2956 if (strstart(filename, "/dev/parport", NULL)) {
2957 return qemu_chr_open_pp(filename);
2959 if (strstart(filename, "/dev/", NULL)) {
2960 return qemu_chr_open_tty(filename);
2964 if (strstart(filename, "COM", NULL)) {
2965 return qemu_chr_open_win(filename);
2967 if (strstart(filename, "pipe:", &p)) {
2968 return qemu_chr_open_win_pipe(p);
2970 if (strstart(filename, "con:", NULL)) {
2971 return qemu_chr_open_win_con(filename);
2973 if (strstart(filename, "file:", &p)) {
2974 return qemu_chr_open_win_file_out(p);
2982 void qemu_chr_close(CharDriverState *chr)
2985 chr->chr_close(chr);
2988 /***********************************************************/
2989 /* network device redirectors */
2991 void hex_dump(FILE *f, const uint8_t *buf, int size)
2995 for(i=0;i<size;i+=16) {
2999 fprintf(f, "%08x ", i);
3002 fprintf(f, " %02x", buf[i+j]);
3007 for(j=0;j<len;j++) {
3009 if (c < ' ' || c > '~')
3011 fprintf(f, "%c", c);
3017 static int parse_macaddr(uint8_t *macaddr, const char *p)
3020 for(i = 0; i < 6; i++) {
3021 macaddr[i] = strtol(p, (char **)&p, 16);
3034 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3039 p1 = strchr(p, sep);
3045 if (len > buf_size - 1)
3047 memcpy(buf, p, len);
3054 int parse_host_src_port(struct sockaddr_in *haddr,
3055 struct sockaddr_in *saddr,
3056 const char *input_str)
3058 char *str = strdup(input_str);
3059 char *host_str = str;
3064 * Chop off any extra arguments at the end of the string which
3065 * would start with a comma, then fill in the src port information
3066 * if it was provided else use the "any address" and "any port".
3068 if ((ptr = strchr(str,',')))
3071 if ((src_str = strchr(input_str,'@'))) {
3076 if (parse_host_port(haddr, host_str) < 0)
3079 if (!src_str || *src_str == '\0')
3082 if (parse_host_port(saddr, src_str) < 0)
3093 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3101 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3103 saddr->sin_family = AF_INET;
3104 if (buf[0] == '\0') {
3105 saddr->sin_addr.s_addr = 0;
3107 if (isdigit(buf[0])) {
3108 if (!inet_aton(buf, &saddr->sin_addr))
3111 if ((he = gethostbyname(buf)) == NULL)
3113 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3116 port = strtol(p, (char **)&r, 0);
3119 saddr->sin_port = htons(port);
3124 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3129 len = MIN(108, strlen(str));
3130 p = strchr(str, ',');
3132 len = MIN(len, p - str);
3134 memset(uaddr, 0, sizeof(*uaddr));
3136 uaddr->sun_family = AF_UNIX;
3137 memcpy(uaddr->sun_path, str, len);
3143 /* find or alloc a new VLAN */
3144 VLANState *qemu_find_vlan(int id)
3146 VLANState **pvlan, *vlan;
3147 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3151 vlan = qemu_mallocz(sizeof(VLANState));
3156 pvlan = &first_vlan;
3157 while (*pvlan != NULL)
3158 pvlan = &(*pvlan)->next;
3163 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3164 IOReadHandler *fd_read,
3165 IOCanRWHandler *fd_can_read,
3168 VLANClientState *vc, **pvc;
3169 vc = qemu_mallocz(sizeof(VLANClientState));
3172 vc->fd_read = fd_read;
3173 vc->fd_can_read = fd_can_read;
3174 vc->opaque = opaque;
3178 pvc = &vlan->first_client;
3179 while (*pvc != NULL)
3180 pvc = &(*pvc)->next;
3185 int qemu_can_send_packet(VLANClientState *vc1)
3187 VLANState *vlan = vc1->vlan;
3188 VLANClientState *vc;
3190 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3192 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3199 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3201 VLANState *vlan = vc1->vlan;
3202 VLANClientState *vc;
3205 printf("vlan %d send:\n", vlan->id);
3206 hex_dump(stdout, buf, size);
3208 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3210 vc->fd_read(vc->opaque, buf, size);
3215 #if defined(CONFIG_SLIRP)
3217 /* slirp network adapter */
3219 static int slirp_inited;
3220 static VLANClientState *slirp_vc;
3222 int slirp_can_output(void)
3224 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3227 void slirp_output(const uint8_t *pkt, int pkt_len)
3230 printf("slirp output:\n");
3231 hex_dump(stdout, pkt, pkt_len);
3235 qemu_send_packet(slirp_vc, pkt, pkt_len);
3238 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3241 printf("slirp input:\n");
3242 hex_dump(stdout, buf, size);
3244 slirp_input(buf, size);
3247 static int net_slirp_init(VLANState *vlan)
3249 if (!slirp_inited) {
3253 slirp_vc = qemu_new_vlan_client(vlan,
3254 slirp_receive, NULL, NULL);
3255 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3259 static void net_slirp_redir(const char *redir_str)
3264 struct in_addr guest_addr;
3265 int host_port, guest_port;
3267 if (!slirp_inited) {
3273 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3275 if (!strcmp(buf, "tcp")) {
3277 } else if (!strcmp(buf, "udp")) {
3283 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3285 host_port = strtol(buf, &r, 0);
3289 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3291 if (buf[0] == '\0') {
3292 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3294 if (!inet_aton(buf, &guest_addr))
3297 guest_port = strtol(p, &r, 0);
3301 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3302 fprintf(stderr, "qemu: could not set up redirection\n");
3307 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3315 static void smb_exit(void)
3319 char filename[1024];
3321 /* erase all the files in the directory */
3322 d = opendir(smb_dir);
3327 if (strcmp(de->d_name, ".") != 0 &&
3328 strcmp(de->d_name, "..") != 0) {
3329 snprintf(filename, sizeof(filename), "%s/%s",
3330 smb_dir, de->d_name);
3338 /* automatic user mode samba server configuration */
3339 void net_slirp_smb(const char *exported_dir)
3341 char smb_conf[1024];
3342 char smb_cmdline[1024];
3345 if (!slirp_inited) {
3350 /* XXX: better tmp dir construction */
3351 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3352 if (mkdir(smb_dir, 0700) < 0) {
3353 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3356 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3358 f = fopen(smb_conf, "w");
3360 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3367 "socket address=127.0.0.1\n"
3368 "pid directory=%s\n"
3369 "lock directory=%s\n"
3370 "log file=%s/log.smbd\n"
3371 "smb passwd file=%s/smbpasswd\n"
3372 "security = share\n"
3387 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3388 SMBD_COMMAND, smb_conf);
3390 slirp_add_exec(0, smb_cmdline, 4, 139);
3393 #endif /* !defined(_WIN32) */
3395 #endif /* CONFIG_SLIRP */
3397 #if !defined(_WIN32)
3399 typedef struct TAPState {
3400 VLANClientState *vc;
3404 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3406 TAPState *s = opaque;
3409 ret = write(s->fd, buf, size);
3410 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3417 static void tap_send(void *opaque)
3419 TAPState *s = opaque;
3426 sbuf.maxlen = sizeof(buf);
3428 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3430 size = read(s->fd, buf, sizeof(buf));
3433 qemu_send_packet(s->vc, buf, size);
3439 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3443 s = qemu_mallocz(sizeof(TAPState));
3447 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3448 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3449 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3454 static int tap_open(char *ifname, int ifname_size)
3460 fd = open("/dev/tap", O_RDWR);
3462 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3467 dev = devname(s.st_rdev, S_IFCHR);
3468 pstrcpy(ifname, ifname_size, dev);
3470 fcntl(fd, F_SETFL, O_NONBLOCK);
3473 #elif defined(__sun__)
3474 #define TUNNEWPPA (('T'<<16) | 0x0001)
3476 * Allocate TAP device, returns opened fd.
3477 * Stores dev name in the first arg(must be large enough).
3479 int tap_alloc(char *dev)
3481 int tap_fd, if_fd, ppa = -1;
3482 static int ip_fd = 0;
3485 static int arp_fd = 0;
3486 int ip_muxid, arp_muxid;
3487 struct strioctl strioc_if, strioc_ppa;
3488 int link_type = I_PLINK;;
3490 char actual_name[32] = "";
3492 memset(&ifr, 0x0, sizeof(ifr));
3496 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3500 /* Check if IP device was opened */
3504 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3505 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3509 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3510 syslog(LOG_ERR, "Can't open /dev/tap");
3514 /* Assign a new PPA and get its unit number. */
3515 strioc_ppa.ic_cmd = TUNNEWPPA;
3516 strioc_ppa.ic_timout = 0;
3517 strioc_ppa.ic_len = sizeof(ppa);
3518 strioc_ppa.ic_dp = (char *)&ppa;
3519 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3520 syslog (LOG_ERR, "Can't assign new interface");
3522 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3523 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3526 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3527 syslog(LOG_ERR, "Can't push IP module");
3531 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3532 syslog(LOG_ERR, "Can't get flags\n");
3534 snprintf (actual_name, 32, "tap%d", ppa);
3535 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3538 /* Assign ppa according to the unit number returned by tun device */
3540 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3541 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3542 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3543 syslog (LOG_ERR, "Can't get flags\n");
3544 /* Push arp module to if_fd */
3545 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3546 syslog (LOG_ERR, "Can't push ARP module (2)");
3548 /* Push arp module to ip_fd */
3549 if (ioctl (ip_fd, I_POP, NULL) < 0)
3550 syslog (LOG_ERR, "I_POP failed\n");
3551 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3552 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3554 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3555 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3557 /* Set ifname to arp */
3558 strioc_if.ic_cmd = SIOCSLIFNAME;
3559 strioc_if.ic_timout = 0;
3560 strioc_if.ic_len = sizeof(ifr);
3561 strioc_if.ic_dp = (char *)𝔦
3562 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3563 syslog (LOG_ERR, "Can't set ifname to arp\n");
3566 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3567 syslog(LOG_ERR, "Can't link TAP device to IP");
3571 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3572 syslog (LOG_ERR, "Can't link TAP device to ARP");
3576 memset(&ifr, 0x0, sizeof(ifr));
3577 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3578 ifr.lifr_ip_muxid = ip_muxid;
3579 ifr.lifr_arp_muxid = arp_muxid;
3581 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3583 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3584 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3585 syslog (LOG_ERR, "Can't set multiplexor id");
3588 sprintf(dev, "tap%d", ppa);
3592 static int tap_open(char *ifname, int ifname_size)
3596 if( (fd = tap_alloc(dev)) < 0 ){
3597 fprintf(stderr, "Cannot allocate TAP device\n");
3600 pstrcpy(ifname, ifname_size, dev);
3601 fcntl(fd, F_SETFL, O_NONBLOCK);
3605 static int tap_open(char *ifname, int ifname_size)
3610 fd = open("/dev/net/tun", O_RDWR);
3612 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3615 memset(&ifr, 0, sizeof(ifr));
3616 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3617 if (ifname[0] != '\0')
3618 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3620 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3621 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3623 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3627 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3628 fcntl(fd, F_SETFL, O_NONBLOCK);
3633 static int net_tap_init(VLANState *vlan, const char *ifname1,
3634 const char *setup_script)
3637 int pid, status, fd;
3642 if (ifname1 != NULL)
3643 pstrcpy(ifname, sizeof(ifname), ifname1);
3646 fd = tap_open(ifname, sizeof(ifname));
3650 if (!setup_script || !strcmp(setup_script, "no"))
3652 if (setup_script[0] != '\0') {
3653 /* try to launch network init script */
3657 int open_max = sysconf (_SC_OPEN_MAX), i;
3658 for (i = 0; i < open_max; i++)
3659 if (i != STDIN_FILENO &&
3660 i != STDOUT_FILENO &&
3661 i != STDERR_FILENO &&
3666 *parg++ = (char *)setup_script;
3669 execv(setup_script, args);
3672 while (waitpid(pid, &status, 0) != pid);
3673 if (!WIFEXITED(status) ||
3674 WEXITSTATUS(status) != 0) {
3675 fprintf(stderr, "%s: could not launch network script\n",
3681 s = net_tap_fd_init(vlan, fd);
3684 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3685 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3689 #endif /* !_WIN32 */
3691 /* network connection */
3692 typedef struct NetSocketState {
3693 VLANClientState *vc;
3695 int state; /* 0 = getting length, 1 = getting data */
3699 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3702 typedef struct NetSocketListenState {
3705 } NetSocketListenState;
3707 /* XXX: we consider we can send the whole packet without blocking */
3708 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3710 NetSocketState *s = opaque;
3714 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3715 send_all(s->fd, buf, size);
3718 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3720 NetSocketState *s = opaque;
3721 sendto(s->fd, buf, size, 0,
3722 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3725 static void net_socket_send(void *opaque)
3727 NetSocketState *s = opaque;
3732 size = recv(s->fd, buf1, sizeof(buf1), 0);
3734 err = socket_error();
3735 if (err != EWOULDBLOCK)
3737 } else if (size == 0) {
3738 /* end of connection */
3740 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3746 /* reassemble a packet from the network */
3752 memcpy(s->buf + s->index, buf, l);
3756 if (s->index == 4) {
3758 s->packet_len = ntohl(*(uint32_t *)s->buf);
3764 l = s->packet_len - s->index;
3767 memcpy(s->buf + s->index, buf, l);
3771 if (s->index >= s->packet_len) {
3772 qemu_send_packet(s->vc, s->buf, s->packet_len);
3781 static void net_socket_send_dgram(void *opaque)
3783 NetSocketState *s = opaque;
3786 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3790 /* end of connection */
3791 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3794 qemu_send_packet(s->vc, s->buf, size);
3797 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3802 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3803 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3804 inet_ntoa(mcastaddr->sin_addr),
3805 (int)ntohl(mcastaddr->sin_addr.s_addr));
3809 fd = socket(PF_INET, SOCK_DGRAM, 0);
3811 perror("socket(PF_INET, SOCK_DGRAM)");
3816 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3817 (const char *)&val, sizeof(val));
3819 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3823 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3829 /* Add host to multicast group */
3830 imr.imr_multiaddr = mcastaddr->sin_addr;
3831 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3833 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3834 (const char *)&imr, sizeof(struct ip_mreq));
3836 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3840 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3842 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3843 (const char *)&val, sizeof(val));
3845 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3849 socket_set_nonblock(fd);
3857 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3860 struct sockaddr_in saddr;
3862 socklen_t saddr_len;
3865 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3866 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3867 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3871 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3873 if (saddr.sin_addr.s_addr==0) {
3874 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3878 /* clone dgram socket */
3879 newfd = net_socket_mcast_create(&saddr);
3881 /* error already reported by net_socket_mcast_create() */
3885 /* clone newfd to fd, close newfd */
3890 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3891 fd, strerror(errno));
3896 s = qemu_mallocz(sizeof(NetSocketState));
3901 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3902 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3904 /* mcast: save bound address as dst */
3905 if (is_connected) s->dgram_dst=saddr;
3907 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3908 "socket: fd=%d (%s mcast=%s:%d)",
3909 fd, is_connected? "cloned" : "",
3910 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3914 static void net_socket_connect(void *opaque)
3916 NetSocketState *s = opaque;
3917 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3920 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3924 s = qemu_mallocz(sizeof(NetSocketState));
3928 s->vc = qemu_new_vlan_client(vlan,
3929 net_socket_receive, NULL, s);
3930 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3931 "socket: fd=%d", fd);
3933 net_socket_connect(s);
3935 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3940 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3943 int so_type=-1, optlen=sizeof(so_type);
3945 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3946 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3951 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3953 return net_socket_fd_init_stream(vlan, fd, is_connected);
3955 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3956 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3957 return net_socket_fd_init_stream(vlan, fd, is_connected);
3962 static void net_socket_accept(void *opaque)
3964 NetSocketListenState *s = opaque;
3966 struct sockaddr_in saddr;
3971 len = sizeof(saddr);
3972 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3973 if (fd < 0 && errno != EINTR) {
3975 } else if (fd >= 0) {
3979 s1 = net_socket_fd_init(s->vlan, fd, 1);
3983 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3984 "socket: connection from %s:%d",
3985 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3989 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3991 NetSocketListenState *s;
3993 struct sockaddr_in saddr;
3995 if (parse_host_port(&saddr, host_str) < 0)
3998 s = qemu_mallocz(sizeof(NetSocketListenState));
4002 fd = socket(PF_INET, SOCK_STREAM, 0);
4007 socket_set_nonblock(fd);
4009 /* allow fast reuse */
4011 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4013 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4018 ret = listen(fd, 0);
4025 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4029 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4032 int fd, connected, ret, err;
4033 struct sockaddr_in saddr;
4035 if (parse_host_port(&saddr, host_str) < 0)
4038 fd = socket(PF_INET, SOCK_STREAM, 0);
4043 socket_set_nonblock(fd);
4047 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4049 err = socket_error();
4050 if (err == EINTR || err == EWOULDBLOCK) {
4051 } else if (err == EINPROGRESS) {
4054 } else if (err == WSAEALREADY) {
4067 s = net_socket_fd_init(vlan, fd, connected);
4070 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4071 "socket: connect to %s:%d",
4072 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4076 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4080 struct sockaddr_in saddr;
4082 if (parse_host_port(&saddr, host_str) < 0)
4086 fd = net_socket_mcast_create(&saddr);
4090 s = net_socket_fd_init(vlan, fd, 0);
4094 s->dgram_dst = saddr;
4096 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4097 "socket: mcast=%s:%d",
4098 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4103 static int get_param_value(char *buf, int buf_size,
4104 const char *tag, const char *str)
4113 while (*p != '\0' && *p != '=') {
4114 if ((q - option) < sizeof(option) - 1)
4122 if (!strcmp(tag, option)) {
4124 while (*p != '\0' && *p != ',') {
4125 if ((q - buf) < buf_size - 1)
4132 while (*p != '\0' && *p != ',') {
4143 static int net_client_init(const char *str)
4154 while (*p != '\0' && *p != ',') {
4155 if ((q - device) < sizeof(device) - 1)
4163 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4164 vlan_id = strtol(buf, NULL, 0);
4166 vlan = qemu_find_vlan(vlan_id);
4168 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4171 if (!strcmp(device, "nic")) {
4175 if (nb_nics >= MAX_NICS) {
4176 fprintf(stderr, "Too Many NICs\n");
4179 nd = &nd_table[nb_nics];
4180 macaddr = nd->macaddr;
4186 macaddr[5] = 0x56 + nb_nics;
4188 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4189 if (parse_macaddr(macaddr, buf) < 0) {
4190 fprintf(stderr, "invalid syntax for ethernet address\n");
4194 if (get_param_value(buf, sizeof(buf), "model", p)) {
4195 nd->model = strdup(buf);
4199 vlan->nb_guest_devs++;
4202 if (!strcmp(device, "none")) {
4203 /* does nothing. It is needed to signal that no network cards
4208 if (!strcmp(device, "user")) {
4209 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4210 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4212 vlan->nb_host_devs++;
4213 ret = net_slirp_init(vlan);
4217 if (!strcmp(device, "tap")) {
4219 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4220 fprintf(stderr, "tap: no interface name\n");
4223 vlan->nb_host_devs++;
4224 ret = tap_win32_init(vlan, ifname);
4227 if (!strcmp(device, "tap")) {
4229 char setup_script[1024];
4231 vlan->nb_host_devs++;
4232 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4233 fd = strtol(buf, NULL, 0);
4235 if (net_tap_fd_init(vlan, fd))
4238 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4241 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4242 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4244 ret = net_tap_init(vlan, ifname, setup_script);
4248 if (!strcmp(device, "socket")) {
4249 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4251 fd = strtol(buf, NULL, 0);
4253 if (net_socket_fd_init(vlan, fd, 1))
4255 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4256 ret = net_socket_listen_init(vlan, buf);
4257 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4258 ret = net_socket_connect_init(vlan, buf);
4259 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4260 ret = net_socket_mcast_init(vlan, buf);
4262 fprintf(stderr, "Unknown socket options: %s\n", p);
4265 vlan->nb_host_devs++;
4268 fprintf(stderr, "Unknown network device: %s\n", device);
4272 fprintf(stderr, "Could not initialize device '%s'\n", device);
4278 void do_info_network(void)
4281 VLANClientState *vc;
4283 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4284 term_printf("VLAN %d devices:\n", vlan->id);
4285 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4286 term_printf(" %s\n", vc->info_str);
4290 /***********************************************************/
4293 static USBPort *used_usb_ports;
4294 static USBPort *free_usb_ports;
4296 /* ??? Maybe change this to register a hub to keep track of the topology. */
4297 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4298 usb_attachfn attach)
4300 port->opaque = opaque;
4301 port->index = index;
4302 port->attach = attach;
4303 port->next = free_usb_ports;
4304 free_usb_ports = port;
4307 static int usb_device_add(const char *devname)
4313 if (!free_usb_ports)
4316 if (strstart(devname, "host:", &p)) {
4317 dev = usb_host_device_open(p);
4318 } else if (!strcmp(devname, "mouse")) {
4319 dev = usb_mouse_init();
4320 } else if (!strcmp(devname, "tablet")) {
4321 dev = usb_tablet_init();
4322 } else if (strstart(devname, "disk:", &p)) {
4323 dev = usb_msd_init(p);
4324 } else if (!strcmp(devname, "wacom-tablet")) {
4325 dev = usb_wacom_init();
4332 /* Find a USB port to add the device to. */
4333 port = free_usb_ports;
4337 /* Create a new hub and chain it on. */
4338 free_usb_ports = NULL;
4339 port->next = used_usb_ports;
4340 used_usb_ports = port;
4342 hub = usb_hub_init(VM_USB_HUB_SIZE);
4343 usb_attach(port, hub);
4344 port = free_usb_ports;
4347 free_usb_ports = port->next;
4348 port->next = used_usb_ports;
4349 used_usb_ports = port;
4350 usb_attach(port, dev);
4354 static int usb_device_del(const char *devname)
4362 if (!used_usb_ports)
4365 p = strchr(devname, '.');
4368 bus_num = strtoul(devname, NULL, 0);
4369 addr = strtoul(p + 1, NULL, 0);
4373 lastp = &used_usb_ports;
4374 port = used_usb_ports;
4375 while (port && port->dev->addr != addr) {
4376 lastp = &port->next;
4384 *lastp = port->next;
4385 usb_attach(port, NULL);
4386 dev->handle_destroy(dev);
4387 port->next = free_usb_ports;
4388 free_usb_ports = port;
4392 void do_usb_add(const char *devname)
4395 ret = usb_device_add(devname);
4397 term_printf("Could not add USB device '%s'\n", devname);
4400 void do_usb_del(const char *devname)
4403 ret = usb_device_del(devname);
4405 term_printf("Could not remove USB device '%s'\n", devname);
4412 const char *speed_str;
4415 term_printf("USB support not enabled\n");
4419 for (port = used_usb_ports; port; port = port->next) {
4423 switch(dev->speed) {
4427 case USB_SPEED_FULL:
4430 case USB_SPEED_HIGH:
4437 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4438 0, dev->addr, speed_str, dev->devname);
4442 /***********************************************************/
4443 /* PCMCIA/Cardbus */
4445 static struct pcmcia_socket_entry_s {
4446 struct pcmcia_socket_s *socket;
4447 struct pcmcia_socket_entry_s *next;
4448 } *pcmcia_sockets = 0;
4450 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4452 struct pcmcia_socket_entry_s *entry;
4454 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4455 entry->socket = socket;
4456 entry->next = pcmcia_sockets;
4457 pcmcia_sockets = entry;
4460 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4462 struct pcmcia_socket_entry_s *entry, **ptr;
4464 ptr = &pcmcia_sockets;
4465 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4466 if (entry->socket == socket) {
4472 void pcmcia_info(void)
4474 struct pcmcia_socket_entry_s *iter;
4475 if (!pcmcia_sockets)
4476 term_printf("No PCMCIA sockets\n");
4478 for (iter = pcmcia_sockets; iter; iter = iter->next)
4479 term_printf("%s: %s\n", iter->socket->slot_string,
4480 iter->socket->attached ? iter->socket->card_string :
4484 /***********************************************************/
4487 #define MAX_IO_HANDLERS 64
4489 typedef struct IOHandlerRecord {
4491 IOCanRWHandler *fd_read_poll;
4493 IOHandler *fd_write;
4496 /* temporary data */
4498 struct IOHandlerRecord *next;
4501 static IOHandlerRecord *first_io_handler;
4503 /* XXX: fd_read_poll should be suppressed, but an API change is
4504 necessary in the character devices to suppress fd_can_read(). */
4505 int qemu_set_fd_handler2(int fd,
4506 IOCanRWHandler *fd_read_poll,
4508 IOHandler *fd_write,
4511 IOHandlerRecord **pioh, *ioh;
4513 if (!fd_read && !fd_write) {
4514 pioh = &first_io_handler;
4519 if (ioh->fd == fd) {
4526 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4530 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4533 ioh->next = first_io_handler;
4534 first_io_handler = ioh;
4537 ioh->fd_read_poll = fd_read_poll;
4538 ioh->fd_read = fd_read;
4539 ioh->fd_write = fd_write;
4540 ioh->opaque = opaque;
4546 int qemu_set_fd_handler(int fd,
4548 IOHandler *fd_write,
4551 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4554 /***********************************************************/
4555 /* Polling handling */
4557 typedef struct PollingEntry {
4560 struct PollingEntry *next;
4563 static PollingEntry *first_polling_entry;
4565 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4567 PollingEntry **ppe, *pe;
4568 pe = qemu_mallocz(sizeof(PollingEntry));
4572 pe->opaque = opaque;
4573 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4578 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4580 PollingEntry **ppe, *pe;
4581 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4583 if (pe->func == func && pe->opaque == opaque) {
4592 /***********************************************************/
4593 /* Wait objects support */
4594 typedef struct WaitObjects {
4596 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4597 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4598 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4601 static WaitObjects wait_objects = {0};
4603 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4605 WaitObjects *w = &wait_objects;
4607 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4609 w->events[w->num] = handle;
4610 w->func[w->num] = func;
4611 w->opaque[w->num] = opaque;
4616 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4619 WaitObjects *w = &wait_objects;
4622 for (i = 0; i < w->num; i++) {
4623 if (w->events[i] == handle)
4626 w->events[i] = w->events[i + 1];
4627 w->func[i] = w->func[i + 1];
4628 w->opaque[i] = w->opaque[i + 1];
4636 /***********************************************************/
4637 /* savevm/loadvm support */
4639 #define IO_BUF_SIZE 32768
4643 BlockDriverState *bs;
4646 int64_t base_offset;
4647 int64_t buf_offset; /* start of buffer when writing, end of buffer
4650 int buf_size; /* 0 when writing */
4651 uint8_t buf[IO_BUF_SIZE];
4654 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4658 f = qemu_mallocz(sizeof(QEMUFile));
4661 if (!strcmp(mode, "wb")) {
4663 } else if (!strcmp(mode, "rb")) {
4668 f->outfile = fopen(filename, mode);
4680 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4684 f = qemu_mallocz(sizeof(QEMUFile));
4689 f->is_writable = is_writable;
4690 f->base_offset = offset;
4694 void qemu_fflush(QEMUFile *f)
4696 if (!f->is_writable)
4698 if (f->buf_index > 0) {
4700 fseek(f->outfile, f->buf_offset, SEEK_SET);
4701 fwrite(f->buf, 1, f->buf_index, f->outfile);
4703 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4704 f->buf, f->buf_index);
4706 f->buf_offset += f->buf_index;
4711 static void qemu_fill_buffer(QEMUFile *f)
4718 fseek(f->outfile, f->buf_offset, SEEK_SET);
4719 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4723 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4724 f->buf, IO_BUF_SIZE);
4730 f->buf_offset += len;
4733 void qemu_fclose(QEMUFile *f)
4743 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4747 l = IO_BUF_SIZE - f->buf_index;
4750 memcpy(f->buf + f->buf_index, buf, l);
4754 if (f->buf_index >= IO_BUF_SIZE)
4759 void qemu_put_byte(QEMUFile *f, int v)
4761 f->buf[f->buf_index++] = v;
4762 if (f->buf_index >= IO_BUF_SIZE)
4766 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4772 l = f->buf_size - f->buf_index;
4774 qemu_fill_buffer(f);
4775 l = f->buf_size - f->buf_index;
4781 memcpy(buf, f->buf + f->buf_index, l);
4786 return size1 - size;
4789 int qemu_get_byte(QEMUFile *f)
4791 if (f->buf_index >= f->buf_size) {
4792 qemu_fill_buffer(f);
4793 if (f->buf_index >= f->buf_size)
4796 return f->buf[f->buf_index++];
4799 int64_t qemu_ftell(QEMUFile *f)
4801 return f->buf_offset - f->buf_size + f->buf_index;
4804 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4806 if (whence == SEEK_SET) {
4808 } else if (whence == SEEK_CUR) {
4809 pos += qemu_ftell(f);
4811 /* SEEK_END not supported */
4814 if (f->is_writable) {
4816 f->buf_offset = pos;
4818 f->buf_offset = pos;
4825 void qemu_put_be16(QEMUFile *f, unsigned int v)
4827 qemu_put_byte(f, v >> 8);
4828 qemu_put_byte(f, v);
4831 void qemu_put_be32(QEMUFile *f, unsigned int v)
4833 qemu_put_byte(f, v >> 24);
4834 qemu_put_byte(f, v >> 16);
4835 qemu_put_byte(f, v >> 8);
4836 qemu_put_byte(f, v);
4839 void qemu_put_be64(QEMUFile *f, uint64_t v)
4841 qemu_put_be32(f, v >> 32);
4842 qemu_put_be32(f, v);
4845 unsigned int qemu_get_be16(QEMUFile *f)
4848 v = qemu_get_byte(f) << 8;
4849 v |= qemu_get_byte(f);
4853 unsigned int qemu_get_be32(QEMUFile *f)
4856 v = qemu_get_byte(f) << 24;
4857 v |= qemu_get_byte(f) << 16;
4858 v |= qemu_get_byte(f) << 8;
4859 v |= qemu_get_byte(f);
4863 uint64_t qemu_get_be64(QEMUFile *f)
4866 v = (uint64_t)qemu_get_be32(f) << 32;
4867 v |= qemu_get_be32(f);
4871 typedef struct SaveStateEntry {
4875 SaveStateHandler *save_state;
4876 LoadStateHandler *load_state;
4878 struct SaveStateEntry *next;
4881 static SaveStateEntry *first_se;
4883 int register_savevm(const char *idstr,
4886 SaveStateHandler *save_state,
4887 LoadStateHandler *load_state,
4890 SaveStateEntry *se, **pse;
4892 se = qemu_malloc(sizeof(SaveStateEntry));
4895 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4896 se->instance_id = instance_id;
4897 se->version_id = version_id;
4898 se->save_state = save_state;
4899 se->load_state = load_state;
4900 se->opaque = opaque;
4903 /* add at the end of list */
4905 while (*pse != NULL)
4906 pse = &(*pse)->next;
4911 #define QEMU_VM_FILE_MAGIC 0x5145564d
4912 #define QEMU_VM_FILE_VERSION 0x00000002
4914 int qemu_savevm_state(QEMUFile *f)
4918 int64_t cur_pos, len_pos, total_len_pos;
4920 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4921 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4922 total_len_pos = qemu_ftell(f);
4923 qemu_put_be64(f, 0); /* total size */
4925 for(se = first_se; se != NULL; se = se->next) {
4927 len = strlen(se->idstr);
4928 qemu_put_byte(f, len);
4929 qemu_put_buffer(f, se->idstr, len);
4931 qemu_put_be32(f, se->instance_id);
4932 qemu_put_be32(f, se->version_id);
4934 /* record size: filled later */
4935 len_pos = qemu_ftell(f);
4936 qemu_put_be32(f, 0);
4938 se->save_state(f, se->opaque);
4940 /* fill record size */
4941 cur_pos = qemu_ftell(f);
4942 len = cur_pos - len_pos - 4;
4943 qemu_fseek(f, len_pos, SEEK_SET);
4944 qemu_put_be32(f, len);
4945 qemu_fseek(f, cur_pos, SEEK_SET);
4947 cur_pos = qemu_ftell(f);
4948 qemu_fseek(f, total_len_pos, SEEK_SET);
4949 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4950 qemu_fseek(f, cur_pos, SEEK_SET);
4956 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4960 for(se = first_se; se != NULL; se = se->next) {
4961 if (!strcmp(se->idstr, idstr) &&
4962 instance_id == se->instance_id)
4968 int qemu_loadvm_state(QEMUFile *f)
4971 int len, ret, instance_id, record_len, version_id;
4972 int64_t total_len, end_pos, cur_pos;
4976 v = qemu_get_be32(f);
4977 if (v != QEMU_VM_FILE_MAGIC)
4979 v = qemu_get_be32(f);
4980 if (v != QEMU_VM_FILE_VERSION) {
4985 total_len = qemu_get_be64(f);
4986 end_pos = total_len + qemu_ftell(f);
4988 if (qemu_ftell(f) >= end_pos)
4990 len = qemu_get_byte(f);
4991 qemu_get_buffer(f, idstr, len);
4993 instance_id = qemu_get_be32(f);
4994 version_id = qemu_get_be32(f);
4995 record_len = qemu_get_be32(f);
4997 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4998 idstr, instance_id, version_id, record_len);
5000 cur_pos = qemu_ftell(f);
5001 se = find_se(idstr, instance_id);
5003 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5004 instance_id, idstr);
5006 ret = se->load_state(f, se->opaque, version_id);
5008 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5009 instance_id, idstr);
5012 /* always seek to exact end of record */
5013 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5020 /* device can contain snapshots */
5021 static int bdrv_can_snapshot(BlockDriverState *bs)
5024 !bdrv_is_removable(bs) &&
5025 !bdrv_is_read_only(bs));
5028 /* device must be snapshots in order to have a reliable snapshot */
5029 static int bdrv_has_snapshot(BlockDriverState *bs)
5032 !bdrv_is_removable(bs) &&
5033 !bdrv_is_read_only(bs));
5036 static BlockDriverState *get_bs_snapshots(void)
5038 BlockDriverState *bs;
5042 return bs_snapshots;
5043 for(i = 0; i <= MAX_DISKS; i++) {
5045 if (bdrv_can_snapshot(bs))
5054 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5057 QEMUSnapshotInfo *sn_tab, *sn;
5061 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5064 for(i = 0; i < nb_sns; i++) {
5066 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5076 void do_savevm(const char *name)
5078 BlockDriverState *bs, *bs1;
5079 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5080 int must_delete, ret, i;
5081 BlockDriverInfo bdi1, *bdi = &bdi1;
5083 int saved_vm_running;
5090 bs = get_bs_snapshots();
5092 term_printf("No block device can accept snapshots\n");
5096 /* ??? Should this occur after vm_stop? */
5099 saved_vm_running = vm_running;
5104 ret = bdrv_snapshot_find(bs, old_sn, name);
5109 memset(sn, 0, sizeof(*sn));
5111 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5112 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5115 pstrcpy(sn->name, sizeof(sn->name), name);
5118 /* fill auxiliary fields */
5121 sn->date_sec = tb.time;
5122 sn->date_nsec = tb.millitm * 1000000;
5124 gettimeofday(&tv, NULL);
5125 sn->date_sec = tv.tv_sec;
5126 sn->date_nsec = tv.tv_usec * 1000;
5128 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5130 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5131 term_printf("Device %s does not support VM state snapshots\n",
5132 bdrv_get_device_name(bs));
5136 /* save the VM state */
5137 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5139 term_printf("Could not open VM state file\n");
5142 ret = qemu_savevm_state(f);
5143 sn->vm_state_size = qemu_ftell(f);
5146 term_printf("Error %d while writing VM\n", ret);
5150 /* create the snapshots */
5152 for(i = 0; i < MAX_DISKS; i++) {
5154 if (bdrv_has_snapshot(bs1)) {
5156 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5158 term_printf("Error while deleting snapshot on '%s'\n",
5159 bdrv_get_device_name(bs1));
5162 ret = bdrv_snapshot_create(bs1, sn);
5164 term_printf("Error while creating snapshot on '%s'\n",
5165 bdrv_get_device_name(bs1));
5171 if (saved_vm_running)
5175 void do_loadvm(const char *name)
5177 BlockDriverState *bs, *bs1;
5178 BlockDriverInfo bdi1, *bdi = &bdi1;
5181 int saved_vm_running;
5183 bs = get_bs_snapshots();
5185 term_printf("No block device supports snapshots\n");
5189 /* Flush all IO requests so they don't interfere with the new state. */
5192 saved_vm_running = vm_running;
5195 for(i = 0; i <= MAX_DISKS; i++) {
5197 if (bdrv_has_snapshot(bs1)) {
5198 ret = bdrv_snapshot_goto(bs1, name);
5201 term_printf("Warning: ");
5204 term_printf("Snapshots not supported on device '%s'\n",
5205 bdrv_get_device_name(bs1));
5208 term_printf("Could not find snapshot '%s' on device '%s'\n",
5209 name, bdrv_get_device_name(bs1));
5212 term_printf("Error %d while activating snapshot on '%s'\n",
5213 ret, bdrv_get_device_name(bs1));
5216 /* fatal on snapshot block device */
5223 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5224 term_printf("Device %s does not support VM state snapshots\n",
5225 bdrv_get_device_name(bs));
5229 /* restore the VM state */
5230 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5232 term_printf("Could not open VM state file\n");
5235 ret = qemu_loadvm_state(f);
5238 term_printf("Error %d while loading VM state\n", ret);
5241 if (saved_vm_running)
5245 void do_delvm(const char *name)
5247 BlockDriverState *bs, *bs1;
5250 bs = get_bs_snapshots();
5252 term_printf("No block device supports snapshots\n");
5256 for(i = 0; i <= MAX_DISKS; i++) {
5258 if (bdrv_has_snapshot(bs1)) {
5259 ret = bdrv_snapshot_delete(bs1, name);
5261 if (ret == -ENOTSUP)
5262 term_printf("Snapshots not supported on device '%s'\n",
5263 bdrv_get_device_name(bs1));
5265 term_printf("Error %d while deleting snapshot on '%s'\n",
5266 ret, bdrv_get_device_name(bs1));
5272 void do_info_snapshots(void)
5274 BlockDriverState *bs, *bs1;
5275 QEMUSnapshotInfo *sn_tab, *sn;
5279 bs = get_bs_snapshots();
5281 term_printf("No available block device supports snapshots\n");
5284 term_printf("Snapshot devices:");
5285 for(i = 0; i <= MAX_DISKS; i++) {
5287 if (bdrv_has_snapshot(bs1)) {
5289 term_printf(" %s", bdrv_get_device_name(bs1));
5294 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5296 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5299 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5300 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5301 for(i = 0; i < nb_sns; i++) {
5303 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5308 /***********************************************************/
5309 /* cpu save/restore */
5311 #if defined(TARGET_I386)
5313 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5315 qemu_put_be32(f, dt->selector);
5316 qemu_put_betl(f, dt->base);
5317 qemu_put_be32(f, dt->limit);
5318 qemu_put_be32(f, dt->flags);
5321 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5323 dt->selector = qemu_get_be32(f);
5324 dt->base = qemu_get_betl(f);
5325 dt->limit = qemu_get_be32(f);
5326 dt->flags = qemu_get_be32(f);
5329 void cpu_save(QEMUFile *f, void *opaque)
5331 CPUState *env = opaque;
5332 uint16_t fptag, fpus, fpuc, fpregs_format;
5336 for(i = 0; i < CPU_NB_REGS; i++)
5337 qemu_put_betls(f, &env->regs[i]);
5338 qemu_put_betls(f, &env->eip);
5339 qemu_put_betls(f, &env->eflags);
5340 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5341 qemu_put_be32s(f, &hflags);
5345 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5347 for(i = 0; i < 8; i++) {
5348 fptag |= ((!env->fptags[i]) << i);
5351 qemu_put_be16s(f, &fpuc);
5352 qemu_put_be16s(f, &fpus);
5353 qemu_put_be16s(f, &fptag);
5355 #ifdef USE_X86LDOUBLE
5360 qemu_put_be16s(f, &fpregs_format);
5362 for(i = 0; i < 8; i++) {
5363 #ifdef USE_X86LDOUBLE
5367 /* we save the real CPU data (in case of MMX usage only 'mant'
5368 contains the MMX register */
5369 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5370 qemu_put_be64(f, mant);
5371 qemu_put_be16(f, exp);
5374 /* if we use doubles for float emulation, we save the doubles to
5375 avoid losing information in case of MMX usage. It can give
5376 problems if the image is restored on a CPU where long
5377 doubles are used instead. */
5378 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5382 for(i = 0; i < 6; i++)
5383 cpu_put_seg(f, &env->segs[i]);
5384 cpu_put_seg(f, &env->ldt);
5385 cpu_put_seg(f, &env->tr);
5386 cpu_put_seg(f, &env->gdt);
5387 cpu_put_seg(f, &env->idt);
5389 qemu_put_be32s(f, &env->sysenter_cs);
5390 qemu_put_be32s(f, &env->sysenter_esp);
5391 qemu_put_be32s(f, &env->sysenter_eip);
5393 qemu_put_betls(f, &env->cr[0]);
5394 qemu_put_betls(f, &env->cr[2]);
5395 qemu_put_betls(f, &env->cr[3]);
5396 qemu_put_betls(f, &env->cr[4]);
5398 for(i = 0; i < 8; i++)
5399 qemu_put_betls(f, &env->dr[i]);
5402 qemu_put_be32s(f, &env->a20_mask);
5405 qemu_put_be32s(f, &env->mxcsr);
5406 for(i = 0; i < CPU_NB_REGS; i++) {
5407 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5408 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5411 #ifdef TARGET_X86_64
5412 qemu_put_be64s(f, &env->efer);
5413 qemu_put_be64s(f, &env->star);
5414 qemu_put_be64s(f, &env->lstar);
5415 qemu_put_be64s(f, &env->cstar);
5416 qemu_put_be64s(f, &env->fmask);
5417 qemu_put_be64s(f, &env->kernelgsbase);
5419 qemu_put_be32s(f, &env->smbase);
5422 #ifdef USE_X86LDOUBLE
5423 /* XXX: add that in a FPU generic layer */
5424 union x86_longdouble {
5429 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5430 #define EXPBIAS1 1023
5431 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5432 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5434 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5438 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5439 /* exponent + sign */
5440 e = EXPD1(temp) - EXPBIAS1 + 16383;
5441 e |= SIGND1(temp) >> 16;
5446 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5448 CPUState *env = opaque;
5451 uint16_t fpus, fpuc, fptag, fpregs_format;
5453 if (version_id != 3 && version_id != 4)
5455 for(i = 0; i < CPU_NB_REGS; i++)
5456 qemu_get_betls(f, &env->regs[i]);
5457 qemu_get_betls(f, &env->eip);
5458 qemu_get_betls(f, &env->eflags);
5459 qemu_get_be32s(f, &hflags);
5461 qemu_get_be16s(f, &fpuc);
5462 qemu_get_be16s(f, &fpus);
5463 qemu_get_be16s(f, &fptag);
5464 qemu_get_be16s(f, &fpregs_format);
5466 /* NOTE: we cannot always restore the FPU state if the image come
5467 from a host with a different 'USE_X86LDOUBLE' define. We guess
5468 if we are in an MMX state to restore correctly in that case. */
5469 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5470 for(i = 0; i < 8; i++) {
5474 switch(fpregs_format) {
5476 mant = qemu_get_be64(f);
5477 exp = qemu_get_be16(f);
5478 #ifdef USE_X86LDOUBLE
5479 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5481 /* difficult case */
5483 env->fpregs[i].mmx.MMX_Q(0) = mant;
5485 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5489 mant = qemu_get_be64(f);
5490 #ifdef USE_X86LDOUBLE
5492 union x86_longdouble *p;
5493 /* difficult case */
5494 p = (void *)&env->fpregs[i];
5499 fp64_to_fp80(p, mant);
5503 env->fpregs[i].mmx.MMX_Q(0) = mant;
5512 /* XXX: restore FPU round state */
5513 env->fpstt = (fpus >> 11) & 7;
5514 env->fpus = fpus & ~0x3800;
5516 for(i = 0; i < 8; i++) {
5517 env->fptags[i] = (fptag >> i) & 1;
5520 for(i = 0; i < 6; i++)
5521 cpu_get_seg(f, &env->segs[i]);
5522 cpu_get_seg(f, &env->ldt);
5523 cpu_get_seg(f, &env->tr);
5524 cpu_get_seg(f, &env->gdt);
5525 cpu_get_seg(f, &env->idt);
5527 qemu_get_be32s(f, &env->sysenter_cs);
5528 qemu_get_be32s(f, &env->sysenter_esp);
5529 qemu_get_be32s(f, &env->sysenter_eip);
5531 qemu_get_betls(f, &env->cr[0]);
5532 qemu_get_betls(f, &env->cr[2]);
5533 qemu_get_betls(f, &env->cr[3]);
5534 qemu_get_betls(f, &env->cr[4]);
5536 for(i = 0; i < 8; i++)
5537 qemu_get_betls(f, &env->dr[i]);
5540 qemu_get_be32s(f, &env->a20_mask);
5542 qemu_get_be32s(f, &env->mxcsr);
5543 for(i = 0; i < CPU_NB_REGS; i++) {
5544 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5545 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5548 #ifdef TARGET_X86_64
5549 qemu_get_be64s(f, &env->efer);
5550 qemu_get_be64s(f, &env->star);
5551 qemu_get_be64s(f, &env->lstar);
5552 qemu_get_be64s(f, &env->cstar);
5553 qemu_get_be64s(f, &env->fmask);
5554 qemu_get_be64s(f, &env->kernelgsbase);
5556 if (version_id >= 4)
5557 qemu_get_be32s(f, &env->smbase);
5559 /* XXX: compute hflags from scratch, except for CPL and IIF */
5560 env->hflags = hflags;
5565 #elif defined(TARGET_PPC)
5566 void cpu_save(QEMUFile *f, void *opaque)
5570 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5575 #elif defined(TARGET_MIPS)
5576 void cpu_save(QEMUFile *f, void *opaque)
5580 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5585 #elif defined(TARGET_SPARC)
5586 void cpu_save(QEMUFile *f, void *opaque)
5588 CPUState *env = opaque;
5592 for(i = 0; i < 8; i++)
5593 qemu_put_betls(f, &env->gregs[i]);
5594 for(i = 0; i < NWINDOWS * 16; i++)
5595 qemu_put_betls(f, &env->regbase[i]);
5598 for(i = 0; i < TARGET_FPREGS; i++) {
5604 qemu_put_be32(f, u.i);
5607 qemu_put_betls(f, &env->pc);
5608 qemu_put_betls(f, &env->npc);
5609 qemu_put_betls(f, &env->y);
5611 qemu_put_be32(f, tmp);
5612 qemu_put_betls(f, &env->fsr);
5613 qemu_put_betls(f, &env->tbr);
5614 #ifndef TARGET_SPARC64
5615 qemu_put_be32s(f, &env->wim);
5617 for(i = 0; i < 16; i++)
5618 qemu_put_be32s(f, &env->mmuregs[i]);
5622 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5624 CPUState *env = opaque;
5628 for(i = 0; i < 8; i++)
5629 qemu_get_betls(f, &env->gregs[i]);
5630 for(i = 0; i < NWINDOWS * 16; i++)
5631 qemu_get_betls(f, &env->regbase[i]);
5634 for(i = 0; i < TARGET_FPREGS; i++) {
5639 u.i = qemu_get_be32(f);
5643 qemu_get_betls(f, &env->pc);
5644 qemu_get_betls(f, &env->npc);
5645 qemu_get_betls(f, &env->y);
5646 tmp = qemu_get_be32(f);
5647 env->cwp = 0; /* needed to ensure that the wrapping registers are
5648 correctly updated */
5650 qemu_get_betls(f, &env->fsr);
5651 qemu_get_betls(f, &env->tbr);
5652 #ifndef TARGET_SPARC64
5653 qemu_get_be32s(f, &env->wim);
5655 for(i = 0; i < 16; i++)
5656 qemu_get_be32s(f, &env->mmuregs[i]);
5662 #elif defined(TARGET_ARM)
5664 void cpu_save(QEMUFile *f, void *opaque)
5667 CPUARMState *env = (CPUARMState *)opaque;
5669 for (i = 0; i < 16; i++) {
5670 qemu_put_be32(f, env->regs[i]);
5672 qemu_put_be32(f, cpsr_read(env));
5673 qemu_put_be32(f, env->spsr);
5674 for (i = 0; i < 6; i++) {
5675 qemu_put_be32(f, env->banked_spsr[i]);
5676 qemu_put_be32(f, env->banked_r13[i]);
5677 qemu_put_be32(f, env->banked_r14[i]);
5679 for (i = 0; i < 5; i++) {
5680 qemu_put_be32(f, env->usr_regs[i]);
5681 qemu_put_be32(f, env->fiq_regs[i]);
5683 qemu_put_be32(f, env->cp15.c0_cpuid);
5684 qemu_put_be32(f, env->cp15.c0_cachetype);
5685 qemu_put_be32(f, env->cp15.c1_sys);
5686 qemu_put_be32(f, env->cp15.c1_coproc);
5687 qemu_put_be32(f, env->cp15.c2_base);
5688 qemu_put_be32(f, env->cp15.c2_data);
5689 qemu_put_be32(f, env->cp15.c2_insn);
5690 qemu_put_be32(f, env->cp15.c3);
5691 qemu_put_be32(f, env->cp15.c5_insn);
5692 qemu_put_be32(f, env->cp15.c5_data);
5693 for (i = 0; i < 8; i++) {
5694 qemu_put_be32(f, env->cp15.c6_region[i]);
5696 qemu_put_be32(f, env->cp15.c6_insn);
5697 qemu_put_be32(f, env->cp15.c6_data);
5698 qemu_put_be32(f, env->cp15.c9_insn);
5699 qemu_put_be32(f, env->cp15.c9_data);
5700 qemu_put_be32(f, env->cp15.c13_fcse);
5701 qemu_put_be32(f, env->cp15.c13_context);
5702 qemu_put_be32(f, env->cp15.c15_cpar);
5704 qemu_put_be32(f, env->features);
5706 if (arm_feature(env, ARM_FEATURE_VFP)) {
5707 for (i = 0; i < 16; i++) {
5709 u.d = env->vfp.regs[i];
5710 qemu_put_be32(f, u.l.upper);
5711 qemu_put_be32(f, u.l.lower);
5713 for (i = 0; i < 16; i++) {
5714 qemu_put_be32(f, env->vfp.xregs[i]);
5717 /* TODO: Should use proper FPSCR access functions. */
5718 qemu_put_be32(f, env->vfp.vec_len);
5719 qemu_put_be32(f, env->vfp.vec_stride);
5722 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5723 for (i = 0; i < 16; i++) {
5724 qemu_put_be64(f, env->iwmmxt.regs[i]);
5726 for (i = 0; i < 16; i++) {
5727 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5732 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5734 CPUARMState *env = (CPUARMState *)opaque;
5737 if (version_id != 0)
5740 for (i = 0; i < 16; i++) {
5741 env->regs[i] = qemu_get_be32(f);
5743 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5744 env->spsr = qemu_get_be32(f);
5745 for (i = 0; i < 6; i++) {
5746 env->banked_spsr[i] = qemu_get_be32(f);
5747 env->banked_r13[i] = qemu_get_be32(f);
5748 env->banked_r14[i] = qemu_get_be32(f);
5750 for (i = 0; i < 5; i++) {
5751 env->usr_regs[i] = qemu_get_be32(f);
5752 env->fiq_regs[i] = qemu_get_be32(f);
5754 env->cp15.c0_cpuid = qemu_get_be32(f);
5755 env->cp15.c0_cachetype = qemu_get_be32(f);
5756 env->cp15.c1_sys = qemu_get_be32(f);
5757 env->cp15.c1_coproc = qemu_get_be32(f);
5758 env->cp15.c2_base = qemu_get_be32(f);
5759 env->cp15.c2_data = qemu_get_be32(f);
5760 env->cp15.c2_insn = qemu_get_be32(f);
5761 env->cp15.c3 = qemu_get_be32(f);
5762 env->cp15.c5_insn = qemu_get_be32(f);
5763 env->cp15.c5_data = qemu_get_be32(f);
5764 for (i = 0; i < 8; i++) {
5765 env->cp15.c6_region[i] = qemu_get_be32(f);
5767 env->cp15.c6_insn = qemu_get_be32(f);
5768 env->cp15.c6_data = qemu_get_be32(f);
5769 env->cp15.c9_insn = qemu_get_be32(f);
5770 env->cp15.c9_data = qemu_get_be32(f);
5771 env->cp15.c13_fcse = qemu_get_be32(f);
5772 env->cp15.c13_context = qemu_get_be32(f);
5773 env->cp15.c15_cpar = qemu_get_be32(f);
5775 env->features = qemu_get_be32(f);
5777 if (arm_feature(env, ARM_FEATURE_VFP)) {
5778 for (i = 0; i < 16; i++) {
5780 u.l.upper = qemu_get_be32(f);
5781 u.l.lower = qemu_get_be32(f);
5782 env->vfp.regs[i] = u.d;
5784 for (i = 0; i < 16; i++) {
5785 env->vfp.xregs[i] = qemu_get_be32(f);
5788 /* TODO: Should use proper FPSCR access functions. */
5789 env->vfp.vec_len = qemu_get_be32(f);
5790 env->vfp.vec_stride = qemu_get_be32(f);
5793 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5794 for (i = 0; i < 16; i++) {
5795 env->iwmmxt.regs[i] = qemu_get_be64(f);
5797 for (i = 0; i < 16; i++) {
5798 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5807 #warning No CPU save/restore functions
5811 /***********************************************************/
5812 /* ram save/restore */
5814 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5818 v = qemu_get_byte(f);
5821 if (qemu_get_buffer(f, buf, len) != len)
5825 v = qemu_get_byte(f);
5826 memset(buf, v, len);
5834 static int ram_load_v1(QEMUFile *f, void *opaque)
5838 if (qemu_get_be32(f) != phys_ram_size)
5840 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5841 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5848 #define BDRV_HASH_BLOCK_SIZE 1024
5849 #define IOBUF_SIZE 4096
5850 #define RAM_CBLOCK_MAGIC 0xfabe
5852 typedef struct RamCompressState {
5855 uint8_t buf[IOBUF_SIZE];
5858 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5861 memset(s, 0, sizeof(*s));
5863 ret = deflateInit2(&s->zstream, 1,
5865 9, Z_DEFAULT_STRATEGY);
5868 s->zstream.avail_out = IOBUF_SIZE;
5869 s->zstream.next_out = s->buf;
5873 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5875 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5876 qemu_put_be16(s->f, len);
5877 qemu_put_buffer(s->f, buf, len);
5880 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5884 s->zstream.avail_in = len;
5885 s->zstream.next_in = (uint8_t *)buf;
5886 while (s->zstream.avail_in > 0) {
5887 ret = deflate(&s->zstream, Z_NO_FLUSH);
5890 if (s->zstream.avail_out == 0) {
5891 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5892 s->zstream.avail_out = IOBUF_SIZE;
5893 s->zstream.next_out = s->buf;
5899 static void ram_compress_close(RamCompressState *s)
5903 /* compress last bytes */
5905 ret = deflate(&s->zstream, Z_FINISH);
5906 if (ret == Z_OK || ret == Z_STREAM_END) {
5907 len = IOBUF_SIZE - s->zstream.avail_out;
5909 ram_put_cblock(s, s->buf, len);
5911 s->zstream.avail_out = IOBUF_SIZE;
5912 s->zstream.next_out = s->buf;
5913 if (ret == Z_STREAM_END)
5920 deflateEnd(&s->zstream);
5923 typedef struct RamDecompressState {
5926 uint8_t buf[IOBUF_SIZE];
5927 } RamDecompressState;
5929 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5932 memset(s, 0, sizeof(*s));
5934 ret = inflateInit(&s->zstream);
5940 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5944 s->zstream.avail_out = len;
5945 s->zstream.next_out = buf;
5946 while (s->zstream.avail_out > 0) {
5947 if (s->zstream.avail_in == 0) {
5948 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5950 clen = qemu_get_be16(s->f);
5951 if (clen > IOBUF_SIZE)
5953 qemu_get_buffer(s->f, s->buf, clen);
5954 s->zstream.avail_in = clen;
5955 s->zstream.next_in = s->buf;
5957 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5958 if (ret != Z_OK && ret != Z_STREAM_END) {
5965 static void ram_decompress_close(RamDecompressState *s)
5967 inflateEnd(&s->zstream);
5970 static void ram_save(QEMUFile *f, void *opaque)
5973 RamCompressState s1, *s = &s1;
5976 qemu_put_be32(f, phys_ram_size);
5977 if (ram_compress_open(s, f) < 0)
5979 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5981 if (tight_savevm_enabled) {
5985 /* find if the memory block is available on a virtual
5988 for(j = 0; j < MAX_DISKS; j++) {
5990 sector_num = bdrv_hash_find(bs_table[j],
5991 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5992 if (sector_num >= 0)
5997 goto normal_compress;
6000 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6001 ram_compress_buf(s, buf, 10);
6007 ram_compress_buf(s, buf, 1);
6008 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6011 ram_compress_close(s);
6014 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6016 RamDecompressState s1, *s = &s1;
6020 if (version_id == 1)
6021 return ram_load_v1(f, opaque);
6022 if (version_id != 2)
6024 if (qemu_get_be32(f) != phys_ram_size)
6026 if (ram_decompress_open(s, f) < 0)
6028 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6029 if (ram_decompress_buf(s, buf, 1) < 0) {
6030 fprintf(stderr, "Error while reading ram block header\n");
6034 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6035 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6044 ram_decompress_buf(s, buf + 1, 9);
6046 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6047 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6048 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6051 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6052 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6053 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6054 bs_index, sector_num);
6061 printf("Error block header\n");
6065 ram_decompress_close(s);
6069 /***********************************************************/
6070 /* bottom halves (can be seen as timers which expire ASAP) */
6079 static QEMUBH *first_bh = NULL;
6081 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6084 bh = qemu_mallocz(sizeof(QEMUBH));
6088 bh->opaque = opaque;
6092 int qemu_bh_poll(void)
6111 void qemu_bh_schedule(QEMUBH *bh)
6113 CPUState *env = cpu_single_env;
6117 bh->next = first_bh;
6120 /* stop the currently executing CPU to execute the BH ASAP */
6122 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6126 void qemu_bh_cancel(QEMUBH *bh)
6129 if (bh->scheduled) {
6132 pbh = &(*pbh)->next;
6138 void qemu_bh_delete(QEMUBH *bh)
6144 /***********************************************************/
6145 /* machine registration */
6147 QEMUMachine *first_machine = NULL;
6149 int qemu_register_machine(QEMUMachine *m)
6152 pm = &first_machine;
6160 QEMUMachine *find_machine(const char *name)
6164 for(m = first_machine; m != NULL; m = m->next) {
6165 if (!strcmp(m->name, name))
6171 /***********************************************************/
6172 /* main execution loop */
6174 void gui_update(void *opaque)
6176 DisplayState *ds = opaque;
6177 ds->dpy_refresh(ds);
6178 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6181 struct vm_change_state_entry {
6182 VMChangeStateHandler *cb;
6184 LIST_ENTRY (vm_change_state_entry) entries;
6187 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6189 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6192 VMChangeStateEntry *e;
6194 e = qemu_mallocz(sizeof (*e));
6200 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6204 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6206 LIST_REMOVE (e, entries);
6210 static void vm_state_notify(int running)
6212 VMChangeStateEntry *e;
6214 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6215 e->cb(e->opaque, running);
6219 /* XXX: support several handlers */
6220 static VMStopHandler *vm_stop_cb;
6221 static void *vm_stop_opaque;
6223 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6226 vm_stop_opaque = opaque;
6230 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6244 void vm_stop(int reason)
6247 cpu_disable_ticks();
6251 vm_stop_cb(vm_stop_opaque, reason);
6258 /* reset/shutdown handler */
6260 typedef struct QEMUResetEntry {
6261 QEMUResetHandler *func;
6263 struct QEMUResetEntry *next;
6266 static QEMUResetEntry *first_reset_entry;
6267 static int reset_requested;
6268 static int shutdown_requested;
6269 static int powerdown_requested;
6271 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6273 QEMUResetEntry **pre, *re;
6275 pre = &first_reset_entry;
6276 while (*pre != NULL)
6277 pre = &(*pre)->next;
6278 re = qemu_mallocz(sizeof(QEMUResetEntry));
6280 re->opaque = opaque;
6285 static void qemu_system_reset(void)
6289 /* reset all devices */
6290 for(re = first_reset_entry; re != NULL; re = re->next) {
6291 re->func(re->opaque);
6295 void qemu_system_reset_request(void)
6298 shutdown_requested = 1;
6300 reset_requested = 1;
6303 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6306 void qemu_system_shutdown_request(void)
6308 shutdown_requested = 1;
6310 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6313 void qemu_system_powerdown_request(void)
6315 powerdown_requested = 1;
6317 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6320 void main_loop_wait(int timeout)
6322 IOHandlerRecord *ioh;
6323 fd_set rfds, wfds, xfds;
6332 /* XXX: need to suppress polling by better using win32 events */
6334 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6335 ret |= pe->func(pe->opaque);
6340 WaitObjects *w = &wait_objects;
6342 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6343 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6344 if (w->func[ret - WAIT_OBJECT_0])
6345 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6347 /* Check for additional signaled events */
6348 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6350 /* Check if event is signaled */
6351 ret2 = WaitForSingleObject(w->events[i], 0);
6352 if(ret2 == WAIT_OBJECT_0) {
6354 w->func[i](w->opaque[i]);
6355 } else if (ret2 == WAIT_TIMEOUT) {
6357 err = GetLastError();
6358 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6361 } else if (ret == WAIT_TIMEOUT) {
6363 err = GetLastError();
6364 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6368 /* poll any events */
6369 /* XXX: separate device handlers from system ones */
6374 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6378 (!ioh->fd_read_poll ||
6379 ioh->fd_read_poll(ioh->opaque) != 0)) {
6380 FD_SET(ioh->fd, &rfds);
6384 if (ioh->fd_write) {
6385 FD_SET(ioh->fd, &wfds);
6395 tv.tv_usec = timeout * 1000;
6397 #if defined(CONFIG_SLIRP)
6399 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6402 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6404 IOHandlerRecord **pioh;
6406 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6409 if (FD_ISSET(ioh->fd, &rfds)) {
6410 ioh->fd_read(ioh->opaque);
6412 if (FD_ISSET(ioh->fd, &wfds)) {
6413 ioh->fd_write(ioh->opaque);
6417 /* remove deleted IO handlers */
6418 pioh = &first_io_handler;
6428 #if defined(CONFIG_SLIRP)
6435 slirp_select_poll(&rfds, &wfds, &xfds);
6441 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6442 qemu_get_clock(vm_clock));
6443 /* run dma transfers, if any */
6447 /* real time timers */
6448 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6449 qemu_get_clock(rt_clock));
6451 /* Check bottom-halves last in case any of the earlier events triggered
6457 static CPUState *cur_cpu;
6462 #ifdef CONFIG_PROFILER
6467 cur_cpu = first_cpu;
6474 env = env->next_cpu;
6477 #ifdef CONFIG_PROFILER
6478 ti = profile_getclock();
6480 ret = cpu_exec(env);
6481 #ifdef CONFIG_PROFILER
6482 qemu_time += profile_getclock() - ti;
6484 if (ret == EXCP_HLT) {
6485 /* Give the next CPU a chance to run. */
6489 if (ret != EXCP_HALTED)
6491 /* all CPUs are halted ? */
6497 if (shutdown_requested) {
6498 ret = EXCP_INTERRUPT;
6501 if (reset_requested) {
6502 reset_requested = 0;
6503 qemu_system_reset();
6504 ret = EXCP_INTERRUPT;
6506 if (powerdown_requested) {
6507 powerdown_requested = 0;
6508 qemu_system_powerdown();
6509 ret = EXCP_INTERRUPT;
6511 if (ret == EXCP_DEBUG) {
6512 vm_stop(EXCP_DEBUG);
6514 /* If all cpus are halted then wait until the next IRQ */
6515 /* XXX: use timeout computed from timers */
6516 if (ret == EXCP_HALTED)
6523 #ifdef CONFIG_PROFILER
6524 ti = profile_getclock();
6526 main_loop_wait(timeout);
6527 #ifdef CONFIG_PROFILER
6528 dev_time += profile_getclock() - ti;
6531 cpu_disable_ticks();
6537 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6538 "usage: %s [options] [disk_image]\n"
6540 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6542 "Standard options:\n"
6543 "-M machine select emulated machine (-M ? for list)\n"
6544 "-cpu cpu select CPU (-cpu ? for list)\n"
6545 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6546 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6547 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6548 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6549 "-mtdblock file use 'file' as on-board Flash memory image\n"
6550 "-sd file use 'file' as SecureDigital card image\n"
6551 "-pflash file use 'file' as a parallel flash image\n"
6552 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6553 "-snapshot write to temporary files instead of disk image files\n"
6555 "-no-frame open SDL window without a frame and window decorations\n"
6556 "-no-quit disable SDL window close capability\n"
6559 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6561 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6562 "-smp n set the number of CPUs to 'n' [default=1]\n"
6563 "-nographic disable graphical output and redirect serial I/Os to console\n"
6564 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6566 "-k language use keyboard layout (for example \"fr\" for French)\n"
6569 "-audio-help print list of audio drivers and their options\n"
6570 "-soundhw c1,... enable audio support\n"
6571 " and only specified sound cards (comma separated list)\n"
6572 " use -soundhw ? to get the list of supported cards\n"
6573 " use -soundhw all to enable all of them\n"
6575 "-localtime set the real time clock to local time [default=utc]\n"
6576 "-full-screen start in full screen\n"
6578 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6580 "-usb enable the USB driver (will be the default soon)\n"
6581 "-usbdevice name add the host or guest USB device 'name'\n"
6582 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6583 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6585 "-name string set the name of the guest\n"
6587 "Network options:\n"
6588 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6589 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6591 "-net user[,vlan=n][,hostname=host]\n"
6592 " connect the user mode network stack to VLAN 'n' and send\n"
6593 " hostname 'host' to DHCP clients\n"
6596 "-net tap[,vlan=n],ifname=name\n"
6597 " connect the host TAP network interface to VLAN 'n'\n"
6599 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6600 " connect the host TAP network interface to VLAN 'n' and use\n"
6601 " the network script 'file' (default=%s);\n"
6602 " use 'script=no' to disable script execution;\n"
6603 " use 'fd=h' to connect to an already opened TAP interface\n"
6605 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6606 " connect the vlan 'n' to another VLAN using a socket connection\n"
6607 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6608 " connect the vlan 'n' to multicast maddr and port\n"
6609 "-net none use it alone to have zero network devices; if no -net option\n"
6610 " is provided, the default is '-net nic -net user'\n"
6613 "-tftp dir allow tftp access to files in dir [-net user]\n"
6614 "-bootp file advertise file in BOOTP replies\n"
6616 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6618 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6619 " redirect TCP or UDP connections from host to guest [-net user]\n"
6622 "Linux boot specific:\n"
6623 "-kernel bzImage use 'bzImage' as kernel image\n"
6624 "-append cmdline use 'cmdline' as kernel command line\n"
6625 "-initrd file use 'file' as initial ram disk\n"
6627 "Debug/Expert options:\n"
6628 "-monitor dev redirect the monitor to char device 'dev'\n"
6629 "-serial dev redirect the serial port to char device 'dev'\n"
6630 "-parallel dev redirect the parallel port to char device 'dev'\n"
6631 "-pidfile file Write PID to 'file'\n"
6632 "-S freeze CPU at startup (use 'c' to start execution)\n"
6633 "-s wait gdb connection to port\n"
6634 "-p port set gdb connection port [default=%s]\n"
6635 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6636 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6637 " translation (t=none or lba) (usually qemu can guess them)\n"
6638 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6640 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6641 "-no-kqemu disable KQEMU kernel module usage\n"
6643 #ifdef USE_CODE_COPY
6644 "-no-code-copy disable code copy acceleration\n"
6647 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6648 " (default is CL-GD5446 PCI VGA)\n"
6649 "-no-acpi disable ACPI\n"
6651 "-no-reboot exit instead of rebooting\n"
6652 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6653 "-vnc display start a VNC server on display\n"
6655 "-daemonize daemonize QEMU after initializing\n"
6657 "-option-rom rom load a file, rom, into the option ROM space\n"
6659 "-prom-env variable=value set OpenBIOS nvram variables\n"
6662 "During emulation, the following keys are useful:\n"
6663 "ctrl-alt-f toggle full screen\n"
6664 "ctrl-alt-n switch to virtual console 'n'\n"
6665 "ctrl-alt toggle mouse and keyboard grab\n"
6667 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6672 DEFAULT_NETWORK_SCRIPT,
6674 DEFAULT_GDBSTUB_PORT,
6679 #define HAS_ARG 0x0001
6693 QEMU_OPTION_mtdblock,
6697 QEMU_OPTION_snapshot,
6699 QEMU_OPTION_no_fd_bootchk,
6702 QEMU_OPTION_nographic,
6703 QEMU_OPTION_portrait,
6705 QEMU_OPTION_audio_help,
6706 QEMU_OPTION_soundhw,
6725 QEMU_OPTION_no_code_copy,
6727 QEMU_OPTION_localtime,
6728 QEMU_OPTION_cirrusvga,
6731 QEMU_OPTION_std_vga,
6733 QEMU_OPTION_monitor,
6735 QEMU_OPTION_parallel,
6737 QEMU_OPTION_full_screen,
6738 QEMU_OPTION_no_frame,
6739 QEMU_OPTION_no_quit,
6740 QEMU_OPTION_pidfile,
6741 QEMU_OPTION_no_kqemu,
6742 QEMU_OPTION_kernel_kqemu,
6743 QEMU_OPTION_win2k_hack,
6745 QEMU_OPTION_usbdevice,
6748 QEMU_OPTION_no_acpi,
6749 QEMU_OPTION_no_reboot,
6750 QEMU_OPTION_show_cursor,
6751 QEMU_OPTION_daemonize,
6752 QEMU_OPTION_option_rom,
6753 QEMU_OPTION_semihosting,
6755 QEMU_OPTION_prom_env,
6758 typedef struct QEMUOption {
6764 const QEMUOption qemu_options[] = {
6765 { "h", 0, QEMU_OPTION_h },
6766 { "help", 0, QEMU_OPTION_h },
6768 { "M", HAS_ARG, QEMU_OPTION_M },
6769 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6770 { "fda", HAS_ARG, QEMU_OPTION_fda },
6771 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6772 { "hda", HAS_ARG, QEMU_OPTION_hda },
6773 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6774 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6775 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6776 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6777 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6778 { "sd", HAS_ARG, QEMU_OPTION_sd },
6779 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6780 { "boot", HAS_ARG, QEMU_OPTION_boot },
6781 { "snapshot", 0, QEMU_OPTION_snapshot },
6783 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6785 { "m", HAS_ARG, QEMU_OPTION_m },
6786 { "nographic", 0, QEMU_OPTION_nographic },
6787 { "portrait", 0, QEMU_OPTION_portrait },
6788 { "k", HAS_ARG, QEMU_OPTION_k },
6790 { "audio-help", 0, QEMU_OPTION_audio_help },
6791 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6794 { "net", HAS_ARG, QEMU_OPTION_net},
6796 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6797 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6799 { "smb", HAS_ARG, QEMU_OPTION_smb },
6801 { "redir", HAS_ARG, QEMU_OPTION_redir },
6804 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6805 { "append", HAS_ARG, QEMU_OPTION_append },
6806 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6808 { "S", 0, QEMU_OPTION_S },
6809 { "s", 0, QEMU_OPTION_s },
6810 { "p", HAS_ARG, QEMU_OPTION_p },
6811 { "d", HAS_ARG, QEMU_OPTION_d },
6812 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6813 { "L", HAS_ARG, QEMU_OPTION_L },
6814 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6816 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6817 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6819 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6820 { "g", 1, QEMU_OPTION_g },
6822 { "localtime", 0, QEMU_OPTION_localtime },
6823 { "std-vga", 0, QEMU_OPTION_std_vga },
6824 { "echr", 1, QEMU_OPTION_echr },
6825 { "monitor", 1, QEMU_OPTION_monitor },
6826 { "serial", 1, QEMU_OPTION_serial },
6827 { "parallel", 1, QEMU_OPTION_parallel },
6828 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6829 { "full-screen", 0, QEMU_OPTION_full_screen },
6831 { "no-frame", 0, QEMU_OPTION_no_frame },
6832 { "no-quit", 0, QEMU_OPTION_no_quit },
6834 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6835 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6836 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6837 { "smp", HAS_ARG, QEMU_OPTION_smp },
6838 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6840 /* temporary options */
6841 { "usb", 0, QEMU_OPTION_usb },
6842 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6843 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6844 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6845 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6846 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6847 { "daemonize", 0, QEMU_OPTION_daemonize },
6848 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6849 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6850 { "semihosting", 0, QEMU_OPTION_semihosting },
6852 { "name", HAS_ARG, QEMU_OPTION_name },
6853 #if defined(TARGET_SPARC)
6854 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6859 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6861 /* this stack is only used during signal handling */
6862 #define SIGNAL_STACK_SIZE 32768
6864 static uint8_t *signal_stack;
6868 /* password input */
6870 int qemu_key_check(BlockDriverState *bs, const char *name)
6875 if (!bdrv_is_encrypted(bs))
6878 term_printf("%s is encrypted.\n", name);
6879 for(i = 0; i < 3; i++) {
6880 monitor_readline("Password: ", 1, password, sizeof(password));
6881 if (bdrv_set_key(bs, password) == 0)
6883 term_printf("invalid password\n");
6888 static BlockDriverState *get_bdrv(int index)
6890 BlockDriverState *bs;
6893 bs = bs_table[index];
6894 } else if (index < 6) {
6895 bs = fd_table[index - 4];
6902 static void read_passwords(void)
6904 BlockDriverState *bs;
6907 for(i = 0; i < 6; i++) {
6910 qemu_key_check(bs, bdrv_get_device_name(bs));
6914 /* XXX: currently we cannot use simultaneously different CPUs */
6915 void register_machines(void)
6917 #if defined(TARGET_I386)
6918 qemu_register_machine(&pc_machine);
6919 qemu_register_machine(&isapc_machine);
6920 #elif defined(TARGET_PPC)
6921 qemu_register_machine(&heathrow_machine);
6922 qemu_register_machine(&core99_machine);
6923 qemu_register_machine(&prep_machine);
6924 qemu_register_machine(&ref405ep_machine);
6925 qemu_register_machine(&taihu_machine);
6926 #elif defined(TARGET_MIPS)
6927 qemu_register_machine(&mips_machine);
6928 qemu_register_machine(&mips_malta_machine);
6929 qemu_register_machine(&mips_pica61_machine);
6930 #elif defined(TARGET_SPARC)
6931 #ifdef TARGET_SPARC64
6932 qemu_register_machine(&sun4u_machine);
6934 qemu_register_machine(&ss5_machine);
6935 qemu_register_machine(&ss10_machine);
6937 #elif defined(TARGET_ARM)
6938 qemu_register_machine(&integratorcp_machine);
6939 qemu_register_machine(&versatilepb_machine);
6940 qemu_register_machine(&versatileab_machine);
6941 qemu_register_machine(&realview_machine);
6942 qemu_register_machine(&akitapda_machine);
6943 qemu_register_machine(&spitzpda_machine);
6944 qemu_register_machine(&borzoipda_machine);
6945 qemu_register_machine(&terrierpda_machine);
6946 #elif defined(TARGET_SH4)
6947 qemu_register_machine(&shix_machine);
6948 #elif defined(TARGET_ALPHA)
6950 #elif defined(TARGET_M68K)
6951 qemu_register_machine(&mcf5208evb_machine);
6952 qemu_register_machine(&an5206_machine);
6954 #error unsupported CPU
6959 struct soundhw soundhw[] = {
6960 #ifdef HAS_AUDIO_CHOICE
6967 { .init_isa = pcspk_audio_init }
6972 "Creative Sound Blaster 16",
6975 { .init_isa = SB16_init }
6982 "Yamaha YMF262 (OPL3)",
6984 "Yamaha YM3812 (OPL2)",
6988 { .init_isa = Adlib_init }
6995 "Gravis Ultrasound GF1",
6998 { .init_isa = GUS_init }
7004 "ENSONIQ AudioPCI ES1370",
7007 { .init_pci = es1370_init }
7011 { NULL, NULL, 0, 0, { NULL } }
7014 static void select_soundhw (const char *optarg)
7018 if (*optarg == '?') {
7021 printf ("Valid sound card names (comma separated):\n");
7022 for (c = soundhw; c->name; ++c) {
7023 printf ("%-11s %s\n", c->name, c->descr);
7025 printf ("\n-soundhw all will enable all of the above\n");
7026 exit (*optarg != '?');
7034 if (!strcmp (optarg, "all")) {
7035 for (c = soundhw; c->name; ++c) {
7043 e = strchr (p, ',');
7044 l = !e ? strlen (p) : (size_t) (e - p);
7046 for (c = soundhw; c->name; ++c) {
7047 if (!strncmp (c->name, p, l)) {
7056 "Unknown sound card name (too big to show)\n");
7059 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7064 p += l + (e != NULL);
7068 goto show_valid_cards;
7074 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7076 exit(STATUS_CONTROL_C_EXIT);
7081 #define MAX_NET_CLIENTS 32
7083 int main(int argc, char **argv)
7085 #ifdef CONFIG_GDBSTUB
7087 const char *gdbstub_port;
7089 int i, cdrom_index, pflash_index;
7090 int snapshot, linux_boot;
7091 const char *initrd_filename;
7092 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7093 const char *pflash_filename[MAX_PFLASH];
7094 const char *sd_filename;
7095 const char *mtd_filename;
7096 const char *kernel_filename, *kernel_cmdline;
7097 DisplayState *ds = &display_state;
7098 int cyls, heads, secs, translation;
7099 char net_clients[MAX_NET_CLIENTS][256];
7102 const char *r, *optarg;
7103 CharDriverState *monitor_hd;
7104 char monitor_device[128];
7105 char serial_devices[MAX_SERIAL_PORTS][128];
7106 int serial_device_index;
7107 char parallel_devices[MAX_PARALLEL_PORTS][128];
7108 int parallel_device_index;
7109 const char *loadvm = NULL;
7110 QEMUMachine *machine;
7111 const char *cpu_model;
7112 char usb_devices[MAX_USB_CMDLINE][128];
7113 int usb_devices_index;
7115 const char *pid_file = NULL;
7118 LIST_INIT (&vm_change_state_head);
7121 struct sigaction act;
7122 sigfillset(&act.sa_mask);
7124 act.sa_handler = SIG_IGN;
7125 sigaction(SIGPIPE, &act, NULL);
7128 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7129 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7130 QEMU to run on a single CPU */
7135 h = GetCurrentProcess();
7136 if (GetProcessAffinityMask(h, &mask, &smask)) {
7137 for(i = 0; i < 32; i++) {
7138 if (mask & (1 << i))
7143 SetProcessAffinityMask(h, mask);
7149 register_machines();
7150 machine = first_machine;
7152 initrd_filename = NULL;
7153 for(i = 0; i < MAX_FD; i++)
7154 fd_filename[i] = NULL;
7155 for(i = 0; i < MAX_DISKS; i++)
7156 hd_filename[i] = NULL;
7157 for(i = 0; i < MAX_PFLASH; i++)
7158 pflash_filename[i] = NULL;
7161 mtd_filename = NULL;
7162 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7163 vga_ram_size = VGA_RAM_SIZE;
7164 #ifdef CONFIG_GDBSTUB
7166 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7170 kernel_filename = NULL;
7171 kernel_cmdline = "";
7177 cyls = heads = secs = 0;
7178 translation = BIOS_ATA_TRANSLATION_AUTO;
7179 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7181 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7182 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7183 serial_devices[i][0] = '\0';
7184 serial_device_index = 0;
7186 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7187 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7188 parallel_devices[i][0] = '\0';
7189 parallel_device_index = 0;
7191 usb_devices_index = 0;
7196 /* default mac address of the first network interface */
7204 hd_filename[0] = argv[optind++];
7206 const QEMUOption *popt;
7209 /* Treat --foo the same as -foo. */
7212 popt = qemu_options;
7215 fprintf(stderr, "%s: invalid option -- '%s'\n",
7219 if (!strcmp(popt->name, r + 1))
7223 if (popt->flags & HAS_ARG) {
7224 if (optind >= argc) {
7225 fprintf(stderr, "%s: option '%s' requires an argument\n",
7229 optarg = argv[optind++];
7234 switch(popt->index) {
7236 machine = find_machine(optarg);
7239 printf("Supported machines are:\n");
7240 for(m = first_machine; m != NULL; m = m->next) {
7241 printf("%-10s %s%s\n",
7243 m == first_machine ? " (default)" : "");
7248 case QEMU_OPTION_cpu:
7249 /* hw initialization will check this */
7250 if (optarg[0] == '?') {
7251 #if defined(TARGET_PPC)
7252 ppc_cpu_list(stdout, &fprintf);
7253 #elif defined(TARGET_ARM)
7255 #elif defined(TARGET_MIPS)
7256 mips_cpu_list(stdout, &fprintf);
7257 #elif defined(TARGET_SPARC)
7258 sparc_cpu_list(stdout, &fprintf);
7265 case QEMU_OPTION_initrd:
7266 initrd_filename = optarg;
7268 case QEMU_OPTION_hda:
7269 case QEMU_OPTION_hdb:
7270 case QEMU_OPTION_hdc:
7271 case QEMU_OPTION_hdd:
7274 hd_index = popt->index - QEMU_OPTION_hda;
7275 hd_filename[hd_index] = optarg;
7276 if (hd_index == cdrom_index)
7280 case QEMU_OPTION_mtdblock:
7281 mtd_filename = optarg;
7283 case QEMU_OPTION_sd:
7284 sd_filename = optarg;
7286 case QEMU_OPTION_pflash:
7287 if (pflash_index >= MAX_PFLASH) {
7288 fprintf(stderr, "qemu: too many parallel flash images\n");
7291 pflash_filename[pflash_index++] = optarg;
7293 case QEMU_OPTION_snapshot:
7296 case QEMU_OPTION_hdachs:
7300 cyls = strtol(p, (char **)&p, 0);
7301 if (cyls < 1 || cyls > 16383)
7306 heads = strtol(p, (char **)&p, 0);
7307 if (heads < 1 || heads > 16)
7312 secs = strtol(p, (char **)&p, 0);
7313 if (secs < 1 || secs > 63)
7317 if (!strcmp(p, "none"))
7318 translation = BIOS_ATA_TRANSLATION_NONE;
7319 else if (!strcmp(p, "lba"))
7320 translation = BIOS_ATA_TRANSLATION_LBA;
7321 else if (!strcmp(p, "auto"))
7322 translation = BIOS_ATA_TRANSLATION_AUTO;
7325 } else if (*p != '\0') {
7327 fprintf(stderr, "qemu: invalid physical CHS format\n");
7332 case QEMU_OPTION_nographic:
7333 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7334 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7335 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7338 case QEMU_OPTION_portrait:
7341 case QEMU_OPTION_kernel:
7342 kernel_filename = optarg;
7344 case QEMU_OPTION_append:
7345 kernel_cmdline = optarg;
7347 case QEMU_OPTION_cdrom:
7348 if (cdrom_index >= 0) {
7349 hd_filename[cdrom_index] = optarg;
7352 case QEMU_OPTION_boot:
7353 boot_device = optarg[0];
7354 if (boot_device != 'a' &&
7355 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7357 boot_device != 'n' &&
7359 boot_device != 'c' && boot_device != 'd') {
7360 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7364 case QEMU_OPTION_fda:
7365 fd_filename[0] = optarg;
7367 case QEMU_OPTION_fdb:
7368 fd_filename[1] = optarg;
7371 case QEMU_OPTION_no_fd_bootchk:
7375 case QEMU_OPTION_no_code_copy:
7376 code_copy_enabled = 0;
7378 case QEMU_OPTION_net:
7379 if (nb_net_clients >= MAX_NET_CLIENTS) {
7380 fprintf(stderr, "qemu: too many network clients\n");
7383 pstrcpy(net_clients[nb_net_clients],
7384 sizeof(net_clients[0]),
7389 case QEMU_OPTION_tftp:
7390 tftp_prefix = optarg;
7392 case QEMU_OPTION_bootp:
7393 bootp_filename = optarg;
7396 case QEMU_OPTION_smb:
7397 net_slirp_smb(optarg);
7400 case QEMU_OPTION_redir:
7401 net_slirp_redir(optarg);
7405 case QEMU_OPTION_audio_help:
7409 case QEMU_OPTION_soundhw:
7410 select_soundhw (optarg);
7417 ram_size = atoi(optarg) * 1024 * 1024;
7420 if (ram_size > PHYS_RAM_MAX_SIZE) {
7421 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7422 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7431 mask = cpu_str_to_log_mask(optarg);
7433 printf("Log items (comma separated):\n");
7434 for(item = cpu_log_items; item->mask != 0; item++) {
7435 printf("%-10s %s\n", item->name, item->help);
7442 #ifdef CONFIG_GDBSTUB
7447 gdbstub_port = optarg;
7457 keyboard_layout = optarg;
7459 case QEMU_OPTION_localtime:
7462 case QEMU_OPTION_cirrusvga:
7463 cirrus_vga_enabled = 1;
7466 case QEMU_OPTION_vmsvga:
7467 cirrus_vga_enabled = 0;
7470 case QEMU_OPTION_std_vga:
7471 cirrus_vga_enabled = 0;
7479 w = strtol(p, (char **)&p, 10);
7482 fprintf(stderr, "qemu: invalid resolution or depth\n");
7488 h = strtol(p, (char **)&p, 10);
7493 depth = strtol(p, (char **)&p, 10);
7494 if (depth != 8 && depth != 15 && depth != 16 &&
7495 depth != 24 && depth != 32)
7497 } else if (*p == '\0') {
7498 depth = graphic_depth;
7505 graphic_depth = depth;
7508 case QEMU_OPTION_echr:
7511 term_escape_char = strtol(optarg, &r, 0);
7513 printf("Bad argument to echr\n");
7516 case QEMU_OPTION_monitor:
7517 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7519 case QEMU_OPTION_serial:
7520 if (serial_device_index >= MAX_SERIAL_PORTS) {
7521 fprintf(stderr, "qemu: too many serial ports\n");
7524 pstrcpy(serial_devices[serial_device_index],
7525 sizeof(serial_devices[0]), optarg);
7526 serial_device_index++;
7528 case QEMU_OPTION_parallel:
7529 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7530 fprintf(stderr, "qemu: too many parallel ports\n");
7533 pstrcpy(parallel_devices[parallel_device_index],
7534 sizeof(parallel_devices[0]), optarg);
7535 parallel_device_index++;
7537 case QEMU_OPTION_loadvm:
7540 case QEMU_OPTION_full_screen:
7544 case QEMU_OPTION_no_frame:
7547 case QEMU_OPTION_no_quit:
7551 case QEMU_OPTION_pidfile:
7555 case QEMU_OPTION_win2k_hack:
7556 win2k_install_hack = 1;
7560 case QEMU_OPTION_no_kqemu:
7563 case QEMU_OPTION_kernel_kqemu:
7567 case QEMU_OPTION_usb:
7570 case QEMU_OPTION_usbdevice:
7572 if (usb_devices_index >= MAX_USB_CMDLINE) {
7573 fprintf(stderr, "Too many USB devices\n");
7576 pstrcpy(usb_devices[usb_devices_index],
7577 sizeof(usb_devices[usb_devices_index]),
7579 usb_devices_index++;
7581 case QEMU_OPTION_smp:
7582 smp_cpus = atoi(optarg);
7583 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7584 fprintf(stderr, "Invalid number of CPUs\n");
7588 case QEMU_OPTION_vnc:
7589 vnc_display = optarg;
7591 case QEMU_OPTION_no_acpi:
7594 case QEMU_OPTION_no_reboot:
7597 case QEMU_OPTION_show_cursor:
7600 case QEMU_OPTION_daemonize:
7603 case QEMU_OPTION_option_rom:
7604 if (nb_option_roms >= MAX_OPTION_ROMS) {
7605 fprintf(stderr, "Too many option ROMs\n");
7608 option_rom[nb_option_roms] = optarg;
7611 case QEMU_OPTION_semihosting:
7612 semihosting_enabled = 1;
7614 case QEMU_OPTION_name:
7618 case QEMU_OPTION_prom_env:
7619 if (nb_prom_envs >= MAX_PROM_ENVS) {
7620 fprintf(stderr, "Too many prom variables\n");
7623 prom_envs[nb_prom_envs] = optarg;
7632 if (daemonize && !nographic && vnc_display == NULL) {
7633 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7640 if (pipe(fds) == -1)
7651 len = read(fds[0], &status, 1);
7652 if (len == -1 && (errno == EINTR))
7657 else if (status == 1) {
7658 fprintf(stderr, "Could not acquire pidfile\n");
7676 signal(SIGTSTP, SIG_IGN);
7677 signal(SIGTTOU, SIG_IGN);
7678 signal(SIGTTIN, SIG_IGN);
7682 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7685 write(fds[1], &status, 1);
7687 fprintf(stderr, "Could not acquire pid file\n");
7695 linux_boot = (kernel_filename != NULL);
7698 boot_device != 'n' &&
7699 hd_filename[0] == '\0' &&
7700 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7701 fd_filename[0] == '\0')
7704 /* boot to floppy or the default cd if no hard disk defined yet */
7705 if (hd_filename[0] == '\0' && boot_device == 'c') {
7706 if (fd_filename[0] != '\0')
7712 setvbuf(stdout, NULL, _IOLBF, 0);
7722 /* init network clients */
7723 if (nb_net_clients == 0) {
7724 /* if no clients, we use a default config */
7725 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7727 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7732 for(i = 0;i < nb_net_clients; i++) {
7733 if (net_client_init(net_clients[i]) < 0)
7736 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7737 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7739 if (vlan->nb_guest_devs == 0) {
7740 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7743 if (vlan->nb_host_devs == 0)
7745 "Warning: vlan %d is not connected to host network\n",
7750 if (boot_device == 'n') {
7751 for (i = 0; i < nb_nics; i++) {
7752 const char *model = nd_table[i].model;
7756 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7757 if (get_image_size(buf) > 0) {
7758 option_rom[nb_option_roms] = strdup(buf);
7764 fprintf(stderr, "No valid PXE rom found for network device\n");
7767 boot_device = 'c'; /* to prevent confusion by the BIOS */
7771 /* init the memory */
7772 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7774 phys_ram_base = qemu_vmalloc(phys_ram_size);
7775 if (!phys_ram_base) {
7776 fprintf(stderr, "Could not allocate physical memory\n");
7780 /* we always create the cdrom drive, even if no disk is there */
7782 if (cdrom_index >= 0) {
7783 bs_table[cdrom_index] = bdrv_new("cdrom");
7784 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7787 /* open the virtual block devices */
7788 for(i = 0; i < MAX_DISKS; i++) {
7789 if (hd_filename[i]) {
7792 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7793 bs_table[i] = bdrv_new(buf);
7795 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7796 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7800 if (i == 0 && cyls != 0) {
7801 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7802 bdrv_set_translation_hint(bs_table[i], translation);
7807 /* we always create at least one floppy disk */
7808 fd_table[0] = bdrv_new("fda");
7809 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7811 for(i = 0; i < MAX_FD; i++) {
7812 if (fd_filename[i]) {
7815 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7816 fd_table[i] = bdrv_new(buf);
7817 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7819 if (fd_filename[i][0] != '\0') {
7820 if (bdrv_open(fd_table[i], fd_filename[i],
7821 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7822 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7830 /* Open the virtual parallel flash block devices */
7831 for(i = 0; i < MAX_PFLASH; i++) {
7832 if (pflash_filename[i]) {
7833 if (!pflash_table[i]) {
7835 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7836 pflash_table[i] = bdrv_new(buf);
7838 if (bdrv_open(pflash_table[i], pflash_filename[i],
7839 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7840 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7841 pflash_filename[i]);
7847 sd_bdrv = bdrv_new ("sd");
7848 /* FIXME: This isn't really a floppy, but it's a reasonable
7850 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7852 if (bdrv_open(sd_bdrv, sd_filename,
7853 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7854 fprintf(stderr, "qemu: could not open SD card image %s\n",
7857 qemu_key_check(sd_bdrv, sd_filename);
7861 mtd_bdrv = bdrv_new ("mtd");
7862 if (bdrv_open(mtd_bdrv, mtd_filename,
7863 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7864 qemu_key_check(mtd_bdrv, mtd_filename)) {
7865 fprintf(stderr, "qemu: could not open Flash image %s\n",
7867 bdrv_delete(mtd_bdrv);
7872 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7873 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7878 memset(&display_state, 0, sizeof(display_state));
7881 } else if (vnc_display != NULL) {
7882 vnc_display_init(ds, vnc_display);
7884 #if defined(CONFIG_SDL)
7885 sdl_display_init(ds, full_screen, no_frame);
7886 #elif defined(CONFIG_COCOA)
7887 cocoa_display_init(ds, full_screen);
7891 /* Maintain compatibility with multiple stdio monitors */
7892 if (!strcmp(monitor_device,"stdio")) {
7893 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7894 if (!strcmp(serial_devices[i],"mon:stdio")) {
7895 monitor_device[0] = '\0';
7897 } else if (!strcmp(serial_devices[i],"stdio")) {
7898 monitor_device[0] = '\0';
7899 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7904 if (monitor_device[0] != '\0') {
7905 monitor_hd = qemu_chr_open(monitor_device);
7907 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7910 monitor_init(monitor_hd, !nographic);
7913 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7914 const char *devname = serial_devices[i];
7915 if (devname[0] != '\0' && strcmp(devname, "none")) {
7916 serial_hds[i] = qemu_chr_open(devname);
7917 if (!serial_hds[i]) {
7918 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7922 if (!strcmp(devname, "vc"))
7923 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7927 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7928 const char *devname = parallel_devices[i];
7929 if (devname[0] != '\0' && strcmp(devname, "none")) {
7930 parallel_hds[i] = qemu_chr_open(devname);
7931 if (!parallel_hds[i]) {
7932 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7936 if (!strcmp(devname, "vc"))
7937 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7941 machine->init(ram_size, vga_ram_size, boot_device,
7942 ds, fd_filename, snapshot,
7943 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7945 /* init USB devices */
7947 for(i = 0; i < usb_devices_index; i++) {
7948 if (usb_device_add(usb_devices[i]) < 0) {
7949 fprintf(stderr, "Warning: could not add USB device %s\n",
7955 if (display_state.dpy_refresh) {
7956 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
7957 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
7960 #ifdef CONFIG_GDBSTUB
7962 /* XXX: use standard host:port notation and modify options
7964 if (gdbserver_start(gdbstub_port) < 0) {
7965 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7975 /* XXX: simplify init */
7988 len = write(fds[1], &status, 1);
7989 if (len == -1 && (errno == EINTR))
7995 fd = open("/dev/null", O_RDWR);