4 * Copyright (c) 2003-2006 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
62 #if defined(CONFIG_SLIRP)
68 #include <sys/timeb.h>
70 #define getopt_long_only getopt_long
71 #define memalign(align, size) malloc(size)
74 #include "qemu_socket.h"
80 #endif /* CONFIG_SDL */
84 #define main qemu_main
85 #endif /* CONFIG_COCOA */
91 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
93 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
95 #define SMBD_COMMAND "/usr/sbin/smbd"
98 //#define DEBUG_UNUSED_IOPORT
99 //#define DEBUG_IOPORT
101 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
104 #define DEFAULT_RAM_SIZE 144
106 #define DEFAULT_RAM_SIZE 128
109 #define GUI_REFRESH_INTERVAL 30
111 /* Max number of USB devices that can be specified on the commandline. */
112 #define MAX_USB_CMDLINE 8
114 /* XXX: use a two level table to limit memory usage */
115 #define MAX_IOPORTS 65536
117 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
118 char phys_ram_file[1024];
119 void *ioport_opaque[MAX_IOPORTS];
120 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
121 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
122 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
123 to store the VM snapshots */
124 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
125 /* point to the block driver where the snapshots are managed */
126 BlockDriverState *bs_snapshots;
129 static DisplayState display_state;
131 const char* keyboard_layout = NULL;
132 int64_t ticks_per_sec;
133 int boot_device = 'c';
135 int pit_min_timer_count = 0;
137 NICInfo nd_table[MAX_NICS];
138 QEMUTimer *gui_timer;
141 int cirrus_vga_enabled = 1;
143 int graphic_width = 1024;
144 int graphic_height = 768;
146 int graphic_width = 800;
147 int graphic_height = 600;
149 int graphic_depth = 15;
152 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
153 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
155 int win2k_install_hack = 0;
158 static VLANState *first_vlan;
160 const char *vnc_display;
161 #if defined(TARGET_SPARC)
163 #elif defined(TARGET_I386)
168 int acpi_enabled = 1;
172 const char *option_rom[MAX_OPTION_ROMS];
175 /***********************************************************/
176 /* x86 ISA bus support */
178 target_phys_addr_t isa_mem_base = 0;
181 uint32_t default_ioport_readb(void *opaque, uint32_t address)
183 #ifdef DEBUG_UNUSED_IOPORT
184 fprintf(stderr, "inb: port=0x%04x\n", address);
189 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
191 #ifdef DEBUG_UNUSED_IOPORT
192 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
196 /* default is to make two byte accesses */
197 uint32_t default_ioport_readw(void *opaque, uint32_t address)
200 data = ioport_read_table[0][address](ioport_opaque[address], address);
201 address = (address + 1) & (MAX_IOPORTS - 1);
202 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
206 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
208 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
209 address = (address + 1) & (MAX_IOPORTS - 1);
210 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
213 uint32_t default_ioport_readl(void *opaque, uint32_t address)
215 #ifdef DEBUG_UNUSED_IOPORT
216 fprintf(stderr, "inl: port=0x%04x\n", address);
221 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
223 #ifdef DEBUG_UNUSED_IOPORT
224 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
228 void init_ioports(void)
232 for(i = 0; i < MAX_IOPORTS; i++) {
233 ioport_read_table[0][i] = default_ioport_readb;
234 ioport_write_table[0][i] = default_ioport_writeb;
235 ioport_read_table[1][i] = default_ioport_readw;
236 ioport_write_table[1][i] = default_ioport_writew;
237 ioport_read_table[2][i] = default_ioport_readl;
238 ioport_write_table[2][i] = default_ioport_writel;
242 /* size is the word size in byte */
243 int register_ioport_read(int start, int length, int size,
244 IOPortReadFunc *func, void *opaque)
250 } else if (size == 2) {
252 } else if (size == 4) {
255 hw_error("register_ioport_read: invalid size");
258 for(i = start; i < start + length; i += size) {
259 ioport_read_table[bsize][i] = func;
260 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
261 hw_error("register_ioport_read: invalid opaque");
262 ioport_opaque[i] = opaque;
267 /* size is the word size in byte */
268 int register_ioport_write(int start, int length, int size,
269 IOPortWriteFunc *func, void *opaque)
275 } else if (size == 2) {
277 } else if (size == 4) {
280 hw_error("register_ioport_write: invalid size");
283 for(i = start; i < start + length; i += size) {
284 ioport_write_table[bsize][i] = func;
285 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
286 hw_error("register_ioport_write: invalid opaque");
287 ioport_opaque[i] = opaque;
292 void isa_unassign_ioport(int start, int length)
296 for(i = start; i < start + length; i++) {
297 ioport_read_table[0][i] = default_ioport_readb;
298 ioport_read_table[1][i] = default_ioport_readw;
299 ioport_read_table[2][i] = default_ioport_readl;
301 ioport_write_table[0][i] = default_ioport_writeb;
302 ioport_write_table[1][i] = default_ioport_writew;
303 ioport_write_table[2][i] = default_ioport_writel;
307 /***********************************************************/
309 void cpu_outb(CPUState *env, int addr, int val)
312 if (loglevel & CPU_LOG_IOPORT)
313 fprintf(logfile, "outb: %04x %02x\n", addr, val);
315 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
318 env->last_io_time = cpu_get_time_fast();
322 void cpu_outw(CPUState *env, int addr, int val)
325 if (loglevel & CPU_LOG_IOPORT)
326 fprintf(logfile, "outw: %04x %04x\n", addr, val);
328 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
331 env->last_io_time = cpu_get_time_fast();
335 void cpu_outl(CPUState *env, int addr, int val)
338 if (loglevel & CPU_LOG_IOPORT)
339 fprintf(logfile, "outl: %04x %08x\n", addr, val);
341 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
344 env->last_io_time = cpu_get_time_fast();
348 int cpu_inb(CPUState *env, int addr)
351 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "inb : %04x %02x\n", addr, val);
358 env->last_io_time = cpu_get_time_fast();
363 int cpu_inw(CPUState *env, int addr)
366 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "inw : %04x %04x\n", addr, val);
373 env->last_io_time = cpu_get_time_fast();
378 int cpu_inl(CPUState *env, int addr)
381 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inl : %04x %08x\n", addr, val);
388 env->last_io_time = cpu_get_time_fast();
393 /***********************************************************/
394 void hw_error(const char *fmt, ...)
400 fprintf(stderr, "qemu: hardware error: ");
401 vfprintf(stderr, fmt, ap);
402 fprintf(stderr, "\n");
403 for(env = first_cpu; env != NULL; env = env->next_cpu) {
404 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
406 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
408 cpu_dump_state(env, stderr, fprintf, 0);
415 /***********************************************************/
418 static QEMUPutKBDEvent *qemu_put_kbd_event;
419 static void *qemu_put_kbd_event_opaque;
420 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
421 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
423 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
425 qemu_put_kbd_event_opaque = opaque;
426 qemu_put_kbd_event = func;
429 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
430 void *opaque, int absolute,
433 QEMUPutMouseEntry *s, *cursor;
435 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
439 s->qemu_put_mouse_event = func;
440 s->qemu_put_mouse_event_opaque = opaque;
441 s->qemu_put_mouse_event_absolute = absolute;
442 s->qemu_put_mouse_event_name = qemu_strdup(name);
445 if (!qemu_put_mouse_event_head) {
446 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
450 cursor = qemu_put_mouse_event_head;
451 while (cursor->next != NULL)
452 cursor = cursor->next;
455 qemu_put_mouse_event_current = s;
460 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
462 QEMUPutMouseEntry *prev = NULL, *cursor;
464 if (!qemu_put_mouse_event_head || entry == NULL)
467 cursor = qemu_put_mouse_event_head;
468 while (cursor != NULL && cursor != entry) {
470 cursor = cursor->next;
473 if (cursor == NULL) // does not exist or list empty
475 else if (prev == NULL) { // entry is head
476 qemu_put_mouse_event_head = cursor->next;
477 if (qemu_put_mouse_event_current == entry)
478 qemu_put_mouse_event_current = cursor->next;
479 qemu_free(entry->qemu_put_mouse_event_name);
484 prev->next = entry->next;
486 if (qemu_put_mouse_event_current == entry)
487 qemu_put_mouse_event_current = prev;
489 qemu_free(entry->qemu_put_mouse_event_name);
493 void kbd_put_keycode(int keycode)
495 if (qemu_put_kbd_event) {
496 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
500 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
502 QEMUPutMouseEvent *mouse_event;
503 void *mouse_event_opaque;
505 if (!qemu_put_mouse_event_current) {
510 qemu_put_mouse_event_current->qemu_put_mouse_event;
512 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
515 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
519 int kbd_mouse_is_absolute(void)
521 if (!qemu_put_mouse_event_current)
524 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
527 void do_info_mice(void)
529 QEMUPutMouseEntry *cursor;
532 if (!qemu_put_mouse_event_head) {
533 term_printf("No mouse devices connected\n");
537 term_printf("Mouse devices available:\n");
538 cursor = qemu_put_mouse_event_head;
539 while (cursor != NULL) {
540 term_printf("%c Mouse #%d: %s\n",
541 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
542 index, cursor->qemu_put_mouse_event_name);
544 cursor = cursor->next;
548 void do_mouse_set(int index)
550 QEMUPutMouseEntry *cursor;
553 if (!qemu_put_mouse_event_head) {
554 term_printf("No mouse devices connected\n");
558 cursor = qemu_put_mouse_event_head;
559 while (cursor != NULL && index != i) {
561 cursor = cursor->next;
565 qemu_put_mouse_event_current = cursor;
567 term_printf("Mouse at given index not found\n");
570 /* compute with 96 bit intermediate result: (a*b)/c */
571 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
576 #ifdef WORDS_BIGENDIAN
586 rl = (uint64_t)u.l.low * (uint64_t)b;
587 rh = (uint64_t)u.l.high * (uint64_t)b;
590 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
594 /***********************************************************/
595 /* real time host monotonic timer */
597 #define QEMU_TIMER_BASE 1000000000LL
601 static int64_t clock_freq;
603 static void init_get_clock(void)
607 ret = QueryPerformanceFrequency(&freq);
609 fprintf(stderr, "Could not calibrate ticks\n");
612 clock_freq = freq.QuadPart;
615 static int64_t get_clock(void)
618 QueryPerformanceCounter(&ti);
619 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
624 static int use_rt_clock;
626 static void init_get_clock(void)
629 #if defined(__linux__)
632 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
639 static int64_t get_clock(void)
641 #if defined(__linux__)
644 clock_gettime(CLOCK_MONOTONIC, &ts);
645 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
649 /* XXX: using gettimeofday leads to problems if the date
650 changes, so it should be avoided. */
652 gettimeofday(&tv, NULL);
653 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
659 /***********************************************************/
660 /* guest cycle counter */
662 static int64_t cpu_ticks_prev;
663 static int64_t cpu_ticks_offset;
664 static int64_t cpu_clock_offset;
665 static int cpu_ticks_enabled;
667 /* return the host CPU cycle counter and handle stop/restart */
668 int64_t cpu_get_ticks(void)
670 if (!cpu_ticks_enabled) {
671 return cpu_ticks_offset;
674 ticks = cpu_get_real_ticks();
675 if (cpu_ticks_prev > ticks) {
676 /* Note: non increasing ticks may happen if the host uses
678 cpu_ticks_offset += cpu_ticks_prev - ticks;
680 cpu_ticks_prev = ticks;
681 return ticks + cpu_ticks_offset;
685 /* return the host CPU monotonic timer and handle stop/restart */
686 static int64_t cpu_get_clock(void)
689 if (!cpu_ticks_enabled) {
690 return cpu_clock_offset;
693 return ti + cpu_clock_offset;
697 /* enable cpu_get_ticks() */
698 void cpu_enable_ticks(void)
700 if (!cpu_ticks_enabled) {
701 cpu_ticks_offset -= cpu_get_real_ticks();
702 cpu_clock_offset -= get_clock();
703 cpu_ticks_enabled = 1;
707 /* disable cpu_get_ticks() : the clock is stopped. You must not call
708 cpu_get_ticks() after that. */
709 void cpu_disable_ticks(void)
711 if (cpu_ticks_enabled) {
712 cpu_ticks_offset = cpu_get_ticks();
713 cpu_clock_offset = cpu_get_clock();
714 cpu_ticks_enabled = 0;
718 /***********************************************************/
721 #define QEMU_TIMER_REALTIME 0
722 #define QEMU_TIMER_VIRTUAL 1
726 /* XXX: add frequency */
734 struct QEMUTimer *next;
740 static QEMUTimer *active_timers[2];
742 static MMRESULT timerID;
743 static HANDLE host_alarm = NULL;
744 static unsigned int period = 1;
746 /* frequency of the times() clock tick */
747 static int timer_freq;
750 QEMUClock *qemu_new_clock(int type)
753 clock = qemu_mallocz(sizeof(QEMUClock));
760 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
764 ts = qemu_mallocz(sizeof(QEMUTimer));
771 void qemu_free_timer(QEMUTimer *ts)
776 /* stop a timer, but do not dealloc it */
777 void qemu_del_timer(QEMUTimer *ts)
781 /* NOTE: this code must be signal safe because
782 qemu_timer_expired() can be called from a signal. */
783 pt = &active_timers[ts->clock->type];
796 /* modify the current timer so that it will be fired when current_time
797 >= expire_time. The corresponding callback will be called. */
798 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
804 /* add the timer in the sorted list */
805 /* NOTE: this code must be signal safe because
806 qemu_timer_expired() can be called from a signal. */
807 pt = &active_timers[ts->clock->type];
812 if (t->expire_time > expire_time)
816 ts->expire_time = expire_time;
821 int qemu_timer_pending(QEMUTimer *ts)
824 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
831 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
835 return (timer_head->expire_time <= current_time);
838 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
844 if (!ts || ts->expire_time > current_time)
846 /* remove timer from the list before calling the callback */
847 *ptimer_head = ts->next;
850 /* run the callback (the timer list can be modified) */
855 int64_t qemu_get_clock(QEMUClock *clock)
857 switch(clock->type) {
858 case QEMU_TIMER_REALTIME:
859 return get_clock() / 1000000;
861 case QEMU_TIMER_VIRTUAL:
862 return cpu_get_clock();
866 static void init_timers(void)
869 ticks_per_sec = QEMU_TIMER_BASE;
870 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
871 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
875 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
877 uint64_t expire_time;
879 if (qemu_timer_pending(ts)) {
880 expire_time = ts->expire_time;
884 qemu_put_be64(f, expire_time);
887 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
889 uint64_t expire_time;
891 expire_time = qemu_get_be64(f);
892 if (expire_time != -1) {
893 qemu_mod_timer(ts, expire_time);
899 static void timer_save(QEMUFile *f, void *opaque)
901 if (cpu_ticks_enabled) {
902 hw_error("cannot save state if virtual timers are running");
904 qemu_put_be64s(f, &cpu_ticks_offset);
905 qemu_put_be64s(f, &ticks_per_sec);
906 qemu_put_be64s(f, &cpu_clock_offset);
909 static int timer_load(QEMUFile *f, void *opaque, int version_id)
911 if (version_id != 1 && version_id != 2)
913 if (cpu_ticks_enabled) {
916 qemu_get_be64s(f, &cpu_ticks_offset);
917 qemu_get_be64s(f, &ticks_per_sec);
918 if (version_id == 2) {
919 qemu_get_be64s(f, &cpu_clock_offset);
925 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
926 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
928 static void host_alarm_handler(int host_signum)
932 #define DISP_FREQ 1000
934 static int64_t delta_min = INT64_MAX;
935 static int64_t delta_max, delta_cum, last_clock, delta, ti;
937 ti = qemu_get_clock(vm_clock);
938 if (last_clock != 0) {
939 delta = ti - last_clock;
940 if (delta < delta_min)
942 if (delta > delta_max)
945 if (++count == DISP_FREQ) {
946 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
947 muldiv64(delta_min, 1000000, ticks_per_sec),
948 muldiv64(delta_max, 1000000, ticks_per_sec),
949 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
950 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
952 delta_min = INT64_MAX;
960 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
961 qemu_get_clock(vm_clock)) ||
962 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
963 qemu_get_clock(rt_clock))) {
965 SetEvent(host_alarm);
967 CPUState *env = cpu_single_env;
969 /* stop the currently executing cpu because a timer occured */
970 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
972 if (env->kqemu_enabled) {
973 kqemu_cpu_interrupt(env);
982 #if defined(__linux__)
984 #define RTC_FREQ 1024
988 static int start_rtc_timer(void)
990 rtc_fd = open("/dev/rtc", O_RDONLY);
993 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
994 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
995 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
996 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
999 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1004 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1010 static int start_rtc_timer(void)
1015 #endif /* !defined(__linux__) */
1017 #endif /* !defined(_WIN32) */
1019 static void init_timer_alarm(void)
1026 ZeroMemory(&tc, sizeof(TIMECAPS));
1027 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1028 if (period < tc.wPeriodMin)
1029 period = tc.wPeriodMin;
1030 timeBeginPeriod(period);
1031 timerID = timeSetEvent(1, // interval (ms)
1032 period, // resolution
1033 host_alarm_handler, // function
1034 (DWORD)&count, // user parameter
1035 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1037 perror("failed timer alarm");
1040 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1042 perror("failed CreateEvent");
1045 qemu_add_wait_object(host_alarm, NULL, NULL);
1047 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1050 struct sigaction act;
1051 struct itimerval itv;
1053 /* get times() syscall frequency */
1054 timer_freq = sysconf(_SC_CLK_TCK);
1057 sigfillset(&act.sa_mask);
1059 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1060 act.sa_flags |= SA_ONSTACK;
1062 act.sa_handler = host_alarm_handler;
1063 sigaction(SIGALRM, &act, NULL);
1065 itv.it_interval.tv_sec = 0;
1066 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1067 itv.it_value.tv_sec = 0;
1068 itv.it_value.tv_usec = 10 * 1000;
1069 setitimer(ITIMER_REAL, &itv, NULL);
1070 /* we probe the tick duration of the kernel to inform the user if
1071 the emulated kernel requested a too high timer frequency */
1072 getitimer(ITIMER_REAL, &itv);
1074 #if defined(__linux__)
1075 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1076 have timers with 1 ms resolution. The correct solution will
1077 be to use the POSIX real time timers available in recent
1079 if (itv.it_interval.tv_usec > 1000 || 1) {
1080 /* try to use /dev/rtc to have a faster timer */
1081 if (start_rtc_timer() < 0)
1083 /* disable itimer */
1084 itv.it_interval.tv_sec = 0;
1085 itv.it_interval.tv_usec = 0;
1086 itv.it_value.tv_sec = 0;
1087 itv.it_value.tv_usec = 0;
1088 setitimer(ITIMER_REAL, &itv, NULL);
1091 sigaction(SIGIO, &act, NULL);
1092 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1093 fcntl(rtc_fd, F_SETOWN, getpid());
1095 #endif /* defined(__linux__) */
1098 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1099 PIT_FREQ) / 1000000;
1105 void quit_timers(void)
1108 timeKillEvent(timerID);
1109 timeEndPeriod(period);
1111 CloseHandle(host_alarm);
1117 /***********************************************************/
1118 /* character device */
1120 static void qemu_chr_reset_bh(void *opaque)
1122 CharDriverState *s = opaque;
1124 s->chr_event(s, CHR_EVENT_RESET);
1125 qemu_bh_delete(s->bh);
1129 void qemu_chr_reset(CharDriverState *s)
1131 if (s->bh == NULL) {
1132 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1133 qemu_bh_schedule(s->bh);
1137 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1139 return s->chr_write(s, buf, len);
1142 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1146 return s->chr_ioctl(s, cmd, arg);
1149 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1154 vsnprintf(buf, sizeof(buf), fmt, ap);
1155 qemu_chr_write(s, buf, strlen(buf));
1159 void qemu_chr_send_event(CharDriverState *s, int event)
1161 if (s->chr_send_event)
1162 s->chr_send_event(s, event);
1165 void qemu_chr_add_read_handler(CharDriverState *s,
1166 IOCanRWHandler *fd_can_read,
1167 IOReadHandler *fd_read, void *opaque)
1169 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1172 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1174 s->chr_event = chr_event;
1177 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1182 static void null_chr_add_read_handler(CharDriverState *chr,
1183 IOCanRWHandler *fd_can_read,
1184 IOReadHandler *fd_read, void *opaque)
1188 static CharDriverState *qemu_chr_open_null(void)
1190 CharDriverState *chr;
1192 chr = qemu_mallocz(sizeof(CharDriverState));
1195 chr->chr_write = null_chr_write;
1196 chr->chr_add_read_handler = null_chr_add_read_handler;
1202 static void socket_cleanup(void)
1207 static int socket_init(void)
1212 ret = WSAStartup(MAKEWORD(2,2), &Data);
1214 err = WSAGetLastError();
1215 fprintf(stderr, "WSAStartup: %d\n", err);
1218 atexit(socket_cleanup);
1222 static int send_all(int fd, const uint8_t *buf, int len1)
1228 ret = send(fd, buf, len, 0);
1231 errno = WSAGetLastError();
1232 if (errno != WSAEWOULDBLOCK) {
1235 } else if (ret == 0) {
1245 void socket_set_nonblock(int fd)
1247 unsigned long opt = 1;
1248 ioctlsocket(fd, FIONBIO, &opt);
1253 static int unix_write(int fd, const uint8_t *buf, int len1)
1259 ret = write(fd, buf, len);
1261 if (errno != EINTR && errno != EAGAIN)
1263 } else if (ret == 0) {
1273 static inline int send_all(int fd, const uint8_t *buf, int len1)
1275 return unix_write(fd, buf, len1);
1278 void socket_set_nonblock(int fd)
1280 fcntl(fd, F_SETFL, O_NONBLOCK);
1282 #endif /* !_WIN32 */
1288 IOCanRWHandler *fd_can_read;
1289 IOReadHandler *fd_read;
1294 #define STDIO_MAX_CLIENTS 2
1296 static int stdio_nb_clients;
1297 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1299 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1301 FDCharDriver *s = chr->opaque;
1302 return unix_write(s->fd_out, buf, len);
1305 static int fd_chr_read_poll(void *opaque)
1307 CharDriverState *chr = opaque;
1308 FDCharDriver *s = chr->opaque;
1310 s->max_size = s->fd_can_read(s->fd_opaque);
1314 static void fd_chr_read(void *opaque)
1316 CharDriverState *chr = opaque;
1317 FDCharDriver *s = chr->opaque;
1322 if (len > s->max_size)
1326 size = read(s->fd_in, buf, len);
1328 /* FD has been closed. Remove it from the active list. */
1329 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1333 s->fd_read(s->fd_opaque, buf, size);
1337 static void fd_chr_add_read_handler(CharDriverState *chr,
1338 IOCanRWHandler *fd_can_read,
1339 IOReadHandler *fd_read, void *opaque)
1341 FDCharDriver *s = chr->opaque;
1343 if (s->fd_in >= 0) {
1344 s->fd_can_read = fd_can_read;
1345 s->fd_read = fd_read;
1346 s->fd_opaque = opaque;
1347 if (nographic && s->fd_in == 0) {
1349 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1350 fd_chr_read, NULL, chr);
1355 /* open a character device to a unix fd */
1356 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1358 CharDriverState *chr;
1361 chr = qemu_mallocz(sizeof(CharDriverState));
1364 s = qemu_mallocz(sizeof(FDCharDriver));
1372 chr->chr_write = fd_chr_write;
1373 chr->chr_add_read_handler = fd_chr_add_read_handler;
1375 qemu_chr_reset(chr);
1380 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1384 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1387 return qemu_chr_open_fd(-1, fd_out);
1390 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1393 char filename_in[256], filename_out[256];
1395 snprintf(filename_in, 256, "%s.in", filename);
1396 snprintf(filename_out, 256, "%s.out", filename);
1397 fd_in = open(filename_in, O_RDWR | O_BINARY);
1398 fd_out = open(filename_out, O_RDWR | O_BINARY);
1399 if (fd_in < 0 || fd_out < 0) {
1404 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1408 return qemu_chr_open_fd(fd_in, fd_out);
1412 /* for STDIO, we handle the case where several clients use it
1415 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1417 #define TERM_FIFO_MAX_SIZE 1
1419 static int term_got_escape, client_index;
1420 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1421 static int term_fifo_size;
1422 static int term_timestamps;
1423 static int64_t term_timestamps_start;
1425 void term_print_help(void)
1428 "C-a h print this help\n"
1429 "C-a x exit emulator\n"
1430 "C-a s save disk data back to file (if -snapshot)\n"
1431 "C-a b send break (magic sysrq)\n"
1432 "C-a t toggle console timestamps\n"
1433 "C-a c switch between console and monitor\n"
1434 "C-a C-a send C-a\n"
1438 /* called when a char is received */
1439 static void stdio_received_byte(int ch)
1441 if (term_got_escape) {
1442 term_got_escape = 0;
1453 for (i = 0; i < MAX_DISKS; i++) {
1455 bdrv_commit(bs_table[i]);
1460 if (client_index < stdio_nb_clients) {
1461 CharDriverState *chr;
1464 chr = stdio_clients[client_index];
1466 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1471 if (client_index >= stdio_nb_clients)
1473 if (client_index == 0) {
1474 /* send a new line in the monitor to get the prompt */
1480 term_timestamps = !term_timestamps;
1481 term_timestamps_start = -1;
1486 } else if (ch == TERM_ESCAPE) {
1487 term_got_escape = 1;
1490 if (client_index < stdio_nb_clients) {
1492 CharDriverState *chr;
1495 chr = stdio_clients[client_index];
1497 if (s->fd_can_read(s->fd_opaque) > 0) {
1499 s->fd_read(s->fd_opaque, buf, 1);
1500 } else if (term_fifo_size == 0) {
1501 term_fifo[term_fifo_size++] = ch;
1507 static int stdio_read_poll(void *opaque)
1509 CharDriverState *chr;
1512 if (client_index < stdio_nb_clients) {
1513 chr = stdio_clients[client_index];
1515 /* try to flush the queue if needed */
1516 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1517 s->fd_read(s->fd_opaque, term_fifo, 1);
1520 /* see if we can absorb more chars */
1521 if (term_fifo_size == 0)
1530 static void stdio_read(void *opaque)
1535 size = read(0, buf, 1);
1537 /* stdin has been closed. Remove it from the active list. */
1538 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1542 stdio_received_byte(buf[0]);
1545 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1547 FDCharDriver *s = chr->opaque;
1548 if (!term_timestamps) {
1549 return unix_write(s->fd_out, buf, len);
1554 for(i = 0; i < len; i++) {
1555 unix_write(s->fd_out, buf + i, 1);
1556 if (buf[i] == '\n') {
1561 if (term_timestamps_start == -1)
1562 term_timestamps_start = ti;
1563 ti -= term_timestamps_start;
1564 secs = ti / 1000000000;
1565 snprintf(buf1, sizeof(buf1),
1566 "[%02d:%02d:%02d.%03d] ",
1570 (int)((ti / 1000000) % 1000));
1571 unix_write(s->fd_out, buf1, strlen(buf1));
1578 /* init terminal so that we can grab keys */
1579 static struct termios oldtty;
1580 static int old_fd0_flags;
1582 static void term_exit(void)
1584 tcsetattr (0, TCSANOW, &oldtty);
1585 fcntl(0, F_SETFL, old_fd0_flags);
1588 static void term_init(void)
1592 tcgetattr (0, &tty);
1594 old_fd0_flags = fcntl(0, F_GETFL);
1596 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1597 |INLCR|IGNCR|ICRNL|IXON);
1598 tty.c_oflag |= OPOST;
1599 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1600 /* if graphical mode, we allow Ctrl-C handling */
1602 tty.c_lflag &= ~ISIG;
1603 tty.c_cflag &= ~(CSIZE|PARENB);
1606 tty.c_cc[VTIME] = 0;
1608 tcsetattr (0, TCSANOW, &tty);
1612 fcntl(0, F_SETFL, O_NONBLOCK);
1615 static CharDriverState *qemu_chr_open_stdio(void)
1617 CharDriverState *chr;
1620 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1622 chr = qemu_chr_open_fd(0, 1);
1623 chr->chr_write = stdio_write;
1624 if (stdio_nb_clients == 0)
1625 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1626 client_index = stdio_nb_clients;
1628 if (stdio_nb_clients != 0)
1630 chr = qemu_chr_open_fd(0, 1);
1632 stdio_clients[stdio_nb_clients++] = chr;
1633 if (stdio_nb_clients == 1) {
1634 /* set the terminal in raw mode */
1640 #if defined(__linux__)
1641 static CharDriverState *qemu_chr_open_pty(void)
1644 char slave_name[1024];
1645 int master_fd, slave_fd;
1647 /* Not satisfying */
1648 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1652 /* Disabling local echo and line-buffered output */
1653 tcgetattr (master_fd, &tty);
1654 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1656 tty.c_cc[VTIME] = 0;
1657 tcsetattr (master_fd, TCSAFLUSH, &tty);
1659 fprintf(stderr, "char device redirected to %s\n", slave_name);
1660 return qemu_chr_open_fd(master_fd, master_fd);
1663 static void tty_serial_init(int fd, int speed,
1664 int parity, int data_bits, int stop_bits)
1670 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1671 speed, parity, data_bits, stop_bits);
1673 tcgetattr (fd, &tty);
1715 cfsetispeed(&tty, spd);
1716 cfsetospeed(&tty, spd);
1718 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1719 |INLCR|IGNCR|ICRNL|IXON);
1720 tty.c_oflag |= OPOST;
1721 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1722 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1743 tty.c_cflag |= PARENB;
1746 tty.c_cflag |= PARENB | PARODD;
1750 tty.c_cflag |= CSTOPB;
1752 tcsetattr (fd, TCSANOW, &tty);
1755 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1757 FDCharDriver *s = chr->opaque;
1760 case CHR_IOCTL_SERIAL_SET_PARAMS:
1762 QEMUSerialSetParams *ssp = arg;
1763 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1764 ssp->data_bits, ssp->stop_bits);
1767 case CHR_IOCTL_SERIAL_SET_BREAK:
1769 int enable = *(int *)arg;
1771 tcsendbreak(s->fd_in, 1);
1780 static CharDriverState *qemu_chr_open_tty(const char *filename)
1782 CharDriverState *chr;
1785 fd = open(filename, O_RDWR | O_NONBLOCK);
1788 fcntl(fd, F_SETFL, O_NONBLOCK);
1789 tty_serial_init(fd, 115200, 'N', 8, 1);
1790 chr = qemu_chr_open_fd(fd, fd);
1793 chr->chr_ioctl = tty_serial_ioctl;
1794 qemu_chr_reset(chr);
1798 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1800 int fd = (int)chr->opaque;
1804 case CHR_IOCTL_PP_READ_DATA:
1805 if (ioctl(fd, PPRDATA, &b) < 0)
1807 *(uint8_t *)arg = b;
1809 case CHR_IOCTL_PP_WRITE_DATA:
1810 b = *(uint8_t *)arg;
1811 if (ioctl(fd, PPWDATA, &b) < 0)
1814 case CHR_IOCTL_PP_READ_CONTROL:
1815 if (ioctl(fd, PPRCONTROL, &b) < 0)
1817 *(uint8_t *)arg = b;
1819 case CHR_IOCTL_PP_WRITE_CONTROL:
1820 b = *(uint8_t *)arg;
1821 if (ioctl(fd, PPWCONTROL, &b) < 0)
1824 case CHR_IOCTL_PP_READ_STATUS:
1825 if (ioctl(fd, PPRSTATUS, &b) < 0)
1827 *(uint8_t *)arg = b;
1835 static CharDriverState *qemu_chr_open_pp(const char *filename)
1837 CharDriverState *chr;
1840 fd = open(filename, O_RDWR);
1844 if (ioctl(fd, PPCLAIM) < 0) {
1849 chr = qemu_mallocz(sizeof(CharDriverState));
1854 chr->opaque = (void *)fd;
1855 chr->chr_write = null_chr_write;
1856 chr->chr_add_read_handler = null_chr_add_read_handler;
1857 chr->chr_ioctl = pp_ioctl;
1859 qemu_chr_reset(chr);
1865 static CharDriverState *qemu_chr_open_pty(void)
1871 #endif /* !defined(_WIN32) */
1875 IOCanRWHandler *fd_can_read;
1876 IOReadHandler *fd_read;
1879 HANDLE hcom, hrecv, hsend;
1880 OVERLAPPED orecv, osend;
1885 #define NSENDBUF 2048
1886 #define NRECVBUF 2048
1887 #define MAXCONNECT 1
1888 #define NTIMEOUT 5000
1890 static int win_chr_poll(void *opaque);
1891 static int win_chr_pipe_poll(void *opaque);
1893 static void win_chr_close2(WinCharState *s)
1896 CloseHandle(s->hsend);
1900 CloseHandle(s->hrecv);
1904 CloseHandle(s->hcom);
1908 qemu_del_polling_cb(win_chr_pipe_poll, s);
1910 qemu_del_polling_cb(win_chr_poll, s);
1913 static void win_chr_close(CharDriverState *chr)
1915 WinCharState *s = chr->opaque;
1919 static int win_chr_init(WinCharState *s, const char *filename)
1922 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1927 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1929 fprintf(stderr, "Failed CreateEvent\n");
1932 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1934 fprintf(stderr, "Failed CreateEvent\n");
1938 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1939 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1940 if (s->hcom == INVALID_HANDLE_VALUE) {
1941 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1946 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1947 fprintf(stderr, "Failed SetupComm\n");
1951 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1952 size = sizeof(COMMCONFIG);
1953 GetDefaultCommConfig(filename, &comcfg, &size);
1954 comcfg.dcb.DCBlength = sizeof(DCB);
1955 CommConfigDialog(filename, NULL, &comcfg);
1957 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1958 fprintf(stderr, "Failed SetCommState\n");
1962 if (!SetCommMask(s->hcom, EV_ERR)) {
1963 fprintf(stderr, "Failed SetCommMask\n");
1967 cto.ReadIntervalTimeout = MAXDWORD;
1968 if (!SetCommTimeouts(s->hcom, &cto)) {
1969 fprintf(stderr, "Failed SetCommTimeouts\n");
1973 if (!ClearCommError(s->hcom, &err, &comstat)) {
1974 fprintf(stderr, "Failed ClearCommError\n");
1977 qemu_add_polling_cb(win_chr_poll, s);
1985 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1987 WinCharState *s = chr->opaque;
1988 DWORD len, ret, size, err;
1991 ZeroMemory(&s->osend, sizeof(s->osend));
1992 s->osend.hEvent = s->hsend;
1995 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1997 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1999 err = GetLastError();
2000 if (err == ERROR_IO_PENDING) {
2001 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2019 static int win_chr_read_poll(WinCharState *s)
2021 s->max_size = s->fd_can_read(s->win_opaque);
2025 static void win_chr_readfile(WinCharState *s)
2031 ZeroMemory(&s->orecv, sizeof(s->orecv));
2032 s->orecv.hEvent = s->hrecv;
2033 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2035 err = GetLastError();
2036 if (err == ERROR_IO_PENDING) {
2037 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2042 s->fd_read(s->win_opaque, buf, size);
2046 static void win_chr_read(WinCharState *s)
2048 if (s->len > s->max_size)
2049 s->len = s->max_size;
2053 win_chr_readfile(s);
2056 static int win_chr_poll(void *opaque)
2058 WinCharState *s = opaque;
2062 ClearCommError(s->hcom, &comerr, &status);
2063 if (status.cbInQue > 0) {
2064 s->len = status.cbInQue;
2065 win_chr_read_poll(s);
2072 static void win_chr_add_read_handler(CharDriverState *chr,
2073 IOCanRWHandler *fd_can_read,
2074 IOReadHandler *fd_read, void *opaque)
2076 WinCharState *s = chr->opaque;
2078 s->fd_can_read = fd_can_read;
2079 s->fd_read = fd_read;
2080 s->win_opaque = opaque;
2083 static CharDriverState *qemu_chr_open_win(const char *filename)
2085 CharDriverState *chr;
2088 chr = qemu_mallocz(sizeof(CharDriverState));
2091 s = qemu_mallocz(sizeof(WinCharState));
2097 chr->chr_write = win_chr_write;
2098 chr->chr_add_read_handler = win_chr_add_read_handler;
2099 chr->chr_close = win_chr_close;
2101 if (win_chr_init(s, filename) < 0) {
2106 qemu_chr_reset(chr);
2110 static int win_chr_pipe_poll(void *opaque)
2112 WinCharState *s = opaque;
2115 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2118 win_chr_read_poll(s);
2125 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2134 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2136 fprintf(stderr, "Failed CreateEvent\n");
2139 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2141 fprintf(stderr, "Failed CreateEvent\n");
2145 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2146 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2147 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2149 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2150 if (s->hcom == INVALID_HANDLE_VALUE) {
2151 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2156 ZeroMemory(&ov, sizeof(ov));
2157 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2158 ret = ConnectNamedPipe(s->hcom, &ov);
2160 fprintf(stderr, "Failed ConnectNamedPipe\n");
2164 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2166 fprintf(stderr, "Failed GetOverlappedResult\n");
2168 CloseHandle(ov.hEvent);
2175 CloseHandle(ov.hEvent);
2178 qemu_add_polling_cb(win_chr_pipe_poll, s);
2187 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2189 CharDriverState *chr;
2192 chr = qemu_mallocz(sizeof(CharDriverState));
2195 s = qemu_mallocz(sizeof(WinCharState));
2201 chr->chr_write = win_chr_write;
2202 chr->chr_add_read_handler = win_chr_add_read_handler;
2203 chr->chr_close = win_chr_close;
2205 if (win_chr_pipe_init(s, filename) < 0) {
2210 qemu_chr_reset(chr);
2214 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2216 CharDriverState *chr;
2219 chr = qemu_mallocz(sizeof(CharDriverState));
2222 s = qemu_mallocz(sizeof(WinCharState));
2229 chr->chr_write = win_chr_write;
2230 chr->chr_add_read_handler = win_chr_add_read_handler;
2231 qemu_chr_reset(chr);
2235 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2239 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2240 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2241 if (fd_out == INVALID_HANDLE_VALUE)
2244 return qemu_chr_open_win_file(fd_out);
2248 /***********************************************************/
2249 /* UDP Net console */
2252 IOCanRWHandler *fd_can_read;
2253 IOReadHandler *fd_read;
2256 struct sockaddr_in daddr;
2263 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2265 NetCharDriver *s = chr->opaque;
2267 return sendto(s->fd, buf, len, 0,
2268 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2271 static int udp_chr_read_poll(void *opaque)
2273 CharDriverState *chr = opaque;
2274 NetCharDriver *s = chr->opaque;
2276 s->max_size = s->fd_can_read(s->fd_opaque);
2278 /* If there were any stray characters in the queue process them
2281 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2282 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2284 s->max_size = s->fd_can_read(s->fd_opaque);
2289 static void udp_chr_read(void *opaque)
2291 CharDriverState *chr = opaque;
2292 NetCharDriver *s = chr->opaque;
2294 if (s->max_size == 0)
2296 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2297 s->bufptr = s->bufcnt;
2302 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2303 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2305 s->max_size = s->fd_can_read(s->fd_opaque);
2309 static void udp_chr_add_read_handler(CharDriverState *chr,
2310 IOCanRWHandler *fd_can_read,
2311 IOReadHandler *fd_read, void *opaque)
2313 NetCharDriver *s = chr->opaque;
2316 s->fd_can_read = fd_can_read;
2317 s->fd_read = fd_read;
2318 s->fd_opaque = opaque;
2319 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2320 udp_chr_read, NULL, chr);
2324 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2326 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2328 int parse_host_src_port(struct sockaddr_in *haddr,
2329 struct sockaddr_in *saddr,
2332 static CharDriverState *qemu_chr_open_udp(const char *def)
2334 CharDriverState *chr = NULL;
2335 NetCharDriver *s = NULL;
2337 struct sockaddr_in saddr;
2339 chr = qemu_mallocz(sizeof(CharDriverState));
2342 s = qemu_mallocz(sizeof(NetCharDriver));
2346 fd = socket(PF_INET, SOCK_DGRAM, 0);
2348 perror("socket(PF_INET, SOCK_DGRAM)");
2352 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2353 printf("Could not parse: %s\n", def);
2357 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2367 chr->chr_write = udp_chr_write;
2368 chr->chr_add_read_handler = udp_chr_add_read_handler;
2381 /***********************************************************/
2382 /* TCP Net console */
2385 IOCanRWHandler *fd_can_read;
2386 IOReadHandler *fd_read;
2395 static void tcp_chr_accept(void *opaque);
2397 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2399 TCPCharDriver *s = chr->opaque;
2401 return send_all(s->fd, buf, len);
2403 /* XXX: indicate an error ? */
2408 static int tcp_chr_read_poll(void *opaque)
2410 CharDriverState *chr = opaque;
2411 TCPCharDriver *s = chr->opaque;
2414 if (!s->fd_can_read)
2416 s->max_size = s->fd_can_read(s->fd_opaque);
2421 #define IAC_BREAK 243
2422 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2424 char *buf, int *size)
2426 /* Handle any telnet client's basic IAC options to satisfy char by
2427 * char mode with no echo. All IAC options will be removed from
2428 * the buf and the do_telnetopt variable will be used to track the
2429 * state of the width of the IAC information.
2431 * IAC commands come in sets of 3 bytes with the exception of the
2432 * "IAC BREAK" command and the double IAC.
2438 for (i = 0; i < *size; i++) {
2439 if (s->do_telnetopt > 1) {
2440 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2441 /* Double IAC means send an IAC */
2445 s->do_telnetopt = 1;
2447 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2448 /* Handle IAC break commands by sending a serial break */
2449 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2454 if (s->do_telnetopt >= 4) {
2455 s->do_telnetopt = 1;
2458 if ((unsigned char)buf[i] == IAC) {
2459 s->do_telnetopt = 2;
2470 static void tcp_chr_read(void *opaque)
2472 CharDriverState *chr = opaque;
2473 TCPCharDriver *s = chr->opaque;
2477 if (!s->connected || s->max_size <= 0)
2480 if (len > s->max_size)
2482 size = recv(s->fd, buf, len, 0);
2484 /* connection closed */
2486 if (s->listen_fd >= 0) {
2487 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2489 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2492 } else if (size > 0) {
2493 if (s->do_telnetopt)
2494 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2496 s->fd_read(s->fd_opaque, buf, size);
2500 static void tcp_chr_add_read_handler(CharDriverState *chr,
2501 IOCanRWHandler *fd_can_read,
2502 IOReadHandler *fd_read, void *opaque)
2504 TCPCharDriver *s = chr->opaque;
2506 s->fd_can_read = fd_can_read;
2507 s->fd_read = fd_read;
2508 s->fd_opaque = opaque;
2511 static void tcp_chr_connect(void *opaque)
2513 CharDriverState *chr = opaque;
2514 TCPCharDriver *s = chr->opaque;
2517 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2518 tcp_chr_read, NULL, chr);
2519 qemu_chr_reset(chr);
2522 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2523 static void tcp_chr_telnet_init(int fd)
2526 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2527 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2528 send(fd, (char *)buf, 3, 0);
2529 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2530 send(fd, (char *)buf, 3, 0);
2531 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2532 send(fd, (char *)buf, 3, 0);
2533 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2534 send(fd, (char *)buf, 3, 0);
2537 static void tcp_chr_accept(void *opaque)
2539 CharDriverState *chr = opaque;
2540 TCPCharDriver *s = chr->opaque;
2541 struct sockaddr_in saddr;
2543 struct sockaddr_un uaddr;
2545 struct sockaddr *addr;
2552 len = sizeof(uaddr);
2553 addr = (struct sockaddr *)&uaddr;
2557 len = sizeof(saddr);
2558 addr = (struct sockaddr *)&saddr;
2560 fd = accept(s->listen_fd, addr, &len);
2561 if (fd < 0 && errno != EINTR) {
2563 } else if (fd >= 0) {
2564 if (s->do_telnetopt)
2565 tcp_chr_telnet_init(fd);
2569 socket_set_nonblock(fd);
2571 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2572 tcp_chr_connect(chr);
2575 static void tcp_chr_close(CharDriverState *chr)
2577 TCPCharDriver *s = chr->opaque;
2580 if (s->listen_fd >= 0)
2581 closesocket(s->listen_fd);
2585 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2589 CharDriverState *chr = NULL;
2590 TCPCharDriver *s = NULL;
2591 int fd = -1, ret, err, val;
2593 int is_waitconnect = 1;
2595 struct sockaddr_in saddr;
2597 struct sockaddr_un uaddr;
2599 struct sockaddr *addr;
2604 addr = (struct sockaddr *)&uaddr;
2605 addrlen = sizeof(uaddr);
2606 if (parse_unix_path(&uaddr, host_str) < 0)
2611 addr = (struct sockaddr *)&saddr;
2612 addrlen = sizeof(saddr);
2613 if (parse_host_port(&saddr, host_str) < 0)
2618 while((ptr = strchr(ptr,','))) {
2620 if (!strncmp(ptr,"server",6)) {
2622 } else if (!strncmp(ptr,"nowait",6)) {
2625 printf("Unknown option: %s\n", ptr);
2632 chr = qemu_mallocz(sizeof(CharDriverState));
2635 s = qemu_mallocz(sizeof(TCPCharDriver));
2641 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2644 fd = socket(PF_INET, SOCK_STREAM, 0);
2649 if (!is_waitconnect)
2650 socket_set_nonblock(fd);
2655 s->is_unix = is_unix;
2658 chr->chr_write = tcp_chr_write;
2659 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2660 chr->chr_close = tcp_chr_close;
2663 /* allow fast reuse */
2667 strncpy(path, uaddr.sun_path, 108);
2674 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2677 ret = bind(fd, addr, addrlen);
2681 ret = listen(fd, 0);
2686 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2688 s->do_telnetopt = 1;
2691 ret = connect(fd, addr, addrlen);
2693 err = socket_error();
2694 if (err == EINTR || err == EWOULDBLOCK) {
2695 } else if (err == EINPROGRESS) {
2707 tcp_chr_connect(chr);
2709 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2712 if (is_listen && is_waitconnect) {
2713 printf("QEMU waiting for connection on: %s\n", host_str);
2714 tcp_chr_accept(chr);
2715 socket_set_nonblock(s->listen_fd);
2727 CharDriverState *qemu_chr_open(const char *filename)
2731 if (!strcmp(filename, "vc")) {
2732 return text_console_init(&display_state);
2733 } else if (!strcmp(filename, "null")) {
2734 return qemu_chr_open_null();
2736 if (strstart(filename, "tcp:", &p)) {
2737 return qemu_chr_open_tcp(p, 0, 0);
2739 if (strstart(filename, "telnet:", &p)) {
2740 return qemu_chr_open_tcp(p, 1, 0);
2742 if (strstart(filename, "udp:", &p)) {
2743 return qemu_chr_open_udp(p);
2746 if (strstart(filename, "unix:", &p)) {
2747 return qemu_chr_open_tcp(p, 0, 1);
2748 } else if (strstart(filename, "file:", &p)) {
2749 return qemu_chr_open_file_out(p);
2750 } else if (strstart(filename, "pipe:", &p)) {
2751 return qemu_chr_open_pipe(p);
2752 } else if (!strcmp(filename, "pty")) {
2753 return qemu_chr_open_pty();
2754 } else if (!strcmp(filename, "stdio")) {
2755 return qemu_chr_open_stdio();
2758 #if defined(__linux__)
2759 if (strstart(filename, "/dev/parport", NULL)) {
2760 return qemu_chr_open_pp(filename);
2762 if (strstart(filename, "/dev/", NULL)) {
2763 return qemu_chr_open_tty(filename);
2767 if (strstart(filename, "COM", NULL)) {
2768 return qemu_chr_open_win(filename);
2770 if (strstart(filename, "pipe:", &p)) {
2771 return qemu_chr_open_win_pipe(p);
2773 if (strstart(filename, "file:", &p)) {
2774 return qemu_chr_open_win_file_out(p);
2782 void qemu_chr_close(CharDriverState *chr)
2785 chr->chr_close(chr);
2788 /***********************************************************/
2789 /* network device redirectors */
2791 void hex_dump(FILE *f, const uint8_t *buf, int size)
2795 for(i=0;i<size;i+=16) {
2799 fprintf(f, "%08x ", i);
2802 fprintf(f, " %02x", buf[i+j]);
2807 for(j=0;j<len;j++) {
2809 if (c < ' ' || c > '~')
2811 fprintf(f, "%c", c);
2817 static int parse_macaddr(uint8_t *macaddr, const char *p)
2820 for(i = 0; i < 6; i++) {
2821 macaddr[i] = strtol(p, (char **)&p, 16);
2834 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2839 p1 = strchr(p, sep);
2845 if (len > buf_size - 1)
2847 memcpy(buf, p, len);
2854 int parse_host_src_port(struct sockaddr_in *haddr,
2855 struct sockaddr_in *saddr,
2856 const char *input_str)
2858 char *str = strdup(input_str);
2859 char *host_str = str;
2864 * Chop off any extra arguments at the end of the string which
2865 * would start with a comma, then fill in the src port information
2866 * if it was provided else use the "any address" and "any port".
2868 if ((ptr = strchr(str,',')))
2871 if ((src_str = strchr(input_str,'@'))) {
2876 if (parse_host_port(haddr, host_str) < 0)
2879 if (!src_str || *src_str == '\0')
2882 if (parse_host_port(saddr, src_str) < 0)
2893 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2901 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2903 saddr->sin_family = AF_INET;
2904 if (buf[0] == '\0') {
2905 saddr->sin_addr.s_addr = 0;
2907 if (isdigit(buf[0])) {
2908 if (!inet_aton(buf, &saddr->sin_addr))
2911 if ((he = gethostbyname(buf)) == NULL)
2913 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2916 port = strtol(p, (char **)&r, 0);
2919 saddr->sin_port = htons(port);
2924 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2929 len = MIN(108, strlen(str));
2930 p = strchr(str, ',');
2932 len = MIN(len, p - str);
2934 memset(uaddr, 0, sizeof(*uaddr));
2936 uaddr->sun_family = AF_UNIX;
2937 memcpy(uaddr->sun_path, str, len);
2943 /* find or alloc a new VLAN */
2944 VLANState *qemu_find_vlan(int id)
2946 VLANState **pvlan, *vlan;
2947 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2951 vlan = qemu_mallocz(sizeof(VLANState));
2956 pvlan = &first_vlan;
2957 while (*pvlan != NULL)
2958 pvlan = &(*pvlan)->next;
2963 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2964 IOReadHandler *fd_read,
2965 IOCanRWHandler *fd_can_read,
2968 VLANClientState *vc, **pvc;
2969 vc = qemu_mallocz(sizeof(VLANClientState));
2972 vc->fd_read = fd_read;
2973 vc->fd_can_read = fd_can_read;
2974 vc->opaque = opaque;
2978 pvc = &vlan->first_client;
2979 while (*pvc != NULL)
2980 pvc = &(*pvc)->next;
2985 int qemu_can_send_packet(VLANClientState *vc1)
2987 VLANState *vlan = vc1->vlan;
2988 VLANClientState *vc;
2990 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2992 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2999 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3001 VLANState *vlan = vc1->vlan;
3002 VLANClientState *vc;
3005 printf("vlan %d send:\n", vlan->id);
3006 hex_dump(stdout, buf, size);
3008 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3010 vc->fd_read(vc->opaque, buf, size);
3015 #if defined(CONFIG_SLIRP)
3017 /* slirp network adapter */
3019 static int slirp_inited;
3020 static VLANClientState *slirp_vc;
3022 int slirp_can_output(void)
3024 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3027 void slirp_output(const uint8_t *pkt, int pkt_len)
3030 printf("slirp output:\n");
3031 hex_dump(stdout, pkt, pkt_len);
3035 qemu_send_packet(slirp_vc, pkt, pkt_len);
3038 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3041 printf("slirp input:\n");
3042 hex_dump(stdout, buf, size);
3044 slirp_input(buf, size);
3047 static int net_slirp_init(VLANState *vlan)
3049 if (!slirp_inited) {
3053 slirp_vc = qemu_new_vlan_client(vlan,
3054 slirp_receive, NULL, NULL);
3055 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3059 static void net_slirp_redir(const char *redir_str)
3064 struct in_addr guest_addr;
3065 int host_port, guest_port;
3067 if (!slirp_inited) {
3073 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3075 if (!strcmp(buf, "tcp")) {
3077 } else if (!strcmp(buf, "udp")) {
3083 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3085 host_port = strtol(buf, &r, 0);
3089 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3091 if (buf[0] == '\0') {
3092 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3094 if (!inet_aton(buf, &guest_addr))
3097 guest_port = strtol(p, &r, 0);
3101 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3102 fprintf(stderr, "qemu: could not set up redirection\n");
3107 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3115 static void smb_exit(void)
3119 char filename[1024];
3121 /* erase all the files in the directory */
3122 d = opendir(smb_dir);
3127 if (strcmp(de->d_name, ".") != 0 &&
3128 strcmp(de->d_name, "..") != 0) {
3129 snprintf(filename, sizeof(filename), "%s/%s",
3130 smb_dir, de->d_name);
3138 /* automatic user mode samba server configuration */
3139 void net_slirp_smb(const char *exported_dir)
3141 char smb_conf[1024];
3142 char smb_cmdline[1024];
3145 if (!slirp_inited) {
3150 /* XXX: better tmp dir construction */
3151 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3152 if (mkdir(smb_dir, 0700) < 0) {
3153 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3156 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3158 f = fopen(smb_conf, "w");
3160 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3167 "socket address=127.0.0.1\n"
3168 "pid directory=%s\n"
3169 "lock directory=%s\n"
3170 "log file=%s/log.smbd\n"
3171 "smb passwd file=%s/smbpasswd\n"
3172 "security = share\n"
3187 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3188 SMBD_COMMAND, smb_conf);
3190 slirp_add_exec(0, smb_cmdline, 4, 139);
3193 #endif /* !defined(_WIN32) */
3195 #endif /* CONFIG_SLIRP */
3197 #if !defined(_WIN32)
3199 typedef struct TAPState {
3200 VLANClientState *vc;
3204 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3206 TAPState *s = opaque;
3209 ret = write(s->fd, buf, size);
3210 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3217 static void tap_send(void *opaque)
3219 TAPState *s = opaque;
3223 size = read(s->fd, buf, sizeof(buf));
3225 qemu_send_packet(s->vc, buf, size);
3231 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3235 s = qemu_mallocz(sizeof(TAPState));
3239 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3240 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3241 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3246 static int tap_open(char *ifname, int ifname_size)
3252 fd = open("/dev/tap", O_RDWR);
3254 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3259 dev = devname(s.st_rdev, S_IFCHR);
3260 pstrcpy(ifname, ifname_size, dev);
3262 fcntl(fd, F_SETFL, O_NONBLOCK);
3265 #elif defined(__sun__)
3266 static int tap_open(char *ifname, int ifname_size)
3268 fprintf(stderr, "warning: tap_open not yet implemented\n");
3272 static int tap_open(char *ifname, int ifname_size)
3277 fd = open("/dev/net/tun", O_RDWR);
3279 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3282 memset(&ifr, 0, sizeof(ifr));
3283 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3284 if (ifname[0] != '\0')
3285 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3287 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3288 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3290 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3294 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3295 fcntl(fd, F_SETFL, O_NONBLOCK);
3300 static int net_tap_init(VLANState *vlan, const char *ifname1,
3301 const char *setup_script)
3304 int pid, status, fd;
3309 if (ifname1 != NULL)
3310 pstrcpy(ifname, sizeof(ifname), ifname1);
3313 fd = tap_open(ifname, sizeof(ifname));
3319 if (setup_script[0] != '\0') {
3320 /* try to launch network init script */
3325 *parg++ = (char *)setup_script;
3328 execv(setup_script, args);
3331 while (waitpid(pid, &status, 0) != pid);
3332 if (!WIFEXITED(status) ||
3333 WEXITSTATUS(status) != 0) {
3334 fprintf(stderr, "%s: could not launch network script\n",
3340 s = net_tap_fd_init(vlan, fd);
3343 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3344 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3348 #endif /* !_WIN32 */
3350 /* network connection */
3351 typedef struct NetSocketState {
3352 VLANClientState *vc;
3354 int state; /* 0 = getting length, 1 = getting data */
3358 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3361 typedef struct NetSocketListenState {
3364 } NetSocketListenState;
3366 /* XXX: we consider we can send the whole packet without blocking */
3367 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3369 NetSocketState *s = opaque;
3373 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3374 send_all(s->fd, buf, size);
3377 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3379 NetSocketState *s = opaque;
3380 sendto(s->fd, buf, size, 0,
3381 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3384 static void net_socket_send(void *opaque)
3386 NetSocketState *s = opaque;
3391 size = recv(s->fd, buf1, sizeof(buf1), 0);
3393 err = socket_error();
3394 if (err != EWOULDBLOCK)
3396 } else if (size == 0) {
3397 /* end of connection */
3399 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3405 /* reassemble a packet from the network */
3411 memcpy(s->buf + s->index, buf, l);
3415 if (s->index == 4) {
3417 s->packet_len = ntohl(*(uint32_t *)s->buf);
3423 l = s->packet_len - s->index;
3426 memcpy(s->buf + s->index, buf, l);
3430 if (s->index >= s->packet_len) {
3431 qemu_send_packet(s->vc, s->buf, s->packet_len);
3440 static void net_socket_send_dgram(void *opaque)
3442 NetSocketState *s = opaque;
3445 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3449 /* end of connection */
3450 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3453 qemu_send_packet(s->vc, s->buf, size);
3456 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3461 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3462 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3463 inet_ntoa(mcastaddr->sin_addr),
3464 (int)ntohl(mcastaddr->sin_addr.s_addr));
3468 fd = socket(PF_INET, SOCK_DGRAM, 0);
3470 perror("socket(PF_INET, SOCK_DGRAM)");
3475 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3476 (const char *)&val, sizeof(val));
3478 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3482 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3488 /* Add host to multicast group */
3489 imr.imr_multiaddr = mcastaddr->sin_addr;
3490 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3492 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3493 (const char *)&imr, sizeof(struct ip_mreq));
3495 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3499 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3501 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3502 (const char *)&val, sizeof(val));
3504 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3508 socket_set_nonblock(fd);
3516 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3519 struct sockaddr_in saddr;
3521 socklen_t saddr_len;
3524 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3525 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3526 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3530 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3532 if (saddr.sin_addr.s_addr==0) {
3533 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3537 /* clone dgram socket */
3538 newfd = net_socket_mcast_create(&saddr);
3540 /* error already reported by net_socket_mcast_create() */
3544 /* clone newfd to fd, close newfd */
3549 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3550 fd, strerror(errno));
3555 s = qemu_mallocz(sizeof(NetSocketState));
3560 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3561 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3563 /* mcast: save bound address as dst */
3564 if (is_connected) s->dgram_dst=saddr;
3566 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3567 "socket: fd=%d (%s mcast=%s:%d)",
3568 fd, is_connected? "cloned" : "",
3569 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3573 static void net_socket_connect(void *opaque)
3575 NetSocketState *s = opaque;
3576 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3579 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3583 s = qemu_mallocz(sizeof(NetSocketState));
3587 s->vc = qemu_new_vlan_client(vlan,
3588 net_socket_receive, NULL, s);
3589 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3590 "socket: fd=%d", fd);
3592 net_socket_connect(s);
3594 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3599 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3602 int so_type=-1, optlen=sizeof(so_type);
3604 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3605 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3610 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3612 return net_socket_fd_init_stream(vlan, fd, is_connected);
3614 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3615 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3616 return net_socket_fd_init_stream(vlan, fd, is_connected);
3621 static void net_socket_accept(void *opaque)
3623 NetSocketListenState *s = opaque;
3625 struct sockaddr_in saddr;
3630 len = sizeof(saddr);
3631 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3632 if (fd < 0 && errno != EINTR) {
3634 } else if (fd >= 0) {
3638 s1 = net_socket_fd_init(s->vlan, fd, 1);
3642 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3643 "socket: connection from %s:%d",
3644 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3648 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3650 NetSocketListenState *s;
3652 struct sockaddr_in saddr;
3654 if (parse_host_port(&saddr, host_str) < 0)
3657 s = qemu_mallocz(sizeof(NetSocketListenState));
3661 fd = socket(PF_INET, SOCK_STREAM, 0);
3666 socket_set_nonblock(fd);
3668 /* allow fast reuse */
3670 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3672 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3677 ret = listen(fd, 0);
3684 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3688 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3691 int fd, connected, ret, err;
3692 struct sockaddr_in saddr;
3694 if (parse_host_port(&saddr, host_str) < 0)
3697 fd = socket(PF_INET, SOCK_STREAM, 0);
3702 socket_set_nonblock(fd);
3706 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3708 err = socket_error();
3709 if (err == EINTR || err == EWOULDBLOCK) {
3710 } else if (err == EINPROGRESS) {
3722 s = net_socket_fd_init(vlan, fd, connected);
3725 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3726 "socket: connect to %s:%d",
3727 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3731 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3735 struct sockaddr_in saddr;
3737 if (parse_host_port(&saddr, host_str) < 0)
3741 fd = net_socket_mcast_create(&saddr);
3745 s = net_socket_fd_init(vlan, fd, 0);
3749 s->dgram_dst = saddr;
3751 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3752 "socket: mcast=%s:%d",
3753 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3758 static int get_param_value(char *buf, int buf_size,
3759 const char *tag, const char *str)
3768 while (*p != '\0' && *p != '=') {
3769 if ((q - option) < sizeof(option) - 1)
3777 if (!strcmp(tag, option)) {
3779 while (*p != '\0' && *p != ',') {
3780 if ((q - buf) < buf_size - 1)
3787 while (*p != '\0' && *p != ',') {
3798 static int net_client_init(const char *str)
3809 while (*p != '\0' && *p != ',') {
3810 if ((q - device) < sizeof(device) - 1)
3818 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3819 vlan_id = strtol(buf, NULL, 0);
3821 vlan = qemu_find_vlan(vlan_id);
3823 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3826 if (!strcmp(device, "nic")) {
3830 if (nb_nics >= MAX_NICS) {
3831 fprintf(stderr, "Too Many NICs\n");
3834 nd = &nd_table[nb_nics];
3835 macaddr = nd->macaddr;
3841 macaddr[5] = 0x56 + nb_nics;
3843 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3844 if (parse_macaddr(macaddr, buf) < 0) {
3845 fprintf(stderr, "invalid syntax for ethernet address\n");
3849 if (get_param_value(buf, sizeof(buf), "model", p)) {
3850 nd->model = strdup(buf);
3856 if (!strcmp(device, "none")) {
3857 /* does nothing. It is needed to signal that no network cards
3862 if (!strcmp(device, "user")) {
3863 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3864 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3866 ret = net_slirp_init(vlan);
3870 if (!strcmp(device, "tap")) {
3872 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3873 fprintf(stderr, "tap: no interface name\n");
3876 ret = tap_win32_init(vlan, ifname);
3879 if (!strcmp(device, "tap")) {
3881 char setup_script[1024];
3883 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3884 fd = strtol(buf, NULL, 0);
3886 if (net_tap_fd_init(vlan, fd))
3889 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3892 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3893 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3895 ret = net_tap_init(vlan, ifname, setup_script);
3899 if (!strcmp(device, "socket")) {
3900 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3902 fd = strtol(buf, NULL, 0);
3904 if (net_socket_fd_init(vlan, fd, 1))
3906 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3907 ret = net_socket_listen_init(vlan, buf);
3908 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3909 ret = net_socket_connect_init(vlan, buf);
3910 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3911 ret = net_socket_mcast_init(vlan, buf);
3913 fprintf(stderr, "Unknown socket options: %s\n", p);
3918 fprintf(stderr, "Unknown network device: %s\n", device);
3922 fprintf(stderr, "Could not initialize device '%s'\n", device);
3928 void do_info_network(void)
3931 VLANClientState *vc;
3933 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3934 term_printf("VLAN %d devices:\n", vlan->id);
3935 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3936 term_printf(" %s\n", vc->info_str);
3940 /***********************************************************/
3943 static USBPort *used_usb_ports;
3944 static USBPort *free_usb_ports;
3946 /* ??? Maybe change this to register a hub to keep track of the topology. */
3947 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3948 usb_attachfn attach)
3950 port->opaque = opaque;
3951 port->index = index;
3952 port->attach = attach;
3953 port->next = free_usb_ports;
3954 free_usb_ports = port;
3957 static int usb_device_add(const char *devname)
3963 if (!free_usb_ports)
3966 if (strstart(devname, "host:", &p)) {
3967 dev = usb_host_device_open(p);
3968 } else if (!strcmp(devname, "mouse")) {
3969 dev = usb_mouse_init();
3970 } else if (!strcmp(devname, "tablet")) {
3971 dev = usb_tablet_init();
3972 } else if (strstart(devname, "disk:", &p)) {
3973 dev = usb_msd_init(p);
3980 /* Find a USB port to add the device to. */
3981 port = free_usb_ports;
3985 /* Create a new hub and chain it on. */
3986 free_usb_ports = NULL;
3987 port->next = used_usb_ports;
3988 used_usb_ports = port;
3990 hub = usb_hub_init(VM_USB_HUB_SIZE);
3991 usb_attach(port, hub);
3992 port = free_usb_ports;
3995 free_usb_ports = port->next;
3996 port->next = used_usb_ports;
3997 used_usb_ports = port;
3998 usb_attach(port, dev);
4002 static int usb_device_del(const char *devname)
4010 if (!used_usb_ports)
4013 p = strchr(devname, '.');
4016 bus_num = strtoul(devname, NULL, 0);
4017 addr = strtoul(p + 1, NULL, 0);
4021 lastp = &used_usb_ports;
4022 port = used_usb_ports;
4023 while (port && port->dev->addr != addr) {
4024 lastp = &port->next;
4032 *lastp = port->next;
4033 usb_attach(port, NULL);
4034 dev->handle_destroy(dev);
4035 port->next = free_usb_ports;
4036 free_usb_ports = port;
4040 void do_usb_add(const char *devname)
4043 ret = usb_device_add(devname);
4045 term_printf("Could not add USB device '%s'\n", devname);
4048 void do_usb_del(const char *devname)
4051 ret = usb_device_del(devname);
4053 term_printf("Could not remove USB device '%s'\n", devname);
4060 const char *speed_str;
4063 term_printf("USB support not enabled\n");
4067 for (port = used_usb_ports; port; port = port->next) {
4071 switch(dev->speed) {
4075 case USB_SPEED_FULL:
4078 case USB_SPEED_HIGH:
4085 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4086 0, dev->addr, speed_str, dev->devname);
4090 /***********************************************************/
4093 static char *pid_filename;
4095 /* Remove PID file. Called on normal exit */
4097 static void remove_pidfile(void)
4099 unlink (pid_filename);
4102 static void create_pidfile(const char *filename)
4104 struct stat pidstat;
4107 /* Try to write our PID to the named file */
4108 if (stat(filename, &pidstat) < 0) {
4109 if (errno == ENOENT) {
4110 if ((f = fopen (filename, "w")) == NULL) {
4111 perror("Opening pidfile");
4114 fprintf(f, "%d\n", getpid());
4116 pid_filename = qemu_strdup(filename);
4117 if (!pid_filename) {
4118 fprintf(stderr, "Could not save PID filename");
4121 atexit(remove_pidfile);
4124 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4130 /***********************************************************/
4133 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4137 static void dumb_resize(DisplayState *ds, int w, int h)
4141 static void dumb_refresh(DisplayState *ds)
4146 void dumb_display_init(DisplayState *ds)
4151 ds->dpy_update = dumb_update;
4152 ds->dpy_resize = dumb_resize;
4153 ds->dpy_refresh = dumb_refresh;
4156 /***********************************************************/
4159 #define MAX_IO_HANDLERS 64
4161 typedef struct IOHandlerRecord {
4163 IOCanRWHandler *fd_read_poll;
4165 IOHandler *fd_write;
4167 /* temporary data */
4169 struct IOHandlerRecord *next;
4172 static IOHandlerRecord *first_io_handler;
4174 /* XXX: fd_read_poll should be suppressed, but an API change is
4175 necessary in the character devices to suppress fd_can_read(). */
4176 int qemu_set_fd_handler2(int fd,
4177 IOCanRWHandler *fd_read_poll,
4179 IOHandler *fd_write,
4182 IOHandlerRecord **pioh, *ioh;
4184 if (!fd_read && !fd_write) {
4185 pioh = &first_io_handler;
4190 if (ioh->fd == fd) {
4198 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4202 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4205 ioh->next = first_io_handler;
4206 first_io_handler = ioh;
4209 ioh->fd_read_poll = fd_read_poll;
4210 ioh->fd_read = fd_read;
4211 ioh->fd_write = fd_write;
4212 ioh->opaque = opaque;
4217 int qemu_set_fd_handler(int fd,
4219 IOHandler *fd_write,
4222 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4225 /***********************************************************/
4226 /* Polling handling */
4228 typedef struct PollingEntry {
4231 struct PollingEntry *next;
4234 static PollingEntry *first_polling_entry;
4236 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4238 PollingEntry **ppe, *pe;
4239 pe = qemu_mallocz(sizeof(PollingEntry));
4243 pe->opaque = opaque;
4244 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4249 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4251 PollingEntry **ppe, *pe;
4252 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4254 if (pe->func == func && pe->opaque == opaque) {
4263 /***********************************************************/
4264 /* Wait objects support */
4265 typedef struct WaitObjects {
4267 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4268 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4269 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4272 static WaitObjects wait_objects = {0};
4274 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4276 WaitObjects *w = &wait_objects;
4278 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4280 w->events[w->num] = handle;
4281 w->func[w->num] = func;
4282 w->opaque[w->num] = opaque;
4287 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4290 WaitObjects *w = &wait_objects;
4293 for (i = 0; i < w->num; i++) {
4294 if (w->events[i] == handle)
4297 w->events[i] = w->events[i + 1];
4298 w->func[i] = w->func[i + 1];
4299 w->opaque[i] = w->opaque[i + 1];
4307 /***********************************************************/
4308 /* savevm/loadvm support */
4310 #define IO_BUF_SIZE 32768
4314 BlockDriverState *bs;
4317 int64_t base_offset;
4318 int64_t buf_offset; /* start of buffer when writing, end of buffer
4321 int buf_size; /* 0 when writing */
4322 uint8_t buf[IO_BUF_SIZE];
4325 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4329 f = qemu_mallocz(sizeof(QEMUFile));
4332 if (!strcmp(mode, "wb")) {
4334 } else if (!strcmp(mode, "rb")) {
4339 f->outfile = fopen(filename, mode);
4351 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4355 f = qemu_mallocz(sizeof(QEMUFile));
4360 f->is_writable = is_writable;
4361 f->base_offset = offset;
4365 void qemu_fflush(QEMUFile *f)
4367 if (!f->is_writable)
4369 if (f->buf_index > 0) {
4371 fseek(f->outfile, f->buf_offset, SEEK_SET);
4372 fwrite(f->buf, 1, f->buf_index, f->outfile);
4374 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4375 f->buf, f->buf_index);
4377 f->buf_offset += f->buf_index;
4382 static void qemu_fill_buffer(QEMUFile *f)
4389 fseek(f->outfile, f->buf_offset, SEEK_SET);
4390 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4394 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4395 f->buf, IO_BUF_SIZE);
4401 f->buf_offset += len;
4404 void qemu_fclose(QEMUFile *f)
4414 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4418 l = IO_BUF_SIZE - f->buf_index;
4421 memcpy(f->buf + f->buf_index, buf, l);
4425 if (f->buf_index >= IO_BUF_SIZE)
4430 void qemu_put_byte(QEMUFile *f, int v)
4432 f->buf[f->buf_index++] = v;
4433 if (f->buf_index >= IO_BUF_SIZE)
4437 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4443 l = f->buf_size - f->buf_index;
4445 qemu_fill_buffer(f);
4446 l = f->buf_size - f->buf_index;
4452 memcpy(buf, f->buf + f->buf_index, l);
4457 return size1 - size;
4460 int qemu_get_byte(QEMUFile *f)
4462 if (f->buf_index >= f->buf_size) {
4463 qemu_fill_buffer(f);
4464 if (f->buf_index >= f->buf_size)
4467 return f->buf[f->buf_index++];
4470 int64_t qemu_ftell(QEMUFile *f)
4472 return f->buf_offset - f->buf_size + f->buf_index;
4475 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4477 if (whence == SEEK_SET) {
4479 } else if (whence == SEEK_CUR) {
4480 pos += qemu_ftell(f);
4482 /* SEEK_END not supported */
4485 if (f->is_writable) {
4487 f->buf_offset = pos;
4489 f->buf_offset = pos;
4496 void qemu_put_be16(QEMUFile *f, unsigned int v)
4498 qemu_put_byte(f, v >> 8);
4499 qemu_put_byte(f, v);
4502 void qemu_put_be32(QEMUFile *f, unsigned int v)
4504 qemu_put_byte(f, v >> 24);
4505 qemu_put_byte(f, v >> 16);
4506 qemu_put_byte(f, v >> 8);
4507 qemu_put_byte(f, v);
4510 void qemu_put_be64(QEMUFile *f, uint64_t v)
4512 qemu_put_be32(f, v >> 32);
4513 qemu_put_be32(f, v);
4516 unsigned int qemu_get_be16(QEMUFile *f)
4519 v = qemu_get_byte(f) << 8;
4520 v |= qemu_get_byte(f);
4524 unsigned int qemu_get_be32(QEMUFile *f)
4527 v = qemu_get_byte(f) << 24;
4528 v |= qemu_get_byte(f) << 16;
4529 v |= qemu_get_byte(f) << 8;
4530 v |= qemu_get_byte(f);
4534 uint64_t qemu_get_be64(QEMUFile *f)
4537 v = (uint64_t)qemu_get_be32(f) << 32;
4538 v |= qemu_get_be32(f);
4542 typedef struct SaveStateEntry {
4546 SaveStateHandler *save_state;
4547 LoadStateHandler *load_state;
4549 struct SaveStateEntry *next;
4552 static SaveStateEntry *first_se;
4554 int register_savevm(const char *idstr,
4557 SaveStateHandler *save_state,
4558 LoadStateHandler *load_state,
4561 SaveStateEntry *se, **pse;
4563 se = qemu_malloc(sizeof(SaveStateEntry));
4566 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4567 se->instance_id = instance_id;
4568 se->version_id = version_id;
4569 se->save_state = save_state;
4570 se->load_state = load_state;
4571 se->opaque = opaque;
4574 /* add at the end of list */
4576 while (*pse != NULL)
4577 pse = &(*pse)->next;
4582 #define QEMU_VM_FILE_MAGIC 0x5145564d
4583 #define QEMU_VM_FILE_VERSION 0x00000002
4585 int qemu_savevm_state(QEMUFile *f)
4589 int64_t cur_pos, len_pos, total_len_pos;
4591 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4592 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4593 total_len_pos = qemu_ftell(f);
4594 qemu_put_be64(f, 0); /* total size */
4596 for(se = first_se; se != NULL; se = se->next) {
4598 len = strlen(se->idstr);
4599 qemu_put_byte(f, len);
4600 qemu_put_buffer(f, se->idstr, len);
4602 qemu_put_be32(f, se->instance_id);
4603 qemu_put_be32(f, se->version_id);
4605 /* record size: filled later */
4606 len_pos = qemu_ftell(f);
4607 qemu_put_be32(f, 0);
4609 se->save_state(f, se->opaque);
4611 /* fill record size */
4612 cur_pos = qemu_ftell(f);
4613 len = cur_pos - len_pos - 4;
4614 qemu_fseek(f, len_pos, SEEK_SET);
4615 qemu_put_be32(f, len);
4616 qemu_fseek(f, cur_pos, SEEK_SET);
4618 cur_pos = qemu_ftell(f);
4619 qemu_fseek(f, total_len_pos, SEEK_SET);
4620 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4621 qemu_fseek(f, cur_pos, SEEK_SET);
4627 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4631 for(se = first_se; se != NULL; se = se->next) {
4632 if (!strcmp(se->idstr, idstr) &&
4633 instance_id == se->instance_id)
4639 int qemu_loadvm_state(QEMUFile *f)
4642 int len, ret, instance_id, record_len, version_id;
4643 int64_t total_len, end_pos, cur_pos;
4647 v = qemu_get_be32(f);
4648 if (v != QEMU_VM_FILE_MAGIC)
4650 v = qemu_get_be32(f);
4651 if (v != QEMU_VM_FILE_VERSION) {
4656 total_len = qemu_get_be64(f);
4657 end_pos = total_len + qemu_ftell(f);
4659 if (qemu_ftell(f) >= end_pos)
4661 len = qemu_get_byte(f);
4662 qemu_get_buffer(f, idstr, len);
4664 instance_id = qemu_get_be32(f);
4665 version_id = qemu_get_be32(f);
4666 record_len = qemu_get_be32(f);
4668 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4669 idstr, instance_id, version_id, record_len);
4671 cur_pos = qemu_ftell(f);
4672 se = find_se(idstr, instance_id);
4674 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4675 instance_id, idstr);
4677 ret = se->load_state(f, se->opaque, version_id);
4679 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4680 instance_id, idstr);
4683 /* always seek to exact end of record */
4684 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4691 /* device can contain snapshots */
4692 static int bdrv_can_snapshot(BlockDriverState *bs)
4695 !bdrv_is_removable(bs) &&
4696 !bdrv_is_read_only(bs));
4699 /* device must be snapshots in order to have a reliable snapshot */
4700 static int bdrv_has_snapshot(BlockDriverState *bs)
4703 !bdrv_is_removable(bs) &&
4704 !bdrv_is_read_only(bs));
4707 static BlockDriverState *get_bs_snapshots(void)
4709 BlockDriverState *bs;
4713 return bs_snapshots;
4714 for(i = 0; i <= MAX_DISKS; i++) {
4716 if (bdrv_can_snapshot(bs))
4725 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4728 QEMUSnapshotInfo *sn_tab, *sn;
4732 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4735 for(i = 0; i < nb_sns; i++) {
4737 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4747 void do_savevm(const char *name)
4749 BlockDriverState *bs, *bs1;
4750 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4751 int must_delete, ret, i;
4752 BlockDriverInfo bdi1, *bdi = &bdi1;
4754 int saved_vm_running;
4761 bs = get_bs_snapshots();
4763 term_printf("No block device can accept snapshots\n");
4767 /* ??? Should this occur after vm_stop? */
4770 saved_vm_running = vm_running;
4775 ret = bdrv_snapshot_find(bs, old_sn, name);
4780 memset(sn, 0, sizeof(*sn));
4782 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4783 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4786 pstrcpy(sn->name, sizeof(sn->name), name);
4789 /* fill auxiliary fields */
4792 sn->date_sec = tb.time;
4793 sn->date_nsec = tb.millitm * 1000000;
4795 gettimeofday(&tv, NULL);
4796 sn->date_sec = tv.tv_sec;
4797 sn->date_nsec = tv.tv_usec * 1000;
4799 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4801 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4802 term_printf("Device %s does not support VM state snapshots\n",
4803 bdrv_get_device_name(bs));
4807 /* save the VM state */
4808 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4810 term_printf("Could not open VM state file\n");
4813 ret = qemu_savevm_state(f);
4814 sn->vm_state_size = qemu_ftell(f);
4817 term_printf("Error %d while writing VM\n", ret);
4821 /* create the snapshots */
4823 for(i = 0; i < MAX_DISKS; i++) {
4825 if (bdrv_has_snapshot(bs1)) {
4827 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4829 term_printf("Error while deleting snapshot on '%s'\n",
4830 bdrv_get_device_name(bs1));
4833 ret = bdrv_snapshot_create(bs1, sn);
4835 term_printf("Error while creating snapshot on '%s'\n",
4836 bdrv_get_device_name(bs1));
4842 if (saved_vm_running)
4846 void do_loadvm(const char *name)
4848 BlockDriverState *bs, *bs1;
4849 BlockDriverInfo bdi1, *bdi = &bdi1;
4852 int saved_vm_running;
4854 bs = get_bs_snapshots();
4856 term_printf("No block device supports snapshots\n");
4860 /* Flush all IO requests so they don't interfere with the new state. */
4863 saved_vm_running = vm_running;
4866 for(i = 0; i <= MAX_DISKS; i++) {
4868 if (bdrv_has_snapshot(bs1)) {
4869 ret = bdrv_snapshot_goto(bs1, name);
4872 term_printf("Warning: ");
4875 term_printf("Snapshots not supported on device '%s'\n",
4876 bdrv_get_device_name(bs1));
4879 term_printf("Could not find snapshot '%s' on device '%s'\n",
4880 name, bdrv_get_device_name(bs1));
4883 term_printf("Error %d while activating snapshot on '%s'\n",
4884 ret, bdrv_get_device_name(bs1));
4887 /* fatal on snapshot block device */
4894 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4895 term_printf("Device %s does not support VM state snapshots\n",
4896 bdrv_get_device_name(bs));
4900 /* restore the VM state */
4901 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4903 term_printf("Could not open VM state file\n");
4906 ret = qemu_loadvm_state(f);
4909 term_printf("Error %d while loading VM state\n", ret);
4912 if (saved_vm_running)
4916 void do_delvm(const char *name)
4918 BlockDriverState *bs, *bs1;
4921 bs = get_bs_snapshots();
4923 term_printf("No block device supports snapshots\n");
4927 for(i = 0; i <= MAX_DISKS; i++) {
4929 if (bdrv_has_snapshot(bs1)) {
4930 ret = bdrv_snapshot_delete(bs1, name);
4932 if (ret == -ENOTSUP)
4933 term_printf("Snapshots not supported on device '%s'\n",
4934 bdrv_get_device_name(bs1));
4936 term_printf("Error %d while deleting snapshot on '%s'\n",
4937 ret, bdrv_get_device_name(bs1));
4943 void do_info_snapshots(void)
4945 BlockDriverState *bs, *bs1;
4946 QEMUSnapshotInfo *sn_tab, *sn;
4950 bs = get_bs_snapshots();
4952 term_printf("No available block device supports snapshots\n");
4955 term_printf("Snapshot devices:");
4956 for(i = 0; i <= MAX_DISKS; i++) {
4958 if (bdrv_has_snapshot(bs1)) {
4960 term_printf(" %s", bdrv_get_device_name(bs1));
4965 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4967 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4970 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4971 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4972 for(i = 0; i < nb_sns; i++) {
4974 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4979 /***********************************************************/
4980 /* cpu save/restore */
4982 #if defined(TARGET_I386)
4984 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4986 qemu_put_be32(f, dt->selector);
4987 qemu_put_betl(f, dt->base);
4988 qemu_put_be32(f, dt->limit);
4989 qemu_put_be32(f, dt->flags);
4992 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4994 dt->selector = qemu_get_be32(f);
4995 dt->base = qemu_get_betl(f);
4996 dt->limit = qemu_get_be32(f);
4997 dt->flags = qemu_get_be32(f);
5000 void cpu_save(QEMUFile *f, void *opaque)
5002 CPUState *env = opaque;
5003 uint16_t fptag, fpus, fpuc, fpregs_format;
5007 for(i = 0; i < CPU_NB_REGS; i++)
5008 qemu_put_betls(f, &env->regs[i]);
5009 qemu_put_betls(f, &env->eip);
5010 qemu_put_betls(f, &env->eflags);
5011 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5012 qemu_put_be32s(f, &hflags);
5016 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5018 for(i = 0; i < 8; i++) {
5019 fptag |= ((!env->fptags[i]) << i);
5022 qemu_put_be16s(f, &fpuc);
5023 qemu_put_be16s(f, &fpus);
5024 qemu_put_be16s(f, &fptag);
5026 #ifdef USE_X86LDOUBLE
5031 qemu_put_be16s(f, &fpregs_format);
5033 for(i = 0; i < 8; i++) {
5034 #ifdef USE_X86LDOUBLE
5038 /* we save the real CPU data (in case of MMX usage only 'mant'
5039 contains the MMX register */
5040 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5041 qemu_put_be64(f, mant);
5042 qemu_put_be16(f, exp);
5045 /* if we use doubles for float emulation, we save the doubles to
5046 avoid losing information in case of MMX usage. It can give
5047 problems if the image is restored on a CPU where long
5048 doubles are used instead. */
5049 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5053 for(i = 0; i < 6; i++)
5054 cpu_put_seg(f, &env->segs[i]);
5055 cpu_put_seg(f, &env->ldt);
5056 cpu_put_seg(f, &env->tr);
5057 cpu_put_seg(f, &env->gdt);
5058 cpu_put_seg(f, &env->idt);
5060 qemu_put_be32s(f, &env->sysenter_cs);
5061 qemu_put_be32s(f, &env->sysenter_esp);
5062 qemu_put_be32s(f, &env->sysenter_eip);
5064 qemu_put_betls(f, &env->cr[0]);
5065 qemu_put_betls(f, &env->cr[2]);
5066 qemu_put_betls(f, &env->cr[3]);
5067 qemu_put_betls(f, &env->cr[4]);
5069 for(i = 0; i < 8; i++)
5070 qemu_put_betls(f, &env->dr[i]);
5073 qemu_put_be32s(f, &env->a20_mask);
5076 qemu_put_be32s(f, &env->mxcsr);
5077 for(i = 0; i < CPU_NB_REGS; i++) {
5078 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5079 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5082 #ifdef TARGET_X86_64
5083 qemu_put_be64s(f, &env->efer);
5084 qemu_put_be64s(f, &env->star);
5085 qemu_put_be64s(f, &env->lstar);
5086 qemu_put_be64s(f, &env->cstar);
5087 qemu_put_be64s(f, &env->fmask);
5088 qemu_put_be64s(f, &env->kernelgsbase);
5090 qemu_put_be32s(f, &env->smbase);
5093 #ifdef USE_X86LDOUBLE
5094 /* XXX: add that in a FPU generic layer */
5095 union x86_longdouble {
5100 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5101 #define EXPBIAS1 1023
5102 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5103 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5105 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5109 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5110 /* exponent + sign */
5111 e = EXPD1(temp) - EXPBIAS1 + 16383;
5112 e |= SIGND1(temp) >> 16;
5117 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5119 CPUState *env = opaque;
5122 uint16_t fpus, fpuc, fptag, fpregs_format;
5124 if (version_id != 3 && version_id != 4)
5126 for(i = 0; i < CPU_NB_REGS; i++)
5127 qemu_get_betls(f, &env->regs[i]);
5128 qemu_get_betls(f, &env->eip);
5129 qemu_get_betls(f, &env->eflags);
5130 qemu_get_be32s(f, &hflags);
5132 qemu_get_be16s(f, &fpuc);
5133 qemu_get_be16s(f, &fpus);
5134 qemu_get_be16s(f, &fptag);
5135 qemu_get_be16s(f, &fpregs_format);
5137 /* NOTE: we cannot always restore the FPU state if the image come
5138 from a host with a different 'USE_X86LDOUBLE' define. We guess
5139 if we are in an MMX state to restore correctly in that case. */
5140 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5141 for(i = 0; i < 8; i++) {
5145 switch(fpregs_format) {
5147 mant = qemu_get_be64(f);
5148 exp = qemu_get_be16(f);
5149 #ifdef USE_X86LDOUBLE
5150 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5152 /* difficult case */
5154 env->fpregs[i].mmx.MMX_Q(0) = mant;
5156 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5160 mant = qemu_get_be64(f);
5161 #ifdef USE_X86LDOUBLE
5163 union x86_longdouble *p;
5164 /* difficult case */
5165 p = (void *)&env->fpregs[i];
5170 fp64_to_fp80(p, mant);
5174 env->fpregs[i].mmx.MMX_Q(0) = mant;
5183 /* XXX: restore FPU round state */
5184 env->fpstt = (fpus >> 11) & 7;
5185 env->fpus = fpus & ~0x3800;
5187 for(i = 0; i < 8; i++) {
5188 env->fptags[i] = (fptag >> i) & 1;
5191 for(i = 0; i < 6; i++)
5192 cpu_get_seg(f, &env->segs[i]);
5193 cpu_get_seg(f, &env->ldt);
5194 cpu_get_seg(f, &env->tr);
5195 cpu_get_seg(f, &env->gdt);
5196 cpu_get_seg(f, &env->idt);
5198 qemu_get_be32s(f, &env->sysenter_cs);
5199 qemu_get_be32s(f, &env->sysenter_esp);
5200 qemu_get_be32s(f, &env->sysenter_eip);
5202 qemu_get_betls(f, &env->cr[0]);
5203 qemu_get_betls(f, &env->cr[2]);
5204 qemu_get_betls(f, &env->cr[3]);
5205 qemu_get_betls(f, &env->cr[4]);
5207 for(i = 0; i < 8; i++)
5208 qemu_get_betls(f, &env->dr[i]);
5211 qemu_get_be32s(f, &env->a20_mask);
5213 qemu_get_be32s(f, &env->mxcsr);
5214 for(i = 0; i < CPU_NB_REGS; i++) {
5215 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5216 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5219 #ifdef TARGET_X86_64
5220 qemu_get_be64s(f, &env->efer);
5221 qemu_get_be64s(f, &env->star);
5222 qemu_get_be64s(f, &env->lstar);
5223 qemu_get_be64s(f, &env->cstar);
5224 qemu_get_be64s(f, &env->fmask);
5225 qemu_get_be64s(f, &env->kernelgsbase);
5227 if (version_id >= 4)
5228 qemu_get_be32s(f, &env->smbase);
5230 /* XXX: compute hflags from scratch, except for CPL and IIF */
5231 env->hflags = hflags;
5236 #elif defined(TARGET_PPC)
5237 void cpu_save(QEMUFile *f, void *opaque)
5241 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5246 #elif defined(TARGET_MIPS)
5247 void cpu_save(QEMUFile *f, void *opaque)
5251 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5256 #elif defined(TARGET_SPARC)
5257 void cpu_save(QEMUFile *f, void *opaque)
5259 CPUState *env = opaque;
5263 for(i = 0; i < 8; i++)
5264 qemu_put_betls(f, &env->gregs[i]);
5265 for(i = 0; i < NWINDOWS * 16; i++)
5266 qemu_put_betls(f, &env->regbase[i]);
5269 for(i = 0; i < TARGET_FPREGS; i++) {
5275 qemu_put_be32(f, u.i);
5278 qemu_put_betls(f, &env->pc);
5279 qemu_put_betls(f, &env->npc);
5280 qemu_put_betls(f, &env->y);
5282 qemu_put_be32(f, tmp);
5283 qemu_put_betls(f, &env->fsr);
5284 qemu_put_betls(f, &env->tbr);
5285 #ifndef TARGET_SPARC64
5286 qemu_put_be32s(f, &env->wim);
5288 for(i = 0; i < 16; i++)
5289 qemu_put_be32s(f, &env->mmuregs[i]);
5293 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5295 CPUState *env = opaque;
5299 for(i = 0; i < 8; i++)
5300 qemu_get_betls(f, &env->gregs[i]);
5301 for(i = 0; i < NWINDOWS * 16; i++)
5302 qemu_get_betls(f, &env->regbase[i]);
5305 for(i = 0; i < TARGET_FPREGS; i++) {
5310 u.i = qemu_get_be32(f);
5314 qemu_get_betls(f, &env->pc);
5315 qemu_get_betls(f, &env->npc);
5316 qemu_get_betls(f, &env->y);
5317 tmp = qemu_get_be32(f);
5318 env->cwp = 0; /* needed to ensure that the wrapping registers are
5319 correctly updated */
5321 qemu_get_betls(f, &env->fsr);
5322 qemu_get_betls(f, &env->tbr);
5323 #ifndef TARGET_SPARC64
5324 qemu_get_be32s(f, &env->wim);
5326 for(i = 0; i < 16; i++)
5327 qemu_get_be32s(f, &env->mmuregs[i]);
5333 #elif defined(TARGET_ARM)
5335 /* ??? Need to implement these. */
5336 void cpu_save(QEMUFile *f, void *opaque)
5340 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5347 #warning No CPU save/restore functions
5351 /***********************************************************/
5352 /* ram save/restore */
5354 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5358 v = qemu_get_byte(f);
5361 if (qemu_get_buffer(f, buf, len) != len)
5365 v = qemu_get_byte(f);
5366 memset(buf, v, len);
5374 static int ram_load_v1(QEMUFile *f, void *opaque)
5378 if (qemu_get_be32(f) != phys_ram_size)
5380 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5381 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5388 #define BDRV_HASH_BLOCK_SIZE 1024
5389 #define IOBUF_SIZE 4096
5390 #define RAM_CBLOCK_MAGIC 0xfabe
5392 typedef struct RamCompressState {
5395 uint8_t buf[IOBUF_SIZE];
5398 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5401 memset(s, 0, sizeof(*s));
5403 ret = deflateInit2(&s->zstream, 1,
5405 9, Z_DEFAULT_STRATEGY);
5408 s->zstream.avail_out = IOBUF_SIZE;
5409 s->zstream.next_out = s->buf;
5413 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5415 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5416 qemu_put_be16(s->f, len);
5417 qemu_put_buffer(s->f, buf, len);
5420 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5424 s->zstream.avail_in = len;
5425 s->zstream.next_in = (uint8_t *)buf;
5426 while (s->zstream.avail_in > 0) {
5427 ret = deflate(&s->zstream, Z_NO_FLUSH);
5430 if (s->zstream.avail_out == 0) {
5431 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5432 s->zstream.avail_out = IOBUF_SIZE;
5433 s->zstream.next_out = s->buf;
5439 static void ram_compress_close(RamCompressState *s)
5443 /* compress last bytes */
5445 ret = deflate(&s->zstream, Z_FINISH);
5446 if (ret == Z_OK || ret == Z_STREAM_END) {
5447 len = IOBUF_SIZE - s->zstream.avail_out;
5449 ram_put_cblock(s, s->buf, len);
5451 s->zstream.avail_out = IOBUF_SIZE;
5452 s->zstream.next_out = s->buf;
5453 if (ret == Z_STREAM_END)
5460 deflateEnd(&s->zstream);
5463 typedef struct RamDecompressState {
5466 uint8_t buf[IOBUF_SIZE];
5467 } RamDecompressState;
5469 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5472 memset(s, 0, sizeof(*s));
5474 ret = inflateInit(&s->zstream);
5480 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5484 s->zstream.avail_out = len;
5485 s->zstream.next_out = buf;
5486 while (s->zstream.avail_out > 0) {
5487 if (s->zstream.avail_in == 0) {
5488 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5490 clen = qemu_get_be16(s->f);
5491 if (clen > IOBUF_SIZE)
5493 qemu_get_buffer(s->f, s->buf, clen);
5494 s->zstream.avail_in = clen;
5495 s->zstream.next_in = s->buf;
5497 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5498 if (ret != Z_OK && ret != Z_STREAM_END) {
5505 static void ram_decompress_close(RamDecompressState *s)
5507 inflateEnd(&s->zstream);
5510 static void ram_save(QEMUFile *f, void *opaque)
5513 RamCompressState s1, *s = &s1;
5516 qemu_put_be32(f, phys_ram_size);
5517 if (ram_compress_open(s, f) < 0)
5519 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5521 if (tight_savevm_enabled) {
5525 /* find if the memory block is available on a virtual
5528 for(j = 0; j < MAX_DISKS; j++) {
5530 sector_num = bdrv_hash_find(bs_table[j],
5531 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5532 if (sector_num >= 0)
5537 goto normal_compress;
5540 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5541 ram_compress_buf(s, buf, 10);
5547 ram_compress_buf(s, buf, 1);
5548 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5551 ram_compress_close(s);
5554 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5556 RamDecompressState s1, *s = &s1;
5560 if (version_id == 1)
5561 return ram_load_v1(f, opaque);
5562 if (version_id != 2)
5564 if (qemu_get_be32(f) != phys_ram_size)
5566 if (ram_decompress_open(s, f) < 0)
5568 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5569 if (ram_decompress_buf(s, buf, 1) < 0) {
5570 fprintf(stderr, "Error while reading ram block header\n");
5574 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5575 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5584 ram_decompress_buf(s, buf + 1, 9);
5586 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5587 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5588 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5591 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5592 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5593 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5594 bs_index, sector_num);
5601 printf("Error block header\n");
5605 ram_decompress_close(s);
5609 /***********************************************************/
5610 /* bottom halves (can be seen as timers which expire ASAP) */
5619 static QEMUBH *first_bh = NULL;
5621 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5624 bh = qemu_mallocz(sizeof(QEMUBH));
5628 bh->opaque = opaque;
5632 int qemu_bh_poll(void)
5651 void qemu_bh_schedule(QEMUBH *bh)
5653 CPUState *env = cpu_single_env;
5657 bh->next = first_bh;
5660 /* stop the currently executing CPU to execute the BH ASAP */
5662 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5666 void qemu_bh_cancel(QEMUBH *bh)
5669 if (bh->scheduled) {
5672 pbh = &(*pbh)->next;
5678 void qemu_bh_delete(QEMUBH *bh)
5684 /***********************************************************/
5685 /* machine registration */
5687 QEMUMachine *first_machine = NULL;
5689 int qemu_register_machine(QEMUMachine *m)
5692 pm = &first_machine;
5700 QEMUMachine *find_machine(const char *name)
5704 for(m = first_machine; m != NULL; m = m->next) {
5705 if (!strcmp(m->name, name))
5711 /***********************************************************/
5712 /* main execution loop */
5714 void gui_update(void *opaque)
5716 display_state.dpy_refresh(&display_state);
5717 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5720 struct vm_change_state_entry {
5721 VMChangeStateHandler *cb;
5723 LIST_ENTRY (vm_change_state_entry) entries;
5726 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5728 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5731 VMChangeStateEntry *e;
5733 e = qemu_mallocz(sizeof (*e));
5739 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5743 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5745 LIST_REMOVE (e, entries);
5749 static void vm_state_notify(int running)
5751 VMChangeStateEntry *e;
5753 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5754 e->cb(e->opaque, running);
5758 /* XXX: support several handlers */
5759 static VMStopHandler *vm_stop_cb;
5760 static void *vm_stop_opaque;
5762 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5765 vm_stop_opaque = opaque;
5769 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5783 void vm_stop(int reason)
5786 cpu_disable_ticks();
5790 vm_stop_cb(vm_stop_opaque, reason);
5797 /* reset/shutdown handler */
5799 typedef struct QEMUResetEntry {
5800 QEMUResetHandler *func;
5802 struct QEMUResetEntry *next;
5805 static QEMUResetEntry *first_reset_entry;
5806 static int reset_requested;
5807 static int shutdown_requested;
5808 static int powerdown_requested;
5810 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5812 QEMUResetEntry **pre, *re;
5814 pre = &first_reset_entry;
5815 while (*pre != NULL)
5816 pre = &(*pre)->next;
5817 re = qemu_mallocz(sizeof(QEMUResetEntry));
5819 re->opaque = opaque;
5824 static void qemu_system_reset(void)
5828 /* reset all devices */
5829 for(re = first_reset_entry; re != NULL; re = re->next) {
5830 re->func(re->opaque);
5834 void qemu_system_reset_request(void)
5837 shutdown_requested = 1;
5839 reset_requested = 1;
5842 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5845 void qemu_system_shutdown_request(void)
5847 shutdown_requested = 1;
5849 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5852 void qemu_system_powerdown_request(void)
5854 powerdown_requested = 1;
5856 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5859 void main_loop_wait(int timeout)
5861 IOHandlerRecord *ioh, *ioh_next;
5862 fd_set rfds, wfds, xfds;
5868 /* XXX: need to suppress polling by better using win32 events */
5870 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5871 ret |= pe->func(pe->opaque);
5874 if (ret == 0 && timeout > 0) {
5876 WaitObjects *w = &wait_objects;
5878 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5879 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5880 if (w->func[ret - WAIT_OBJECT_0])
5881 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5882 } else if (ret == WAIT_TIMEOUT) {
5884 err = GetLastError();
5885 fprintf(stderr, "Wait error %d %d\n", ret, err);
5889 /* poll any events */
5890 /* XXX: separate device handlers from system ones */
5895 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5897 (!ioh->fd_read_poll ||
5898 ioh->fd_read_poll(ioh->opaque) != 0)) {
5899 FD_SET(ioh->fd, &rfds);
5903 if (ioh->fd_write) {
5904 FD_SET(ioh->fd, &wfds);
5914 tv.tv_usec = timeout * 1000;
5916 #if defined(CONFIG_SLIRP)
5918 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5921 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5923 /* XXX: better handling of removal */
5924 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5925 ioh_next = ioh->next;
5926 if (FD_ISSET(ioh->fd, &rfds)) {
5927 ioh->fd_read(ioh->opaque);
5929 if (FD_ISSET(ioh->fd, &wfds)) {
5930 ioh->fd_write(ioh->opaque);
5934 #if defined(CONFIG_SLIRP)
5941 slirp_select_poll(&rfds, &wfds, &xfds);
5948 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5949 qemu_get_clock(vm_clock));
5950 /* run dma transfers, if any */
5954 /* real time timers */
5955 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5956 qemu_get_clock(rt_clock));
5959 static CPUState *cur_cpu;
5964 #ifdef CONFIG_PROFILER
5969 cur_cpu = first_cpu;
5976 env = env->next_cpu;
5979 #ifdef CONFIG_PROFILER
5980 ti = profile_getclock();
5982 ret = cpu_exec(env);
5983 #ifdef CONFIG_PROFILER
5984 qemu_time += profile_getclock() - ti;
5986 if (ret != EXCP_HALTED)
5988 /* all CPUs are halted ? */
5989 if (env == cur_cpu) {
5996 if (shutdown_requested) {
5997 ret = EXCP_INTERRUPT;
6000 if (reset_requested) {
6001 reset_requested = 0;
6002 qemu_system_reset();
6003 ret = EXCP_INTERRUPT;
6005 if (powerdown_requested) {
6006 powerdown_requested = 0;
6007 qemu_system_powerdown();
6008 ret = EXCP_INTERRUPT;
6010 if (ret == EXCP_DEBUG) {
6011 vm_stop(EXCP_DEBUG);
6013 /* if hlt instruction, we wait until the next IRQ */
6014 /* XXX: use timeout computed from timers */
6015 if (ret == EXCP_HLT)
6022 #ifdef CONFIG_PROFILER
6023 ti = profile_getclock();
6025 main_loop_wait(timeout);
6026 #ifdef CONFIG_PROFILER
6027 dev_time += profile_getclock() - ti;
6030 cpu_disable_ticks();
6036 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6037 "usage: %s [options] [disk_image]\n"
6039 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6041 "Standard options:\n"
6042 "-M machine select emulated machine (-M ? for list)\n"
6043 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6044 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6045 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6046 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6047 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6048 "-snapshot write to temporary files instead of disk image files\n"
6050 "-no-quit disable SDL window close capability\n"
6053 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6055 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6056 "-smp n set the number of CPUs to 'n' [default=1]\n"
6057 "-nographic disable graphical output and redirect serial I/Os to console\n"
6059 "-k language use keyboard layout (for example \"fr\" for French)\n"
6062 "-audio-help print list of audio drivers and their options\n"
6063 "-soundhw c1,... enable audio support\n"
6064 " and only specified sound cards (comma separated list)\n"
6065 " use -soundhw ? to get the list of supported cards\n"
6066 " use -soundhw all to enable all of them\n"
6068 "-localtime set the real time clock to local time [default=utc]\n"
6069 "-full-screen start in full screen\n"
6071 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6073 "-usb enable the USB driver (will be the default soon)\n"
6074 "-usbdevice name add the host or guest USB device 'name'\n"
6075 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6076 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6079 "Network options:\n"
6080 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6081 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6083 "-net user[,vlan=n][,hostname=host]\n"
6084 " connect the user mode network stack to VLAN 'n' and send\n"
6085 " hostname 'host' to DHCP clients\n"
6088 "-net tap[,vlan=n],ifname=name\n"
6089 " connect the host TAP network interface to VLAN 'n'\n"
6091 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6092 " connect the host TAP network interface to VLAN 'n' and use\n"
6093 " the network script 'file' (default=%s);\n"
6094 " use 'fd=h' to connect to an already opened TAP interface\n"
6096 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6097 " connect the vlan 'n' to another VLAN using a socket connection\n"
6098 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6099 " connect the vlan 'n' to multicast maddr and port\n"
6100 "-net none use it alone to have zero network devices; if no -net option\n"
6101 " is provided, the default is '-net nic -net user'\n"
6104 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6106 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6108 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6109 " redirect TCP or UDP connections from host to guest [-net user]\n"
6112 "Linux boot specific:\n"
6113 "-kernel bzImage use 'bzImage' as kernel image\n"
6114 "-append cmdline use 'cmdline' as kernel command line\n"
6115 "-initrd file use 'file' as initial ram disk\n"
6117 "Debug/Expert options:\n"
6118 "-monitor dev redirect the monitor to char device 'dev'\n"
6119 "-serial dev redirect the serial port to char device 'dev'\n"
6120 "-parallel dev redirect the parallel port to char device 'dev'\n"
6121 "-pidfile file Write PID to 'file'\n"
6122 "-S freeze CPU at startup (use 'c' to start execution)\n"
6123 "-s wait gdb connection to port %d\n"
6124 "-p port change gdb connection port\n"
6125 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6126 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6127 " translation (t=none or lba) (usually qemu can guess them)\n"
6128 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6130 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6131 "-no-kqemu disable KQEMU kernel module usage\n"
6133 #ifdef USE_CODE_COPY
6134 "-no-code-copy disable code copy acceleration\n"
6137 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6138 " (default is CL-GD5446 PCI VGA)\n"
6139 "-no-acpi disable ACPI\n"
6141 "-no-reboot exit instead of rebooting\n"
6142 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6143 "-vnc display start a VNC server on display\n"
6145 "-daemonize daemonize QEMU after initializing\n"
6147 "-option-rom rom load a file, rom, into the option ROM space\n"
6149 "During emulation, the following keys are useful:\n"
6150 "ctrl-alt-f toggle full screen\n"
6151 "ctrl-alt-n switch to virtual console 'n'\n"
6152 "ctrl-alt toggle mouse and keyboard grab\n"
6154 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6159 DEFAULT_NETWORK_SCRIPT,
6161 DEFAULT_GDBSTUB_PORT,
6166 #define HAS_ARG 0x0001
6180 QEMU_OPTION_snapshot,
6182 QEMU_OPTION_no_fd_bootchk,
6185 QEMU_OPTION_nographic,
6187 QEMU_OPTION_audio_help,
6188 QEMU_OPTION_soundhw,
6206 QEMU_OPTION_no_code_copy,
6208 QEMU_OPTION_localtime,
6209 QEMU_OPTION_cirrusvga,
6211 QEMU_OPTION_std_vga,
6212 QEMU_OPTION_monitor,
6214 QEMU_OPTION_parallel,
6216 QEMU_OPTION_full_screen,
6217 QEMU_OPTION_no_quit,
6218 QEMU_OPTION_pidfile,
6219 QEMU_OPTION_no_kqemu,
6220 QEMU_OPTION_kernel_kqemu,
6221 QEMU_OPTION_win2k_hack,
6223 QEMU_OPTION_usbdevice,
6226 QEMU_OPTION_no_acpi,
6227 QEMU_OPTION_no_reboot,
6228 QEMU_OPTION_daemonize,
6229 QEMU_OPTION_option_rom,
6232 typedef struct QEMUOption {
6238 const QEMUOption qemu_options[] = {
6239 { "h", 0, QEMU_OPTION_h },
6241 { "M", HAS_ARG, QEMU_OPTION_M },
6242 { "fda", HAS_ARG, QEMU_OPTION_fda },
6243 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6244 { "hda", HAS_ARG, QEMU_OPTION_hda },
6245 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6246 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6247 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6248 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6249 { "boot", HAS_ARG, QEMU_OPTION_boot },
6250 { "snapshot", 0, QEMU_OPTION_snapshot },
6252 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6254 { "m", HAS_ARG, QEMU_OPTION_m },
6255 { "nographic", 0, QEMU_OPTION_nographic },
6256 { "k", HAS_ARG, QEMU_OPTION_k },
6258 { "audio-help", 0, QEMU_OPTION_audio_help },
6259 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6262 { "net", HAS_ARG, QEMU_OPTION_net},
6264 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6266 { "smb", HAS_ARG, QEMU_OPTION_smb },
6268 { "redir", HAS_ARG, QEMU_OPTION_redir },
6271 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6272 { "append", HAS_ARG, QEMU_OPTION_append },
6273 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6275 { "S", 0, QEMU_OPTION_S },
6276 { "s", 0, QEMU_OPTION_s },
6277 { "p", HAS_ARG, QEMU_OPTION_p },
6278 { "d", HAS_ARG, QEMU_OPTION_d },
6279 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6280 { "L", HAS_ARG, QEMU_OPTION_L },
6281 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6283 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6284 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6286 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6287 { "g", 1, QEMU_OPTION_g },
6289 { "localtime", 0, QEMU_OPTION_localtime },
6290 { "std-vga", 0, QEMU_OPTION_std_vga },
6291 { "monitor", 1, QEMU_OPTION_monitor },
6292 { "serial", 1, QEMU_OPTION_serial },
6293 { "parallel", 1, QEMU_OPTION_parallel },
6294 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6295 { "full-screen", 0, QEMU_OPTION_full_screen },
6297 { "no-quit", 0, QEMU_OPTION_no_quit },
6299 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6300 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6301 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6302 { "smp", HAS_ARG, QEMU_OPTION_smp },
6303 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6305 /* temporary options */
6306 { "usb", 0, QEMU_OPTION_usb },
6307 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6308 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6309 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6310 { "daemonize", 0, QEMU_OPTION_daemonize },
6311 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6315 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6317 /* this stack is only used during signal handling */
6318 #define SIGNAL_STACK_SIZE 32768
6320 static uint8_t *signal_stack;
6324 /* password input */
6326 static BlockDriverState *get_bdrv(int index)
6328 BlockDriverState *bs;
6331 bs = bs_table[index];
6332 } else if (index < 6) {
6333 bs = fd_table[index - 4];
6340 static void read_passwords(void)
6342 BlockDriverState *bs;
6346 for(i = 0; i < 6; i++) {
6348 if (bs && bdrv_is_encrypted(bs)) {
6349 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6350 for(j = 0; j < 3; j++) {
6351 monitor_readline("Password: ",
6352 1, password, sizeof(password));
6353 if (bdrv_set_key(bs, password) == 0)
6355 term_printf("invalid password\n");
6361 /* XXX: currently we cannot use simultaneously different CPUs */
6362 void register_machines(void)
6364 #if defined(TARGET_I386)
6365 qemu_register_machine(&pc_machine);
6366 qemu_register_machine(&isapc_machine);
6367 #elif defined(TARGET_PPC)
6368 qemu_register_machine(&heathrow_machine);
6369 qemu_register_machine(&core99_machine);
6370 qemu_register_machine(&prep_machine);
6371 #elif defined(TARGET_MIPS)
6372 qemu_register_machine(&mips_machine);
6373 qemu_register_machine(&mips_malta_machine);
6374 #elif defined(TARGET_SPARC)
6375 #ifdef TARGET_SPARC64
6376 qemu_register_machine(&sun4u_machine);
6378 qemu_register_machine(&sun4m_machine);
6380 #elif defined(TARGET_ARM)
6381 qemu_register_machine(&integratorcp926_machine);
6382 qemu_register_machine(&integratorcp1026_machine);
6383 qemu_register_machine(&versatilepb_machine);
6384 qemu_register_machine(&versatileab_machine);
6385 qemu_register_machine(&realview_machine);
6386 #elif defined(TARGET_SH4)
6387 qemu_register_machine(&shix_machine);
6389 #error unsupported CPU
6394 struct soundhw soundhw[] = {
6401 { .init_isa = pcspk_audio_init }
6406 "Creative Sound Blaster 16",
6409 { .init_isa = SB16_init }
6416 "Yamaha YMF262 (OPL3)",
6418 "Yamaha YM3812 (OPL2)",
6422 { .init_isa = Adlib_init }
6429 "Gravis Ultrasound GF1",
6432 { .init_isa = GUS_init }
6438 "ENSONIQ AudioPCI ES1370",
6441 { .init_pci = es1370_init }
6444 { NULL, NULL, 0, 0, { NULL } }
6447 static void select_soundhw (const char *optarg)
6451 if (*optarg == '?') {
6454 printf ("Valid sound card names (comma separated):\n");
6455 for (c = soundhw; c->name; ++c) {
6456 printf ("%-11s %s\n", c->name, c->descr);
6458 printf ("\n-soundhw all will enable all of the above\n");
6459 exit (*optarg != '?');
6467 if (!strcmp (optarg, "all")) {
6468 for (c = soundhw; c->name; ++c) {
6476 e = strchr (p, ',');
6477 l = !e ? strlen (p) : (size_t) (e - p);
6479 for (c = soundhw; c->name; ++c) {
6480 if (!strncmp (c->name, p, l)) {
6489 "Unknown sound card name (too big to show)\n");
6492 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6497 p += l + (e != NULL);
6501 goto show_valid_cards;
6507 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6509 exit(STATUS_CONTROL_C_EXIT);
6514 #define MAX_NET_CLIENTS 32
6516 int main(int argc, char **argv)
6518 #ifdef CONFIG_GDBSTUB
6519 int use_gdbstub, gdbstub_port;
6522 int snapshot, linux_boot;
6523 const char *initrd_filename;
6524 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6525 const char *kernel_filename, *kernel_cmdline;
6526 DisplayState *ds = &display_state;
6527 int cyls, heads, secs, translation;
6528 int start_emulation = 1;
6529 char net_clients[MAX_NET_CLIENTS][256];
6532 const char *r, *optarg;
6533 CharDriverState *monitor_hd;
6534 char monitor_device[128];
6535 char serial_devices[MAX_SERIAL_PORTS][128];
6536 int serial_device_index;
6537 char parallel_devices[MAX_PARALLEL_PORTS][128];
6538 int parallel_device_index;
6539 const char *loadvm = NULL;
6540 QEMUMachine *machine;
6541 char usb_devices[MAX_USB_CMDLINE][128];
6542 int usb_devices_index;
6545 LIST_INIT (&vm_change_state_head);
6548 struct sigaction act;
6549 sigfillset(&act.sa_mask);
6551 act.sa_handler = SIG_IGN;
6552 sigaction(SIGPIPE, &act, NULL);
6555 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6556 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6557 QEMU to run on a single CPU */
6562 h = GetCurrentProcess();
6563 if (GetProcessAffinityMask(h, &mask, &smask)) {
6564 for(i = 0; i < 32; i++) {
6565 if (mask & (1 << i))
6570 SetProcessAffinityMask(h, mask);
6576 register_machines();
6577 machine = first_machine;
6578 initrd_filename = NULL;
6579 for(i = 0; i < MAX_FD; i++)
6580 fd_filename[i] = NULL;
6581 for(i = 0; i < MAX_DISKS; i++)
6582 hd_filename[i] = NULL;
6583 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6584 vga_ram_size = VGA_RAM_SIZE;
6585 bios_size = BIOS_SIZE;
6586 #ifdef CONFIG_GDBSTUB
6588 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6592 kernel_filename = NULL;
6593 kernel_cmdline = "";
6599 cyls = heads = secs = 0;
6600 translation = BIOS_ATA_TRANSLATION_AUTO;
6601 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6603 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6604 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6605 serial_devices[i][0] = '\0';
6606 serial_device_index = 0;
6608 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6609 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6610 parallel_devices[i][0] = '\0';
6611 parallel_device_index = 0;
6613 usb_devices_index = 0;
6618 /* default mac address of the first network interface */
6626 hd_filename[0] = argv[optind++];
6628 const QEMUOption *popt;
6631 popt = qemu_options;
6634 fprintf(stderr, "%s: invalid option -- '%s'\n",
6638 if (!strcmp(popt->name, r + 1))
6642 if (popt->flags & HAS_ARG) {
6643 if (optind >= argc) {
6644 fprintf(stderr, "%s: option '%s' requires an argument\n",
6648 optarg = argv[optind++];
6653 switch(popt->index) {
6655 machine = find_machine(optarg);
6658 printf("Supported machines are:\n");
6659 for(m = first_machine; m != NULL; m = m->next) {
6660 printf("%-10s %s%s\n",
6662 m == first_machine ? " (default)" : "");
6667 case QEMU_OPTION_initrd:
6668 initrd_filename = optarg;
6670 case QEMU_OPTION_hda:
6671 case QEMU_OPTION_hdb:
6672 case QEMU_OPTION_hdc:
6673 case QEMU_OPTION_hdd:
6676 hd_index = popt->index - QEMU_OPTION_hda;
6677 hd_filename[hd_index] = optarg;
6678 if (hd_index == cdrom_index)
6682 case QEMU_OPTION_snapshot:
6685 case QEMU_OPTION_hdachs:
6689 cyls = strtol(p, (char **)&p, 0);
6690 if (cyls < 1 || cyls > 16383)
6695 heads = strtol(p, (char **)&p, 0);
6696 if (heads < 1 || heads > 16)
6701 secs = strtol(p, (char **)&p, 0);
6702 if (secs < 1 || secs > 63)
6706 if (!strcmp(p, "none"))
6707 translation = BIOS_ATA_TRANSLATION_NONE;
6708 else if (!strcmp(p, "lba"))
6709 translation = BIOS_ATA_TRANSLATION_LBA;
6710 else if (!strcmp(p, "auto"))
6711 translation = BIOS_ATA_TRANSLATION_AUTO;
6714 } else if (*p != '\0') {
6716 fprintf(stderr, "qemu: invalid physical CHS format\n");
6721 case QEMU_OPTION_nographic:
6722 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6723 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6726 case QEMU_OPTION_kernel:
6727 kernel_filename = optarg;
6729 case QEMU_OPTION_append:
6730 kernel_cmdline = optarg;
6732 case QEMU_OPTION_cdrom:
6733 if (cdrom_index >= 0) {
6734 hd_filename[cdrom_index] = optarg;
6737 case QEMU_OPTION_boot:
6738 boot_device = optarg[0];
6739 if (boot_device != 'a' &&
6740 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6742 boot_device != 'n' &&
6744 boot_device != 'c' && boot_device != 'd') {
6745 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6749 case QEMU_OPTION_fda:
6750 fd_filename[0] = optarg;
6752 case QEMU_OPTION_fdb:
6753 fd_filename[1] = optarg;
6756 case QEMU_OPTION_no_fd_bootchk:
6760 case QEMU_OPTION_no_code_copy:
6761 code_copy_enabled = 0;
6763 case QEMU_OPTION_net:
6764 if (nb_net_clients >= MAX_NET_CLIENTS) {
6765 fprintf(stderr, "qemu: too many network clients\n");
6768 pstrcpy(net_clients[nb_net_clients],
6769 sizeof(net_clients[0]),
6774 case QEMU_OPTION_tftp:
6775 tftp_prefix = optarg;
6778 case QEMU_OPTION_smb:
6779 net_slirp_smb(optarg);
6782 case QEMU_OPTION_redir:
6783 net_slirp_redir(optarg);
6787 case QEMU_OPTION_audio_help:
6791 case QEMU_OPTION_soundhw:
6792 select_soundhw (optarg);
6799 ram_size = atoi(optarg) * 1024 * 1024;
6802 if (ram_size > PHYS_RAM_MAX_SIZE) {
6803 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6804 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6813 mask = cpu_str_to_log_mask(optarg);
6815 printf("Log items (comma separated):\n");
6816 for(item = cpu_log_items; item->mask != 0; item++) {
6817 printf("%-10s %s\n", item->name, item->help);
6824 #ifdef CONFIG_GDBSTUB
6829 gdbstub_port = atoi(optarg);
6836 start_emulation = 0;
6839 keyboard_layout = optarg;
6841 case QEMU_OPTION_localtime:
6844 case QEMU_OPTION_cirrusvga:
6845 cirrus_vga_enabled = 1;
6847 case QEMU_OPTION_std_vga:
6848 cirrus_vga_enabled = 0;
6855 w = strtol(p, (char **)&p, 10);
6858 fprintf(stderr, "qemu: invalid resolution or depth\n");
6864 h = strtol(p, (char **)&p, 10);
6869 depth = strtol(p, (char **)&p, 10);
6870 if (depth != 8 && depth != 15 && depth != 16 &&
6871 depth != 24 && depth != 32)
6873 } else if (*p == '\0') {
6874 depth = graphic_depth;
6881 graphic_depth = depth;
6884 case QEMU_OPTION_monitor:
6885 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6887 case QEMU_OPTION_serial:
6888 if (serial_device_index >= MAX_SERIAL_PORTS) {
6889 fprintf(stderr, "qemu: too many serial ports\n");
6892 pstrcpy(serial_devices[serial_device_index],
6893 sizeof(serial_devices[0]), optarg);
6894 serial_device_index++;
6896 case QEMU_OPTION_parallel:
6897 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6898 fprintf(stderr, "qemu: too many parallel ports\n");
6901 pstrcpy(parallel_devices[parallel_device_index],
6902 sizeof(parallel_devices[0]), optarg);
6903 parallel_device_index++;
6905 case QEMU_OPTION_loadvm:
6908 case QEMU_OPTION_full_screen:
6912 case QEMU_OPTION_no_quit:
6916 case QEMU_OPTION_pidfile:
6917 create_pidfile(optarg);
6920 case QEMU_OPTION_win2k_hack:
6921 win2k_install_hack = 1;
6925 case QEMU_OPTION_no_kqemu:
6928 case QEMU_OPTION_kernel_kqemu:
6932 case QEMU_OPTION_usb:
6935 case QEMU_OPTION_usbdevice:
6937 if (usb_devices_index >= MAX_USB_CMDLINE) {
6938 fprintf(stderr, "Too many USB devices\n");
6941 pstrcpy(usb_devices[usb_devices_index],
6942 sizeof(usb_devices[usb_devices_index]),
6944 usb_devices_index++;
6946 case QEMU_OPTION_smp:
6947 smp_cpus = atoi(optarg);
6948 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6949 fprintf(stderr, "Invalid number of CPUs\n");
6953 case QEMU_OPTION_vnc:
6954 vnc_display = optarg;
6956 case QEMU_OPTION_no_acpi:
6959 case QEMU_OPTION_no_reboot:
6962 case QEMU_OPTION_daemonize:
6965 case QEMU_OPTION_option_rom:
6966 if (nb_option_roms >= MAX_OPTION_ROMS) {
6967 fprintf(stderr, "Too many option ROMs\n");
6970 option_rom[nb_option_roms] = optarg;
6978 if (daemonize && !nographic && vnc_display == NULL) {
6979 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
6986 if (pipe(fds) == -1)
6997 len = read(fds[0], &status, 1);
6998 if (len == -1 && (errno == EINTR))
7001 if (len != 1 || status != 0)
7019 signal(SIGTSTP, SIG_IGN);
7020 signal(SIGTTOU, SIG_IGN);
7021 signal(SIGTTIN, SIG_IGN);
7029 linux_boot = (kernel_filename != NULL);
7032 hd_filename[0] == '\0' &&
7033 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7034 fd_filename[0] == '\0')
7037 /* boot to floppy or the default cd if no hard disk defined yet */
7038 if (hd_filename[0] == '\0' && boot_device == 'c') {
7039 if (fd_filename[0] != '\0')
7045 setvbuf(stdout, NULL, _IOLBF, 0);
7055 /* init network clients */
7056 if (nb_net_clients == 0) {
7057 /* if no clients, we use a default config */
7058 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7060 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7065 for(i = 0;i < nb_net_clients; i++) {
7066 if (net_client_init(net_clients[i]) < 0)
7071 if (boot_device == 'n') {
7072 for (i = 0; i < nb_nics; i++) {
7073 const char *model = nd_table[i].model;
7077 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7078 if (get_image_size(buf) > 0) {
7079 option_rom[nb_option_roms] = strdup(buf);
7085 fprintf(stderr, "No valid PXE rom found for network device\n");
7088 boot_device = 'c'; /* to prevent confusion by the BIOS */
7092 /* init the memory */
7093 phys_ram_size = ram_size + vga_ram_size + bios_size;
7095 for (i = 0; i < nb_option_roms; i++) {
7096 int ret = get_image_size(option_rom[i]);
7098 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7101 phys_ram_size += ret;
7104 phys_ram_base = qemu_vmalloc(phys_ram_size);
7105 if (!phys_ram_base) {
7106 fprintf(stderr, "Could not allocate physical memory\n");
7110 /* we always create the cdrom drive, even if no disk is there */
7112 if (cdrom_index >= 0) {
7113 bs_table[cdrom_index] = bdrv_new("cdrom");
7114 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7117 /* open the virtual block devices */
7118 for(i = 0; i < MAX_DISKS; i++) {
7119 if (hd_filename[i]) {
7122 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7123 bs_table[i] = bdrv_new(buf);
7125 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7126 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7130 if (i == 0 && cyls != 0) {
7131 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7132 bdrv_set_translation_hint(bs_table[i], translation);
7137 /* we always create at least one floppy disk */
7138 fd_table[0] = bdrv_new("fda");
7139 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7141 for(i = 0; i < MAX_FD; i++) {
7142 if (fd_filename[i]) {
7145 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7146 fd_table[i] = bdrv_new(buf);
7147 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7149 if (fd_filename[i] != '\0') {
7150 if (bdrv_open(fd_table[i], fd_filename[i],
7151 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7152 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7160 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7161 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7167 dumb_display_init(ds);
7168 } else if (vnc_display != NULL) {
7169 vnc_display_init(ds, vnc_display);
7171 #if defined(CONFIG_SDL)
7172 sdl_display_init(ds, full_screen);
7173 #elif defined(CONFIG_COCOA)
7174 cocoa_display_init(ds, full_screen);
7176 dumb_display_init(ds);
7180 monitor_hd = qemu_chr_open(monitor_device);
7182 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7185 monitor_init(monitor_hd, !nographic);
7187 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7188 const char *devname = serial_devices[i];
7189 if (devname[0] != '\0' && strcmp(devname, "none")) {
7190 serial_hds[i] = qemu_chr_open(devname);
7191 if (!serial_hds[i]) {
7192 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7196 if (!strcmp(devname, "vc"))
7197 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7201 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7202 const char *devname = parallel_devices[i];
7203 if (devname[0] != '\0' && strcmp(devname, "none")) {
7204 parallel_hds[i] = qemu_chr_open(devname);
7205 if (!parallel_hds[i]) {
7206 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7210 if (!strcmp(devname, "vc"))
7211 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7215 machine->init(ram_size, vga_ram_size, boot_device,
7216 ds, fd_filename, snapshot,
7217 kernel_filename, kernel_cmdline, initrd_filename);
7219 /* init USB devices */
7221 for(i = 0; i < usb_devices_index; i++) {
7222 if (usb_device_add(usb_devices[i]) < 0) {
7223 fprintf(stderr, "Warning: could not add USB device %s\n",
7229 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7230 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7232 #ifdef CONFIG_GDBSTUB
7234 if (gdbserver_start(gdbstub_port) < 0) {
7235 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
7239 printf("Waiting gdb connection on port %d\n", gdbstub_port);
7247 /* XXX: simplify init */
7249 if (start_emulation) {
7260 len = write(fds[1], &status, 1);
7261 if (len == -1 && (errno == EINTR))
7267 fd = open("/dev/null", O_RDWR);