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];
174 int semihosting_enabled = 0;
177 /***********************************************************/
178 /* x86 ISA bus support */
180 target_phys_addr_t isa_mem_base = 0;
183 uint32_t default_ioport_readb(void *opaque, uint32_t address)
185 #ifdef DEBUG_UNUSED_IOPORT
186 fprintf(stderr, "inb: port=0x%04x\n", address);
191 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
193 #ifdef DEBUG_UNUSED_IOPORT
194 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
198 /* default is to make two byte accesses */
199 uint32_t default_ioport_readw(void *opaque, uint32_t address)
202 data = ioport_read_table[0][address](ioport_opaque[address], address);
203 address = (address + 1) & (MAX_IOPORTS - 1);
204 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
208 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
210 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
211 address = (address + 1) & (MAX_IOPORTS - 1);
212 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
215 uint32_t default_ioport_readl(void *opaque, uint32_t address)
217 #ifdef DEBUG_UNUSED_IOPORT
218 fprintf(stderr, "inl: port=0x%04x\n", address);
223 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
225 #ifdef DEBUG_UNUSED_IOPORT
226 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
230 void init_ioports(void)
234 for(i = 0; i < MAX_IOPORTS; i++) {
235 ioport_read_table[0][i] = default_ioport_readb;
236 ioport_write_table[0][i] = default_ioport_writeb;
237 ioport_read_table[1][i] = default_ioport_readw;
238 ioport_write_table[1][i] = default_ioport_writew;
239 ioport_read_table[2][i] = default_ioport_readl;
240 ioport_write_table[2][i] = default_ioport_writel;
244 /* size is the word size in byte */
245 int register_ioport_read(int start, int length, int size,
246 IOPortReadFunc *func, void *opaque)
252 } else if (size == 2) {
254 } else if (size == 4) {
257 hw_error("register_ioport_read: invalid size");
260 for(i = start; i < start + length; i += size) {
261 ioport_read_table[bsize][i] = func;
262 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
263 hw_error("register_ioport_read: invalid opaque");
264 ioport_opaque[i] = opaque;
269 /* size is the word size in byte */
270 int register_ioport_write(int start, int length, int size,
271 IOPortWriteFunc *func, void *opaque)
277 } else if (size == 2) {
279 } else if (size == 4) {
282 hw_error("register_ioport_write: invalid size");
285 for(i = start; i < start + length; i += size) {
286 ioport_write_table[bsize][i] = func;
287 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
288 hw_error("register_ioport_write: invalid opaque");
289 ioport_opaque[i] = opaque;
294 void isa_unassign_ioport(int start, int length)
298 for(i = start; i < start + length; i++) {
299 ioport_read_table[0][i] = default_ioport_readb;
300 ioport_read_table[1][i] = default_ioport_readw;
301 ioport_read_table[2][i] = default_ioport_readl;
303 ioport_write_table[0][i] = default_ioport_writeb;
304 ioport_write_table[1][i] = default_ioport_writew;
305 ioport_write_table[2][i] = default_ioport_writel;
309 /***********************************************************/
311 void cpu_outb(CPUState *env, int addr, int val)
314 if (loglevel & CPU_LOG_IOPORT)
315 fprintf(logfile, "outb: %04x %02x\n", addr, val);
317 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
320 env->last_io_time = cpu_get_time_fast();
324 void cpu_outw(CPUState *env, int addr, int val)
327 if (loglevel & CPU_LOG_IOPORT)
328 fprintf(logfile, "outw: %04x %04x\n", addr, val);
330 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
333 env->last_io_time = cpu_get_time_fast();
337 void cpu_outl(CPUState *env, int addr, int val)
340 if (loglevel & CPU_LOG_IOPORT)
341 fprintf(logfile, "outl: %04x %08x\n", addr, val);
343 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
346 env->last_io_time = cpu_get_time_fast();
350 int cpu_inb(CPUState *env, int addr)
353 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "inb : %04x %02x\n", addr, val);
360 env->last_io_time = cpu_get_time_fast();
365 int cpu_inw(CPUState *env, int addr)
368 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "inw : %04x %04x\n", addr, val);
375 env->last_io_time = cpu_get_time_fast();
380 int cpu_inl(CPUState *env, int addr)
383 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inl : %04x %08x\n", addr, val);
390 env->last_io_time = cpu_get_time_fast();
395 /***********************************************************/
396 void hw_error(const char *fmt, ...)
402 fprintf(stderr, "qemu: hardware error: ");
403 vfprintf(stderr, fmt, ap);
404 fprintf(stderr, "\n");
405 for(env = first_cpu; env != NULL; env = env->next_cpu) {
406 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
408 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
410 cpu_dump_state(env, stderr, fprintf, 0);
417 /***********************************************************/
420 static QEMUPutKBDEvent *qemu_put_kbd_event;
421 static void *qemu_put_kbd_event_opaque;
422 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
423 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
425 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
427 qemu_put_kbd_event_opaque = opaque;
428 qemu_put_kbd_event = func;
431 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
432 void *opaque, int absolute,
435 QEMUPutMouseEntry *s, *cursor;
437 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
441 s->qemu_put_mouse_event = func;
442 s->qemu_put_mouse_event_opaque = opaque;
443 s->qemu_put_mouse_event_absolute = absolute;
444 s->qemu_put_mouse_event_name = qemu_strdup(name);
447 if (!qemu_put_mouse_event_head) {
448 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
452 cursor = qemu_put_mouse_event_head;
453 while (cursor->next != NULL)
454 cursor = cursor->next;
457 qemu_put_mouse_event_current = s;
462 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
464 QEMUPutMouseEntry *prev = NULL, *cursor;
466 if (!qemu_put_mouse_event_head || entry == NULL)
469 cursor = qemu_put_mouse_event_head;
470 while (cursor != NULL && cursor != entry) {
472 cursor = cursor->next;
475 if (cursor == NULL) // does not exist or list empty
477 else if (prev == NULL) { // entry is head
478 qemu_put_mouse_event_head = cursor->next;
479 if (qemu_put_mouse_event_current == entry)
480 qemu_put_mouse_event_current = cursor->next;
481 qemu_free(entry->qemu_put_mouse_event_name);
486 prev->next = entry->next;
488 if (qemu_put_mouse_event_current == entry)
489 qemu_put_mouse_event_current = prev;
491 qemu_free(entry->qemu_put_mouse_event_name);
495 void kbd_put_keycode(int keycode)
497 if (qemu_put_kbd_event) {
498 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
502 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
504 QEMUPutMouseEvent *mouse_event;
505 void *mouse_event_opaque;
507 if (!qemu_put_mouse_event_current) {
512 qemu_put_mouse_event_current->qemu_put_mouse_event;
514 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
517 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
521 int kbd_mouse_is_absolute(void)
523 if (!qemu_put_mouse_event_current)
526 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
529 void do_info_mice(void)
531 QEMUPutMouseEntry *cursor;
534 if (!qemu_put_mouse_event_head) {
535 term_printf("No mouse devices connected\n");
539 term_printf("Mouse devices available:\n");
540 cursor = qemu_put_mouse_event_head;
541 while (cursor != NULL) {
542 term_printf("%c Mouse #%d: %s\n",
543 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
544 index, cursor->qemu_put_mouse_event_name);
546 cursor = cursor->next;
550 void do_mouse_set(int index)
552 QEMUPutMouseEntry *cursor;
555 if (!qemu_put_mouse_event_head) {
556 term_printf("No mouse devices connected\n");
560 cursor = qemu_put_mouse_event_head;
561 while (cursor != NULL && index != i) {
563 cursor = cursor->next;
567 qemu_put_mouse_event_current = cursor;
569 term_printf("Mouse at given index not found\n");
572 /* compute with 96 bit intermediate result: (a*b)/c */
573 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
578 #ifdef WORDS_BIGENDIAN
588 rl = (uint64_t)u.l.low * (uint64_t)b;
589 rh = (uint64_t)u.l.high * (uint64_t)b;
592 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
596 /***********************************************************/
597 /* real time host monotonic timer */
599 #define QEMU_TIMER_BASE 1000000000LL
603 static int64_t clock_freq;
605 static void init_get_clock(void)
609 ret = QueryPerformanceFrequency(&freq);
611 fprintf(stderr, "Could not calibrate ticks\n");
614 clock_freq = freq.QuadPart;
617 static int64_t get_clock(void)
620 QueryPerformanceCounter(&ti);
621 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
626 static int use_rt_clock;
628 static void init_get_clock(void)
631 #if defined(__linux__)
634 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
641 static int64_t get_clock(void)
643 #if defined(__linux__)
646 clock_gettime(CLOCK_MONOTONIC, &ts);
647 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
651 /* XXX: using gettimeofday leads to problems if the date
652 changes, so it should be avoided. */
654 gettimeofday(&tv, NULL);
655 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
661 /***********************************************************/
662 /* guest cycle counter */
664 static int64_t cpu_ticks_prev;
665 static int64_t cpu_ticks_offset;
666 static int64_t cpu_clock_offset;
667 static int cpu_ticks_enabled;
669 /* return the host CPU cycle counter and handle stop/restart */
670 int64_t cpu_get_ticks(void)
672 if (!cpu_ticks_enabled) {
673 return cpu_ticks_offset;
676 ticks = cpu_get_real_ticks();
677 if (cpu_ticks_prev > ticks) {
678 /* Note: non increasing ticks may happen if the host uses
680 cpu_ticks_offset += cpu_ticks_prev - ticks;
682 cpu_ticks_prev = ticks;
683 return ticks + cpu_ticks_offset;
687 /* return the host CPU monotonic timer and handle stop/restart */
688 static int64_t cpu_get_clock(void)
691 if (!cpu_ticks_enabled) {
692 return cpu_clock_offset;
695 return ti + cpu_clock_offset;
699 /* enable cpu_get_ticks() */
700 void cpu_enable_ticks(void)
702 if (!cpu_ticks_enabled) {
703 cpu_ticks_offset -= cpu_get_real_ticks();
704 cpu_clock_offset -= get_clock();
705 cpu_ticks_enabled = 1;
709 /* disable cpu_get_ticks() : the clock is stopped. You must not call
710 cpu_get_ticks() after that. */
711 void cpu_disable_ticks(void)
713 if (cpu_ticks_enabled) {
714 cpu_ticks_offset = cpu_get_ticks();
715 cpu_clock_offset = cpu_get_clock();
716 cpu_ticks_enabled = 0;
720 /***********************************************************/
723 #define QEMU_TIMER_REALTIME 0
724 #define QEMU_TIMER_VIRTUAL 1
728 /* XXX: add frequency */
736 struct QEMUTimer *next;
742 static QEMUTimer *active_timers[2];
744 static MMRESULT timerID;
745 static HANDLE host_alarm = NULL;
746 static unsigned int period = 1;
748 /* frequency of the times() clock tick */
749 static int timer_freq;
752 QEMUClock *qemu_new_clock(int type)
755 clock = qemu_mallocz(sizeof(QEMUClock));
762 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
766 ts = qemu_mallocz(sizeof(QEMUTimer));
773 void qemu_free_timer(QEMUTimer *ts)
778 /* stop a timer, but do not dealloc it */
779 void qemu_del_timer(QEMUTimer *ts)
783 /* NOTE: this code must be signal safe because
784 qemu_timer_expired() can be called from a signal. */
785 pt = &active_timers[ts->clock->type];
798 /* modify the current timer so that it will be fired when current_time
799 >= expire_time. The corresponding callback will be called. */
800 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
806 /* add the timer in the sorted list */
807 /* NOTE: this code must be signal safe because
808 qemu_timer_expired() can be called from a signal. */
809 pt = &active_timers[ts->clock->type];
814 if (t->expire_time > expire_time)
818 ts->expire_time = expire_time;
823 int qemu_timer_pending(QEMUTimer *ts)
826 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
833 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
837 return (timer_head->expire_time <= current_time);
840 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
846 if (!ts || ts->expire_time > current_time)
848 /* remove timer from the list before calling the callback */
849 *ptimer_head = ts->next;
852 /* run the callback (the timer list can be modified) */
857 int64_t qemu_get_clock(QEMUClock *clock)
859 switch(clock->type) {
860 case QEMU_TIMER_REALTIME:
861 return get_clock() / 1000000;
863 case QEMU_TIMER_VIRTUAL:
864 return cpu_get_clock();
868 static void init_timers(void)
871 ticks_per_sec = QEMU_TIMER_BASE;
872 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
873 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
877 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
879 uint64_t expire_time;
881 if (qemu_timer_pending(ts)) {
882 expire_time = ts->expire_time;
886 qemu_put_be64(f, expire_time);
889 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
891 uint64_t expire_time;
893 expire_time = qemu_get_be64(f);
894 if (expire_time != -1) {
895 qemu_mod_timer(ts, expire_time);
901 static void timer_save(QEMUFile *f, void *opaque)
903 if (cpu_ticks_enabled) {
904 hw_error("cannot save state if virtual timers are running");
906 qemu_put_be64s(f, &cpu_ticks_offset);
907 qemu_put_be64s(f, &ticks_per_sec);
908 qemu_put_be64s(f, &cpu_clock_offset);
911 static int timer_load(QEMUFile *f, void *opaque, int version_id)
913 if (version_id != 1 && version_id != 2)
915 if (cpu_ticks_enabled) {
918 qemu_get_be64s(f, &cpu_ticks_offset);
919 qemu_get_be64s(f, &ticks_per_sec);
920 if (version_id == 2) {
921 qemu_get_be64s(f, &cpu_clock_offset);
927 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
928 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
930 static void host_alarm_handler(int host_signum)
934 #define DISP_FREQ 1000
936 static int64_t delta_min = INT64_MAX;
937 static int64_t delta_max, delta_cum, last_clock, delta, ti;
939 ti = qemu_get_clock(vm_clock);
940 if (last_clock != 0) {
941 delta = ti - last_clock;
942 if (delta < delta_min)
944 if (delta > delta_max)
947 if (++count == DISP_FREQ) {
948 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
949 muldiv64(delta_min, 1000000, ticks_per_sec),
950 muldiv64(delta_max, 1000000, ticks_per_sec),
951 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
952 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
954 delta_min = INT64_MAX;
962 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
963 qemu_get_clock(vm_clock)) ||
964 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
965 qemu_get_clock(rt_clock))) {
967 SetEvent(host_alarm);
969 CPUState *env = cpu_single_env;
971 /* stop the currently executing cpu because a timer occured */
972 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
974 if (env->kqemu_enabled) {
975 kqemu_cpu_interrupt(env);
984 #if defined(__linux__)
986 #define RTC_FREQ 1024
990 static int start_rtc_timer(void)
992 rtc_fd = open("/dev/rtc", O_RDONLY);
995 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
996 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
997 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
998 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1001 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1006 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1012 static int start_rtc_timer(void)
1017 #endif /* !defined(__linux__) */
1019 #endif /* !defined(_WIN32) */
1021 static void init_timer_alarm(void)
1028 ZeroMemory(&tc, sizeof(TIMECAPS));
1029 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1030 if (period < tc.wPeriodMin)
1031 period = tc.wPeriodMin;
1032 timeBeginPeriod(period);
1033 timerID = timeSetEvent(1, // interval (ms)
1034 period, // resolution
1035 host_alarm_handler, // function
1036 (DWORD)&count, // user parameter
1037 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1039 perror("failed timer alarm");
1042 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1044 perror("failed CreateEvent");
1047 qemu_add_wait_object(host_alarm, NULL, NULL);
1049 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1052 struct sigaction act;
1053 struct itimerval itv;
1055 /* get times() syscall frequency */
1056 timer_freq = sysconf(_SC_CLK_TCK);
1059 sigfillset(&act.sa_mask);
1061 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1062 act.sa_flags |= SA_ONSTACK;
1064 act.sa_handler = host_alarm_handler;
1065 sigaction(SIGALRM, &act, NULL);
1067 itv.it_interval.tv_sec = 0;
1068 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1069 itv.it_value.tv_sec = 0;
1070 itv.it_value.tv_usec = 10 * 1000;
1071 setitimer(ITIMER_REAL, &itv, NULL);
1072 /* we probe the tick duration of the kernel to inform the user if
1073 the emulated kernel requested a too high timer frequency */
1074 getitimer(ITIMER_REAL, &itv);
1076 #if defined(__linux__)
1077 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1078 have timers with 1 ms resolution. The correct solution will
1079 be to use the POSIX real time timers available in recent
1081 if (itv.it_interval.tv_usec > 1000 || 1) {
1082 /* try to use /dev/rtc to have a faster timer */
1083 if (start_rtc_timer() < 0)
1085 /* disable itimer */
1086 itv.it_interval.tv_sec = 0;
1087 itv.it_interval.tv_usec = 0;
1088 itv.it_value.tv_sec = 0;
1089 itv.it_value.tv_usec = 0;
1090 setitimer(ITIMER_REAL, &itv, NULL);
1093 sigaction(SIGIO, &act, NULL);
1094 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1095 fcntl(rtc_fd, F_SETOWN, getpid());
1097 #endif /* defined(__linux__) */
1100 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1101 PIT_FREQ) / 1000000;
1107 void quit_timers(void)
1110 timeKillEvent(timerID);
1111 timeEndPeriod(period);
1113 CloseHandle(host_alarm);
1119 /***********************************************************/
1120 /* character device */
1122 static void qemu_chr_event(CharDriverState *s, int event)
1126 s->chr_event(s->handler_opaque, event);
1129 static void qemu_chr_reset_bh(void *opaque)
1131 CharDriverState *s = opaque;
1132 qemu_chr_event(s, CHR_EVENT_RESET);
1133 qemu_bh_delete(s->bh);
1137 void qemu_chr_reset(CharDriverState *s)
1139 if (s->bh == NULL) {
1140 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1141 qemu_bh_schedule(s->bh);
1145 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1147 return s->chr_write(s, buf, len);
1150 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1154 return s->chr_ioctl(s, cmd, arg);
1157 int qemu_chr_can_read(CharDriverState *s)
1159 if (!s->chr_can_read)
1161 return s->chr_can_read(s->handler_opaque);
1164 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1166 s->chr_read(s->handler_opaque, buf, len);
1170 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1175 vsnprintf(buf, sizeof(buf), fmt, ap);
1176 qemu_chr_write(s, buf, strlen(buf));
1180 void qemu_chr_send_event(CharDriverState *s, int event)
1182 if (s->chr_send_event)
1183 s->chr_send_event(s, event);
1186 void qemu_chr_add_handlers(CharDriverState *s,
1187 IOCanRWHandler *fd_can_read,
1188 IOReadHandler *fd_read,
1189 IOEventHandler *fd_event,
1192 s->chr_can_read = fd_can_read;
1193 s->chr_read = fd_read;
1194 s->chr_event = fd_event;
1195 s->handler_opaque = opaque;
1196 if (s->chr_update_read_handler)
1197 s->chr_update_read_handler(s);
1200 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1205 static CharDriverState *qemu_chr_open_null(void)
1207 CharDriverState *chr;
1209 chr = qemu_mallocz(sizeof(CharDriverState));
1212 chr->chr_write = null_chr_write;
1218 static void socket_cleanup(void)
1223 static int socket_init(void)
1228 ret = WSAStartup(MAKEWORD(2,2), &Data);
1230 err = WSAGetLastError();
1231 fprintf(stderr, "WSAStartup: %d\n", err);
1234 atexit(socket_cleanup);
1238 static int send_all(int fd, const uint8_t *buf, int len1)
1244 ret = send(fd, buf, len, 0);
1247 errno = WSAGetLastError();
1248 if (errno != WSAEWOULDBLOCK) {
1251 } else if (ret == 0) {
1261 void socket_set_nonblock(int fd)
1263 unsigned long opt = 1;
1264 ioctlsocket(fd, FIONBIO, &opt);
1269 static int unix_write(int fd, const uint8_t *buf, int len1)
1275 ret = write(fd, buf, len);
1277 if (errno != EINTR && errno != EAGAIN)
1279 } else if (ret == 0) {
1289 static inline int send_all(int fd, const uint8_t *buf, int len1)
1291 return unix_write(fd, buf, len1);
1294 void socket_set_nonblock(int fd)
1296 fcntl(fd, F_SETFL, O_NONBLOCK);
1298 #endif /* !_WIN32 */
1307 #define STDIO_MAX_CLIENTS 2
1309 static int stdio_nb_clients;
1310 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1312 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1314 FDCharDriver *s = chr->opaque;
1315 return unix_write(s->fd_out, buf, len);
1318 static int fd_chr_read_poll(void *opaque)
1320 CharDriverState *chr = opaque;
1321 FDCharDriver *s = chr->opaque;
1323 s->max_size = qemu_chr_can_read(chr);
1327 static void fd_chr_read(void *opaque)
1329 CharDriverState *chr = opaque;
1330 FDCharDriver *s = chr->opaque;
1335 if (len > s->max_size)
1339 size = read(s->fd_in, buf, len);
1341 /* FD has been closed. Remove it from the active list. */
1342 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1346 qemu_chr_read(chr, buf, size);
1350 static void fd_chr_update_read_handler(CharDriverState *chr)
1352 FDCharDriver *s = chr->opaque;
1354 if (s->fd_in >= 0) {
1355 if (nographic && s->fd_in == 0) {
1357 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1358 fd_chr_read, NULL, chr);
1363 /* open a character device to a unix fd */
1364 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1366 CharDriverState *chr;
1369 chr = qemu_mallocz(sizeof(CharDriverState));
1372 s = qemu_mallocz(sizeof(FDCharDriver));
1380 chr->chr_write = fd_chr_write;
1381 chr->chr_update_read_handler = fd_chr_update_read_handler;
1383 qemu_chr_reset(chr);
1388 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1392 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1395 return qemu_chr_open_fd(-1, fd_out);
1398 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1401 char filename_in[256], filename_out[256];
1403 snprintf(filename_in, 256, "%s.in", filename);
1404 snprintf(filename_out, 256, "%s.out", filename);
1405 fd_in = open(filename_in, O_RDWR | O_BINARY);
1406 fd_out = open(filename_out, O_RDWR | O_BINARY);
1407 if (fd_in < 0 || fd_out < 0) {
1412 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1416 return qemu_chr_open_fd(fd_in, fd_out);
1420 /* for STDIO, we handle the case where several clients use it
1423 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1425 #define TERM_FIFO_MAX_SIZE 1
1427 static int term_got_escape, client_index;
1428 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1429 static int term_fifo_size;
1430 static int term_timestamps;
1431 static int64_t term_timestamps_start;
1433 void term_print_help(void)
1436 "C-a h print this help\n"
1437 "C-a x exit emulator\n"
1438 "C-a s save disk data back to file (if -snapshot)\n"
1439 "C-a b send break (magic sysrq)\n"
1440 "C-a t toggle console timestamps\n"
1441 "C-a c switch between console and monitor\n"
1442 "C-a C-a send C-a\n"
1446 /* called when a char is received */
1447 static void stdio_received_byte(int ch)
1449 if (term_got_escape) {
1450 term_got_escape = 0;
1461 for (i = 0; i < MAX_DISKS; i++) {
1463 bdrv_commit(bs_table[i]);
1468 if (client_index < stdio_nb_clients) {
1469 CharDriverState *chr;
1472 chr = stdio_clients[client_index];
1474 qemu_chr_event(chr, CHR_EVENT_BREAK);
1479 if (client_index >= stdio_nb_clients)
1481 if (client_index == 0) {
1482 /* send a new line in the monitor to get the prompt */
1488 term_timestamps = !term_timestamps;
1489 term_timestamps_start = -1;
1494 } else if (ch == TERM_ESCAPE) {
1495 term_got_escape = 1;
1498 if (client_index < stdio_nb_clients) {
1500 CharDriverState *chr;
1502 chr = stdio_clients[client_index];
1503 if (qemu_chr_can_read(chr) > 0) {
1505 qemu_chr_read(chr, buf, 1);
1506 } else if (term_fifo_size == 0) {
1507 term_fifo[term_fifo_size++] = ch;
1513 static int stdio_read_poll(void *opaque)
1515 CharDriverState *chr;
1517 if (client_index < stdio_nb_clients) {
1518 chr = stdio_clients[client_index];
1519 /* try to flush the queue if needed */
1520 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1521 qemu_chr_read(chr, term_fifo, 1);
1524 /* see if we can absorb more chars */
1525 if (term_fifo_size == 0)
1534 static void stdio_read(void *opaque)
1539 size = read(0, buf, 1);
1541 /* stdin has been closed. Remove it from the active list. */
1542 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1546 stdio_received_byte(buf[0]);
1549 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1551 FDCharDriver *s = chr->opaque;
1552 if (!term_timestamps) {
1553 return unix_write(s->fd_out, buf, len);
1558 for(i = 0; i < len; i++) {
1559 unix_write(s->fd_out, buf + i, 1);
1560 if (buf[i] == '\n') {
1565 if (term_timestamps_start == -1)
1566 term_timestamps_start = ti;
1567 ti -= term_timestamps_start;
1568 secs = ti / 1000000000;
1569 snprintf(buf1, sizeof(buf1),
1570 "[%02d:%02d:%02d.%03d] ",
1574 (int)((ti / 1000000) % 1000));
1575 unix_write(s->fd_out, buf1, strlen(buf1));
1582 /* init terminal so that we can grab keys */
1583 static struct termios oldtty;
1584 static int old_fd0_flags;
1586 static void term_exit(void)
1588 tcsetattr (0, TCSANOW, &oldtty);
1589 fcntl(0, F_SETFL, old_fd0_flags);
1592 static void term_init(void)
1596 tcgetattr (0, &tty);
1598 old_fd0_flags = fcntl(0, F_GETFL);
1600 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1601 |INLCR|IGNCR|ICRNL|IXON);
1602 tty.c_oflag |= OPOST;
1603 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1604 /* if graphical mode, we allow Ctrl-C handling */
1606 tty.c_lflag &= ~ISIG;
1607 tty.c_cflag &= ~(CSIZE|PARENB);
1610 tty.c_cc[VTIME] = 0;
1612 tcsetattr (0, TCSANOW, &tty);
1616 fcntl(0, F_SETFL, O_NONBLOCK);
1619 static CharDriverState *qemu_chr_open_stdio(void)
1621 CharDriverState *chr;
1624 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1626 chr = qemu_chr_open_fd(0, 1);
1627 chr->chr_write = stdio_write;
1628 if (stdio_nb_clients == 0)
1629 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1630 client_index = stdio_nb_clients;
1632 if (stdio_nb_clients != 0)
1634 chr = qemu_chr_open_fd(0, 1);
1636 stdio_clients[stdio_nb_clients++] = chr;
1637 if (stdio_nb_clients == 1) {
1638 /* set the terminal in raw mode */
1644 #if defined(__linux__)
1645 static CharDriverState *qemu_chr_open_pty(void)
1648 char slave_name[1024];
1649 int master_fd, slave_fd;
1651 /* Not satisfying */
1652 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1656 /* Disabling local echo and line-buffered output */
1657 tcgetattr (master_fd, &tty);
1658 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1660 tty.c_cc[VTIME] = 0;
1661 tcsetattr (master_fd, TCSAFLUSH, &tty);
1663 fprintf(stderr, "char device redirected to %s\n", slave_name);
1664 return qemu_chr_open_fd(master_fd, master_fd);
1667 static void tty_serial_init(int fd, int speed,
1668 int parity, int data_bits, int stop_bits)
1674 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1675 speed, parity, data_bits, stop_bits);
1677 tcgetattr (fd, &tty);
1719 cfsetispeed(&tty, spd);
1720 cfsetospeed(&tty, spd);
1722 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1723 |INLCR|IGNCR|ICRNL|IXON);
1724 tty.c_oflag |= OPOST;
1725 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1726 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1747 tty.c_cflag |= PARENB;
1750 tty.c_cflag |= PARENB | PARODD;
1754 tty.c_cflag |= CSTOPB;
1756 tcsetattr (fd, TCSANOW, &tty);
1759 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1761 FDCharDriver *s = chr->opaque;
1764 case CHR_IOCTL_SERIAL_SET_PARAMS:
1766 QEMUSerialSetParams *ssp = arg;
1767 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1768 ssp->data_bits, ssp->stop_bits);
1771 case CHR_IOCTL_SERIAL_SET_BREAK:
1773 int enable = *(int *)arg;
1775 tcsendbreak(s->fd_in, 1);
1784 static CharDriverState *qemu_chr_open_tty(const char *filename)
1786 CharDriverState *chr;
1789 fd = open(filename, O_RDWR | O_NONBLOCK);
1792 fcntl(fd, F_SETFL, O_NONBLOCK);
1793 tty_serial_init(fd, 115200, 'N', 8, 1);
1794 chr = qemu_chr_open_fd(fd, fd);
1797 chr->chr_ioctl = tty_serial_ioctl;
1798 qemu_chr_reset(chr);
1802 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1804 int fd = (int)chr->opaque;
1808 case CHR_IOCTL_PP_READ_DATA:
1809 if (ioctl(fd, PPRDATA, &b) < 0)
1811 *(uint8_t *)arg = b;
1813 case CHR_IOCTL_PP_WRITE_DATA:
1814 b = *(uint8_t *)arg;
1815 if (ioctl(fd, PPWDATA, &b) < 0)
1818 case CHR_IOCTL_PP_READ_CONTROL:
1819 if (ioctl(fd, PPRCONTROL, &b) < 0)
1821 *(uint8_t *)arg = b;
1823 case CHR_IOCTL_PP_WRITE_CONTROL:
1824 b = *(uint8_t *)arg;
1825 if (ioctl(fd, PPWCONTROL, &b) < 0)
1828 case CHR_IOCTL_PP_READ_STATUS:
1829 if (ioctl(fd, PPRSTATUS, &b) < 0)
1831 *(uint8_t *)arg = b;
1839 static CharDriverState *qemu_chr_open_pp(const char *filename)
1841 CharDriverState *chr;
1844 fd = open(filename, O_RDWR);
1848 if (ioctl(fd, PPCLAIM) < 0) {
1853 chr = qemu_mallocz(sizeof(CharDriverState));
1858 chr->opaque = (void *)fd;
1859 chr->chr_write = null_chr_write;
1860 chr->chr_ioctl = pp_ioctl;
1862 qemu_chr_reset(chr);
1868 static CharDriverState *qemu_chr_open_pty(void)
1874 #endif /* !defined(_WIN32) */
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 = qemu_chr_can_read(s->chr);
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 qemu_chr_read(s->chr, 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 CharDriverState *qemu_chr_open_win(const char *filename)
2074 CharDriverState *chr;
2077 chr = qemu_mallocz(sizeof(CharDriverState));
2080 s = qemu_mallocz(sizeof(WinCharState));
2086 chr->chr_write = win_chr_write;
2087 chr->chr_close = win_chr_close;
2089 if (win_chr_init(s, filename) < 0) {
2094 qemu_chr_reset(chr);
2098 static int win_chr_pipe_poll(void *opaque)
2100 WinCharState *s = opaque;
2103 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2106 win_chr_read_poll(s);
2113 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2122 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2124 fprintf(stderr, "Failed CreateEvent\n");
2127 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2129 fprintf(stderr, "Failed CreateEvent\n");
2133 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2134 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2135 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2137 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2138 if (s->hcom == INVALID_HANDLE_VALUE) {
2139 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2144 ZeroMemory(&ov, sizeof(ov));
2145 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2146 ret = ConnectNamedPipe(s->hcom, &ov);
2148 fprintf(stderr, "Failed ConnectNamedPipe\n");
2152 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2154 fprintf(stderr, "Failed GetOverlappedResult\n");
2156 CloseHandle(ov.hEvent);
2163 CloseHandle(ov.hEvent);
2166 qemu_add_polling_cb(win_chr_pipe_poll, s);
2175 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2177 CharDriverState *chr;
2180 chr = qemu_mallocz(sizeof(CharDriverState));
2183 s = qemu_mallocz(sizeof(WinCharState));
2189 chr->chr_write = win_chr_write;
2190 chr->chr_close = win_chr_close;
2192 if (win_chr_pipe_init(s, filename) < 0) {
2197 qemu_chr_reset(chr);
2201 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2203 CharDriverState *chr;
2206 chr = qemu_mallocz(sizeof(CharDriverState));
2209 s = qemu_mallocz(sizeof(WinCharState));
2216 chr->chr_write = win_chr_write;
2217 qemu_chr_reset(chr);
2221 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2225 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2226 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2227 if (fd_out == INVALID_HANDLE_VALUE)
2230 return qemu_chr_open_win_file(fd_out);
2234 /***********************************************************/
2235 /* UDP Net console */
2239 struct sockaddr_in daddr;
2246 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2248 NetCharDriver *s = chr->opaque;
2250 return sendto(s->fd, buf, len, 0,
2251 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2254 static int udp_chr_read_poll(void *opaque)
2256 CharDriverState *chr = opaque;
2257 NetCharDriver *s = chr->opaque;
2259 s->max_size = qemu_chr_can_read(chr);
2261 /* If there were any stray characters in the queue process them
2264 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2265 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2267 s->max_size = qemu_chr_can_read(chr);
2272 static void udp_chr_read(void *opaque)
2274 CharDriverState *chr = opaque;
2275 NetCharDriver *s = chr->opaque;
2277 if (s->max_size == 0)
2279 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2280 s->bufptr = s->bufcnt;
2285 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2286 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2288 s->max_size = qemu_chr_can_read(chr);
2292 static void udp_chr_update_read_handler(CharDriverState *chr)
2294 NetCharDriver *s = chr->opaque;
2297 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2298 udp_chr_read, NULL, chr);
2302 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2304 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2306 int parse_host_src_port(struct sockaddr_in *haddr,
2307 struct sockaddr_in *saddr,
2310 static CharDriverState *qemu_chr_open_udp(const char *def)
2312 CharDriverState *chr = NULL;
2313 NetCharDriver *s = NULL;
2315 struct sockaddr_in saddr;
2317 chr = qemu_mallocz(sizeof(CharDriverState));
2320 s = qemu_mallocz(sizeof(NetCharDriver));
2324 fd = socket(PF_INET, SOCK_DGRAM, 0);
2326 perror("socket(PF_INET, SOCK_DGRAM)");
2330 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2331 printf("Could not parse: %s\n", def);
2335 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2345 chr->chr_write = udp_chr_write;
2346 chr->chr_update_read_handler = udp_chr_update_read_handler;
2359 /***********************************************************/
2360 /* TCP Net console */
2371 static void tcp_chr_accept(void *opaque);
2373 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2375 TCPCharDriver *s = chr->opaque;
2377 return send_all(s->fd, buf, len);
2379 /* XXX: indicate an error ? */
2384 static int tcp_chr_read_poll(void *opaque)
2386 CharDriverState *chr = opaque;
2387 TCPCharDriver *s = chr->opaque;
2390 s->max_size = qemu_chr_can_read(chr);
2395 #define IAC_BREAK 243
2396 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2398 char *buf, int *size)
2400 /* Handle any telnet client's basic IAC options to satisfy char by
2401 * char mode with no echo. All IAC options will be removed from
2402 * the buf and the do_telnetopt variable will be used to track the
2403 * state of the width of the IAC information.
2405 * IAC commands come in sets of 3 bytes with the exception of the
2406 * "IAC BREAK" command and the double IAC.
2412 for (i = 0; i < *size; i++) {
2413 if (s->do_telnetopt > 1) {
2414 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2415 /* Double IAC means send an IAC */
2419 s->do_telnetopt = 1;
2421 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2422 /* Handle IAC break commands by sending a serial break */
2423 qemu_chr_event(chr, CHR_EVENT_BREAK);
2428 if (s->do_telnetopt >= 4) {
2429 s->do_telnetopt = 1;
2432 if ((unsigned char)buf[i] == IAC) {
2433 s->do_telnetopt = 2;
2444 static void tcp_chr_read(void *opaque)
2446 CharDriverState *chr = opaque;
2447 TCPCharDriver *s = chr->opaque;
2451 if (!s->connected || s->max_size <= 0)
2454 if (len > s->max_size)
2456 size = recv(s->fd, buf, len, 0);
2458 /* connection closed */
2460 if (s->listen_fd >= 0) {
2461 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2463 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2466 } else if (size > 0) {
2467 if (s->do_telnetopt)
2468 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2470 qemu_chr_read(chr, buf, size);
2474 static void tcp_chr_connect(void *opaque)
2476 CharDriverState *chr = opaque;
2477 TCPCharDriver *s = chr->opaque;
2480 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2481 tcp_chr_read, NULL, chr);
2482 qemu_chr_reset(chr);
2485 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2486 static void tcp_chr_telnet_init(int fd)
2489 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2490 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2491 send(fd, (char *)buf, 3, 0);
2492 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2493 send(fd, (char *)buf, 3, 0);
2494 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2495 send(fd, (char *)buf, 3, 0);
2496 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2497 send(fd, (char *)buf, 3, 0);
2500 static void socket_set_nodelay(int fd)
2503 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2506 static void tcp_chr_accept(void *opaque)
2508 CharDriverState *chr = opaque;
2509 TCPCharDriver *s = chr->opaque;
2510 struct sockaddr_in saddr;
2512 struct sockaddr_un uaddr;
2514 struct sockaddr *addr;
2521 len = sizeof(uaddr);
2522 addr = (struct sockaddr *)&uaddr;
2526 len = sizeof(saddr);
2527 addr = (struct sockaddr *)&saddr;
2529 fd = accept(s->listen_fd, addr, &len);
2530 if (fd < 0 && errno != EINTR) {
2532 } else if (fd >= 0) {
2533 if (s->do_telnetopt)
2534 tcp_chr_telnet_init(fd);
2538 socket_set_nonblock(fd);
2540 socket_set_nodelay(fd);
2542 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2543 tcp_chr_connect(chr);
2546 static void tcp_chr_close(CharDriverState *chr)
2548 TCPCharDriver *s = chr->opaque;
2551 if (s->listen_fd >= 0)
2552 closesocket(s->listen_fd);
2556 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2560 CharDriverState *chr = NULL;
2561 TCPCharDriver *s = NULL;
2562 int fd = -1, ret, err, val;
2564 int is_waitconnect = 1;
2567 struct sockaddr_in saddr;
2569 struct sockaddr_un uaddr;
2571 struct sockaddr *addr;
2576 addr = (struct sockaddr *)&uaddr;
2577 addrlen = sizeof(uaddr);
2578 if (parse_unix_path(&uaddr, host_str) < 0)
2583 addr = (struct sockaddr *)&saddr;
2584 addrlen = sizeof(saddr);
2585 if (parse_host_port(&saddr, host_str) < 0)
2590 while((ptr = strchr(ptr,','))) {
2592 if (!strncmp(ptr,"server",6)) {
2594 } else if (!strncmp(ptr,"nowait",6)) {
2596 } else if (!strncmp(ptr,"nodelay",6)) {
2599 printf("Unknown option: %s\n", ptr);
2606 chr = qemu_mallocz(sizeof(CharDriverState));
2609 s = qemu_mallocz(sizeof(TCPCharDriver));
2615 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2618 fd = socket(PF_INET, SOCK_STREAM, 0);
2623 if (!is_waitconnect)
2624 socket_set_nonblock(fd);
2629 s->is_unix = is_unix;
2630 s->do_nodelay = do_nodelay && !is_unix;
2633 chr->chr_write = tcp_chr_write;
2634 chr->chr_close = tcp_chr_close;
2637 /* allow fast reuse */
2641 strncpy(path, uaddr.sun_path, 108);
2648 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2651 ret = bind(fd, addr, addrlen);
2655 ret = listen(fd, 0);
2660 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2662 s->do_telnetopt = 1;
2665 ret = connect(fd, addr, addrlen);
2667 err = socket_error();
2668 if (err == EINTR || err == EWOULDBLOCK) {
2669 } else if (err == EINPROGRESS) {
2680 socket_set_nodelay(fd);
2682 tcp_chr_connect(chr);
2684 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2687 if (is_listen && is_waitconnect) {
2688 printf("QEMU waiting for connection on: %s\n", host_str);
2689 tcp_chr_accept(chr);
2690 socket_set_nonblock(s->listen_fd);
2702 CharDriverState *qemu_chr_open(const char *filename)
2706 if (!strcmp(filename, "vc")) {
2707 return text_console_init(&display_state);
2708 } else if (!strcmp(filename, "null")) {
2709 return qemu_chr_open_null();
2711 if (strstart(filename, "tcp:", &p)) {
2712 return qemu_chr_open_tcp(p, 0, 0);
2714 if (strstart(filename, "telnet:", &p)) {
2715 return qemu_chr_open_tcp(p, 1, 0);
2717 if (strstart(filename, "udp:", &p)) {
2718 return qemu_chr_open_udp(p);
2721 if (strstart(filename, "unix:", &p)) {
2722 return qemu_chr_open_tcp(p, 0, 1);
2723 } else if (strstart(filename, "file:", &p)) {
2724 return qemu_chr_open_file_out(p);
2725 } else if (strstart(filename, "pipe:", &p)) {
2726 return qemu_chr_open_pipe(p);
2727 } else if (!strcmp(filename, "pty")) {
2728 return qemu_chr_open_pty();
2729 } else if (!strcmp(filename, "stdio")) {
2730 return qemu_chr_open_stdio();
2733 #if defined(__linux__)
2734 if (strstart(filename, "/dev/parport", NULL)) {
2735 return qemu_chr_open_pp(filename);
2737 if (strstart(filename, "/dev/", NULL)) {
2738 return qemu_chr_open_tty(filename);
2742 if (strstart(filename, "COM", NULL)) {
2743 return qemu_chr_open_win(filename);
2745 if (strstart(filename, "pipe:", &p)) {
2746 return qemu_chr_open_win_pipe(p);
2748 if (strstart(filename, "file:", &p)) {
2749 return qemu_chr_open_win_file_out(p);
2757 void qemu_chr_close(CharDriverState *chr)
2760 chr->chr_close(chr);
2763 /***********************************************************/
2764 /* network device redirectors */
2766 void hex_dump(FILE *f, const uint8_t *buf, int size)
2770 for(i=0;i<size;i+=16) {
2774 fprintf(f, "%08x ", i);
2777 fprintf(f, " %02x", buf[i+j]);
2782 for(j=0;j<len;j++) {
2784 if (c < ' ' || c > '~')
2786 fprintf(f, "%c", c);
2792 static int parse_macaddr(uint8_t *macaddr, const char *p)
2795 for(i = 0; i < 6; i++) {
2796 macaddr[i] = strtol(p, (char **)&p, 16);
2809 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2814 p1 = strchr(p, sep);
2820 if (len > buf_size - 1)
2822 memcpy(buf, p, len);
2829 int parse_host_src_port(struct sockaddr_in *haddr,
2830 struct sockaddr_in *saddr,
2831 const char *input_str)
2833 char *str = strdup(input_str);
2834 char *host_str = str;
2839 * Chop off any extra arguments at the end of the string which
2840 * would start with a comma, then fill in the src port information
2841 * if it was provided else use the "any address" and "any port".
2843 if ((ptr = strchr(str,',')))
2846 if ((src_str = strchr(input_str,'@'))) {
2851 if (parse_host_port(haddr, host_str) < 0)
2854 if (!src_str || *src_str == '\0')
2857 if (parse_host_port(saddr, src_str) < 0)
2868 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2876 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2878 saddr->sin_family = AF_INET;
2879 if (buf[0] == '\0') {
2880 saddr->sin_addr.s_addr = 0;
2882 if (isdigit(buf[0])) {
2883 if (!inet_aton(buf, &saddr->sin_addr))
2886 if ((he = gethostbyname(buf)) == NULL)
2888 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2891 port = strtol(p, (char **)&r, 0);
2894 saddr->sin_port = htons(port);
2899 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
2904 len = MIN(108, strlen(str));
2905 p = strchr(str, ',');
2907 len = MIN(len, p - str);
2909 memset(uaddr, 0, sizeof(*uaddr));
2911 uaddr->sun_family = AF_UNIX;
2912 memcpy(uaddr->sun_path, str, len);
2918 /* find or alloc a new VLAN */
2919 VLANState *qemu_find_vlan(int id)
2921 VLANState **pvlan, *vlan;
2922 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2926 vlan = qemu_mallocz(sizeof(VLANState));
2931 pvlan = &first_vlan;
2932 while (*pvlan != NULL)
2933 pvlan = &(*pvlan)->next;
2938 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2939 IOReadHandler *fd_read,
2940 IOCanRWHandler *fd_can_read,
2943 VLANClientState *vc, **pvc;
2944 vc = qemu_mallocz(sizeof(VLANClientState));
2947 vc->fd_read = fd_read;
2948 vc->fd_can_read = fd_can_read;
2949 vc->opaque = opaque;
2953 pvc = &vlan->first_client;
2954 while (*pvc != NULL)
2955 pvc = &(*pvc)->next;
2960 int qemu_can_send_packet(VLANClientState *vc1)
2962 VLANState *vlan = vc1->vlan;
2963 VLANClientState *vc;
2965 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2967 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2974 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2976 VLANState *vlan = vc1->vlan;
2977 VLANClientState *vc;
2980 printf("vlan %d send:\n", vlan->id);
2981 hex_dump(stdout, buf, size);
2983 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2985 vc->fd_read(vc->opaque, buf, size);
2990 #if defined(CONFIG_SLIRP)
2992 /* slirp network adapter */
2994 static int slirp_inited;
2995 static VLANClientState *slirp_vc;
2997 int slirp_can_output(void)
2999 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3002 void slirp_output(const uint8_t *pkt, int pkt_len)
3005 printf("slirp output:\n");
3006 hex_dump(stdout, pkt, pkt_len);
3010 qemu_send_packet(slirp_vc, pkt, pkt_len);
3013 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3016 printf("slirp input:\n");
3017 hex_dump(stdout, buf, size);
3019 slirp_input(buf, size);
3022 static int net_slirp_init(VLANState *vlan)
3024 if (!slirp_inited) {
3028 slirp_vc = qemu_new_vlan_client(vlan,
3029 slirp_receive, NULL, NULL);
3030 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3034 static void net_slirp_redir(const char *redir_str)
3039 struct in_addr guest_addr;
3040 int host_port, guest_port;
3042 if (!slirp_inited) {
3048 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3050 if (!strcmp(buf, "tcp")) {
3052 } else if (!strcmp(buf, "udp")) {
3058 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3060 host_port = strtol(buf, &r, 0);
3064 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3066 if (buf[0] == '\0') {
3067 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3069 if (!inet_aton(buf, &guest_addr))
3072 guest_port = strtol(p, &r, 0);
3076 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3077 fprintf(stderr, "qemu: could not set up redirection\n");
3082 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3090 static void smb_exit(void)
3094 char filename[1024];
3096 /* erase all the files in the directory */
3097 d = opendir(smb_dir);
3102 if (strcmp(de->d_name, ".") != 0 &&
3103 strcmp(de->d_name, "..") != 0) {
3104 snprintf(filename, sizeof(filename), "%s/%s",
3105 smb_dir, de->d_name);
3113 /* automatic user mode samba server configuration */
3114 void net_slirp_smb(const char *exported_dir)
3116 char smb_conf[1024];
3117 char smb_cmdline[1024];
3120 if (!slirp_inited) {
3125 /* XXX: better tmp dir construction */
3126 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3127 if (mkdir(smb_dir, 0700) < 0) {
3128 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3131 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3133 f = fopen(smb_conf, "w");
3135 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3142 "socket address=127.0.0.1\n"
3143 "pid directory=%s\n"
3144 "lock directory=%s\n"
3145 "log file=%s/log.smbd\n"
3146 "smb passwd file=%s/smbpasswd\n"
3147 "security = share\n"
3162 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3163 SMBD_COMMAND, smb_conf);
3165 slirp_add_exec(0, smb_cmdline, 4, 139);
3168 #endif /* !defined(_WIN32) */
3170 #endif /* CONFIG_SLIRP */
3172 #if !defined(_WIN32)
3174 typedef struct TAPState {
3175 VLANClientState *vc;
3179 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3181 TAPState *s = opaque;
3184 ret = write(s->fd, buf, size);
3185 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3192 static void tap_send(void *opaque)
3194 TAPState *s = opaque;
3198 size = read(s->fd, buf, sizeof(buf));
3200 qemu_send_packet(s->vc, buf, size);
3206 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3210 s = qemu_mallocz(sizeof(TAPState));
3214 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3215 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3216 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3221 static int tap_open(char *ifname, int ifname_size)
3227 fd = open("/dev/tap", O_RDWR);
3229 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3234 dev = devname(s.st_rdev, S_IFCHR);
3235 pstrcpy(ifname, ifname_size, dev);
3237 fcntl(fd, F_SETFL, O_NONBLOCK);
3240 #elif defined(__sun__)
3241 static int tap_open(char *ifname, int ifname_size)
3243 fprintf(stderr, "warning: tap_open not yet implemented\n");
3247 static int tap_open(char *ifname, int ifname_size)
3252 fd = open("/dev/net/tun", O_RDWR);
3254 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3257 memset(&ifr, 0, sizeof(ifr));
3258 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3259 if (ifname[0] != '\0')
3260 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3262 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3263 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3265 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3269 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3270 fcntl(fd, F_SETFL, O_NONBLOCK);
3275 static int net_tap_init(VLANState *vlan, const char *ifname1,
3276 const char *setup_script)
3279 int pid, status, fd;
3284 if (ifname1 != NULL)
3285 pstrcpy(ifname, sizeof(ifname), ifname1);
3288 fd = tap_open(ifname, sizeof(ifname));
3292 if (!setup_script || !strcmp(setup_script, "no"))
3294 if (setup_script[0] != '\0') {
3295 /* try to launch network init script */
3300 *parg++ = (char *)setup_script;
3303 execv(setup_script, args);
3306 while (waitpid(pid, &status, 0) != pid);
3307 if (!WIFEXITED(status) ||
3308 WEXITSTATUS(status) != 0) {
3309 fprintf(stderr, "%s: could not launch network script\n",
3315 s = net_tap_fd_init(vlan, fd);
3318 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3319 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3323 #endif /* !_WIN32 */
3325 /* network connection */
3326 typedef struct NetSocketState {
3327 VLANClientState *vc;
3329 int state; /* 0 = getting length, 1 = getting data */
3333 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3336 typedef struct NetSocketListenState {
3339 } NetSocketListenState;
3341 /* XXX: we consider we can send the whole packet without blocking */
3342 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3344 NetSocketState *s = opaque;
3348 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3349 send_all(s->fd, buf, size);
3352 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3354 NetSocketState *s = opaque;
3355 sendto(s->fd, buf, size, 0,
3356 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3359 static void net_socket_send(void *opaque)
3361 NetSocketState *s = opaque;
3366 size = recv(s->fd, buf1, sizeof(buf1), 0);
3368 err = socket_error();
3369 if (err != EWOULDBLOCK)
3371 } else if (size == 0) {
3372 /* end of connection */
3374 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3380 /* reassemble a packet from the network */
3386 memcpy(s->buf + s->index, buf, l);
3390 if (s->index == 4) {
3392 s->packet_len = ntohl(*(uint32_t *)s->buf);
3398 l = s->packet_len - s->index;
3401 memcpy(s->buf + s->index, buf, l);
3405 if (s->index >= s->packet_len) {
3406 qemu_send_packet(s->vc, s->buf, s->packet_len);
3415 static void net_socket_send_dgram(void *opaque)
3417 NetSocketState *s = opaque;
3420 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3424 /* end of connection */
3425 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3428 qemu_send_packet(s->vc, s->buf, size);
3431 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3436 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3437 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3438 inet_ntoa(mcastaddr->sin_addr),
3439 (int)ntohl(mcastaddr->sin_addr.s_addr));
3443 fd = socket(PF_INET, SOCK_DGRAM, 0);
3445 perror("socket(PF_INET, SOCK_DGRAM)");
3450 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3451 (const char *)&val, sizeof(val));
3453 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3457 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3463 /* Add host to multicast group */
3464 imr.imr_multiaddr = mcastaddr->sin_addr;
3465 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3467 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3468 (const char *)&imr, sizeof(struct ip_mreq));
3470 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3474 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3476 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3477 (const char *)&val, sizeof(val));
3479 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3483 socket_set_nonblock(fd);
3491 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3494 struct sockaddr_in saddr;
3496 socklen_t saddr_len;
3499 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3500 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3501 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3505 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3507 if (saddr.sin_addr.s_addr==0) {
3508 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3512 /* clone dgram socket */
3513 newfd = net_socket_mcast_create(&saddr);
3515 /* error already reported by net_socket_mcast_create() */
3519 /* clone newfd to fd, close newfd */
3524 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3525 fd, strerror(errno));
3530 s = qemu_mallocz(sizeof(NetSocketState));
3535 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3536 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3538 /* mcast: save bound address as dst */
3539 if (is_connected) s->dgram_dst=saddr;
3541 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3542 "socket: fd=%d (%s mcast=%s:%d)",
3543 fd, is_connected? "cloned" : "",
3544 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3548 static void net_socket_connect(void *opaque)
3550 NetSocketState *s = opaque;
3551 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3554 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3558 s = qemu_mallocz(sizeof(NetSocketState));
3562 s->vc = qemu_new_vlan_client(vlan,
3563 net_socket_receive, NULL, s);
3564 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3565 "socket: fd=%d", fd);
3567 net_socket_connect(s);
3569 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3574 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3577 int so_type=-1, optlen=sizeof(so_type);
3579 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3580 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3585 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3587 return net_socket_fd_init_stream(vlan, fd, is_connected);
3589 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3590 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3591 return net_socket_fd_init_stream(vlan, fd, is_connected);
3596 static void net_socket_accept(void *opaque)
3598 NetSocketListenState *s = opaque;
3600 struct sockaddr_in saddr;
3605 len = sizeof(saddr);
3606 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3607 if (fd < 0 && errno != EINTR) {
3609 } else if (fd >= 0) {
3613 s1 = net_socket_fd_init(s->vlan, fd, 1);
3617 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3618 "socket: connection from %s:%d",
3619 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3623 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3625 NetSocketListenState *s;
3627 struct sockaddr_in saddr;
3629 if (parse_host_port(&saddr, host_str) < 0)
3632 s = qemu_mallocz(sizeof(NetSocketListenState));
3636 fd = socket(PF_INET, SOCK_STREAM, 0);
3641 socket_set_nonblock(fd);
3643 /* allow fast reuse */
3645 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3647 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3652 ret = listen(fd, 0);
3659 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3663 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3666 int fd, connected, ret, err;
3667 struct sockaddr_in saddr;
3669 if (parse_host_port(&saddr, host_str) < 0)
3672 fd = socket(PF_INET, SOCK_STREAM, 0);
3677 socket_set_nonblock(fd);
3681 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3683 err = socket_error();
3684 if (err == EINTR || err == EWOULDBLOCK) {
3685 } else if (err == EINPROGRESS) {
3697 s = net_socket_fd_init(vlan, fd, connected);
3700 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3701 "socket: connect to %s:%d",
3702 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3706 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3710 struct sockaddr_in saddr;
3712 if (parse_host_port(&saddr, host_str) < 0)
3716 fd = net_socket_mcast_create(&saddr);
3720 s = net_socket_fd_init(vlan, fd, 0);
3724 s->dgram_dst = saddr;
3726 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3727 "socket: mcast=%s:%d",
3728 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3733 static int get_param_value(char *buf, int buf_size,
3734 const char *tag, const char *str)
3743 while (*p != '\0' && *p != '=') {
3744 if ((q - option) < sizeof(option) - 1)
3752 if (!strcmp(tag, option)) {
3754 while (*p != '\0' && *p != ',') {
3755 if ((q - buf) < buf_size - 1)
3762 while (*p != '\0' && *p != ',') {
3773 static int net_client_init(const char *str)
3784 while (*p != '\0' && *p != ',') {
3785 if ((q - device) < sizeof(device) - 1)
3793 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3794 vlan_id = strtol(buf, NULL, 0);
3796 vlan = qemu_find_vlan(vlan_id);
3798 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3801 if (!strcmp(device, "nic")) {
3805 if (nb_nics >= MAX_NICS) {
3806 fprintf(stderr, "Too Many NICs\n");
3809 nd = &nd_table[nb_nics];
3810 macaddr = nd->macaddr;
3816 macaddr[5] = 0x56 + nb_nics;
3818 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3819 if (parse_macaddr(macaddr, buf) < 0) {
3820 fprintf(stderr, "invalid syntax for ethernet address\n");
3824 if (get_param_value(buf, sizeof(buf), "model", p)) {
3825 nd->model = strdup(buf);
3831 if (!strcmp(device, "none")) {
3832 /* does nothing. It is needed to signal that no network cards
3837 if (!strcmp(device, "user")) {
3838 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3839 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3841 ret = net_slirp_init(vlan);
3845 if (!strcmp(device, "tap")) {
3847 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3848 fprintf(stderr, "tap: no interface name\n");
3851 ret = tap_win32_init(vlan, ifname);
3854 if (!strcmp(device, "tap")) {
3856 char setup_script[1024];
3858 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3859 fd = strtol(buf, NULL, 0);
3861 if (net_tap_fd_init(vlan, fd))
3864 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3867 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3868 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3870 ret = net_tap_init(vlan, ifname, setup_script);
3874 if (!strcmp(device, "socket")) {
3875 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3877 fd = strtol(buf, NULL, 0);
3879 if (net_socket_fd_init(vlan, fd, 1))
3881 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3882 ret = net_socket_listen_init(vlan, buf);
3883 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3884 ret = net_socket_connect_init(vlan, buf);
3885 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3886 ret = net_socket_mcast_init(vlan, buf);
3888 fprintf(stderr, "Unknown socket options: %s\n", p);
3893 fprintf(stderr, "Unknown network device: %s\n", device);
3897 fprintf(stderr, "Could not initialize device '%s'\n", device);
3903 void do_info_network(void)
3906 VLANClientState *vc;
3908 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3909 term_printf("VLAN %d devices:\n", vlan->id);
3910 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3911 term_printf(" %s\n", vc->info_str);
3915 /***********************************************************/
3918 static USBPort *used_usb_ports;
3919 static USBPort *free_usb_ports;
3921 /* ??? Maybe change this to register a hub to keep track of the topology. */
3922 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3923 usb_attachfn attach)
3925 port->opaque = opaque;
3926 port->index = index;
3927 port->attach = attach;
3928 port->next = free_usb_ports;
3929 free_usb_ports = port;
3932 static int usb_device_add(const char *devname)
3938 if (!free_usb_ports)
3941 if (strstart(devname, "host:", &p)) {
3942 dev = usb_host_device_open(p);
3943 } else if (!strcmp(devname, "mouse")) {
3944 dev = usb_mouse_init();
3945 } else if (!strcmp(devname, "tablet")) {
3946 dev = usb_tablet_init();
3947 } else if (strstart(devname, "disk:", &p)) {
3948 dev = usb_msd_init(p);
3955 /* Find a USB port to add the device to. */
3956 port = free_usb_ports;
3960 /* Create a new hub and chain it on. */
3961 free_usb_ports = NULL;
3962 port->next = used_usb_ports;
3963 used_usb_ports = port;
3965 hub = usb_hub_init(VM_USB_HUB_SIZE);
3966 usb_attach(port, hub);
3967 port = free_usb_ports;
3970 free_usb_ports = port->next;
3971 port->next = used_usb_ports;
3972 used_usb_ports = port;
3973 usb_attach(port, dev);
3977 static int usb_device_del(const char *devname)
3985 if (!used_usb_ports)
3988 p = strchr(devname, '.');
3991 bus_num = strtoul(devname, NULL, 0);
3992 addr = strtoul(p + 1, NULL, 0);
3996 lastp = &used_usb_ports;
3997 port = used_usb_ports;
3998 while (port && port->dev->addr != addr) {
3999 lastp = &port->next;
4007 *lastp = port->next;
4008 usb_attach(port, NULL);
4009 dev->handle_destroy(dev);
4010 port->next = free_usb_ports;
4011 free_usb_ports = port;
4015 void do_usb_add(const char *devname)
4018 ret = usb_device_add(devname);
4020 term_printf("Could not add USB device '%s'\n", devname);
4023 void do_usb_del(const char *devname)
4026 ret = usb_device_del(devname);
4028 term_printf("Could not remove USB device '%s'\n", devname);
4035 const char *speed_str;
4038 term_printf("USB support not enabled\n");
4042 for (port = used_usb_ports; port; port = port->next) {
4046 switch(dev->speed) {
4050 case USB_SPEED_FULL:
4053 case USB_SPEED_HIGH:
4060 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4061 0, dev->addr, speed_str, dev->devname);
4065 /***********************************************************/
4068 static char *pid_filename;
4070 /* Remove PID file. Called on normal exit */
4072 static void remove_pidfile(void)
4074 unlink (pid_filename);
4077 static void create_pidfile(const char *filename)
4079 struct stat pidstat;
4082 /* Try to write our PID to the named file */
4083 if (stat(filename, &pidstat) < 0) {
4084 if (errno == ENOENT) {
4085 if ((f = fopen (filename, "w")) == NULL) {
4086 perror("Opening pidfile");
4089 fprintf(f, "%d\n", getpid());
4091 pid_filename = qemu_strdup(filename);
4092 if (!pid_filename) {
4093 fprintf(stderr, "Could not save PID filename");
4096 atexit(remove_pidfile);
4099 fprintf(stderr, "%s already exists. Remove it and try again.\n",
4105 /***********************************************************/
4108 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4112 static void dumb_resize(DisplayState *ds, int w, int h)
4116 static void dumb_refresh(DisplayState *ds)
4121 void dumb_display_init(DisplayState *ds)
4126 ds->dpy_update = dumb_update;
4127 ds->dpy_resize = dumb_resize;
4128 ds->dpy_refresh = dumb_refresh;
4131 /***********************************************************/
4134 #define MAX_IO_HANDLERS 64
4136 typedef struct IOHandlerRecord {
4138 IOCanRWHandler *fd_read_poll;
4140 IOHandler *fd_write;
4142 /* temporary data */
4144 struct IOHandlerRecord *next;
4147 static IOHandlerRecord *first_io_handler;
4149 /* XXX: fd_read_poll should be suppressed, but an API change is
4150 necessary in the character devices to suppress fd_can_read(). */
4151 int qemu_set_fd_handler2(int fd,
4152 IOCanRWHandler *fd_read_poll,
4154 IOHandler *fd_write,
4157 IOHandlerRecord **pioh, *ioh;
4159 if (!fd_read && !fd_write) {
4160 pioh = &first_io_handler;
4165 if (ioh->fd == fd) {
4173 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4177 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4180 ioh->next = first_io_handler;
4181 first_io_handler = ioh;
4184 ioh->fd_read_poll = fd_read_poll;
4185 ioh->fd_read = fd_read;
4186 ioh->fd_write = fd_write;
4187 ioh->opaque = opaque;
4192 int qemu_set_fd_handler(int fd,
4194 IOHandler *fd_write,
4197 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4200 /***********************************************************/
4201 /* Polling handling */
4203 typedef struct PollingEntry {
4206 struct PollingEntry *next;
4209 static PollingEntry *first_polling_entry;
4211 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4213 PollingEntry **ppe, *pe;
4214 pe = qemu_mallocz(sizeof(PollingEntry));
4218 pe->opaque = opaque;
4219 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4224 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4226 PollingEntry **ppe, *pe;
4227 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4229 if (pe->func == func && pe->opaque == opaque) {
4238 /***********************************************************/
4239 /* Wait objects support */
4240 typedef struct WaitObjects {
4242 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4243 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4244 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4247 static WaitObjects wait_objects = {0};
4249 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4251 WaitObjects *w = &wait_objects;
4253 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4255 w->events[w->num] = handle;
4256 w->func[w->num] = func;
4257 w->opaque[w->num] = opaque;
4262 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4265 WaitObjects *w = &wait_objects;
4268 for (i = 0; i < w->num; i++) {
4269 if (w->events[i] == handle)
4272 w->events[i] = w->events[i + 1];
4273 w->func[i] = w->func[i + 1];
4274 w->opaque[i] = w->opaque[i + 1];
4282 /***********************************************************/
4283 /* savevm/loadvm support */
4285 #define IO_BUF_SIZE 32768
4289 BlockDriverState *bs;
4292 int64_t base_offset;
4293 int64_t buf_offset; /* start of buffer when writing, end of buffer
4296 int buf_size; /* 0 when writing */
4297 uint8_t buf[IO_BUF_SIZE];
4300 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4304 f = qemu_mallocz(sizeof(QEMUFile));
4307 if (!strcmp(mode, "wb")) {
4309 } else if (!strcmp(mode, "rb")) {
4314 f->outfile = fopen(filename, mode);
4326 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4330 f = qemu_mallocz(sizeof(QEMUFile));
4335 f->is_writable = is_writable;
4336 f->base_offset = offset;
4340 void qemu_fflush(QEMUFile *f)
4342 if (!f->is_writable)
4344 if (f->buf_index > 0) {
4346 fseek(f->outfile, f->buf_offset, SEEK_SET);
4347 fwrite(f->buf, 1, f->buf_index, f->outfile);
4349 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4350 f->buf, f->buf_index);
4352 f->buf_offset += f->buf_index;
4357 static void qemu_fill_buffer(QEMUFile *f)
4364 fseek(f->outfile, f->buf_offset, SEEK_SET);
4365 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4369 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4370 f->buf, IO_BUF_SIZE);
4376 f->buf_offset += len;
4379 void qemu_fclose(QEMUFile *f)
4389 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4393 l = IO_BUF_SIZE - f->buf_index;
4396 memcpy(f->buf + f->buf_index, buf, l);
4400 if (f->buf_index >= IO_BUF_SIZE)
4405 void qemu_put_byte(QEMUFile *f, int v)
4407 f->buf[f->buf_index++] = v;
4408 if (f->buf_index >= IO_BUF_SIZE)
4412 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4418 l = f->buf_size - f->buf_index;
4420 qemu_fill_buffer(f);
4421 l = f->buf_size - f->buf_index;
4427 memcpy(buf, f->buf + f->buf_index, l);
4432 return size1 - size;
4435 int qemu_get_byte(QEMUFile *f)
4437 if (f->buf_index >= f->buf_size) {
4438 qemu_fill_buffer(f);
4439 if (f->buf_index >= f->buf_size)
4442 return f->buf[f->buf_index++];
4445 int64_t qemu_ftell(QEMUFile *f)
4447 return f->buf_offset - f->buf_size + f->buf_index;
4450 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4452 if (whence == SEEK_SET) {
4454 } else if (whence == SEEK_CUR) {
4455 pos += qemu_ftell(f);
4457 /* SEEK_END not supported */
4460 if (f->is_writable) {
4462 f->buf_offset = pos;
4464 f->buf_offset = pos;
4471 void qemu_put_be16(QEMUFile *f, unsigned int v)
4473 qemu_put_byte(f, v >> 8);
4474 qemu_put_byte(f, v);
4477 void qemu_put_be32(QEMUFile *f, unsigned int v)
4479 qemu_put_byte(f, v >> 24);
4480 qemu_put_byte(f, v >> 16);
4481 qemu_put_byte(f, v >> 8);
4482 qemu_put_byte(f, v);
4485 void qemu_put_be64(QEMUFile *f, uint64_t v)
4487 qemu_put_be32(f, v >> 32);
4488 qemu_put_be32(f, v);
4491 unsigned int qemu_get_be16(QEMUFile *f)
4494 v = qemu_get_byte(f) << 8;
4495 v |= qemu_get_byte(f);
4499 unsigned int qemu_get_be32(QEMUFile *f)
4502 v = qemu_get_byte(f) << 24;
4503 v |= qemu_get_byte(f) << 16;
4504 v |= qemu_get_byte(f) << 8;
4505 v |= qemu_get_byte(f);
4509 uint64_t qemu_get_be64(QEMUFile *f)
4512 v = (uint64_t)qemu_get_be32(f) << 32;
4513 v |= qemu_get_be32(f);
4517 typedef struct SaveStateEntry {
4521 SaveStateHandler *save_state;
4522 LoadStateHandler *load_state;
4524 struct SaveStateEntry *next;
4527 static SaveStateEntry *first_se;
4529 int register_savevm(const char *idstr,
4532 SaveStateHandler *save_state,
4533 LoadStateHandler *load_state,
4536 SaveStateEntry *se, **pse;
4538 se = qemu_malloc(sizeof(SaveStateEntry));
4541 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4542 se->instance_id = instance_id;
4543 se->version_id = version_id;
4544 se->save_state = save_state;
4545 se->load_state = load_state;
4546 se->opaque = opaque;
4549 /* add at the end of list */
4551 while (*pse != NULL)
4552 pse = &(*pse)->next;
4557 #define QEMU_VM_FILE_MAGIC 0x5145564d
4558 #define QEMU_VM_FILE_VERSION 0x00000002
4560 int qemu_savevm_state(QEMUFile *f)
4564 int64_t cur_pos, len_pos, total_len_pos;
4566 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4567 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4568 total_len_pos = qemu_ftell(f);
4569 qemu_put_be64(f, 0); /* total size */
4571 for(se = first_se; se != NULL; se = se->next) {
4573 len = strlen(se->idstr);
4574 qemu_put_byte(f, len);
4575 qemu_put_buffer(f, se->idstr, len);
4577 qemu_put_be32(f, se->instance_id);
4578 qemu_put_be32(f, se->version_id);
4580 /* record size: filled later */
4581 len_pos = qemu_ftell(f);
4582 qemu_put_be32(f, 0);
4584 se->save_state(f, se->opaque);
4586 /* fill record size */
4587 cur_pos = qemu_ftell(f);
4588 len = cur_pos - len_pos - 4;
4589 qemu_fseek(f, len_pos, SEEK_SET);
4590 qemu_put_be32(f, len);
4591 qemu_fseek(f, cur_pos, SEEK_SET);
4593 cur_pos = qemu_ftell(f);
4594 qemu_fseek(f, total_len_pos, SEEK_SET);
4595 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4596 qemu_fseek(f, cur_pos, SEEK_SET);
4602 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4606 for(se = first_se; se != NULL; se = se->next) {
4607 if (!strcmp(se->idstr, idstr) &&
4608 instance_id == se->instance_id)
4614 int qemu_loadvm_state(QEMUFile *f)
4617 int len, ret, instance_id, record_len, version_id;
4618 int64_t total_len, end_pos, cur_pos;
4622 v = qemu_get_be32(f);
4623 if (v != QEMU_VM_FILE_MAGIC)
4625 v = qemu_get_be32(f);
4626 if (v != QEMU_VM_FILE_VERSION) {
4631 total_len = qemu_get_be64(f);
4632 end_pos = total_len + qemu_ftell(f);
4634 if (qemu_ftell(f) >= end_pos)
4636 len = qemu_get_byte(f);
4637 qemu_get_buffer(f, idstr, len);
4639 instance_id = qemu_get_be32(f);
4640 version_id = qemu_get_be32(f);
4641 record_len = qemu_get_be32(f);
4643 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4644 idstr, instance_id, version_id, record_len);
4646 cur_pos = qemu_ftell(f);
4647 se = find_se(idstr, instance_id);
4649 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4650 instance_id, idstr);
4652 ret = se->load_state(f, se->opaque, version_id);
4654 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4655 instance_id, idstr);
4658 /* always seek to exact end of record */
4659 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4666 /* device can contain snapshots */
4667 static int bdrv_can_snapshot(BlockDriverState *bs)
4670 !bdrv_is_removable(bs) &&
4671 !bdrv_is_read_only(bs));
4674 /* device must be snapshots in order to have a reliable snapshot */
4675 static int bdrv_has_snapshot(BlockDriverState *bs)
4678 !bdrv_is_removable(bs) &&
4679 !bdrv_is_read_only(bs));
4682 static BlockDriverState *get_bs_snapshots(void)
4684 BlockDriverState *bs;
4688 return bs_snapshots;
4689 for(i = 0; i <= MAX_DISKS; i++) {
4691 if (bdrv_can_snapshot(bs))
4700 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4703 QEMUSnapshotInfo *sn_tab, *sn;
4707 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4710 for(i = 0; i < nb_sns; i++) {
4712 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4722 void do_savevm(const char *name)
4724 BlockDriverState *bs, *bs1;
4725 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4726 int must_delete, ret, i;
4727 BlockDriverInfo bdi1, *bdi = &bdi1;
4729 int saved_vm_running;
4736 bs = get_bs_snapshots();
4738 term_printf("No block device can accept snapshots\n");
4742 /* ??? Should this occur after vm_stop? */
4745 saved_vm_running = vm_running;
4750 ret = bdrv_snapshot_find(bs, old_sn, name);
4755 memset(sn, 0, sizeof(*sn));
4757 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4758 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4761 pstrcpy(sn->name, sizeof(sn->name), name);
4764 /* fill auxiliary fields */
4767 sn->date_sec = tb.time;
4768 sn->date_nsec = tb.millitm * 1000000;
4770 gettimeofday(&tv, NULL);
4771 sn->date_sec = tv.tv_sec;
4772 sn->date_nsec = tv.tv_usec * 1000;
4774 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4776 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4777 term_printf("Device %s does not support VM state snapshots\n",
4778 bdrv_get_device_name(bs));
4782 /* save the VM state */
4783 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4785 term_printf("Could not open VM state file\n");
4788 ret = qemu_savevm_state(f);
4789 sn->vm_state_size = qemu_ftell(f);
4792 term_printf("Error %d while writing VM\n", ret);
4796 /* create the snapshots */
4798 for(i = 0; i < MAX_DISKS; i++) {
4800 if (bdrv_has_snapshot(bs1)) {
4802 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4804 term_printf("Error while deleting snapshot on '%s'\n",
4805 bdrv_get_device_name(bs1));
4808 ret = bdrv_snapshot_create(bs1, sn);
4810 term_printf("Error while creating snapshot on '%s'\n",
4811 bdrv_get_device_name(bs1));
4817 if (saved_vm_running)
4821 void do_loadvm(const char *name)
4823 BlockDriverState *bs, *bs1;
4824 BlockDriverInfo bdi1, *bdi = &bdi1;
4827 int saved_vm_running;
4829 bs = get_bs_snapshots();
4831 term_printf("No block device supports snapshots\n");
4835 /* Flush all IO requests so they don't interfere with the new state. */
4838 saved_vm_running = vm_running;
4841 for(i = 0; i <= MAX_DISKS; i++) {
4843 if (bdrv_has_snapshot(bs1)) {
4844 ret = bdrv_snapshot_goto(bs1, name);
4847 term_printf("Warning: ");
4850 term_printf("Snapshots not supported on device '%s'\n",
4851 bdrv_get_device_name(bs1));
4854 term_printf("Could not find snapshot '%s' on device '%s'\n",
4855 name, bdrv_get_device_name(bs1));
4858 term_printf("Error %d while activating snapshot on '%s'\n",
4859 ret, bdrv_get_device_name(bs1));
4862 /* fatal on snapshot block device */
4869 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4870 term_printf("Device %s does not support VM state snapshots\n",
4871 bdrv_get_device_name(bs));
4875 /* restore the VM state */
4876 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4878 term_printf("Could not open VM state file\n");
4881 ret = qemu_loadvm_state(f);
4884 term_printf("Error %d while loading VM state\n", ret);
4887 if (saved_vm_running)
4891 void do_delvm(const char *name)
4893 BlockDriverState *bs, *bs1;
4896 bs = get_bs_snapshots();
4898 term_printf("No block device supports snapshots\n");
4902 for(i = 0; i <= MAX_DISKS; i++) {
4904 if (bdrv_has_snapshot(bs1)) {
4905 ret = bdrv_snapshot_delete(bs1, name);
4907 if (ret == -ENOTSUP)
4908 term_printf("Snapshots not supported on device '%s'\n",
4909 bdrv_get_device_name(bs1));
4911 term_printf("Error %d while deleting snapshot on '%s'\n",
4912 ret, bdrv_get_device_name(bs1));
4918 void do_info_snapshots(void)
4920 BlockDriverState *bs, *bs1;
4921 QEMUSnapshotInfo *sn_tab, *sn;
4925 bs = get_bs_snapshots();
4927 term_printf("No available block device supports snapshots\n");
4930 term_printf("Snapshot devices:");
4931 for(i = 0; i <= MAX_DISKS; i++) {
4933 if (bdrv_has_snapshot(bs1)) {
4935 term_printf(" %s", bdrv_get_device_name(bs1));
4940 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4942 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4945 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4946 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4947 for(i = 0; i < nb_sns; i++) {
4949 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4954 /***********************************************************/
4955 /* cpu save/restore */
4957 #if defined(TARGET_I386)
4959 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4961 qemu_put_be32(f, dt->selector);
4962 qemu_put_betl(f, dt->base);
4963 qemu_put_be32(f, dt->limit);
4964 qemu_put_be32(f, dt->flags);
4967 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4969 dt->selector = qemu_get_be32(f);
4970 dt->base = qemu_get_betl(f);
4971 dt->limit = qemu_get_be32(f);
4972 dt->flags = qemu_get_be32(f);
4975 void cpu_save(QEMUFile *f, void *opaque)
4977 CPUState *env = opaque;
4978 uint16_t fptag, fpus, fpuc, fpregs_format;
4982 for(i = 0; i < CPU_NB_REGS; i++)
4983 qemu_put_betls(f, &env->regs[i]);
4984 qemu_put_betls(f, &env->eip);
4985 qemu_put_betls(f, &env->eflags);
4986 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4987 qemu_put_be32s(f, &hflags);
4991 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4993 for(i = 0; i < 8; i++) {
4994 fptag |= ((!env->fptags[i]) << i);
4997 qemu_put_be16s(f, &fpuc);
4998 qemu_put_be16s(f, &fpus);
4999 qemu_put_be16s(f, &fptag);
5001 #ifdef USE_X86LDOUBLE
5006 qemu_put_be16s(f, &fpregs_format);
5008 for(i = 0; i < 8; i++) {
5009 #ifdef USE_X86LDOUBLE
5013 /* we save the real CPU data (in case of MMX usage only 'mant'
5014 contains the MMX register */
5015 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5016 qemu_put_be64(f, mant);
5017 qemu_put_be16(f, exp);
5020 /* if we use doubles for float emulation, we save the doubles to
5021 avoid losing information in case of MMX usage. It can give
5022 problems if the image is restored on a CPU where long
5023 doubles are used instead. */
5024 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5028 for(i = 0; i < 6; i++)
5029 cpu_put_seg(f, &env->segs[i]);
5030 cpu_put_seg(f, &env->ldt);
5031 cpu_put_seg(f, &env->tr);
5032 cpu_put_seg(f, &env->gdt);
5033 cpu_put_seg(f, &env->idt);
5035 qemu_put_be32s(f, &env->sysenter_cs);
5036 qemu_put_be32s(f, &env->sysenter_esp);
5037 qemu_put_be32s(f, &env->sysenter_eip);
5039 qemu_put_betls(f, &env->cr[0]);
5040 qemu_put_betls(f, &env->cr[2]);
5041 qemu_put_betls(f, &env->cr[3]);
5042 qemu_put_betls(f, &env->cr[4]);
5044 for(i = 0; i < 8; i++)
5045 qemu_put_betls(f, &env->dr[i]);
5048 qemu_put_be32s(f, &env->a20_mask);
5051 qemu_put_be32s(f, &env->mxcsr);
5052 for(i = 0; i < CPU_NB_REGS; i++) {
5053 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5054 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5057 #ifdef TARGET_X86_64
5058 qemu_put_be64s(f, &env->efer);
5059 qemu_put_be64s(f, &env->star);
5060 qemu_put_be64s(f, &env->lstar);
5061 qemu_put_be64s(f, &env->cstar);
5062 qemu_put_be64s(f, &env->fmask);
5063 qemu_put_be64s(f, &env->kernelgsbase);
5065 qemu_put_be32s(f, &env->smbase);
5068 #ifdef USE_X86LDOUBLE
5069 /* XXX: add that in a FPU generic layer */
5070 union x86_longdouble {
5075 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5076 #define EXPBIAS1 1023
5077 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5078 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5080 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5084 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5085 /* exponent + sign */
5086 e = EXPD1(temp) - EXPBIAS1 + 16383;
5087 e |= SIGND1(temp) >> 16;
5092 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5094 CPUState *env = opaque;
5097 uint16_t fpus, fpuc, fptag, fpregs_format;
5099 if (version_id != 3 && version_id != 4)
5101 for(i = 0; i < CPU_NB_REGS; i++)
5102 qemu_get_betls(f, &env->regs[i]);
5103 qemu_get_betls(f, &env->eip);
5104 qemu_get_betls(f, &env->eflags);
5105 qemu_get_be32s(f, &hflags);
5107 qemu_get_be16s(f, &fpuc);
5108 qemu_get_be16s(f, &fpus);
5109 qemu_get_be16s(f, &fptag);
5110 qemu_get_be16s(f, &fpregs_format);
5112 /* NOTE: we cannot always restore the FPU state if the image come
5113 from a host with a different 'USE_X86LDOUBLE' define. We guess
5114 if we are in an MMX state to restore correctly in that case. */
5115 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5116 for(i = 0; i < 8; i++) {
5120 switch(fpregs_format) {
5122 mant = qemu_get_be64(f);
5123 exp = qemu_get_be16(f);
5124 #ifdef USE_X86LDOUBLE
5125 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5127 /* difficult case */
5129 env->fpregs[i].mmx.MMX_Q(0) = mant;
5131 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5135 mant = qemu_get_be64(f);
5136 #ifdef USE_X86LDOUBLE
5138 union x86_longdouble *p;
5139 /* difficult case */
5140 p = (void *)&env->fpregs[i];
5145 fp64_to_fp80(p, mant);
5149 env->fpregs[i].mmx.MMX_Q(0) = mant;
5158 /* XXX: restore FPU round state */
5159 env->fpstt = (fpus >> 11) & 7;
5160 env->fpus = fpus & ~0x3800;
5162 for(i = 0; i < 8; i++) {
5163 env->fptags[i] = (fptag >> i) & 1;
5166 for(i = 0; i < 6; i++)
5167 cpu_get_seg(f, &env->segs[i]);
5168 cpu_get_seg(f, &env->ldt);
5169 cpu_get_seg(f, &env->tr);
5170 cpu_get_seg(f, &env->gdt);
5171 cpu_get_seg(f, &env->idt);
5173 qemu_get_be32s(f, &env->sysenter_cs);
5174 qemu_get_be32s(f, &env->sysenter_esp);
5175 qemu_get_be32s(f, &env->sysenter_eip);
5177 qemu_get_betls(f, &env->cr[0]);
5178 qemu_get_betls(f, &env->cr[2]);
5179 qemu_get_betls(f, &env->cr[3]);
5180 qemu_get_betls(f, &env->cr[4]);
5182 for(i = 0; i < 8; i++)
5183 qemu_get_betls(f, &env->dr[i]);
5186 qemu_get_be32s(f, &env->a20_mask);
5188 qemu_get_be32s(f, &env->mxcsr);
5189 for(i = 0; i < CPU_NB_REGS; i++) {
5190 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5191 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5194 #ifdef TARGET_X86_64
5195 qemu_get_be64s(f, &env->efer);
5196 qemu_get_be64s(f, &env->star);
5197 qemu_get_be64s(f, &env->lstar);
5198 qemu_get_be64s(f, &env->cstar);
5199 qemu_get_be64s(f, &env->fmask);
5200 qemu_get_be64s(f, &env->kernelgsbase);
5202 if (version_id >= 4)
5203 qemu_get_be32s(f, &env->smbase);
5205 /* XXX: compute hflags from scratch, except for CPL and IIF */
5206 env->hflags = hflags;
5211 #elif defined(TARGET_PPC)
5212 void cpu_save(QEMUFile *f, void *opaque)
5216 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5221 #elif defined(TARGET_MIPS)
5222 void cpu_save(QEMUFile *f, void *opaque)
5226 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5231 #elif defined(TARGET_SPARC)
5232 void cpu_save(QEMUFile *f, void *opaque)
5234 CPUState *env = opaque;
5238 for(i = 0; i < 8; i++)
5239 qemu_put_betls(f, &env->gregs[i]);
5240 for(i = 0; i < NWINDOWS * 16; i++)
5241 qemu_put_betls(f, &env->regbase[i]);
5244 for(i = 0; i < TARGET_FPREGS; i++) {
5250 qemu_put_be32(f, u.i);
5253 qemu_put_betls(f, &env->pc);
5254 qemu_put_betls(f, &env->npc);
5255 qemu_put_betls(f, &env->y);
5257 qemu_put_be32(f, tmp);
5258 qemu_put_betls(f, &env->fsr);
5259 qemu_put_betls(f, &env->tbr);
5260 #ifndef TARGET_SPARC64
5261 qemu_put_be32s(f, &env->wim);
5263 for(i = 0; i < 16; i++)
5264 qemu_put_be32s(f, &env->mmuregs[i]);
5268 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5270 CPUState *env = opaque;
5274 for(i = 0; i < 8; i++)
5275 qemu_get_betls(f, &env->gregs[i]);
5276 for(i = 0; i < NWINDOWS * 16; i++)
5277 qemu_get_betls(f, &env->regbase[i]);
5280 for(i = 0; i < TARGET_FPREGS; i++) {
5285 u.i = qemu_get_be32(f);
5289 qemu_get_betls(f, &env->pc);
5290 qemu_get_betls(f, &env->npc);
5291 qemu_get_betls(f, &env->y);
5292 tmp = qemu_get_be32(f);
5293 env->cwp = 0; /* needed to ensure that the wrapping registers are
5294 correctly updated */
5296 qemu_get_betls(f, &env->fsr);
5297 qemu_get_betls(f, &env->tbr);
5298 #ifndef TARGET_SPARC64
5299 qemu_get_be32s(f, &env->wim);
5301 for(i = 0; i < 16; i++)
5302 qemu_get_be32s(f, &env->mmuregs[i]);
5308 #elif defined(TARGET_ARM)
5310 /* ??? Need to implement these. */
5311 void cpu_save(QEMUFile *f, void *opaque)
5315 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5322 #warning No CPU save/restore functions
5326 /***********************************************************/
5327 /* ram save/restore */
5329 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5333 v = qemu_get_byte(f);
5336 if (qemu_get_buffer(f, buf, len) != len)
5340 v = qemu_get_byte(f);
5341 memset(buf, v, len);
5349 static int ram_load_v1(QEMUFile *f, void *opaque)
5353 if (qemu_get_be32(f) != phys_ram_size)
5355 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5356 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5363 #define BDRV_HASH_BLOCK_SIZE 1024
5364 #define IOBUF_SIZE 4096
5365 #define RAM_CBLOCK_MAGIC 0xfabe
5367 typedef struct RamCompressState {
5370 uint8_t buf[IOBUF_SIZE];
5373 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5376 memset(s, 0, sizeof(*s));
5378 ret = deflateInit2(&s->zstream, 1,
5380 9, Z_DEFAULT_STRATEGY);
5383 s->zstream.avail_out = IOBUF_SIZE;
5384 s->zstream.next_out = s->buf;
5388 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5390 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5391 qemu_put_be16(s->f, len);
5392 qemu_put_buffer(s->f, buf, len);
5395 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5399 s->zstream.avail_in = len;
5400 s->zstream.next_in = (uint8_t *)buf;
5401 while (s->zstream.avail_in > 0) {
5402 ret = deflate(&s->zstream, Z_NO_FLUSH);
5405 if (s->zstream.avail_out == 0) {
5406 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5407 s->zstream.avail_out = IOBUF_SIZE;
5408 s->zstream.next_out = s->buf;
5414 static void ram_compress_close(RamCompressState *s)
5418 /* compress last bytes */
5420 ret = deflate(&s->zstream, Z_FINISH);
5421 if (ret == Z_OK || ret == Z_STREAM_END) {
5422 len = IOBUF_SIZE - s->zstream.avail_out;
5424 ram_put_cblock(s, s->buf, len);
5426 s->zstream.avail_out = IOBUF_SIZE;
5427 s->zstream.next_out = s->buf;
5428 if (ret == Z_STREAM_END)
5435 deflateEnd(&s->zstream);
5438 typedef struct RamDecompressState {
5441 uint8_t buf[IOBUF_SIZE];
5442 } RamDecompressState;
5444 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5447 memset(s, 0, sizeof(*s));
5449 ret = inflateInit(&s->zstream);
5455 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5459 s->zstream.avail_out = len;
5460 s->zstream.next_out = buf;
5461 while (s->zstream.avail_out > 0) {
5462 if (s->zstream.avail_in == 0) {
5463 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5465 clen = qemu_get_be16(s->f);
5466 if (clen > IOBUF_SIZE)
5468 qemu_get_buffer(s->f, s->buf, clen);
5469 s->zstream.avail_in = clen;
5470 s->zstream.next_in = s->buf;
5472 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5473 if (ret != Z_OK && ret != Z_STREAM_END) {
5480 static void ram_decompress_close(RamDecompressState *s)
5482 inflateEnd(&s->zstream);
5485 static void ram_save(QEMUFile *f, void *opaque)
5488 RamCompressState s1, *s = &s1;
5491 qemu_put_be32(f, phys_ram_size);
5492 if (ram_compress_open(s, f) < 0)
5494 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5496 if (tight_savevm_enabled) {
5500 /* find if the memory block is available on a virtual
5503 for(j = 0; j < MAX_DISKS; j++) {
5505 sector_num = bdrv_hash_find(bs_table[j],
5506 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5507 if (sector_num >= 0)
5512 goto normal_compress;
5515 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5516 ram_compress_buf(s, buf, 10);
5522 ram_compress_buf(s, buf, 1);
5523 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5526 ram_compress_close(s);
5529 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5531 RamDecompressState s1, *s = &s1;
5535 if (version_id == 1)
5536 return ram_load_v1(f, opaque);
5537 if (version_id != 2)
5539 if (qemu_get_be32(f) != phys_ram_size)
5541 if (ram_decompress_open(s, f) < 0)
5543 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5544 if (ram_decompress_buf(s, buf, 1) < 0) {
5545 fprintf(stderr, "Error while reading ram block header\n");
5549 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5550 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5559 ram_decompress_buf(s, buf + 1, 9);
5561 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5562 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5563 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5566 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5567 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5568 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5569 bs_index, sector_num);
5576 printf("Error block header\n");
5580 ram_decompress_close(s);
5584 /***********************************************************/
5585 /* bottom halves (can be seen as timers which expire ASAP) */
5594 static QEMUBH *first_bh = NULL;
5596 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5599 bh = qemu_mallocz(sizeof(QEMUBH));
5603 bh->opaque = opaque;
5607 int qemu_bh_poll(void)
5626 void qemu_bh_schedule(QEMUBH *bh)
5628 CPUState *env = cpu_single_env;
5632 bh->next = first_bh;
5635 /* stop the currently executing CPU to execute the BH ASAP */
5637 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5641 void qemu_bh_cancel(QEMUBH *bh)
5644 if (bh->scheduled) {
5647 pbh = &(*pbh)->next;
5653 void qemu_bh_delete(QEMUBH *bh)
5659 /***********************************************************/
5660 /* machine registration */
5662 QEMUMachine *first_machine = NULL;
5664 int qemu_register_machine(QEMUMachine *m)
5667 pm = &first_machine;
5675 QEMUMachine *find_machine(const char *name)
5679 for(m = first_machine; m != NULL; m = m->next) {
5680 if (!strcmp(m->name, name))
5686 /***********************************************************/
5687 /* main execution loop */
5689 void gui_update(void *opaque)
5691 display_state.dpy_refresh(&display_state);
5692 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5695 struct vm_change_state_entry {
5696 VMChangeStateHandler *cb;
5698 LIST_ENTRY (vm_change_state_entry) entries;
5701 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5703 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5706 VMChangeStateEntry *e;
5708 e = qemu_mallocz(sizeof (*e));
5714 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5718 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5720 LIST_REMOVE (e, entries);
5724 static void vm_state_notify(int running)
5726 VMChangeStateEntry *e;
5728 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5729 e->cb(e->opaque, running);
5733 /* XXX: support several handlers */
5734 static VMStopHandler *vm_stop_cb;
5735 static void *vm_stop_opaque;
5737 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5740 vm_stop_opaque = opaque;
5744 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5758 void vm_stop(int reason)
5761 cpu_disable_ticks();
5765 vm_stop_cb(vm_stop_opaque, reason);
5772 /* reset/shutdown handler */
5774 typedef struct QEMUResetEntry {
5775 QEMUResetHandler *func;
5777 struct QEMUResetEntry *next;
5780 static QEMUResetEntry *first_reset_entry;
5781 static int reset_requested;
5782 static int shutdown_requested;
5783 static int powerdown_requested;
5785 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5787 QEMUResetEntry **pre, *re;
5789 pre = &first_reset_entry;
5790 while (*pre != NULL)
5791 pre = &(*pre)->next;
5792 re = qemu_mallocz(sizeof(QEMUResetEntry));
5794 re->opaque = opaque;
5799 static void qemu_system_reset(void)
5803 /* reset all devices */
5804 for(re = first_reset_entry; re != NULL; re = re->next) {
5805 re->func(re->opaque);
5809 void qemu_system_reset_request(void)
5812 shutdown_requested = 1;
5814 reset_requested = 1;
5817 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5820 void qemu_system_shutdown_request(void)
5822 shutdown_requested = 1;
5824 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5827 void qemu_system_powerdown_request(void)
5829 powerdown_requested = 1;
5831 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5834 void main_loop_wait(int timeout)
5836 IOHandlerRecord *ioh, *ioh_next;
5837 fd_set rfds, wfds, xfds;
5843 /* XXX: need to suppress polling by better using win32 events */
5845 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5846 ret |= pe->func(pe->opaque);
5849 if (ret == 0 && timeout > 0) {
5851 WaitObjects *w = &wait_objects;
5853 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5854 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5855 if (w->func[ret - WAIT_OBJECT_0])
5856 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5857 } else if (ret == WAIT_TIMEOUT) {
5859 err = GetLastError();
5860 fprintf(stderr, "Wait error %d %d\n", ret, err);
5864 /* poll any events */
5865 /* XXX: separate device handlers from system ones */
5870 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5872 (!ioh->fd_read_poll ||
5873 ioh->fd_read_poll(ioh->opaque) != 0)) {
5874 FD_SET(ioh->fd, &rfds);
5878 if (ioh->fd_write) {
5879 FD_SET(ioh->fd, &wfds);
5889 tv.tv_usec = timeout * 1000;
5891 #if defined(CONFIG_SLIRP)
5893 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5896 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5898 /* XXX: better handling of removal */
5899 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5900 ioh_next = ioh->next;
5901 if (FD_ISSET(ioh->fd, &rfds)) {
5902 ioh->fd_read(ioh->opaque);
5904 if (FD_ISSET(ioh->fd, &wfds)) {
5905 ioh->fd_write(ioh->opaque);
5909 #if defined(CONFIG_SLIRP)
5916 slirp_select_poll(&rfds, &wfds, &xfds);
5923 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5924 qemu_get_clock(vm_clock));
5925 /* run dma transfers, if any */
5929 /* real time timers */
5930 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5931 qemu_get_clock(rt_clock));
5934 static CPUState *cur_cpu;
5939 #ifdef CONFIG_PROFILER
5944 cur_cpu = first_cpu;
5951 env = env->next_cpu;
5954 #ifdef CONFIG_PROFILER
5955 ti = profile_getclock();
5957 ret = cpu_exec(env);
5958 #ifdef CONFIG_PROFILER
5959 qemu_time += profile_getclock() - ti;
5961 if (ret != EXCP_HALTED)
5963 /* all CPUs are halted ? */
5964 if (env == cur_cpu) {
5971 if (shutdown_requested) {
5972 ret = EXCP_INTERRUPT;
5975 if (reset_requested) {
5976 reset_requested = 0;
5977 qemu_system_reset();
5978 ret = EXCP_INTERRUPT;
5980 if (powerdown_requested) {
5981 powerdown_requested = 0;
5982 qemu_system_powerdown();
5983 ret = EXCP_INTERRUPT;
5985 if (ret == EXCP_DEBUG) {
5986 vm_stop(EXCP_DEBUG);
5988 /* if hlt instruction, we wait until the next IRQ */
5989 /* XXX: use timeout computed from timers */
5990 if (ret == EXCP_HLT)
5997 #ifdef CONFIG_PROFILER
5998 ti = profile_getclock();
6000 main_loop_wait(timeout);
6001 #ifdef CONFIG_PROFILER
6002 dev_time += profile_getclock() - ti;
6005 cpu_disable_ticks();
6011 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2006 Fabrice Bellard\n"
6012 "usage: %s [options] [disk_image]\n"
6014 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6016 "Standard options:\n"
6017 "-M machine select emulated machine (-M ? for list)\n"
6018 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6019 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6020 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6021 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6022 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6023 "-snapshot write to temporary files instead of disk image files\n"
6025 "-no-quit disable SDL window close capability\n"
6028 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6030 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6031 "-smp n set the number of CPUs to 'n' [default=1]\n"
6032 "-nographic disable graphical output and redirect serial I/Os to console\n"
6034 "-k language use keyboard layout (for example \"fr\" for French)\n"
6037 "-audio-help print list of audio drivers and their options\n"
6038 "-soundhw c1,... enable audio support\n"
6039 " and only specified sound cards (comma separated list)\n"
6040 " use -soundhw ? to get the list of supported cards\n"
6041 " use -soundhw all to enable all of them\n"
6043 "-localtime set the real time clock to local time [default=utc]\n"
6044 "-full-screen start in full screen\n"
6046 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6048 "-usb enable the USB driver (will be the default soon)\n"
6049 "-usbdevice name add the host or guest USB device 'name'\n"
6050 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6051 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6054 "Network options:\n"
6055 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6056 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6058 "-net user[,vlan=n][,hostname=host]\n"
6059 " connect the user mode network stack to VLAN 'n' and send\n"
6060 " hostname 'host' to DHCP clients\n"
6063 "-net tap[,vlan=n],ifname=name\n"
6064 " connect the host TAP network interface to VLAN 'n'\n"
6066 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6067 " connect the host TAP network interface to VLAN 'n' and use\n"
6068 " the network script 'file' (default=%s);\n"
6069 " use 'script=no' to disable script execution;\n"
6070 " use 'fd=h' to connect to an already opened TAP interface\n"
6072 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6073 " connect the vlan 'n' to another VLAN using a socket connection\n"
6074 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6075 " connect the vlan 'n' to multicast maddr and port\n"
6076 "-net none use it alone to have zero network devices; if no -net option\n"
6077 " is provided, the default is '-net nic -net user'\n"
6080 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
6082 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6084 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6085 " redirect TCP or UDP connections from host to guest [-net user]\n"
6088 "Linux boot specific:\n"
6089 "-kernel bzImage use 'bzImage' as kernel image\n"
6090 "-append cmdline use 'cmdline' as kernel command line\n"
6091 "-initrd file use 'file' as initial ram disk\n"
6093 "Debug/Expert options:\n"
6094 "-monitor dev redirect the monitor to char device 'dev'\n"
6095 "-serial dev redirect the serial port to char device 'dev'\n"
6096 "-parallel dev redirect the parallel port to char device 'dev'\n"
6097 "-pidfile file Write PID to 'file'\n"
6098 "-S freeze CPU at startup (use 'c' to start execution)\n"
6099 "-s wait gdb connection to port %d\n"
6100 "-p port change gdb connection port\n"
6101 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6102 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6103 " translation (t=none or lba) (usually qemu can guess them)\n"
6104 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6106 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6107 "-no-kqemu disable KQEMU kernel module usage\n"
6109 #ifdef USE_CODE_COPY
6110 "-no-code-copy disable code copy acceleration\n"
6113 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6114 " (default is CL-GD5446 PCI VGA)\n"
6115 "-no-acpi disable ACPI\n"
6117 "-no-reboot exit instead of rebooting\n"
6118 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6119 "-vnc display start a VNC server on display\n"
6121 "-daemonize daemonize QEMU after initializing\n"
6123 "-option-rom rom load a file, rom, into the option ROM space\n"
6125 "During emulation, the following keys are useful:\n"
6126 "ctrl-alt-f toggle full screen\n"
6127 "ctrl-alt-n switch to virtual console 'n'\n"
6128 "ctrl-alt toggle mouse and keyboard grab\n"
6130 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6135 DEFAULT_NETWORK_SCRIPT,
6137 DEFAULT_GDBSTUB_PORT,
6142 #define HAS_ARG 0x0001
6156 QEMU_OPTION_snapshot,
6158 QEMU_OPTION_no_fd_bootchk,
6161 QEMU_OPTION_nographic,
6163 QEMU_OPTION_audio_help,
6164 QEMU_OPTION_soundhw,
6182 QEMU_OPTION_no_code_copy,
6184 QEMU_OPTION_localtime,
6185 QEMU_OPTION_cirrusvga,
6187 QEMU_OPTION_std_vga,
6188 QEMU_OPTION_monitor,
6190 QEMU_OPTION_parallel,
6192 QEMU_OPTION_full_screen,
6193 QEMU_OPTION_no_quit,
6194 QEMU_OPTION_pidfile,
6195 QEMU_OPTION_no_kqemu,
6196 QEMU_OPTION_kernel_kqemu,
6197 QEMU_OPTION_win2k_hack,
6199 QEMU_OPTION_usbdevice,
6202 QEMU_OPTION_no_acpi,
6203 QEMU_OPTION_no_reboot,
6204 QEMU_OPTION_daemonize,
6205 QEMU_OPTION_option_rom,
6206 QEMU_OPTION_semihosting
6209 typedef struct QEMUOption {
6215 const QEMUOption qemu_options[] = {
6216 { "h", 0, QEMU_OPTION_h },
6217 { "help", 0, QEMU_OPTION_h },
6219 { "M", HAS_ARG, QEMU_OPTION_M },
6220 { "fda", HAS_ARG, QEMU_OPTION_fda },
6221 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6222 { "hda", HAS_ARG, QEMU_OPTION_hda },
6223 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6224 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6225 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6226 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6227 { "boot", HAS_ARG, QEMU_OPTION_boot },
6228 { "snapshot", 0, QEMU_OPTION_snapshot },
6230 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6232 { "m", HAS_ARG, QEMU_OPTION_m },
6233 { "nographic", 0, QEMU_OPTION_nographic },
6234 { "k", HAS_ARG, QEMU_OPTION_k },
6236 { "audio-help", 0, QEMU_OPTION_audio_help },
6237 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6240 { "net", HAS_ARG, QEMU_OPTION_net},
6242 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6244 { "smb", HAS_ARG, QEMU_OPTION_smb },
6246 { "redir", HAS_ARG, QEMU_OPTION_redir },
6249 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6250 { "append", HAS_ARG, QEMU_OPTION_append },
6251 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6253 { "S", 0, QEMU_OPTION_S },
6254 { "s", 0, QEMU_OPTION_s },
6255 { "p", HAS_ARG, QEMU_OPTION_p },
6256 { "d", HAS_ARG, QEMU_OPTION_d },
6257 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6258 { "L", HAS_ARG, QEMU_OPTION_L },
6259 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6261 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6262 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6264 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6265 { "g", 1, QEMU_OPTION_g },
6267 { "localtime", 0, QEMU_OPTION_localtime },
6268 { "std-vga", 0, QEMU_OPTION_std_vga },
6269 { "monitor", 1, QEMU_OPTION_monitor },
6270 { "serial", 1, QEMU_OPTION_serial },
6271 { "parallel", 1, QEMU_OPTION_parallel },
6272 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6273 { "full-screen", 0, QEMU_OPTION_full_screen },
6275 { "no-quit", 0, QEMU_OPTION_no_quit },
6277 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6278 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6279 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6280 { "smp", HAS_ARG, QEMU_OPTION_smp },
6281 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6283 /* temporary options */
6284 { "usb", 0, QEMU_OPTION_usb },
6285 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6286 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6287 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6288 { "daemonize", 0, QEMU_OPTION_daemonize },
6289 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6290 #if defined(TARGET_ARM)
6291 { "semihosting", 0, QEMU_OPTION_semihosting },
6296 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6298 /* this stack is only used during signal handling */
6299 #define SIGNAL_STACK_SIZE 32768
6301 static uint8_t *signal_stack;
6305 /* password input */
6307 static BlockDriverState *get_bdrv(int index)
6309 BlockDriverState *bs;
6312 bs = bs_table[index];
6313 } else if (index < 6) {
6314 bs = fd_table[index - 4];
6321 static void read_passwords(void)
6323 BlockDriverState *bs;
6327 for(i = 0; i < 6; i++) {
6329 if (bs && bdrv_is_encrypted(bs)) {
6330 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6331 for(j = 0; j < 3; j++) {
6332 monitor_readline("Password: ",
6333 1, password, sizeof(password));
6334 if (bdrv_set_key(bs, password) == 0)
6336 term_printf("invalid password\n");
6342 /* XXX: currently we cannot use simultaneously different CPUs */
6343 void register_machines(void)
6345 #if defined(TARGET_I386)
6346 qemu_register_machine(&pc_machine);
6347 qemu_register_machine(&isapc_machine);
6348 #elif defined(TARGET_PPC)
6349 qemu_register_machine(&heathrow_machine);
6350 qemu_register_machine(&core99_machine);
6351 qemu_register_machine(&prep_machine);
6352 #elif defined(TARGET_MIPS)
6353 qemu_register_machine(&mips_machine);
6354 qemu_register_machine(&mips_malta_machine);
6355 #elif defined(TARGET_SPARC)
6356 #ifdef TARGET_SPARC64
6357 qemu_register_machine(&sun4u_machine);
6359 qemu_register_machine(&sun4m_machine);
6361 #elif defined(TARGET_ARM)
6362 qemu_register_machine(&integratorcp926_machine);
6363 qemu_register_machine(&integratorcp1026_machine);
6364 qemu_register_machine(&versatilepb_machine);
6365 qemu_register_machine(&versatileab_machine);
6366 qemu_register_machine(&realview_machine);
6367 #elif defined(TARGET_SH4)
6368 qemu_register_machine(&shix_machine);
6370 #error unsupported CPU
6375 struct soundhw soundhw[] = {
6382 { .init_isa = pcspk_audio_init }
6387 "Creative Sound Blaster 16",
6390 { .init_isa = SB16_init }
6397 "Yamaha YMF262 (OPL3)",
6399 "Yamaha YM3812 (OPL2)",
6403 { .init_isa = Adlib_init }
6410 "Gravis Ultrasound GF1",
6413 { .init_isa = GUS_init }
6419 "ENSONIQ AudioPCI ES1370",
6422 { .init_pci = es1370_init }
6425 { NULL, NULL, 0, 0, { NULL } }
6428 static void select_soundhw (const char *optarg)
6432 if (*optarg == '?') {
6435 printf ("Valid sound card names (comma separated):\n");
6436 for (c = soundhw; c->name; ++c) {
6437 printf ("%-11s %s\n", c->name, c->descr);
6439 printf ("\n-soundhw all will enable all of the above\n");
6440 exit (*optarg != '?');
6448 if (!strcmp (optarg, "all")) {
6449 for (c = soundhw; c->name; ++c) {
6457 e = strchr (p, ',');
6458 l = !e ? strlen (p) : (size_t) (e - p);
6460 for (c = soundhw; c->name; ++c) {
6461 if (!strncmp (c->name, p, l)) {
6470 "Unknown sound card name (too big to show)\n");
6473 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6478 p += l + (e != NULL);
6482 goto show_valid_cards;
6488 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6490 exit(STATUS_CONTROL_C_EXIT);
6495 #define MAX_NET_CLIENTS 32
6497 int main(int argc, char **argv)
6499 #ifdef CONFIG_GDBSTUB
6501 char gdbstub_port_name[128];
6504 int snapshot, linux_boot;
6505 const char *initrd_filename;
6506 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6507 const char *kernel_filename, *kernel_cmdline;
6508 DisplayState *ds = &display_state;
6509 int cyls, heads, secs, translation;
6510 char net_clients[MAX_NET_CLIENTS][256];
6513 const char *r, *optarg;
6514 CharDriverState *monitor_hd;
6515 char monitor_device[128];
6516 char serial_devices[MAX_SERIAL_PORTS][128];
6517 int serial_device_index;
6518 char parallel_devices[MAX_PARALLEL_PORTS][128];
6519 int parallel_device_index;
6520 const char *loadvm = NULL;
6521 QEMUMachine *machine;
6522 char usb_devices[MAX_USB_CMDLINE][128];
6523 int usb_devices_index;
6526 LIST_INIT (&vm_change_state_head);
6529 struct sigaction act;
6530 sigfillset(&act.sa_mask);
6532 act.sa_handler = SIG_IGN;
6533 sigaction(SIGPIPE, &act, NULL);
6536 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6537 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6538 QEMU to run on a single CPU */
6543 h = GetCurrentProcess();
6544 if (GetProcessAffinityMask(h, &mask, &smask)) {
6545 for(i = 0; i < 32; i++) {
6546 if (mask & (1 << i))
6551 SetProcessAffinityMask(h, mask);
6557 register_machines();
6558 machine = first_machine;
6559 initrd_filename = NULL;
6560 for(i = 0; i < MAX_FD; i++)
6561 fd_filename[i] = NULL;
6562 for(i = 0; i < MAX_DISKS; i++)
6563 hd_filename[i] = NULL;
6564 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6565 vga_ram_size = VGA_RAM_SIZE;
6566 bios_size = BIOS_SIZE;
6567 #ifdef CONFIG_GDBSTUB
6569 sprintf(gdbstub_port_name, "%d", DEFAULT_GDBSTUB_PORT);
6573 kernel_filename = NULL;
6574 kernel_cmdline = "";
6580 cyls = heads = secs = 0;
6581 translation = BIOS_ATA_TRANSLATION_AUTO;
6582 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6584 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6585 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6586 serial_devices[i][0] = '\0';
6587 serial_device_index = 0;
6589 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6590 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6591 parallel_devices[i][0] = '\0';
6592 parallel_device_index = 0;
6594 usb_devices_index = 0;
6599 /* default mac address of the first network interface */
6607 hd_filename[0] = argv[optind++];
6609 const QEMUOption *popt;
6612 /* Treat --foo the same as -foo. */
6615 popt = qemu_options;
6618 fprintf(stderr, "%s: invalid option -- '%s'\n",
6622 if (!strcmp(popt->name, r + 1))
6626 if (popt->flags & HAS_ARG) {
6627 if (optind >= argc) {
6628 fprintf(stderr, "%s: option '%s' requires an argument\n",
6632 optarg = argv[optind++];
6637 switch(popt->index) {
6639 machine = find_machine(optarg);
6642 printf("Supported machines are:\n");
6643 for(m = first_machine; m != NULL; m = m->next) {
6644 printf("%-10s %s%s\n",
6646 m == first_machine ? " (default)" : "");
6651 case QEMU_OPTION_initrd:
6652 initrd_filename = optarg;
6654 case QEMU_OPTION_hda:
6655 case QEMU_OPTION_hdb:
6656 case QEMU_OPTION_hdc:
6657 case QEMU_OPTION_hdd:
6660 hd_index = popt->index - QEMU_OPTION_hda;
6661 hd_filename[hd_index] = optarg;
6662 if (hd_index == cdrom_index)
6666 case QEMU_OPTION_snapshot:
6669 case QEMU_OPTION_hdachs:
6673 cyls = strtol(p, (char **)&p, 0);
6674 if (cyls < 1 || cyls > 16383)
6679 heads = strtol(p, (char **)&p, 0);
6680 if (heads < 1 || heads > 16)
6685 secs = strtol(p, (char **)&p, 0);
6686 if (secs < 1 || secs > 63)
6690 if (!strcmp(p, "none"))
6691 translation = BIOS_ATA_TRANSLATION_NONE;
6692 else if (!strcmp(p, "lba"))
6693 translation = BIOS_ATA_TRANSLATION_LBA;
6694 else if (!strcmp(p, "auto"))
6695 translation = BIOS_ATA_TRANSLATION_AUTO;
6698 } else if (*p != '\0') {
6700 fprintf(stderr, "qemu: invalid physical CHS format\n");
6705 case QEMU_OPTION_nographic:
6706 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6707 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6710 case QEMU_OPTION_kernel:
6711 kernel_filename = optarg;
6713 case QEMU_OPTION_append:
6714 kernel_cmdline = optarg;
6716 case QEMU_OPTION_cdrom:
6717 if (cdrom_index >= 0) {
6718 hd_filename[cdrom_index] = optarg;
6721 case QEMU_OPTION_boot:
6722 boot_device = optarg[0];
6723 if (boot_device != 'a' &&
6724 #if defined(TARGET_SPARC) || defined(TARGET_I386)
6726 boot_device != 'n' &&
6728 boot_device != 'c' && boot_device != 'd') {
6729 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6733 case QEMU_OPTION_fda:
6734 fd_filename[0] = optarg;
6736 case QEMU_OPTION_fdb:
6737 fd_filename[1] = optarg;
6740 case QEMU_OPTION_no_fd_bootchk:
6744 case QEMU_OPTION_no_code_copy:
6745 code_copy_enabled = 0;
6747 case QEMU_OPTION_net:
6748 if (nb_net_clients >= MAX_NET_CLIENTS) {
6749 fprintf(stderr, "qemu: too many network clients\n");
6752 pstrcpy(net_clients[nb_net_clients],
6753 sizeof(net_clients[0]),
6758 case QEMU_OPTION_tftp:
6759 tftp_prefix = optarg;
6762 case QEMU_OPTION_smb:
6763 net_slirp_smb(optarg);
6766 case QEMU_OPTION_redir:
6767 net_slirp_redir(optarg);
6771 case QEMU_OPTION_audio_help:
6775 case QEMU_OPTION_soundhw:
6776 select_soundhw (optarg);
6783 ram_size = atoi(optarg) * 1024 * 1024;
6786 if (ram_size > PHYS_RAM_MAX_SIZE) {
6787 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6788 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6797 mask = cpu_str_to_log_mask(optarg);
6799 printf("Log items (comma separated):\n");
6800 for(item = cpu_log_items; item->mask != 0; item++) {
6801 printf("%-10s %s\n", item->name, item->help);
6808 #ifdef CONFIG_GDBSTUB
6813 pstrcpy(gdbstub_port_name, sizeof(gdbstub_port_name), optarg);
6823 keyboard_layout = optarg;
6825 case QEMU_OPTION_localtime:
6828 case QEMU_OPTION_cirrusvga:
6829 cirrus_vga_enabled = 1;
6831 case QEMU_OPTION_std_vga:
6832 cirrus_vga_enabled = 0;
6839 w = strtol(p, (char **)&p, 10);
6842 fprintf(stderr, "qemu: invalid resolution or depth\n");
6848 h = strtol(p, (char **)&p, 10);
6853 depth = strtol(p, (char **)&p, 10);
6854 if (depth != 8 && depth != 15 && depth != 16 &&
6855 depth != 24 && depth != 32)
6857 } else if (*p == '\0') {
6858 depth = graphic_depth;
6865 graphic_depth = depth;
6868 case QEMU_OPTION_monitor:
6869 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6871 case QEMU_OPTION_serial:
6872 if (serial_device_index >= MAX_SERIAL_PORTS) {
6873 fprintf(stderr, "qemu: too many serial ports\n");
6876 pstrcpy(serial_devices[serial_device_index],
6877 sizeof(serial_devices[0]), optarg);
6878 serial_device_index++;
6880 case QEMU_OPTION_parallel:
6881 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6882 fprintf(stderr, "qemu: too many parallel ports\n");
6885 pstrcpy(parallel_devices[parallel_device_index],
6886 sizeof(parallel_devices[0]), optarg);
6887 parallel_device_index++;
6889 case QEMU_OPTION_loadvm:
6892 case QEMU_OPTION_full_screen:
6896 case QEMU_OPTION_no_quit:
6900 case QEMU_OPTION_pidfile:
6901 create_pidfile(optarg);
6904 case QEMU_OPTION_win2k_hack:
6905 win2k_install_hack = 1;
6909 case QEMU_OPTION_no_kqemu:
6912 case QEMU_OPTION_kernel_kqemu:
6916 case QEMU_OPTION_usb:
6919 case QEMU_OPTION_usbdevice:
6921 if (usb_devices_index >= MAX_USB_CMDLINE) {
6922 fprintf(stderr, "Too many USB devices\n");
6925 pstrcpy(usb_devices[usb_devices_index],
6926 sizeof(usb_devices[usb_devices_index]),
6928 usb_devices_index++;
6930 case QEMU_OPTION_smp:
6931 smp_cpus = atoi(optarg);
6932 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6933 fprintf(stderr, "Invalid number of CPUs\n");
6937 case QEMU_OPTION_vnc:
6938 vnc_display = optarg;
6940 case QEMU_OPTION_no_acpi:
6943 case QEMU_OPTION_no_reboot:
6946 case QEMU_OPTION_daemonize:
6949 case QEMU_OPTION_option_rom:
6950 if (nb_option_roms >= MAX_OPTION_ROMS) {
6951 fprintf(stderr, "Too many option ROMs\n");
6954 option_rom[nb_option_roms] = optarg;
6957 case QEMU_OPTION_semihosting:
6958 semihosting_enabled = 1;
6965 if (daemonize && !nographic && vnc_display == NULL) {
6966 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
6973 if (pipe(fds) == -1)
6984 len = read(fds[0], &status, 1);
6985 if (len == -1 && (errno == EINTR))
6988 if (len != 1 || status != 0)
7006 signal(SIGTSTP, SIG_IGN);
7007 signal(SIGTTOU, SIG_IGN);
7008 signal(SIGTTIN, SIG_IGN);
7016 linux_boot = (kernel_filename != NULL);
7019 hd_filename[0] == '\0' &&
7020 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7021 fd_filename[0] == '\0')
7024 /* boot to floppy or the default cd if no hard disk defined yet */
7025 if (hd_filename[0] == '\0' && boot_device == 'c') {
7026 if (fd_filename[0] != '\0')
7032 setvbuf(stdout, NULL, _IOLBF, 0);
7042 /* init network clients */
7043 if (nb_net_clients == 0) {
7044 /* if no clients, we use a default config */
7045 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7047 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7052 for(i = 0;i < nb_net_clients; i++) {
7053 if (net_client_init(net_clients[i]) < 0)
7058 if (boot_device == 'n') {
7059 for (i = 0; i < nb_nics; i++) {
7060 const char *model = nd_table[i].model;
7064 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7065 if (get_image_size(buf) > 0) {
7066 option_rom[nb_option_roms] = strdup(buf);
7072 fprintf(stderr, "No valid PXE rom found for network device\n");
7075 boot_device = 'c'; /* to prevent confusion by the BIOS */
7079 /* init the memory */
7080 phys_ram_size = ram_size + vga_ram_size + bios_size;
7082 for (i = 0; i < nb_option_roms; i++) {
7083 int ret = get_image_size(option_rom[i]);
7085 fprintf(stderr, "Could not load option rom '%s'\n", option_rom[i]);
7088 phys_ram_size += ret;
7091 phys_ram_base = qemu_vmalloc(phys_ram_size);
7092 if (!phys_ram_base) {
7093 fprintf(stderr, "Could not allocate physical memory\n");
7097 /* we always create the cdrom drive, even if no disk is there */
7099 if (cdrom_index >= 0) {
7100 bs_table[cdrom_index] = bdrv_new("cdrom");
7101 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7104 /* open the virtual block devices */
7105 for(i = 0; i < MAX_DISKS; i++) {
7106 if (hd_filename[i]) {
7109 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7110 bs_table[i] = bdrv_new(buf);
7112 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7113 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7117 if (i == 0 && cyls != 0) {
7118 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7119 bdrv_set_translation_hint(bs_table[i], translation);
7124 /* we always create at least one floppy disk */
7125 fd_table[0] = bdrv_new("fda");
7126 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7128 for(i = 0; i < MAX_FD; i++) {
7129 if (fd_filename[i]) {
7132 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7133 fd_table[i] = bdrv_new(buf);
7134 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7136 if (fd_filename[i] != '\0') {
7137 if (bdrv_open(fd_table[i], fd_filename[i],
7138 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7139 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7147 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7148 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7154 dumb_display_init(ds);
7155 } else if (vnc_display != NULL) {
7156 vnc_display_init(ds, vnc_display);
7158 #if defined(CONFIG_SDL)
7159 sdl_display_init(ds, full_screen);
7160 #elif defined(CONFIG_COCOA)
7161 cocoa_display_init(ds, full_screen);
7163 dumb_display_init(ds);
7167 monitor_hd = qemu_chr_open(monitor_device);
7169 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7172 monitor_init(monitor_hd, !nographic);
7174 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7175 const char *devname = serial_devices[i];
7176 if (devname[0] != '\0' && strcmp(devname, "none")) {
7177 serial_hds[i] = qemu_chr_open(devname);
7178 if (!serial_hds[i]) {
7179 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7183 if (!strcmp(devname, "vc"))
7184 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7188 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7189 const char *devname = parallel_devices[i];
7190 if (devname[0] != '\0' && strcmp(devname, "none")) {
7191 parallel_hds[i] = qemu_chr_open(devname);
7192 if (!parallel_hds[i]) {
7193 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7197 if (!strcmp(devname, "vc"))
7198 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7202 machine->init(ram_size, vga_ram_size, boot_device,
7203 ds, fd_filename, snapshot,
7204 kernel_filename, kernel_cmdline, initrd_filename);
7206 /* init USB devices */
7208 for(i = 0; i < usb_devices_index; i++) {
7209 if (usb_device_add(usb_devices[i]) < 0) {
7210 fprintf(stderr, "Warning: could not add USB device %s\n",
7216 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7217 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7219 #ifdef CONFIG_GDBSTUB
7221 CharDriverState *chr;
7224 port = atoi(gdbstub_port_name);
7226 sprintf(gdbstub_port_name, "tcp::%d,nowait,nodelay,server", port);
7227 chr = qemu_chr_open(gdbstub_port_name);
7229 fprintf(stderr, "qemu: could not open gdbstub device '%s'\n",
7233 gdbserver_start(chr);
7240 /* XXX: simplify init */
7253 len = write(fds[1], &status, 1);
7254 if (len == -1 && (errno == EINTR))
7260 fd = open("/dev/null", O_RDWR);