4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
50 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
55 #include <linux/if_tun.h>
58 #include <linux/rtc.h>
59 #include <linux/ppdev.h>
60 #include <linux/parport.h>
63 #include <sys/ethernet.h>
64 #include <sys/sockio.h>
65 #include <arpa/inet.h>
66 #include <netinet/arp.h>
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_icmp.h> // must come after ip.h
71 #include <netinet/udp.h>
72 #include <netinet/tcp.h>
80 #if defined(CONFIG_SLIRP)
86 #include <sys/timeb.h>
88 #define getopt_long_only getopt_long
89 #define memalign(align, size) malloc(size)
92 #include "qemu_socket.h"
98 #endif /* CONFIG_SDL */
102 #define main qemu_main
103 #endif /* CONFIG_COCOA */
107 #include "exec-all.h"
109 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
111 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
113 #define SMBD_COMMAND "/usr/sbin/smbd"
116 //#define DEBUG_UNUSED_IOPORT
117 //#define DEBUG_IOPORT
119 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
122 #define DEFAULT_RAM_SIZE 144
124 #define DEFAULT_RAM_SIZE 128
127 #define GUI_REFRESH_INTERVAL 30
129 /* Max number of USB devices that can be specified on the commandline. */
130 #define MAX_USB_CMDLINE 8
132 /* XXX: use a two level table to limit memory usage */
133 #define MAX_IOPORTS 65536
135 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
136 char phys_ram_file[1024];
137 void *ioport_opaque[MAX_IOPORTS];
138 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
139 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
140 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
141 to store the VM snapshots */
142 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
143 BlockDriverState *pflash_table[MAX_PFLASH];
144 BlockDriverState *sd_bdrv;
145 BlockDriverState *mtd_bdrv;
146 /* point to the block driver where the snapshots are managed */
147 BlockDriverState *bs_snapshots;
149 static DisplayState display_state;
151 const char* keyboard_layout = NULL;
152 int64_t ticks_per_sec;
153 int boot_device = 'c';
155 int pit_min_timer_count = 0;
157 NICInfo nd_table[MAX_NICS];
160 int cirrus_vga_enabled = 1;
161 int vmsvga_enabled = 0;
163 int graphic_width = 1024;
164 int graphic_height = 768;
165 int graphic_depth = 8;
167 int graphic_width = 800;
168 int graphic_height = 600;
169 int graphic_depth = 15;
174 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
175 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
177 int win2k_install_hack = 0;
180 static VLANState *first_vlan;
182 const char *vnc_display;
183 #if defined(TARGET_SPARC)
185 #elif defined(TARGET_I386)
190 int acpi_enabled = 1;
194 int graphic_rotate = 0;
196 const char *option_rom[MAX_OPTION_ROMS];
198 int semihosting_enabled = 0;
200 const char *qemu_name;
203 unsigned int nb_prom_envs = 0;
204 const char *prom_envs[MAX_PROM_ENVS];
207 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
209 /***********************************************************/
210 /* x86 ISA bus support */
212 target_phys_addr_t isa_mem_base = 0;
215 uint32_t default_ioport_readb(void *opaque, uint32_t address)
217 #ifdef DEBUG_UNUSED_IOPORT
218 fprintf(stderr, "unused inb: port=0x%04x\n", address);
223 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
225 #ifdef DEBUG_UNUSED_IOPORT
226 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
230 /* default is to make two byte accesses */
231 uint32_t default_ioport_readw(void *opaque, uint32_t address)
234 data = ioport_read_table[0][address](ioport_opaque[address], address);
235 address = (address + 1) & (MAX_IOPORTS - 1);
236 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
240 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
242 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
243 address = (address + 1) & (MAX_IOPORTS - 1);
244 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
247 uint32_t default_ioport_readl(void *opaque, uint32_t address)
249 #ifdef DEBUG_UNUSED_IOPORT
250 fprintf(stderr, "unused inl: port=0x%04x\n", address);
255 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
257 #ifdef DEBUG_UNUSED_IOPORT
258 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
262 void init_ioports(void)
266 for(i = 0; i < MAX_IOPORTS; i++) {
267 ioport_read_table[0][i] = default_ioport_readb;
268 ioport_write_table[0][i] = default_ioport_writeb;
269 ioport_read_table[1][i] = default_ioport_readw;
270 ioport_write_table[1][i] = default_ioport_writew;
271 ioport_read_table[2][i] = default_ioport_readl;
272 ioport_write_table[2][i] = default_ioport_writel;
276 /* size is the word size in byte */
277 int register_ioport_read(int start, int length, int size,
278 IOPortReadFunc *func, void *opaque)
284 } else if (size == 2) {
286 } else if (size == 4) {
289 hw_error("register_ioport_read: invalid size");
292 for(i = start; i < start + length; i += size) {
293 ioport_read_table[bsize][i] = func;
294 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
295 hw_error("register_ioport_read: invalid opaque");
296 ioport_opaque[i] = opaque;
301 /* size is the word size in byte */
302 int register_ioport_write(int start, int length, int size,
303 IOPortWriteFunc *func, void *opaque)
309 } else if (size == 2) {
311 } else if (size == 4) {
314 hw_error("register_ioport_write: invalid size");
317 for(i = start; i < start + length; i += size) {
318 ioport_write_table[bsize][i] = func;
319 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
320 hw_error("register_ioport_write: invalid opaque");
321 ioport_opaque[i] = opaque;
326 void isa_unassign_ioport(int start, int length)
330 for(i = start; i < start + length; i++) {
331 ioport_read_table[0][i] = default_ioport_readb;
332 ioport_read_table[1][i] = default_ioport_readw;
333 ioport_read_table[2][i] = default_ioport_readl;
335 ioport_write_table[0][i] = default_ioport_writeb;
336 ioport_write_table[1][i] = default_ioport_writew;
337 ioport_write_table[2][i] = default_ioport_writel;
341 /***********************************************************/
343 void cpu_outb(CPUState *env, int addr, int val)
346 if (loglevel & CPU_LOG_IOPORT)
347 fprintf(logfile, "outb: %04x %02x\n", addr, val);
349 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
352 env->last_io_time = cpu_get_time_fast();
356 void cpu_outw(CPUState *env, int addr, int val)
359 if (loglevel & CPU_LOG_IOPORT)
360 fprintf(logfile, "outw: %04x %04x\n", addr, val);
362 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
365 env->last_io_time = cpu_get_time_fast();
369 void cpu_outl(CPUState *env, int addr, int val)
372 if (loglevel & CPU_LOG_IOPORT)
373 fprintf(logfile, "outl: %04x %08x\n", addr, val);
375 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
378 env->last_io_time = cpu_get_time_fast();
382 int cpu_inb(CPUState *env, int addr)
385 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
387 if (loglevel & CPU_LOG_IOPORT)
388 fprintf(logfile, "inb : %04x %02x\n", addr, val);
392 env->last_io_time = cpu_get_time_fast();
397 int cpu_inw(CPUState *env, int addr)
400 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "inw : %04x %04x\n", addr, val);
407 env->last_io_time = cpu_get_time_fast();
412 int cpu_inl(CPUState *env, int addr)
415 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "inl : %04x %08x\n", addr, val);
422 env->last_io_time = cpu_get_time_fast();
427 /***********************************************************/
428 void hw_error(const char *fmt, ...)
434 fprintf(stderr, "qemu: hardware error: ");
435 vfprintf(stderr, fmt, ap);
436 fprintf(stderr, "\n");
437 for(env = first_cpu; env != NULL; env = env->next_cpu) {
438 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
440 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
442 cpu_dump_state(env, stderr, fprintf, 0);
449 /***********************************************************/
452 static QEMUPutKBDEvent *qemu_put_kbd_event;
453 static void *qemu_put_kbd_event_opaque;
454 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
455 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
457 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
459 qemu_put_kbd_event_opaque = opaque;
460 qemu_put_kbd_event = func;
463 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
464 void *opaque, int absolute,
467 QEMUPutMouseEntry *s, *cursor;
469 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
473 s->qemu_put_mouse_event = func;
474 s->qemu_put_mouse_event_opaque = opaque;
475 s->qemu_put_mouse_event_absolute = absolute;
476 s->qemu_put_mouse_event_name = qemu_strdup(name);
479 if (!qemu_put_mouse_event_head) {
480 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
484 cursor = qemu_put_mouse_event_head;
485 while (cursor->next != NULL)
486 cursor = cursor->next;
489 qemu_put_mouse_event_current = s;
494 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
496 QEMUPutMouseEntry *prev = NULL, *cursor;
498 if (!qemu_put_mouse_event_head || entry == NULL)
501 cursor = qemu_put_mouse_event_head;
502 while (cursor != NULL && cursor != entry) {
504 cursor = cursor->next;
507 if (cursor == NULL) // does not exist or list empty
509 else if (prev == NULL) { // entry is head
510 qemu_put_mouse_event_head = cursor->next;
511 if (qemu_put_mouse_event_current == entry)
512 qemu_put_mouse_event_current = cursor->next;
513 qemu_free(entry->qemu_put_mouse_event_name);
518 prev->next = entry->next;
520 if (qemu_put_mouse_event_current == entry)
521 qemu_put_mouse_event_current = prev;
523 qemu_free(entry->qemu_put_mouse_event_name);
527 void kbd_put_keycode(int keycode)
529 if (qemu_put_kbd_event) {
530 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
534 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
536 QEMUPutMouseEvent *mouse_event;
537 void *mouse_event_opaque;
540 if (!qemu_put_mouse_event_current) {
545 qemu_put_mouse_event_current->qemu_put_mouse_event;
547 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
550 if (graphic_rotate) {
551 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
554 width = graphic_width;
555 mouse_event(mouse_event_opaque,
556 width - dy, dx, dz, buttons_state);
558 mouse_event(mouse_event_opaque,
559 dx, dy, dz, buttons_state);
563 int kbd_mouse_is_absolute(void)
565 if (!qemu_put_mouse_event_current)
568 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
571 void do_info_mice(void)
573 QEMUPutMouseEntry *cursor;
576 if (!qemu_put_mouse_event_head) {
577 term_printf("No mouse devices connected\n");
581 term_printf("Mouse devices available:\n");
582 cursor = qemu_put_mouse_event_head;
583 while (cursor != NULL) {
584 term_printf("%c Mouse #%d: %s\n",
585 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
586 index, cursor->qemu_put_mouse_event_name);
588 cursor = cursor->next;
592 void do_mouse_set(int index)
594 QEMUPutMouseEntry *cursor;
597 if (!qemu_put_mouse_event_head) {
598 term_printf("No mouse devices connected\n");
602 cursor = qemu_put_mouse_event_head;
603 while (cursor != NULL && index != i) {
605 cursor = cursor->next;
609 qemu_put_mouse_event_current = cursor;
611 term_printf("Mouse at given index not found\n");
614 /* compute with 96 bit intermediate result: (a*b)/c */
615 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
620 #ifdef WORDS_BIGENDIAN
630 rl = (uint64_t)u.l.low * (uint64_t)b;
631 rh = (uint64_t)u.l.high * (uint64_t)b;
634 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
638 /***********************************************************/
639 /* real time host monotonic timer */
641 #define QEMU_TIMER_BASE 1000000000LL
645 static int64_t clock_freq;
647 static void init_get_clock(void)
651 ret = QueryPerformanceFrequency(&freq);
653 fprintf(stderr, "Could not calibrate ticks\n");
656 clock_freq = freq.QuadPart;
659 static int64_t get_clock(void)
662 QueryPerformanceCounter(&ti);
663 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
668 static int use_rt_clock;
670 static void init_get_clock(void)
673 #if defined(__linux__)
676 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
683 static int64_t get_clock(void)
685 #if defined(__linux__)
688 clock_gettime(CLOCK_MONOTONIC, &ts);
689 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
693 /* XXX: using gettimeofday leads to problems if the date
694 changes, so it should be avoided. */
696 gettimeofday(&tv, NULL);
697 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
703 /***********************************************************/
704 /* guest cycle counter */
706 static int64_t cpu_ticks_prev;
707 static int64_t cpu_ticks_offset;
708 static int64_t cpu_clock_offset;
709 static int cpu_ticks_enabled;
711 /* return the host CPU cycle counter and handle stop/restart */
712 int64_t cpu_get_ticks(void)
714 if (!cpu_ticks_enabled) {
715 return cpu_ticks_offset;
718 ticks = cpu_get_real_ticks();
719 if (cpu_ticks_prev > ticks) {
720 /* Note: non increasing ticks may happen if the host uses
722 cpu_ticks_offset += cpu_ticks_prev - ticks;
724 cpu_ticks_prev = ticks;
725 return ticks + cpu_ticks_offset;
729 /* return the host CPU monotonic timer and handle stop/restart */
730 static int64_t cpu_get_clock(void)
733 if (!cpu_ticks_enabled) {
734 return cpu_clock_offset;
737 return ti + cpu_clock_offset;
741 /* enable cpu_get_ticks() */
742 void cpu_enable_ticks(void)
744 if (!cpu_ticks_enabled) {
745 cpu_ticks_offset -= cpu_get_real_ticks();
746 cpu_clock_offset -= get_clock();
747 cpu_ticks_enabled = 1;
751 /* disable cpu_get_ticks() : the clock is stopped. You must not call
752 cpu_get_ticks() after that. */
753 void cpu_disable_ticks(void)
755 if (cpu_ticks_enabled) {
756 cpu_ticks_offset = cpu_get_ticks();
757 cpu_clock_offset = cpu_get_clock();
758 cpu_ticks_enabled = 0;
762 /***********************************************************/
765 #define QEMU_TIMER_REALTIME 0
766 #define QEMU_TIMER_VIRTUAL 1
770 /* XXX: add frequency */
778 struct QEMUTimer *next;
784 static QEMUTimer *active_timers[2];
786 static MMRESULT timerID;
787 static HANDLE host_alarm = NULL;
788 static unsigned int period = 1;
790 /* frequency of the times() clock tick */
791 static int timer_freq;
794 QEMUClock *qemu_new_clock(int type)
797 clock = qemu_mallocz(sizeof(QEMUClock));
804 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
808 ts = qemu_mallocz(sizeof(QEMUTimer));
815 void qemu_free_timer(QEMUTimer *ts)
820 /* stop a timer, but do not dealloc it */
821 void qemu_del_timer(QEMUTimer *ts)
825 /* NOTE: this code must be signal safe because
826 qemu_timer_expired() can be called from a signal. */
827 pt = &active_timers[ts->clock->type];
840 /* modify the current timer so that it will be fired when current_time
841 >= expire_time. The corresponding callback will be called. */
842 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
848 /* add the timer in the sorted list */
849 /* NOTE: this code must be signal safe because
850 qemu_timer_expired() can be called from a signal. */
851 pt = &active_timers[ts->clock->type];
856 if (t->expire_time > expire_time)
860 ts->expire_time = expire_time;
865 int qemu_timer_pending(QEMUTimer *ts)
868 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
875 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
879 return (timer_head->expire_time <= current_time);
882 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
888 if (!ts || ts->expire_time > current_time)
890 /* remove timer from the list before calling the callback */
891 *ptimer_head = ts->next;
894 /* run the callback (the timer list can be modified) */
899 int64_t qemu_get_clock(QEMUClock *clock)
901 switch(clock->type) {
902 case QEMU_TIMER_REALTIME:
903 return get_clock() / 1000000;
905 case QEMU_TIMER_VIRTUAL:
906 return cpu_get_clock();
910 static void init_timers(void)
913 ticks_per_sec = QEMU_TIMER_BASE;
914 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
915 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
919 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
921 uint64_t expire_time;
923 if (qemu_timer_pending(ts)) {
924 expire_time = ts->expire_time;
928 qemu_put_be64(f, expire_time);
931 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
933 uint64_t expire_time;
935 expire_time = qemu_get_be64(f);
936 if (expire_time != -1) {
937 qemu_mod_timer(ts, expire_time);
943 static void timer_save(QEMUFile *f, void *opaque)
945 if (cpu_ticks_enabled) {
946 hw_error("cannot save state if virtual timers are running");
948 qemu_put_be64s(f, &cpu_ticks_offset);
949 qemu_put_be64s(f, &ticks_per_sec);
950 qemu_put_be64s(f, &cpu_clock_offset);
953 static int timer_load(QEMUFile *f, void *opaque, int version_id)
955 if (version_id != 1 && version_id != 2)
957 if (cpu_ticks_enabled) {
960 qemu_get_be64s(f, &cpu_ticks_offset);
961 qemu_get_be64s(f, &ticks_per_sec);
962 if (version_id == 2) {
963 qemu_get_be64s(f, &cpu_clock_offset);
969 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
970 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
972 static void host_alarm_handler(int host_signum)
976 #define DISP_FREQ 1000
978 static int64_t delta_min = INT64_MAX;
979 static int64_t delta_max, delta_cum, last_clock, delta, ti;
981 ti = qemu_get_clock(vm_clock);
982 if (last_clock != 0) {
983 delta = ti - last_clock;
984 if (delta < delta_min)
986 if (delta > delta_max)
989 if (++count == DISP_FREQ) {
990 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
991 muldiv64(delta_min, 1000000, ticks_per_sec),
992 muldiv64(delta_max, 1000000, ticks_per_sec),
993 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
994 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
996 delta_min = INT64_MAX;
1004 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1005 qemu_get_clock(vm_clock)) ||
1006 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1007 qemu_get_clock(rt_clock))) {
1009 SetEvent(host_alarm);
1011 CPUState *env = cpu_single_env;
1013 /* stop the currently executing cpu because a timer occured */
1014 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1016 if (env->kqemu_enabled) {
1017 kqemu_cpu_interrupt(env);
1026 #if defined(__linux__)
1028 #define RTC_FREQ 1024
1032 static int start_rtc_timer(void)
1034 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1037 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1038 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1039 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1040 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1043 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1048 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1054 static int start_rtc_timer(void)
1059 #endif /* !defined(__linux__) */
1061 #endif /* !defined(_WIN32) */
1063 static void init_timer_alarm(void)
1070 ZeroMemory(&tc, sizeof(TIMECAPS));
1071 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1072 if (period < tc.wPeriodMin)
1073 period = tc.wPeriodMin;
1074 timeBeginPeriod(period);
1075 timerID = timeSetEvent(1, // interval (ms)
1076 period, // resolution
1077 host_alarm_handler, // function
1078 (DWORD)&count, // user parameter
1079 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1081 perror("failed timer alarm");
1084 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1086 perror("failed CreateEvent");
1089 qemu_add_wait_object(host_alarm, NULL, NULL);
1091 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1094 struct sigaction act;
1095 struct itimerval itv;
1097 /* get times() syscall frequency */
1098 timer_freq = sysconf(_SC_CLK_TCK);
1101 sigfillset(&act.sa_mask);
1103 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1104 act.sa_flags |= SA_ONSTACK;
1106 act.sa_handler = host_alarm_handler;
1107 sigaction(SIGALRM, &act, NULL);
1109 itv.it_interval.tv_sec = 0;
1110 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1111 itv.it_value.tv_sec = 0;
1112 itv.it_value.tv_usec = 10 * 1000;
1113 setitimer(ITIMER_REAL, &itv, NULL);
1114 /* we probe the tick duration of the kernel to inform the user if
1115 the emulated kernel requested a too high timer frequency */
1116 getitimer(ITIMER_REAL, &itv);
1118 #if defined(__linux__)
1119 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1120 have timers with 1 ms resolution. The correct solution will
1121 be to use the POSIX real time timers available in recent
1123 if (itv.it_interval.tv_usec > 1000 || 1) {
1124 /* try to use /dev/rtc to have a faster timer */
1125 if (start_rtc_timer() < 0)
1127 /* disable itimer */
1128 itv.it_interval.tv_sec = 0;
1129 itv.it_interval.tv_usec = 0;
1130 itv.it_value.tv_sec = 0;
1131 itv.it_value.tv_usec = 0;
1132 setitimer(ITIMER_REAL, &itv, NULL);
1135 sigaction(SIGIO, &act, NULL);
1136 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1137 fcntl(rtc_fd, F_SETOWN, getpid());
1139 #endif /* defined(__linux__) */
1142 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1143 PIT_FREQ) / 1000000;
1149 void quit_timers(void)
1152 timeKillEvent(timerID);
1153 timeEndPeriod(period);
1155 CloseHandle(host_alarm);
1161 /***********************************************************/
1162 /* character device */
1164 static void qemu_chr_event(CharDriverState *s, int event)
1168 s->chr_event(s->handler_opaque, event);
1171 static void qemu_chr_reset_bh(void *opaque)
1173 CharDriverState *s = opaque;
1174 qemu_chr_event(s, CHR_EVENT_RESET);
1175 qemu_bh_delete(s->bh);
1179 void qemu_chr_reset(CharDriverState *s)
1181 if (s->bh == NULL) {
1182 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1183 qemu_bh_schedule(s->bh);
1187 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1189 return s->chr_write(s, buf, len);
1192 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1196 return s->chr_ioctl(s, cmd, arg);
1199 int qemu_chr_can_read(CharDriverState *s)
1201 if (!s->chr_can_read)
1203 return s->chr_can_read(s->handler_opaque);
1206 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1208 s->chr_read(s->handler_opaque, buf, len);
1212 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1217 vsnprintf(buf, sizeof(buf), fmt, ap);
1218 qemu_chr_write(s, buf, strlen(buf));
1222 void qemu_chr_send_event(CharDriverState *s, int event)
1224 if (s->chr_send_event)
1225 s->chr_send_event(s, event);
1228 void qemu_chr_add_handlers(CharDriverState *s,
1229 IOCanRWHandler *fd_can_read,
1230 IOReadHandler *fd_read,
1231 IOEventHandler *fd_event,
1234 s->chr_can_read = fd_can_read;
1235 s->chr_read = fd_read;
1236 s->chr_event = fd_event;
1237 s->handler_opaque = opaque;
1238 if (s->chr_update_read_handler)
1239 s->chr_update_read_handler(s);
1242 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1247 static CharDriverState *qemu_chr_open_null(void)
1249 CharDriverState *chr;
1251 chr = qemu_mallocz(sizeof(CharDriverState));
1254 chr->chr_write = null_chr_write;
1258 /* MUX driver for serial I/O splitting */
1259 static int term_timestamps;
1260 static int64_t term_timestamps_start;
1263 IOCanRWHandler *chr_can_read[MAX_MUX];
1264 IOReadHandler *chr_read[MAX_MUX];
1265 IOEventHandler *chr_event[MAX_MUX];
1266 void *ext_opaque[MAX_MUX];
1267 CharDriverState *drv;
1269 int term_got_escape;
1274 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1276 MuxDriver *d = chr->opaque;
1278 if (!term_timestamps) {
1279 ret = d->drv->chr_write(d->drv, buf, len);
1284 for(i = 0; i < len; i++) {
1285 ret += d->drv->chr_write(d->drv, buf+i, 1);
1286 if (buf[i] == '\n') {
1292 if (term_timestamps_start == -1)
1293 term_timestamps_start = ti;
1294 ti -= term_timestamps_start;
1295 secs = ti / 1000000000;
1296 snprintf(buf1, sizeof(buf1),
1297 "[%02d:%02d:%02d.%03d] ",
1301 (int)((ti / 1000000) % 1000));
1302 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1309 static char *mux_help[] = {
1310 "% h print this help\n\r",
1311 "% x exit emulator\n\r",
1312 "% s save disk data back to file (if -snapshot)\n\r",
1313 "% t toggle console timestamps\n\r"
1314 "% b send break (magic sysrq)\n\r",
1315 "% c switch between console and monitor\n\r",
1320 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1321 static void mux_print_help(CharDriverState *chr)
1324 char ebuf[15] = "Escape-Char";
1325 char cbuf[50] = "\n\r";
1327 if (term_escape_char > 0 && term_escape_char < 26) {
1328 sprintf(cbuf,"\n\r");
1329 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1331 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1333 chr->chr_write(chr, cbuf, strlen(cbuf));
1334 for (i = 0; mux_help[i] != NULL; i++) {
1335 for (j=0; mux_help[i][j] != '\0'; j++) {
1336 if (mux_help[i][j] == '%')
1337 chr->chr_write(chr, ebuf, strlen(ebuf));
1339 chr->chr_write(chr, &mux_help[i][j], 1);
1344 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1346 if (d->term_got_escape) {
1347 d->term_got_escape = 0;
1348 if (ch == term_escape_char)
1353 mux_print_help(chr);
1357 char *term = "QEMU: Terminated\n\r";
1358 chr->chr_write(chr,term,strlen(term));
1365 for (i = 0; i < MAX_DISKS; i++) {
1367 bdrv_commit(bs_table[i]);
1370 bdrv_commit(mtd_bdrv);
1374 qemu_chr_event(chr, CHR_EVENT_BREAK);
1377 /* Switch to the next registered device */
1379 if (chr->focus >= d->mux_cnt)
1383 term_timestamps = !term_timestamps;
1384 term_timestamps_start = -1;
1387 } else if (ch == term_escape_char) {
1388 d->term_got_escape = 1;
1396 static int mux_chr_can_read(void *opaque)
1398 CharDriverState *chr = opaque;
1399 MuxDriver *d = chr->opaque;
1400 if (d->chr_can_read[chr->focus])
1401 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1405 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1407 CharDriverState *chr = opaque;
1408 MuxDriver *d = chr->opaque;
1410 for(i = 0; i < size; i++)
1411 if (mux_proc_byte(chr, d, buf[i]))
1412 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1415 static void mux_chr_event(void *opaque, int event)
1417 CharDriverState *chr = opaque;
1418 MuxDriver *d = chr->opaque;
1421 /* Send the event to all registered listeners */
1422 for (i = 0; i < d->mux_cnt; i++)
1423 if (d->chr_event[i])
1424 d->chr_event[i](d->ext_opaque[i], event);
1427 static void mux_chr_update_read_handler(CharDriverState *chr)
1429 MuxDriver *d = chr->opaque;
1431 if (d->mux_cnt >= MAX_MUX) {
1432 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1435 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1436 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1437 d->chr_read[d->mux_cnt] = chr->chr_read;
1438 d->chr_event[d->mux_cnt] = chr->chr_event;
1439 /* Fix up the real driver with mux routines */
1440 if (d->mux_cnt == 0) {
1441 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1442 mux_chr_event, chr);
1444 chr->focus = d->mux_cnt;
1448 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1450 CharDriverState *chr;
1453 chr = qemu_mallocz(sizeof(CharDriverState));
1456 d = qemu_mallocz(sizeof(MuxDriver));
1465 chr->chr_write = mux_chr_write;
1466 chr->chr_update_read_handler = mux_chr_update_read_handler;
1473 static void socket_cleanup(void)
1478 static int socket_init(void)
1483 ret = WSAStartup(MAKEWORD(2,2), &Data);
1485 err = WSAGetLastError();
1486 fprintf(stderr, "WSAStartup: %d\n", err);
1489 atexit(socket_cleanup);
1493 static int send_all(int fd, const uint8_t *buf, int len1)
1499 ret = send(fd, buf, len, 0);
1502 errno = WSAGetLastError();
1503 if (errno != WSAEWOULDBLOCK) {
1506 } else if (ret == 0) {
1516 void socket_set_nonblock(int fd)
1518 unsigned long opt = 1;
1519 ioctlsocket(fd, FIONBIO, &opt);
1524 static int unix_write(int fd, const uint8_t *buf, int len1)
1530 ret = write(fd, buf, len);
1532 if (errno != EINTR && errno != EAGAIN)
1534 } else if (ret == 0) {
1544 static inline int send_all(int fd, const uint8_t *buf, int len1)
1546 return unix_write(fd, buf, len1);
1549 void socket_set_nonblock(int fd)
1551 fcntl(fd, F_SETFL, O_NONBLOCK);
1553 #endif /* !_WIN32 */
1562 #define STDIO_MAX_CLIENTS 1
1563 static int stdio_nb_clients = 0;
1565 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1567 FDCharDriver *s = chr->opaque;
1568 return unix_write(s->fd_out, buf, len);
1571 static int fd_chr_read_poll(void *opaque)
1573 CharDriverState *chr = opaque;
1574 FDCharDriver *s = chr->opaque;
1576 s->max_size = qemu_chr_can_read(chr);
1580 static void fd_chr_read(void *opaque)
1582 CharDriverState *chr = opaque;
1583 FDCharDriver *s = chr->opaque;
1588 if (len > s->max_size)
1592 size = read(s->fd_in, buf, len);
1594 /* FD has been closed. Remove it from the active list. */
1595 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1599 qemu_chr_read(chr, buf, size);
1603 static void fd_chr_update_read_handler(CharDriverState *chr)
1605 FDCharDriver *s = chr->opaque;
1607 if (s->fd_in >= 0) {
1608 if (nographic && s->fd_in == 0) {
1610 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1611 fd_chr_read, NULL, chr);
1616 /* open a character device to a unix fd */
1617 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1619 CharDriverState *chr;
1622 chr = qemu_mallocz(sizeof(CharDriverState));
1625 s = qemu_mallocz(sizeof(FDCharDriver));
1633 chr->chr_write = fd_chr_write;
1634 chr->chr_update_read_handler = fd_chr_update_read_handler;
1636 qemu_chr_reset(chr);
1641 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1645 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
1648 return qemu_chr_open_fd(-1, fd_out);
1651 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1654 char filename_in[256], filename_out[256];
1656 snprintf(filename_in, 256, "%s.in", filename);
1657 snprintf(filename_out, 256, "%s.out", filename);
1658 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
1659 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
1660 if (fd_in < 0 || fd_out < 0) {
1665 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
1669 return qemu_chr_open_fd(fd_in, fd_out);
1673 /* for STDIO, we handle the case where several clients use it
1676 #define TERM_FIFO_MAX_SIZE 1
1678 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1679 static int term_fifo_size;
1681 static int stdio_read_poll(void *opaque)
1683 CharDriverState *chr = opaque;
1685 /* try to flush the queue if needed */
1686 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1687 qemu_chr_read(chr, term_fifo, 1);
1690 /* see if we can absorb more chars */
1691 if (term_fifo_size == 0)
1697 static void stdio_read(void *opaque)
1701 CharDriverState *chr = opaque;
1703 size = read(0, buf, 1);
1705 /* stdin has been closed. Remove it from the active list. */
1706 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1710 if (qemu_chr_can_read(chr) > 0) {
1711 qemu_chr_read(chr, buf, 1);
1712 } else if (term_fifo_size == 0) {
1713 term_fifo[term_fifo_size++] = buf[0];
1718 /* init terminal so that we can grab keys */
1719 static struct termios oldtty;
1720 static int old_fd0_flags;
1722 static void term_exit(void)
1724 tcsetattr (0, TCSANOW, &oldtty);
1725 fcntl(0, F_SETFL, old_fd0_flags);
1728 static void term_init(void)
1732 tcgetattr (0, &tty);
1734 old_fd0_flags = fcntl(0, F_GETFL);
1736 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1737 |INLCR|IGNCR|ICRNL|IXON);
1738 tty.c_oflag |= OPOST;
1739 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1740 /* if graphical mode, we allow Ctrl-C handling */
1742 tty.c_lflag &= ~ISIG;
1743 tty.c_cflag &= ~(CSIZE|PARENB);
1746 tty.c_cc[VTIME] = 0;
1748 tcsetattr (0, TCSANOW, &tty);
1752 fcntl(0, F_SETFL, O_NONBLOCK);
1755 static CharDriverState *qemu_chr_open_stdio(void)
1757 CharDriverState *chr;
1759 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1761 chr = qemu_chr_open_fd(0, 1);
1762 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1769 #if defined(__linux__) || defined(__sun__)
1770 static CharDriverState *qemu_chr_open_pty(void)
1773 char slave_name[1024];
1774 int master_fd, slave_fd;
1776 #if defined(__linux__)
1777 /* Not satisfying */
1778 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1783 /* Disabling local echo and line-buffered output */
1784 tcgetattr (master_fd, &tty);
1785 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1787 tty.c_cc[VTIME] = 0;
1788 tcsetattr (master_fd, TCSAFLUSH, &tty);
1790 fprintf(stderr, "char device redirected to %s\n", slave_name);
1791 return qemu_chr_open_fd(master_fd, master_fd);
1794 static void tty_serial_init(int fd, int speed,
1795 int parity, int data_bits, int stop_bits)
1801 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1802 speed, parity, data_bits, stop_bits);
1804 tcgetattr (fd, &tty);
1846 cfsetispeed(&tty, spd);
1847 cfsetospeed(&tty, spd);
1849 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1850 |INLCR|IGNCR|ICRNL|IXON);
1851 tty.c_oflag |= OPOST;
1852 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1853 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1874 tty.c_cflag |= PARENB;
1877 tty.c_cflag |= PARENB | PARODD;
1881 tty.c_cflag |= CSTOPB;
1883 tcsetattr (fd, TCSANOW, &tty);
1886 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1888 FDCharDriver *s = chr->opaque;
1891 case CHR_IOCTL_SERIAL_SET_PARAMS:
1893 QEMUSerialSetParams *ssp = arg;
1894 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1895 ssp->data_bits, ssp->stop_bits);
1898 case CHR_IOCTL_SERIAL_SET_BREAK:
1900 int enable = *(int *)arg;
1902 tcsendbreak(s->fd_in, 1);
1911 static CharDriverState *qemu_chr_open_tty(const char *filename)
1913 CharDriverState *chr;
1916 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
1917 fcntl(fd, F_SETFL, O_NONBLOCK);
1918 tty_serial_init(fd, 115200, 'N', 8, 1);
1919 chr = qemu_chr_open_fd(fd, fd);
1924 chr->chr_ioctl = tty_serial_ioctl;
1925 qemu_chr_reset(chr);
1928 #else /* ! __linux__ && ! __sun__ */
1929 static CharDriverState *qemu_chr_open_pty(void)
1933 #endif /* __linux__ || __sun__ */
1935 #if defined(__linux__)
1939 } ParallelCharDriver;
1941 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1943 if (s->mode != mode) {
1945 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1952 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1954 ParallelCharDriver *drv = chr->opaque;
1959 case CHR_IOCTL_PP_READ_DATA:
1960 if (ioctl(fd, PPRDATA, &b) < 0)
1962 *(uint8_t *)arg = b;
1964 case CHR_IOCTL_PP_WRITE_DATA:
1965 b = *(uint8_t *)arg;
1966 if (ioctl(fd, PPWDATA, &b) < 0)
1969 case CHR_IOCTL_PP_READ_CONTROL:
1970 if (ioctl(fd, PPRCONTROL, &b) < 0)
1972 /* Linux gives only the lowest bits, and no way to know data
1973 direction! For better compatibility set the fixed upper
1975 *(uint8_t *)arg = b | 0xc0;
1977 case CHR_IOCTL_PP_WRITE_CONTROL:
1978 b = *(uint8_t *)arg;
1979 if (ioctl(fd, PPWCONTROL, &b) < 0)
1982 case CHR_IOCTL_PP_READ_STATUS:
1983 if (ioctl(fd, PPRSTATUS, &b) < 0)
1985 *(uint8_t *)arg = b;
1987 case CHR_IOCTL_PP_EPP_READ_ADDR:
1988 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1989 struct ParallelIOArg *parg = arg;
1990 int n = read(fd, parg->buffer, parg->count);
1991 if (n != parg->count) {
1996 case CHR_IOCTL_PP_EPP_READ:
1997 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1998 struct ParallelIOArg *parg = arg;
1999 int n = read(fd, parg->buffer, parg->count);
2000 if (n != parg->count) {
2005 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2006 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2007 struct ParallelIOArg *parg = arg;
2008 int n = write(fd, parg->buffer, parg->count);
2009 if (n != parg->count) {
2014 case CHR_IOCTL_PP_EPP_WRITE:
2015 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2016 struct ParallelIOArg *parg = arg;
2017 int n = write(fd, parg->buffer, parg->count);
2018 if (n != parg->count) {
2029 static void pp_close(CharDriverState *chr)
2031 ParallelCharDriver *drv = chr->opaque;
2034 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2035 ioctl(fd, PPRELEASE);
2040 static CharDriverState *qemu_chr_open_pp(const char *filename)
2042 CharDriverState *chr;
2043 ParallelCharDriver *drv;
2046 TFR(fd = open(filename, O_RDWR));
2050 if (ioctl(fd, PPCLAIM) < 0) {
2055 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2061 drv->mode = IEEE1284_MODE_COMPAT;
2063 chr = qemu_mallocz(sizeof(CharDriverState));
2069 chr->chr_write = null_chr_write;
2070 chr->chr_ioctl = pp_ioctl;
2071 chr->chr_close = pp_close;
2074 qemu_chr_reset(chr);
2078 #endif /* __linux__ */
2084 HANDLE hcom, hrecv, hsend;
2085 OVERLAPPED orecv, osend;
2090 #define NSENDBUF 2048
2091 #define NRECVBUF 2048
2092 #define MAXCONNECT 1
2093 #define NTIMEOUT 5000
2095 static int win_chr_poll(void *opaque);
2096 static int win_chr_pipe_poll(void *opaque);
2098 static void win_chr_close(CharDriverState *chr)
2100 WinCharState *s = chr->opaque;
2103 CloseHandle(s->hsend);
2107 CloseHandle(s->hrecv);
2111 CloseHandle(s->hcom);
2115 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2117 qemu_del_polling_cb(win_chr_poll, chr);
2120 static int win_chr_init(CharDriverState *chr, const char *filename)
2122 WinCharState *s = chr->opaque;
2124 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2129 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2131 fprintf(stderr, "Failed CreateEvent\n");
2134 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2136 fprintf(stderr, "Failed CreateEvent\n");
2140 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2141 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2142 if (s->hcom == INVALID_HANDLE_VALUE) {
2143 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2148 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2149 fprintf(stderr, "Failed SetupComm\n");
2153 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2154 size = sizeof(COMMCONFIG);
2155 GetDefaultCommConfig(filename, &comcfg, &size);
2156 comcfg.dcb.DCBlength = sizeof(DCB);
2157 CommConfigDialog(filename, NULL, &comcfg);
2159 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2160 fprintf(stderr, "Failed SetCommState\n");
2164 if (!SetCommMask(s->hcom, EV_ERR)) {
2165 fprintf(stderr, "Failed SetCommMask\n");
2169 cto.ReadIntervalTimeout = MAXDWORD;
2170 if (!SetCommTimeouts(s->hcom, &cto)) {
2171 fprintf(stderr, "Failed SetCommTimeouts\n");
2175 if (!ClearCommError(s->hcom, &err, &comstat)) {
2176 fprintf(stderr, "Failed ClearCommError\n");
2179 qemu_add_polling_cb(win_chr_poll, chr);
2187 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2189 WinCharState *s = chr->opaque;
2190 DWORD len, ret, size, err;
2193 ZeroMemory(&s->osend, sizeof(s->osend));
2194 s->osend.hEvent = s->hsend;
2197 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2199 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2201 err = GetLastError();
2202 if (err == ERROR_IO_PENDING) {
2203 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2221 static int win_chr_read_poll(CharDriverState *chr)
2223 WinCharState *s = chr->opaque;
2225 s->max_size = qemu_chr_can_read(chr);
2229 static void win_chr_readfile(CharDriverState *chr)
2231 WinCharState *s = chr->opaque;
2236 ZeroMemory(&s->orecv, sizeof(s->orecv));
2237 s->orecv.hEvent = s->hrecv;
2238 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2240 err = GetLastError();
2241 if (err == ERROR_IO_PENDING) {
2242 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2247 qemu_chr_read(chr, buf, size);
2251 static void win_chr_read(CharDriverState *chr)
2253 WinCharState *s = chr->opaque;
2255 if (s->len > s->max_size)
2256 s->len = s->max_size;
2260 win_chr_readfile(chr);
2263 static int win_chr_poll(void *opaque)
2265 CharDriverState *chr = opaque;
2266 WinCharState *s = chr->opaque;
2270 ClearCommError(s->hcom, &comerr, &status);
2271 if (status.cbInQue > 0) {
2272 s->len = status.cbInQue;
2273 win_chr_read_poll(chr);
2280 static CharDriverState *qemu_chr_open_win(const char *filename)
2282 CharDriverState *chr;
2285 chr = qemu_mallocz(sizeof(CharDriverState));
2288 s = qemu_mallocz(sizeof(WinCharState));
2294 chr->chr_write = win_chr_write;
2295 chr->chr_close = win_chr_close;
2297 if (win_chr_init(chr, filename) < 0) {
2302 qemu_chr_reset(chr);
2306 static int win_chr_pipe_poll(void *opaque)
2308 CharDriverState *chr = opaque;
2309 WinCharState *s = chr->opaque;
2312 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2315 win_chr_read_poll(chr);
2322 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2324 WinCharState *s = chr->opaque;
2332 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2334 fprintf(stderr, "Failed CreateEvent\n");
2337 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2339 fprintf(stderr, "Failed CreateEvent\n");
2343 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2344 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2345 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2347 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2348 if (s->hcom == INVALID_HANDLE_VALUE) {
2349 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2354 ZeroMemory(&ov, sizeof(ov));
2355 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2356 ret = ConnectNamedPipe(s->hcom, &ov);
2358 fprintf(stderr, "Failed ConnectNamedPipe\n");
2362 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2364 fprintf(stderr, "Failed GetOverlappedResult\n");
2366 CloseHandle(ov.hEvent);
2373 CloseHandle(ov.hEvent);
2376 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2385 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2387 CharDriverState *chr;
2390 chr = qemu_mallocz(sizeof(CharDriverState));
2393 s = qemu_mallocz(sizeof(WinCharState));
2399 chr->chr_write = win_chr_write;
2400 chr->chr_close = win_chr_close;
2402 if (win_chr_pipe_init(chr, filename) < 0) {
2407 qemu_chr_reset(chr);
2411 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2413 CharDriverState *chr;
2416 chr = qemu_mallocz(sizeof(CharDriverState));
2419 s = qemu_mallocz(sizeof(WinCharState));
2426 chr->chr_write = win_chr_write;
2427 qemu_chr_reset(chr);
2431 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2433 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2436 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2440 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2441 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2442 if (fd_out == INVALID_HANDLE_VALUE)
2445 return qemu_chr_open_win_file(fd_out);
2447 #endif /* !_WIN32 */
2449 /***********************************************************/
2450 /* UDP Net console */
2454 struct sockaddr_in daddr;
2461 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2463 NetCharDriver *s = chr->opaque;
2465 return sendto(s->fd, buf, len, 0,
2466 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2469 static int udp_chr_read_poll(void *opaque)
2471 CharDriverState *chr = opaque;
2472 NetCharDriver *s = chr->opaque;
2474 s->max_size = qemu_chr_can_read(chr);
2476 /* If there were any stray characters in the queue process them
2479 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2480 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2482 s->max_size = qemu_chr_can_read(chr);
2487 static void udp_chr_read(void *opaque)
2489 CharDriverState *chr = opaque;
2490 NetCharDriver *s = chr->opaque;
2492 if (s->max_size == 0)
2494 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2495 s->bufptr = s->bufcnt;
2500 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2501 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2503 s->max_size = qemu_chr_can_read(chr);
2507 static void udp_chr_update_read_handler(CharDriverState *chr)
2509 NetCharDriver *s = chr->opaque;
2512 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2513 udp_chr_read, NULL, chr);
2517 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2519 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2521 int parse_host_src_port(struct sockaddr_in *haddr,
2522 struct sockaddr_in *saddr,
2525 static CharDriverState *qemu_chr_open_udp(const char *def)
2527 CharDriverState *chr = NULL;
2528 NetCharDriver *s = NULL;
2530 struct sockaddr_in saddr;
2532 chr = qemu_mallocz(sizeof(CharDriverState));
2535 s = qemu_mallocz(sizeof(NetCharDriver));
2539 fd = socket(PF_INET, SOCK_DGRAM, 0);
2541 perror("socket(PF_INET, SOCK_DGRAM)");
2545 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2546 printf("Could not parse: %s\n", def);
2550 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2560 chr->chr_write = udp_chr_write;
2561 chr->chr_update_read_handler = udp_chr_update_read_handler;
2574 /***********************************************************/
2575 /* TCP Net console */
2586 static void tcp_chr_accept(void *opaque);
2588 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2590 TCPCharDriver *s = chr->opaque;
2592 return send_all(s->fd, buf, len);
2594 /* XXX: indicate an error ? */
2599 static int tcp_chr_read_poll(void *opaque)
2601 CharDriverState *chr = opaque;
2602 TCPCharDriver *s = chr->opaque;
2605 s->max_size = qemu_chr_can_read(chr);
2610 #define IAC_BREAK 243
2611 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2613 char *buf, int *size)
2615 /* Handle any telnet client's basic IAC options to satisfy char by
2616 * char mode with no echo. All IAC options will be removed from
2617 * the buf and the do_telnetopt variable will be used to track the
2618 * state of the width of the IAC information.
2620 * IAC commands come in sets of 3 bytes with the exception of the
2621 * "IAC BREAK" command and the double IAC.
2627 for (i = 0; i < *size; i++) {
2628 if (s->do_telnetopt > 1) {
2629 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2630 /* Double IAC means send an IAC */
2634 s->do_telnetopt = 1;
2636 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2637 /* Handle IAC break commands by sending a serial break */
2638 qemu_chr_event(chr, CHR_EVENT_BREAK);
2643 if (s->do_telnetopt >= 4) {
2644 s->do_telnetopt = 1;
2647 if ((unsigned char)buf[i] == IAC) {
2648 s->do_telnetopt = 2;
2659 static void tcp_chr_read(void *opaque)
2661 CharDriverState *chr = opaque;
2662 TCPCharDriver *s = chr->opaque;
2666 if (!s->connected || s->max_size <= 0)
2669 if (len > s->max_size)
2671 size = recv(s->fd, buf, len, 0);
2673 /* connection closed */
2675 if (s->listen_fd >= 0) {
2676 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2678 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2681 } else if (size > 0) {
2682 if (s->do_telnetopt)
2683 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2685 qemu_chr_read(chr, buf, size);
2689 static void tcp_chr_connect(void *opaque)
2691 CharDriverState *chr = opaque;
2692 TCPCharDriver *s = chr->opaque;
2695 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2696 tcp_chr_read, NULL, chr);
2697 qemu_chr_reset(chr);
2700 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2701 static void tcp_chr_telnet_init(int fd)
2704 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2705 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2706 send(fd, (char *)buf, 3, 0);
2707 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2708 send(fd, (char *)buf, 3, 0);
2709 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2710 send(fd, (char *)buf, 3, 0);
2711 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2712 send(fd, (char *)buf, 3, 0);
2715 static void socket_set_nodelay(int fd)
2718 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2721 static void tcp_chr_accept(void *opaque)
2723 CharDriverState *chr = opaque;
2724 TCPCharDriver *s = chr->opaque;
2725 struct sockaddr_in saddr;
2727 struct sockaddr_un uaddr;
2729 struct sockaddr *addr;
2736 len = sizeof(uaddr);
2737 addr = (struct sockaddr *)&uaddr;
2741 len = sizeof(saddr);
2742 addr = (struct sockaddr *)&saddr;
2744 fd = accept(s->listen_fd, addr, &len);
2745 if (fd < 0 && errno != EINTR) {
2747 } else if (fd >= 0) {
2748 if (s->do_telnetopt)
2749 tcp_chr_telnet_init(fd);
2753 socket_set_nonblock(fd);
2755 socket_set_nodelay(fd);
2757 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2758 tcp_chr_connect(chr);
2761 static void tcp_chr_close(CharDriverState *chr)
2763 TCPCharDriver *s = chr->opaque;
2766 if (s->listen_fd >= 0)
2767 closesocket(s->listen_fd);
2771 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2775 CharDriverState *chr = NULL;
2776 TCPCharDriver *s = NULL;
2777 int fd = -1, ret, err, val;
2779 int is_waitconnect = 1;
2782 struct sockaddr_in saddr;
2784 struct sockaddr_un uaddr;
2786 struct sockaddr *addr;
2791 addr = (struct sockaddr *)&uaddr;
2792 addrlen = sizeof(uaddr);
2793 if (parse_unix_path(&uaddr, host_str) < 0)
2798 addr = (struct sockaddr *)&saddr;
2799 addrlen = sizeof(saddr);
2800 if (parse_host_port(&saddr, host_str) < 0)
2805 while((ptr = strchr(ptr,','))) {
2807 if (!strncmp(ptr,"server",6)) {
2809 } else if (!strncmp(ptr,"nowait",6)) {
2811 } else if (!strncmp(ptr,"nodelay",6)) {
2814 printf("Unknown option: %s\n", ptr);
2821 chr = qemu_mallocz(sizeof(CharDriverState));
2824 s = qemu_mallocz(sizeof(TCPCharDriver));
2830 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2833 fd = socket(PF_INET, SOCK_STREAM, 0);
2838 if (!is_waitconnect)
2839 socket_set_nonblock(fd);
2844 s->is_unix = is_unix;
2845 s->do_nodelay = do_nodelay && !is_unix;
2848 chr->chr_write = tcp_chr_write;
2849 chr->chr_close = tcp_chr_close;
2852 /* allow fast reuse */
2856 strncpy(path, uaddr.sun_path, 108);
2863 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2866 ret = bind(fd, addr, addrlen);
2870 ret = listen(fd, 0);
2875 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2877 s->do_telnetopt = 1;
2880 ret = connect(fd, addr, addrlen);
2882 err = socket_error();
2883 if (err == EINTR || err == EWOULDBLOCK) {
2884 } else if (err == EINPROGRESS) {
2887 } else if (err == WSAEALREADY) {
2899 socket_set_nodelay(fd);
2901 tcp_chr_connect(chr);
2903 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2906 if (is_listen && is_waitconnect) {
2907 printf("QEMU waiting for connection on: %s\n", host_str);
2908 tcp_chr_accept(chr);
2909 socket_set_nonblock(s->listen_fd);
2921 CharDriverState *qemu_chr_open(const char *filename)
2925 if (!strcmp(filename, "vc")) {
2926 return text_console_init(&display_state);
2927 } else if (!strcmp(filename, "null")) {
2928 return qemu_chr_open_null();
2930 if (strstart(filename, "tcp:", &p)) {
2931 return qemu_chr_open_tcp(p, 0, 0);
2933 if (strstart(filename, "telnet:", &p)) {
2934 return qemu_chr_open_tcp(p, 1, 0);
2936 if (strstart(filename, "udp:", &p)) {
2937 return qemu_chr_open_udp(p);
2939 if (strstart(filename, "mon:", &p)) {
2940 CharDriverState *drv = qemu_chr_open(p);
2942 drv = qemu_chr_open_mux(drv);
2943 monitor_init(drv, !nographic);
2946 printf("Unable to open driver: %s\n", p);
2950 if (strstart(filename, "unix:", &p)) {
2951 return qemu_chr_open_tcp(p, 0, 1);
2952 } else if (strstart(filename, "file:", &p)) {
2953 return qemu_chr_open_file_out(p);
2954 } else if (strstart(filename, "pipe:", &p)) {
2955 return qemu_chr_open_pipe(p);
2956 } else if (!strcmp(filename, "pty")) {
2957 return qemu_chr_open_pty();
2958 } else if (!strcmp(filename, "stdio")) {
2959 return qemu_chr_open_stdio();
2961 #if defined(__linux__)
2962 if (strstart(filename, "/dev/parport", NULL)) {
2963 return qemu_chr_open_pp(filename);
2966 #if defined(__linux__) || defined(__sun__)
2967 if (strstart(filename, "/dev/", NULL)) {
2968 return qemu_chr_open_tty(filename);
2972 if (strstart(filename, "COM", NULL)) {
2973 return qemu_chr_open_win(filename);
2975 if (strstart(filename, "pipe:", &p)) {
2976 return qemu_chr_open_win_pipe(p);
2978 if (strstart(filename, "con:", NULL)) {
2979 return qemu_chr_open_win_con(filename);
2981 if (strstart(filename, "file:", &p)) {
2982 return qemu_chr_open_win_file_out(p);
2990 void qemu_chr_close(CharDriverState *chr)
2993 chr->chr_close(chr);
2996 /***********************************************************/
2997 /* network device redirectors */
2999 void hex_dump(FILE *f, const uint8_t *buf, int size)
3003 for(i=0;i<size;i+=16) {
3007 fprintf(f, "%08x ", i);
3010 fprintf(f, " %02x", buf[i+j]);
3015 for(j=0;j<len;j++) {
3017 if (c < ' ' || c > '~')
3019 fprintf(f, "%c", c);
3025 static int parse_macaddr(uint8_t *macaddr, const char *p)
3028 for(i = 0; i < 6; i++) {
3029 macaddr[i] = strtol(p, (char **)&p, 16);
3042 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3047 p1 = strchr(p, sep);
3053 if (len > buf_size - 1)
3055 memcpy(buf, p, len);
3062 int parse_host_src_port(struct sockaddr_in *haddr,
3063 struct sockaddr_in *saddr,
3064 const char *input_str)
3066 char *str = strdup(input_str);
3067 char *host_str = str;
3072 * Chop off any extra arguments at the end of the string which
3073 * would start with a comma, then fill in the src port information
3074 * if it was provided else use the "any address" and "any port".
3076 if ((ptr = strchr(str,',')))
3079 if ((src_str = strchr(input_str,'@'))) {
3084 if (parse_host_port(haddr, host_str) < 0)
3087 if (!src_str || *src_str == '\0')
3090 if (parse_host_port(saddr, src_str) < 0)
3101 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3109 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3111 saddr->sin_family = AF_INET;
3112 if (buf[0] == '\0') {
3113 saddr->sin_addr.s_addr = 0;
3115 if (isdigit(buf[0])) {
3116 if (!inet_aton(buf, &saddr->sin_addr))
3119 if ((he = gethostbyname(buf)) == NULL)
3121 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3124 port = strtol(p, (char **)&r, 0);
3127 saddr->sin_port = htons(port);
3132 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3137 len = MIN(108, strlen(str));
3138 p = strchr(str, ',');
3140 len = MIN(len, p - str);
3142 memset(uaddr, 0, sizeof(*uaddr));
3144 uaddr->sun_family = AF_UNIX;
3145 memcpy(uaddr->sun_path, str, len);
3151 /* find or alloc a new VLAN */
3152 VLANState *qemu_find_vlan(int id)
3154 VLANState **pvlan, *vlan;
3155 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3159 vlan = qemu_mallocz(sizeof(VLANState));
3164 pvlan = &first_vlan;
3165 while (*pvlan != NULL)
3166 pvlan = &(*pvlan)->next;
3171 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3172 IOReadHandler *fd_read,
3173 IOCanRWHandler *fd_can_read,
3176 VLANClientState *vc, **pvc;
3177 vc = qemu_mallocz(sizeof(VLANClientState));
3180 vc->fd_read = fd_read;
3181 vc->fd_can_read = fd_can_read;
3182 vc->opaque = opaque;
3186 pvc = &vlan->first_client;
3187 while (*pvc != NULL)
3188 pvc = &(*pvc)->next;
3193 int qemu_can_send_packet(VLANClientState *vc1)
3195 VLANState *vlan = vc1->vlan;
3196 VLANClientState *vc;
3198 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3200 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3207 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3209 VLANState *vlan = vc1->vlan;
3210 VLANClientState *vc;
3213 printf("vlan %d send:\n", vlan->id);
3214 hex_dump(stdout, buf, size);
3216 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3218 vc->fd_read(vc->opaque, buf, size);
3223 #if defined(CONFIG_SLIRP)
3225 /* slirp network adapter */
3227 static int slirp_inited;
3228 static VLANClientState *slirp_vc;
3230 int slirp_can_output(void)
3232 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3235 void slirp_output(const uint8_t *pkt, int pkt_len)
3238 printf("slirp output:\n");
3239 hex_dump(stdout, pkt, pkt_len);
3243 qemu_send_packet(slirp_vc, pkt, pkt_len);
3246 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3249 printf("slirp input:\n");
3250 hex_dump(stdout, buf, size);
3252 slirp_input(buf, size);
3255 static int net_slirp_init(VLANState *vlan)
3257 if (!slirp_inited) {
3261 slirp_vc = qemu_new_vlan_client(vlan,
3262 slirp_receive, NULL, NULL);
3263 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3267 static void net_slirp_redir(const char *redir_str)
3272 struct in_addr guest_addr;
3273 int host_port, guest_port;
3275 if (!slirp_inited) {
3281 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3283 if (!strcmp(buf, "tcp")) {
3285 } else if (!strcmp(buf, "udp")) {
3291 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3293 host_port = strtol(buf, &r, 0);
3297 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3299 if (buf[0] == '\0') {
3300 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3302 if (!inet_aton(buf, &guest_addr))
3305 guest_port = strtol(p, &r, 0);
3309 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3310 fprintf(stderr, "qemu: could not set up redirection\n");
3315 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3323 static void smb_exit(void)
3327 char filename[1024];
3329 /* erase all the files in the directory */
3330 d = opendir(smb_dir);
3335 if (strcmp(de->d_name, ".") != 0 &&
3336 strcmp(de->d_name, "..") != 0) {
3337 snprintf(filename, sizeof(filename), "%s/%s",
3338 smb_dir, de->d_name);
3346 /* automatic user mode samba server configuration */
3347 void net_slirp_smb(const char *exported_dir)
3349 char smb_conf[1024];
3350 char smb_cmdline[1024];
3353 if (!slirp_inited) {
3358 /* XXX: better tmp dir construction */
3359 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3360 if (mkdir(smb_dir, 0700) < 0) {
3361 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3364 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3366 f = fopen(smb_conf, "w");
3368 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3375 "socket address=127.0.0.1\n"
3376 "pid directory=%s\n"
3377 "lock directory=%s\n"
3378 "log file=%s/log.smbd\n"
3379 "smb passwd file=%s/smbpasswd\n"
3380 "security = share\n"
3395 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3396 SMBD_COMMAND, smb_conf);
3398 slirp_add_exec(0, smb_cmdline, 4, 139);
3401 #endif /* !defined(_WIN32) */
3403 #endif /* CONFIG_SLIRP */
3405 #if !defined(_WIN32)
3407 typedef struct TAPState {
3408 VLANClientState *vc;
3412 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3414 TAPState *s = opaque;
3417 ret = write(s->fd, buf, size);
3418 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3425 static void tap_send(void *opaque)
3427 TAPState *s = opaque;
3434 sbuf.maxlen = sizeof(buf);
3436 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3438 size = read(s->fd, buf, sizeof(buf));
3441 qemu_send_packet(s->vc, buf, size);
3447 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3451 s = qemu_mallocz(sizeof(TAPState));
3455 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3456 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3457 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3461 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3462 static int tap_open(char *ifname, int ifname_size)
3468 TFR(fd = open("/dev/tap", O_RDWR));
3470 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3475 dev = devname(s.st_rdev, S_IFCHR);
3476 pstrcpy(ifname, ifname_size, dev);
3478 fcntl(fd, F_SETFL, O_NONBLOCK);
3481 #elif defined(__sun__)
3482 #define TUNNEWPPA (('T'<<16) | 0x0001)
3484 * Allocate TAP device, returns opened fd.
3485 * Stores dev name in the first arg(must be large enough).
3487 int tap_alloc(char *dev)
3489 int tap_fd, if_fd, ppa = -1;
3490 static int ip_fd = 0;
3493 static int arp_fd = 0;
3494 int ip_muxid, arp_muxid;
3495 struct strioctl strioc_if, strioc_ppa;
3496 int link_type = I_PLINK;;
3498 char actual_name[32] = "";
3500 memset(&ifr, 0x0, sizeof(ifr));
3504 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3508 /* Check if IP device was opened */
3512 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3514 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3518 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3520 syslog(LOG_ERR, "Can't open /dev/tap");
3524 /* Assign a new PPA and get its unit number. */
3525 strioc_ppa.ic_cmd = TUNNEWPPA;
3526 strioc_ppa.ic_timout = 0;
3527 strioc_ppa.ic_len = sizeof(ppa);
3528 strioc_ppa.ic_dp = (char *)&ppa;
3529 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3530 syslog (LOG_ERR, "Can't assign new interface");
3532 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3534 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3537 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3538 syslog(LOG_ERR, "Can't push IP module");
3542 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3543 syslog(LOG_ERR, "Can't get flags\n");
3545 snprintf (actual_name, 32, "tap%d", ppa);
3546 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3549 /* Assign ppa according to the unit number returned by tun device */
3551 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3552 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3553 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3554 syslog (LOG_ERR, "Can't get flags\n");
3555 /* Push arp module to if_fd */
3556 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3557 syslog (LOG_ERR, "Can't push ARP module (2)");
3559 /* Push arp module to ip_fd */
3560 if (ioctl (ip_fd, I_POP, NULL) < 0)
3561 syslog (LOG_ERR, "I_POP failed\n");
3562 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3563 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3565 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3567 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3569 /* Set ifname to arp */
3570 strioc_if.ic_cmd = SIOCSLIFNAME;
3571 strioc_if.ic_timout = 0;
3572 strioc_if.ic_len = sizeof(ifr);
3573 strioc_if.ic_dp = (char *)𝔦
3574 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3575 syslog (LOG_ERR, "Can't set ifname to arp\n");
3578 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3579 syslog(LOG_ERR, "Can't link TAP device to IP");
3583 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3584 syslog (LOG_ERR, "Can't link TAP device to ARP");
3588 memset(&ifr, 0x0, sizeof(ifr));
3589 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3590 ifr.lifr_ip_muxid = ip_muxid;
3591 ifr.lifr_arp_muxid = arp_muxid;
3593 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3595 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3596 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3597 syslog (LOG_ERR, "Can't set multiplexor id");
3600 sprintf(dev, "tap%d", ppa);
3604 static int tap_open(char *ifname, int ifname_size)
3608 if( (fd = tap_alloc(dev)) < 0 ){
3609 fprintf(stderr, "Cannot allocate TAP device\n");
3612 pstrcpy(ifname, ifname_size, dev);
3613 fcntl(fd, F_SETFL, O_NONBLOCK);
3617 static int tap_open(char *ifname, int ifname_size)
3622 TFR(fd = open("/dev/net/tun", O_RDWR));
3624 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3627 memset(&ifr, 0, sizeof(ifr));
3628 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3629 if (ifname[0] != '\0')
3630 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3632 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3633 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3635 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3639 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3640 fcntl(fd, F_SETFL, O_NONBLOCK);
3645 static int net_tap_init(VLANState *vlan, const char *ifname1,
3646 const char *setup_script)
3649 int pid, status, fd;
3654 if (ifname1 != NULL)
3655 pstrcpy(ifname, sizeof(ifname), ifname1);
3658 TFR(fd = tap_open(ifname, sizeof(ifname)));
3662 if (!setup_script || !strcmp(setup_script, "no"))
3664 if (setup_script[0] != '\0') {
3665 /* try to launch network init script */
3669 int open_max = sysconf (_SC_OPEN_MAX), i;
3670 for (i = 0; i < open_max; i++)
3671 if (i != STDIN_FILENO &&
3672 i != STDOUT_FILENO &&
3673 i != STDERR_FILENO &&
3678 *parg++ = (char *)setup_script;
3681 execv(setup_script, args);
3684 while (waitpid(pid, &status, 0) != pid);
3685 if (!WIFEXITED(status) ||
3686 WEXITSTATUS(status) != 0) {
3687 fprintf(stderr, "%s: could not launch network script\n",
3693 s = net_tap_fd_init(vlan, fd);
3696 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3697 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3701 #endif /* !_WIN32 */
3703 /* network connection */
3704 typedef struct NetSocketState {
3705 VLANClientState *vc;
3707 int state; /* 0 = getting length, 1 = getting data */
3711 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3714 typedef struct NetSocketListenState {
3717 } NetSocketListenState;
3719 /* XXX: we consider we can send the whole packet without blocking */
3720 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3722 NetSocketState *s = opaque;
3726 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3727 send_all(s->fd, buf, size);
3730 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3732 NetSocketState *s = opaque;
3733 sendto(s->fd, buf, size, 0,
3734 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3737 static void net_socket_send(void *opaque)
3739 NetSocketState *s = opaque;
3744 size = recv(s->fd, buf1, sizeof(buf1), 0);
3746 err = socket_error();
3747 if (err != EWOULDBLOCK)
3749 } else if (size == 0) {
3750 /* end of connection */
3752 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3758 /* reassemble a packet from the network */
3764 memcpy(s->buf + s->index, buf, l);
3768 if (s->index == 4) {
3770 s->packet_len = ntohl(*(uint32_t *)s->buf);
3776 l = s->packet_len - s->index;
3779 memcpy(s->buf + s->index, buf, l);
3783 if (s->index >= s->packet_len) {
3784 qemu_send_packet(s->vc, s->buf, s->packet_len);
3793 static void net_socket_send_dgram(void *opaque)
3795 NetSocketState *s = opaque;
3798 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3802 /* end of connection */
3803 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3806 qemu_send_packet(s->vc, s->buf, size);
3809 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3814 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3815 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3816 inet_ntoa(mcastaddr->sin_addr),
3817 (int)ntohl(mcastaddr->sin_addr.s_addr));
3821 fd = socket(PF_INET, SOCK_DGRAM, 0);
3823 perror("socket(PF_INET, SOCK_DGRAM)");
3828 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3829 (const char *)&val, sizeof(val));
3831 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3835 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3841 /* Add host to multicast group */
3842 imr.imr_multiaddr = mcastaddr->sin_addr;
3843 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3845 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3846 (const char *)&imr, sizeof(struct ip_mreq));
3848 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3852 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3854 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3855 (const char *)&val, sizeof(val));
3857 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3861 socket_set_nonblock(fd);
3869 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3872 struct sockaddr_in saddr;
3874 socklen_t saddr_len;
3877 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3878 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3879 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3883 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3885 if (saddr.sin_addr.s_addr==0) {
3886 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3890 /* clone dgram socket */
3891 newfd = net_socket_mcast_create(&saddr);
3893 /* error already reported by net_socket_mcast_create() */
3897 /* clone newfd to fd, close newfd */
3902 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3903 fd, strerror(errno));
3908 s = qemu_mallocz(sizeof(NetSocketState));
3913 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3914 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3916 /* mcast: save bound address as dst */
3917 if (is_connected) s->dgram_dst=saddr;
3919 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3920 "socket: fd=%d (%s mcast=%s:%d)",
3921 fd, is_connected? "cloned" : "",
3922 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3926 static void net_socket_connect(void *opaque)
3928 NetSocketState *s = opaque;
3929 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3932 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3936 s = qemu_mallocz(sizeof(NetSocketState));
3940 s->vc = qemu_new_vlan_client(vlan,
3941 net_socket_receive, NULL, s);
3942 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3943 "socket: fd=%d", fd);
3945 net_socket_connect(s);
3947 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3952 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3955 int so_type=-1, optlen=sizeof(so_type);
3957 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3958 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3963 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3965 return net_socket_fd_init_stream(vlan, fd, is_connected);
3967 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3968 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3969 return net_socket_fd_init_stream(vlan, fd, is_connected);
3974 static void net_socket_accept(void *opaque)
3976 NetSocketListenState *s = opaque;
3978 struct sockaddr_in saddr;
3983 len = sizeof(saddr);
3984 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3985 if (fd < 0 && errno != EINTR) {
3987 } else if (fd >= 0) {
3991 s1 = net_socket_fd_init(s->vlan, fd, 1);
3995 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3996 "socket: connection from %s:%d",
3997 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4001 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4003 NetSocketListenState *s;
4005 struct sockaddr_in saddr;
4007 if (parse_host_port(&saddr, host_str) < 0)
4010 s = qemu_mallocz(sizeof(NetSocketListenState));
4014 fd = socket(PF_INET, SOCK_STREAM, 0);
4019 socket_set_nonblock(fd);
4021 /* allow fast reuse */
4023 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4025 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4030 ret = listen(fd, 0);
4037 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4041 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4044 int fd, connected, ret, err;
4045 struct sockaddr_in saddr;
4047 if (parse_host_port(&saddr, host_str) < 0)
4050 fd = socket(PF_INET, SOCK_STREAM, 0);
4055 socket_set_nonblock(fd);
4059 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4061 err = socket_error();
4062 if (err == EINTR || err == EWOULDBLOCK) {
4063 } else if (err == EINPROGRESS) {
4066 } else if (err == WSAEALREADY) {
4079 s = net_socket_fd_init(vlan, fd, connected);
4082 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4083 "socket: connect to %s:%d",
4084 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4088 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4092 struct sockaddr_in saddr;
4094 if (parse_host_port(&saddr, host_str) < 0)
4098 fd = net_socket_mcast_create(&saddr);
4102 s = net_socket_fd_init(vlan, fd, 0);
4106 s->dgram_dst = saddr;
4108 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4109 "socket: mcast=%s:%d",
4110 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4115 static int get_param_value(char *buf, int buf_size,
4116 const char *tag, const char *str)
4125 while (*p != '\0' && *p != '=') {
4126 if ((q - option) < sizeof(option) - 1)
4134 if (!strcmp(tag, option)) {
4136 while (*p != '\0' && *p != ',') {
4137 if ((q - buf) < buf_size - 1)
4144 while (*p != '\0' && *p != ',') {
4155 static int net_client_init(const char *str)
4166 while (*p != '\0' && *p != ',') {
4167 if ((q - device) < sizeof(device) - 1)
4175 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4176 vlan_id = strtol(buf, NULL, 0);
4178 vlan = qemu_find_vlan(vlan_id);
4180 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4183 if (!strcmp(device, "nic")) {
4187 if (nb_nics >= MAX_NICS) {
4188 fprintf(stderr, "Too Many NICs\n");
4191 nd = &nd_table[nb_nics];
4192 macaddr = nd->macaddr;
4198 macaddr[5] = 0x56 + nb_nics;
4200 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4201 if (parse_macaddr(macaddr, buf) < 0) {
4202 fprintf(stderr, "invalid syntax for ethernet address\n");
4206 if (get_param_value(buf, sizeof(buf), "model", p)) {
4207 nd->model = strdup(buf);
4211 vlan->nb_guest_devs++;
4214 if (!strcmp(device, "none")) {
4215 /* does nothing. It is needed to signal that no network cards
4220 if (!strcmp(device, "user")) {
4221 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4222 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4224 vlan->nb_host_devs++;
4225 ret = net_slirp_init(vlan);
4229 if (!strcmp(device, "tap")) {
4231 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4232 fprintf(stderr, "tap: no interface name\n");
4235 vlan->nb_host_devs++;
4236 ret = tap_win32_init(vlan, ifname);
4239 if (!strcmp(device, "tap")) {
4241 char setup_script[1024];
4243 vlan->nb_host_devs++;
4244 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4245 fd = strtol(buf, NULL, 0);
4247 if (net_tap_fd_init(vlan, fd))
4250 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4253 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4254 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4256 ret = net_tap_init(vlan, ifname, setup_script);
4260 if (!strcmp(device, "socket")) {
4261 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4263 fd = strtol(buf, NULL, 0);
4265 if (net_socket_fd_init(vlan, fd, 1))
4267 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4268 ret = net_socket_listen_init(vlan, buf);
4269 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4270 ret = net_socket_connect_init(vlan, buf);
4271 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4272 ret = net_socket_mcast_init(vlan, buf);
4274 fprintf(stderr, "Unknown socket options: %s\n", p);
4277 vlan->nb_host_devs++;
4280 fprintf(stderr, "Unknown network device: %s\n", device);
4284 fprintf(stderr, "Could not initialize device '%s'\n", device);
4290 void do_info_network(void)
4293 VLANClientState *vc;
4295 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4296 term_printf("VLAN %d devices:\n", vlan->id);
4297 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4298 term_printf(" %s\n", vc->info_str);
4302 /***********************************************************/
4305 static USBPort *used_usb_ports;
4306 static USBPort *free_usb_ports;
4308 /* ??? Maybe change this to register a hub to keep track of the topology. */
4309 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4310 usb_attachfn attach)
4312 port->opaque = opaque;
4313 port->index = index;
4314 port->attach = attach;
4315 port->next = free_usb_ports;
4316 free_usb_ports = port;
4319 static int usb_device_add(const char *devname)
4325 if (!free_usb_ports)
4328 if (strstart(devname, "host:", &p)) {
4329 dev = usb_host_device_open(p);
4330 } else if (!strcmp(devname, "mouse")) {
4331 dev = usb_mouse_init();
4332 } else if (!strcmp(devname, "tablet")) {
4333 dev = usb_tablet_init();
4334 } else if (!strcmp(devname, "keyboard")) {
4335 dev = usb_keyboard_init();
4336 } else if (strstart(devname, "disk:", &p)) {
4337 dev = usb_msd_init(p);
4338 } else if (!strcmp(devname, "wacom-tablet")) {
4339 dev = usb_wacom_init();
4346 /* Find a USB port to add the device to. */
4347 port = free_usb_ports;
4351 /* Create a new hub and chain it on. */
4352 free_usb_ports = NULL;
4353 port->next = used_usb_ports;
4354 used_usb_ports = port;
4356 hub = usb_hub_init(VM_USB_HUB_SIZE);
4357 usb_attach(port, hub);
4358 port = free_usb_ports;
4361 free_usb_ports = port->next;
4362 port->next = used_usb_ports;
4363 used_usb_ports = port;
4364 usb_attach(port, dev);
4368 static int usb_device_del(const char *devname)
4376 if (!used_usb_ports)
4379 p = strchr(devname, '.');
4382 bus_num = strtoul(devname, NULL, 0);
4383 addr = strtoul(p + 1, NULL, 0);
4387 lastp = &used_usb_ports;
4388 port = used_usb_ports;
4389 while (port && port->dev->addr != addr) {
4390 lastp = &port->next;
4398 *lastp = port->next;
4399 usb_attach(port, NULL);
4400 dev->handle_destroy(dev);
4401 port->next = free_usb_ports;
4402 free_usb_ports = port;
4406 void do_usb_add(const char *devname)
4409 ret = usb_device_add(devname);
4411 term_printf("Could not add USB device '%s'\n", devname);
4414 void do_usb_del(const char *devname)
4417 ret = usb_device_del(devname);
4419 term_printf("Could not remove USB device '%s'\n", devname);
4426 const char *speed_str;
4429 term_printf("USB support not enabled\n");
4433 for (port = used_usb_ports; port; port = port->next) {
4437 switch(dev->speed) {
4441 case USB_SPEED_FULL:
4444 case USB_SPEED_HIGH:
4451 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4452 0, dev->addr, speed_str, dev->devname);
4456 /***********************************************************/
4457 /* PCMCIA/Cardbus */
4459 static struct pcmcia_socket_entry_s {
4460 struct pcmcia_socket_s *socket;
4461 struct pcmcia_socket_entry_s *next;
4462 } *pcmcia_sockets = 0;
4464 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4466 struct pcmcia_socket_entry_s *entry;
4468 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4469 entry->socket = socket;
4470 entry->next = pcmcia_sockets;
4471 pcmcia_sockets = entry;
4474 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4476 struct pcmcia_socket_entry_s *entry, **ptr;
4478 ptr = &pcmcia_sockets;
4479 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4480 if (entry->socket == socket) {
4486 void pcmcia_info(void)
4488 struct pcmcia_socket_entry_s *iter;
4489 if (!pcmcia_sockets)
4490 term_printf("No PCMCIA sockets\n");
4492 for (iter = pcmcia_sockets; iter; iter = iter->next)
4493 term_printf("%s: %s\n", iter->socket->slot_string,
4494 iter->socket->attached ? iter->socket->card_string :
4498 /***********************************************************/
4501 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4505 static void dumb_resize(DisplayState *ds, int w, int h)
4509 static void dumb_refresh(DisplayState *ds)
4511 #if defined(CONFIG_SDL)
4516 static void dumb_display_init(DisplayState *ds)
4521 ds->dpy_update = dumb_update;
4522 ds->dpy_resize = dumb_resize;
4523 ds->dpy_refresh = dumb_refresh;
4526 /***********************************************************/
4529 #define MAX_IO_HANDLERS 64
4531 typedef struct IOHandlerRecord {
4533 IOCanRWHandler *fd_read_poll;
4535 IOHandler *fd_write;
4538 /* temporary data */
4540 struct IOHandlerRecord *next;
4543 static IOHandlerRecord *first_io_handler;
4545 /* XXX: fd_read_poll should be suppressed, but an API change is
4546 necessary in the character devices to suppress fd_can_read(). */
4547 int qemu_set_fd_handler2(int fd,
4548 IOCanRWHandler *fd_read_poll,
4550 IOHandler *fd_write,
4553 IOHandlerRecord **pioh, *ioh;
4555 if (!fd_read && !fd_write) {
4556 pioh = &first_io_handler;
4561 if (ioh->fd == fd) {
4568 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4572 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4575 ioh->next = first_io_handler;
4576 first_io_handler = ioh;
4579 ioh->fd_read_poll = fd_read_poll;
4580 ioh->fd_read = fd_read;
4581 ioh->fd_write = fd_write;
4582 ioh->opaque = opaque;
4588 int qemu_set_fd_handler(int fd,
4590 IOHandler *fd_write,
4593 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4596 /***********************************************************/
4597 /* Polling handling */
4599 typedef struct PollingEntry {
4602 struct PollingEntry *next;
4605 static PollingEntry *first_polling_entry;
4607 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4609 PollingEntry **ppe, *pe;
4610 pe = qemu_mallocz(sizeof(PollingEntry));
4614 pe->opaque = opaque;
4615 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4620 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4622 PollingEntry **ppe, *pe;
4623 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4625 if (pe->func == func && pe->opaque == opaque) {
4634 /***********************************************************/
4635 /* Wait objects support */
4636 typedef struct WaitObjects {
4638 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4639 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4640 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4643 static WaitObjects wait_objects = {0};
4645 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4647 WaitObjects *w = &wait_objects;
4649 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4651 w->events[w->num] = handle;
4652 w->func[w->num] = func;
4653 w->opaque[w->num] = opaque;
4658 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4661 WaitObjects *w = &wait_objects;
4664 for (i = 0; i < w->num; i++) {
4665 if (w->events[i] == handle)
4668 w->events[i] = w->events[i + 1];
4669 w->func[i] = w->func[i + 1];
4670 w->opaque[i] = w->opaque[i + 1];
4678 /***********************************************************/
4679 /* savevm/loadvm support */
4681 #define IO_BUF_SIZE 32768
4685 BlockDriverState *bs;
4688 int64_t base_offset;
4689 int64_t buf_offset; /* start of buffer when writing, end of buffer
4692 int buf_size; /* 0 when writing */
4693 uint8_t buf[IO_BUF_SIZE];
4696 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4700 f = qemu_mallocz(sizeof(QEMUFile));
4703 if (!strcmp(mode, "wb")) {
4705 } else if (!strcmp(mode, "rb")) {
4710 f->outfile = fopen(filename, mode);
4722 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4726 f = qemu_mallocz(sizeof(QEMUFile));
4731 f->is_writable = is_writable;
4732 f->base_offset = offset;
4736 void qemu_fflush(QEMUFile *f)
4738 if (!f->is_writable)
4740 if (f->buf_index > 0) {
4742 fseek(f->outfile, f->buf_offset, SEEK_SET);
4743 fwrite(f->buf, 1, f->buf_index, f->outfile);
4745 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4746 f->buf, f->buf_index);
4748 f->buf_offset += f->buf_index;
4753 static void qemu_fill_buffer(QEMUFile *f)
4760 fseek(f->outfile, f->buf_offset, SEEK_SET);
4761 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4765 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4766 f->buf, IO_BUF_SIZE);
4772 f->buf_offset += len;
4775 void qemu_fclose(QEMUFile *f)
4785 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4789 l = IO_BUF_SIZE - f->buf_index;
4792 memcpy(f->buf + f->buf_index, buf, l);
4796 if (f->buf_index >= IO_BUF_SIZE)
4801 void qemu_put_byte(QEMUFile *f, int v)
4803 f->buf[f->buf_index++] = v;
4804 if (f->buf_index >= IO_BUF_SIZE)
4808 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4814 l = f->buf_size - f->buf_index;
4816 qemu_fill_buffer(f);
4817 l = f->buf_size - f->buf_index;
4823 memcpy(buf, f->buf + f->buf_index, l);
4828 return size1 - size;
4831 int qemu_get_byte(QEMUFile *f)
4833 if (f->buf_index >= f->buf_size) {
4834 qemu_fill_buffer(f);
4835 if (f->buf_index >= f->buf_size)
4838 return f->buf[f->buf_index++];
4841 int64_t qemu_ftell(QEMUFile *f)
4843 return f->buf_offset - f->buf_size + f->buf_index;
4846 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4848 if (whence == SEEK_SET) {
4850 } else if (whence == SEEK_CUR) {
4851 pos += qemu_ftell(f);
4853 /* SEEK_END not supported */
4856 if (f->is_writable) {
4858 f->buf_offset = pos;
4860 f->buf_offset = pos;
4867 void qemu_put_be16(QEMUFile *f, unsigned int v)
4869 qemu_put_byte(f, v >> 8);
4870 qemu_put_byte(f, v);
4873 void qemu_put_be32(QEMUFile *f, unsigned int v)
4875 qemu_put_byte(f, v >> 24);
4876 qemu_put_byte(f, v >> 16);
4877 qemu_put_byte(f, v >> 8);
4878 qemu_put_byte(f, v);
4881 void qemu_put_be64(QEMUFile *f, uint64_t v)
4883 qemu_put_be32(f, v >> 32);
4884 qemu_put_be32(f, v);
4887 unsigned int qemu_get_be16(QEMUFile *f)
4890 v = qemu_get_byte(f) << 8;
4891 v |= qemu_get_byte(f);
4895 unsigned int qemu_get_be32(QEMUFile *f)
4898 v = qemu_get_byte(f) << 24;
4899 v |= qemu_get_byte(f) << 16;
4900 v |= qemu_get_byte(f) << 8;
4901 v |= qemu_get_byte(f);
4905 uint64_t qemu_get_be64(QEMUFile *f)
4908 v = (uint64_t)qemu_get_be32(f) << 32;
4909 v |= qemu_get_be32(f);
4913 typedef struct SaveStateEntry {
4917 SaveStateHandler *save_state;
4918 LoadStateHandler *load_state;
4920 struct SaveStateEntry *next;
4923 static SaveStateEntry *first_se;
4925 int register_savevm(const char *idstr,
4928 SaveStateHandler *save_state,
4929 LoadStateHandler *load_state,
4932 SaveStateEntry *se, **pse;
4934 se = qemu_malloc(sizeof(SaveStateEntry));
4937 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4938 se->instance_id = instance_id;
4939 se->version_id = version_id;
4940 se->save_state = save_state;
4941 se->load_state = load_state;
4942 se->opaque = opaque;
4945 /* add at the end of list */
4947 while (*pse != NULL)
4948 pse = &(*pse)->next;
4953 #define QEMU_VM_FILE_MAGIC 0x5145564d
4954 #define QEMU_VM_FILE_VERSION 0x00000002
4956 int qemu_savevm_state(QEMUFile *f)
4960 int64_t cur_pos, len_pos, total_len_pos;
4962 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4963 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4964 total_len_pos = qemu_ftell(f);
4965 qemu_put_be64(f, 0); /* total size */
4967 for(se = first_se; se != NULL; se = se->next) {
4969 len = strlen(se->idstr);
4970 qemu_put_byte(f, len);
4971 qemu_put_buffer(f, se->idstr, len);
4973 qemu_put_be32(f, se->instance_id);
4974 qemu_put_be32(f, se->version_id);
4976 /* record size: filled later */
4977 len_pos = qemu_ftell(f);
4978 qemu_put_be32(f, 0);
4980 se->save_state(f, se->opaque);
4982 /* fill record size */
4983 cur_pos = qemu_ftell(f);
4984 len = cur_pos - len_pos - 4;
4985 qemu_fseek(f, len_pos, SEEK_SET);
4986 qemu_put_be32(f, len);
4987 qemu_fseek(f, cur_pos, SEEK_SET);
4989 cur_pos = qemu_ftell(f);
4990 qemu_fseek(f, total_len_pos, SEEK_SET);
4991 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4992 qemu_fseek(f, cur_pos, SEEK_SET);
4998 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5002 for(se = first_se; se != NULL; se = se->next) {
5003 if (!strcmp(se->idstr, idstr) &&
5004 instance_id == se->instance_id)
5010 int qemu_loadvm_state(QEMUFile *f)
5013 int len, ret, instance_id, record_len, version_id;
5014 int64_t total_len, end_pos, cur_pos;
5018 v = qemu_get_be32(f);
5019 if (v != QEMU_VM_FILE_MAGIC)
5021 v = qemu_get_be32(f);
5022 if (v != QEMU_VM_FILE_VERSION) {
5027 total_len = qemu_get_be64(f);
5028 end_pos = total_len + qemu_ftell(f);
5030 if (qemu_ftell(f) >= end_pos)
5032 len = qemu_get_byte(f);
5033 qemu_get_buffer(f, idstr, len);
5035 instance_id = qemu_get_be32(f);
5036 version_id = qemu_get_be32(f);
5037 record_len = qemu_get_be32(f);
5039 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5040 idstr, instance_id, version_id, record_len);
5042 cur_pos = qemu_ftell(f);
5043 se = find_se(idstr, instance_id);
5045 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5046 instance_id, idstr);
5048 ret = se->load_state(f, se->opaque, version_id);
5050 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5051 instance_id, idstr);
5054 /* always seek to exact end of record */
5055 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5062 /* device can contain snapshots */
5063 static int bdrv_can_snapshot(BlockDriverState *bs)
5066 !bdrv_is_removable(bs) &&
5067 !bdrv_is_read_only(bs));
5070 /* device must be snapshots in order to have a reliable snapshot */
5071 static int bdrv_has_snapshot(BlockDriverState *bs)
5074 !bdrv_is_removable(bs) &&
5075 !bdrv_is_read_only(bs));
5078 static BlockDriverState *get_bs_snapshots(void)
5080 BlockDriverState *bs;
5084 return bs_snapshots;
5085 for(i = 0; i <= MAX_DISKS; i++) {
5087 if (bdrv_can_snapshot(bs))
5096 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5099 QEMUSnapshotInfo *sn_tab, *sn;
5103 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5106 for(i = 0; i < nb_sns; i++) {
5108 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5118 void do_savevm(const char *name)
5120 BlockDriverState *bs, *bs1;
5121 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5122 int must_delete, ret, i;
5123 BlockDriverInfo bdi1, *bdi = &bdi1;
5125 int saved_vm_running;
5132 bs = get_bs_snapshots();
5134 term_printf("No block device can accept snapshots\n");
5138 /* ??? Should this occur after vm_stop? */
5141 saved_vm_running = vm_running;
5146 ret = bdrv_snapshot_find(bs, old_sn, name);
5151 memset(sn, 0, sizeof(*sn));
5153 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5154 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5157 pstrcpy(sn->name, sizeof(sn->name), name);
5160 /* fill auxiliary fields */
5163 sn->date_sec = tb.time;
5164 sn->date_nsec = tb.millitm * 1000000;
5166 gettimeofday(&tv, NULL);
5167 sn->date_sec = tv.tv_sec;
5168 sn->date_nsec = tv.tv_usec * 1000;
5170 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5172 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5173 term_printf("Device %s does not support VM state snapshots\n",
5174 bdrv_get_device_name(bs));
5178 /* save the VM state */
5179 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5181 term_printf("Could not open VM state file\n");
5184 ret = qemu_savevm_state(f);
5185 sn->vm_state_size = qemu_ftell(f);
5188 term_printf("Error %d while writing VM\n", ret);
5192 /* create the snapshots */
5194 for(i = 0; i < MAX_DISKS; i++) {
5196 if (bdrv_has_snapshot(bs1)) {
5198 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5200 term_printf("Error while deleting snapshot on '%s'\n",
5201 bdrv_get_device_name(bs1));
5204 ret = bdrv_snapshot_create(bs1, sn);
5206 term_printf("Error while creating snapshot on '%s'\n",
5207 bdrv_get_device_name(bs1));
5213 if (saved_vm_running)
5217 void do_loadvm(const char *name)
5219 BlockDriverState *bs, *bs1;
5220 BlockDriverInfo bdi1, *bdi = &bdi1;
5223 int saved_vm_running;
5225 bs = get_bs_snapshots();
5227 term_printf("No block device supports snapshots\n");
5231 /* Flush all IO requests so they don't interfere with the new state. */
5234 saved_vm_running = vm_running;
5237 for(i = 0; i <= MAX_DISKS; i++) {
5239 if (bdrv_has_snapshot(bs1)) {
5240 ret = bdrv_snapshot_goto(bs1, name);
5243 term_printf("Warning: ");
5246 term_printf("Snapshots not supported on device '%s'\n",
5247 bdrv_get_device_name(bs1));
5250 term_printf("Could not find snapshot '%s' on device '%s'\n",
5251 name, bdrv_get_device_name(bs1));
5254 term_printf("Error %d while activating snapshot on '%s'\n",
5255 ret, bdrv_get_device_name(bs1));
5258 /* fatal on snapshot block device */
5265 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5266 term_printf("Device %s does not support VM state snapshots\n",
5267 bdrv_get_device_name(bs));
5271 /* restore the VM state */
5272 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5274 term_printf("Could not open VM state file\n");
5277 ret = qemu_loadvm_state(f);
5280 term_printf("Error %d while loading VM state\n", ret);
5283 if (saved_vm_running)
5287 void do_delvm(const char *name)
5289 BlockDriverState *bs, *bs1;
5292 bs = get_bs_snapshots();
5294 term_printf("No block device supports snapshots\n");
5298 for(i = 0; i <= MAX_DISKS; i++) {
5300 if (bdrv_has_snapshot(bs1)) {
5301 ret = bdrv_snapshot_delete(bs1, name);
5303 if (ret == -ENOTSUP)
5304 term_printf("Snapshots not supported on device '%s'\n",
5305 bdrv_get_device_name(bs1));
5307 term_printf("Error %d while deleting snapshot on '%s'\n",
5308 ret, bdrv_get_device_name(bs1));
5314 void do_info_snapshots(void)
5316 BlockDriverState *bs, *bs1;
5317 QEMUSnapshotInfo *sn_tab, *sn;
5321 bs = get_bs_snapshots();
5323 term_printf("No available block device supports snapshots\n");
5326 term_printf("Snapshot devices:");
5327 for(i = 0; i <= MAX_DISKS; i++) {
5329 if (bdrv_has_snapshot(bs1)) {
5331 term_printf(" %s", bdrv_get_device_name(bs1));
5336 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5338 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5341 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5342 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5343 for(i = 0; i < nb_sns; i++) {
5345 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5350 /***********************************************************/
5351 /* cpu save/restore */
5353 #if defined(TARGET_I386)
5355 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5357 qemu_put_be32(f, dt->selector);
5358 qemu_put_betl(f, dt->base);
5359 qemu_put_be32(f, dt->limit);
5360 qemu_put_be32(f, dt->flags);
5363 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5365 dt->selector = qemu_get_be32(f);
5366 dt->base = qemu_get_betl(f);
5367 dt->limit = qemu_get_be32(f);
5368 dt->flags = qemu_get_be32(f);
5371 void cpu_save(QEMUFile *f, void *opaque)
5373 CPUState *env = opaque;
5374 uint16_t fptag, fpus, fpuc, fpregs_format;
5378 for(i = 0; i < CPU_NB_REGS; i++)
5379 qemu_put_betls(f, &env->regs[i]);
5380 qemu_put_betls(f, &env->eip);
5381 qemu_put_betls(f, &env->eflags);
5382 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5383 qemu_put_be32s(f, &hflags);
5387 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5389 for(i = 0; i < 8; i++) {
5390 fptag |= ((!env->fptags[i]) << i);
5393 qemu_put_be16s(f, &fpuc);
5394 qemu_put_be16s(f, &fpus);
5395 qemu_put_be16s(f, &fptag);
5397 #ifdef USE_X86LDOUBLE
5402 qemu_put_be16s(f, &fpregs_format);
5404 for(i = 0; i < 8; i++) {
5405 #ifdef USE_X86LDOUBLE
5409 /* we save the real CPU data (in case of MMX usage only 'mant'
5410 contains the MMX register */
5411 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5412 qemu_put_be64(f, mant);
5413 qemu_put_be16(f, exp);
5416 /* if we use doubles for float emulation, we save the doubles to
5417 avoid losing information in case of MMX usage. It can give
5418 problems if the image is restored on a CPU where long
5419 doubles are used instead. */
5420 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5424 for(i = 0; i < 6; i++)
5425 cpu_put_seg(f, &env->segs[i]);
5426 cpu_put_seg(f, &env->ldt);
5427 cpu_put_seg(f, &env->tr);
5428 cpu_put_seg(f, &env->gdt);
5429 cpu_put_seg(f, &env->idt);
5431 qemu_put_be32s(f, &env->sysenter_cs);
5432 qemu_put_be32s(f, &env->sysenter_esp);
5433 qemu_put_be32s(f, &env->sysenter_eip);
5435 qemu_put_betls(f, &env->cr[0]);
5436 qemu_put_betls(f, &env->cr[2]);
5437 qemu_put_betls(f, &env->cr[3]);
5438 qemu_put_betls(f, &env->cr[4]);
5440 for(i = 0; i < 8; i++)
5441 qemu_put_betls(f, &env->dr[i]);
5444 qemu_put_be32s(f, &env->a20_mask);
5447 qemu_put_be32s(f, &env->mxcsr);
5448 for(i = 0; i < CPU_NB_REGS; i++) {
5449 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5450 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5453 #ifdef TARGET_X86_64
5454 qemu_put_be64s(f, &env->efer);
5455 qemu_put_be64s(f, &env->star);
5456 qemu_put_be64s(f, &env->lstar);
5457 qemu_put_be64s(f, &env->cstar);
5458 qemu_put_be64s(f, &env->fmask);
5459 qemu_put_be64s(f, &env->kernelgsbase);
5461 qemu_put_be32s(f, &env->smbase);
5464 #ifdef USE_X86LDOUBLE
5465 /* XXX: add that in a FPU generic layer */
5466 union x86_longdouble {
5471 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5472 #define EXPBIAS1 1023
5473 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5474 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5476 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5480 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5481 /* exponent + sign */
5482 e = EXPD1(temp) - EXPBIAS1 + 16383;
5483 e |= SIGND1(temp) >> 16;
5488 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5490 CPUState *env = opaque;
5493 uint16_t fpus, fpuc, fptag, fpregs_format;
5495 if (version_id != 3 && version_id != 4)
5497 for(i = 0; i < CPU_NB_REGS; i++)
5498 qemu_get_betls(f, &env->regs[i]);
5499 qemu_get_betls(f, &env->eip);
5500 qemu_get_betls(f, &env->eflags);
5501 qemu_get_be32s(f, &hflags);
5503 qemu_get_be16s(f, &fpuc);
5504 qemu_get_be16s(f, &fpus);
5505 qemu_get_be16s(f, &fptag);
5506 qemu_get_be16s(f, &fpregs_format);
5508 /* NOTE: we cannot always restore the FPU state if the image come
5509 from a host with a different 'USE_X86LDOUBLE' define. We guess
5510 if we are in an MMX state to restore correctly in that case. */
5511 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5512 for(i = 0; i < 8; i++) {
5516 switch(fpregs_format) {
5518 mant = qemu_get_be64(f);
5519 exp = qemu_get_be16(f);
5520 #ifdef USE_X86LDOUBLE
5521 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5523 /* difficult case */
5525 env->fpregs[i].mmx.MMX_Q(0) = mant;
5527 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5531 mant = qemu_get_be64(f);
5532 #ifdef USE_X86LDOUBLE
5534 union x86_longdouble *p;
5535 /* difficult case */
5536 p = (void *)&env->fpregs[i];
5541 fp64_to_fp80(p, mant);
5545 env->fpregs[i].mmx.MMX_Q(0) = mant;
5554 /* XXX: restore FPU round state */
5555 env->fpstt = (fpus >> 11) & 7;
5556 env->fpus = fpus & ~0x3800;
5558 for(i = 0; i < 8; i++) {
5559 env->fptags[i] = (fptag >> i) & 1;
5562 for(i = 0; i < 6; i++)
5563 cpu_get_seg(f, &env->segs[i]);
5564 cpu_get_seg(f, &env->ldt);
5565 cpu_get_seg(f, &env->tr);
5566 cpu_get_seg(f, &env->gdt);
5567 cpu_get_seg(f, &env->idt);
5569 qemu_get_be32s(f, &env->sysenter_cs);
5570 qemu_get_be32s(f, &env->sysenter_esp);
5571 qemu_get_be32s(f, &env->sysenter_eip);
5573 qemu_get_betls(f, &env->cr[0]);
5574 qemu_get_betls(f, &env->cr[2]);
5575 qemu_get_betls(f, &env->cr[3]);
5576 qemu_get_betls(f, &env->cr[4]);
5578 for(i = 0; i < 8; i++)
5579 qemu_get_betls(f, &env->dr[i]);
5582 qemu_get_be32s(f, &env->a20_mask);
5584 qemu_get_be32s(f, &env->mxcsr);
5585 for(i = 0; i < CPU_NB_REGS; i++) {
5586 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5587 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5590 #ifdef TARGET_X86_64
5591 qemu_get_be64s(f, &env->efer);
5592 qemu_get_be64s(f, &env->star);
5593 qemu_get_be64s(f, &env->lstar);
5594 qemu_get_be64s(f, &env->cstar);
5595 qemu_get_be64s(f, &env->fmask);
5596 qemu_get_be64s(f, &env->kernelgsbase);
5598 if (version_id >= 4)
5599 qemu_get_be32s(f, &env->smbase);
5601 /* XXX: compute hflags from scratch, except for CPL and IIF */
5602 env->hflags = hflags;
5607 #elif defined(TARGET_PPC)
5608 void cpu_save(QEMUFile *f, void *opaque)
5612 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5617 #elif defined(TARGET_MIPS)
5618 void cpu_save(QEMUFile *f, void *opaque)
5622 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5627 #elif defined(TARGET_SPARC)
5628 void cpu_save(QEMUFile *f, void *opaque)
5630 CPUState *env = opaque;
5634 for(i = 0; i < 8; i++)
5635 qemu_put_betls(f, &env->gregs[i]);
5636 for(i = 0; i < NWINDOWS * 16; i++)
5637 qemu_put_betls(f, &env->regbase[i]);
5640 for(i = 0; i < TARGET_FPREGS; i++) {
5646 qemu_put_be32(f, u.i);
5649 qemu_put_betls(f, &env->pc);
5650 qemu_put_betls(f, &env->npc);
5651 qemu_put_betls(f, &env->y);
5653 qemu_put_be32(f, tmp);
5654 qemu_put_betls(f, &env->fsr);
5655 qemu_put_betls(f, &env->tbr);
5656 #ifndef TARGET_SPARC64
5657 qemu_put_be32s(f, &env->wim);
5659 for(i = 0; i < 16; i++)
5660 qemu_put_be32s(f, &env->mmuregs[i]);
5664 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5666 CPUState *env = opaque;
5670 for(i = 0; i < 8; i++)
5671 qemu_get_betls(f, &env->gregs[i]);
5672 for(i = 0; i < NWINDOWS * 16; i++)
5673 qemu_get_betls(f, &env->regbase[i]);
5676 for(i = 0; i < TARGET_FPREGS; i++) {
5681 u.i = qemu_get_be32(f);
5685 qemu_get_betls(f, &env->pc);
5686 qemu_get_betls(f, &env->npc);
5687 qemu_get_betls(f, &env->y);
5688 tmp = qemu_get_be32(f);
5689 env->cwp = 0; /* needed to ensure that the wrapping registers are
5690 correctly updated */
5692 qemu_get_betls(f, &env->fsr);
5693 qemu_get_betls(f, &env->tbr);
5694 #ifndef TARGET_SPARC64
5695 qemu_get_be32s(f, &env->wim);
5697 for(i = 0; i < 16; i++)
5698 qemu_get_be32s(f, &env->mmuregs[i]);
5704 #elif defined(TARGET_ARM)
5706 void cpu_save(QEMUFile *f, void *opaque)
5709 CPUARMState *env = (CPUARMState *)opaque;
5711 for (i = 0; i < 16; i++) {
5712 qemu_put_be32(f, env->regs[i]);
5714 qemu_put_be32(f, cpsr_read(env));
5715 qemu_put_be32(f, env->spsr);
5716 for (i = 0; i < 6; i++) {
5717 qemu_put_be32(f, env->banked_spsr[i]);
5718 qemu_put_be32(f, env->banked_r13[i]);
5719 qemu_put_be32(f, env->banked_r14[i]);
5721 for (i = 0; i < 5; i++) {
5722 qemu_put_be32(f, env->usr_regs[i]);
5723 qemu_put_be32(f, env->fiq_regs[i]);
5725 qemu_put_be32(f, env->cp15.c0_cpuid);
5726 qemu_put_be32(f, env->cp15.c0_cachetype);
5727 qemu_put_be32(f, env->cp15.c1_sys);
5728 qemu_put_be32(f, env->cp15.c1_coproc);
5729 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5730 qemu_put_be32(f, env->cp15.c2_base);
5731 qemu_put_be32(f, env->cp15.c2_data);
5732 qemu_put_be32(f, env->cp15.c2_insn);
5733 qemu_put_be32(f, env->cp15.c3);
5734 qemu_put_be32(f, env->cp15.c5_insn);
5735 qemu_put_be32(f, env->cp15.c5_data);
5736 for (i = 0; i < 8; i++) {
5737 qemu_put_be32(f, env->cp15.c6_region[i]);
5739 qemu_put_be32(f, env->cp15.c6_insn);
5740 qemu_put_be32(f, env->cp15.c6_data);
5741 qemu_put_be32(f, env->cp15.c9_insn);
5742 qemu_put_be32(f, env->cp15.c9_data);
5743 qemu_put_be32(f, env->cp15.c13_fcse);
5744 qemu_put_be32(f, env->cp15.c13_context);
5745 qemu_put_be32(f, env->cp15.c15_cpar);
5747 qemu_put_be32(f, env->features);
5749 if (arm_feature(env, ARM_FEATURE_VFP)) {
5750 for (i = 0; i < 16; i++) {
5752 u.d = env->vfp.regs[i];
5753 qemu_put_be32(f, u.l.upper);
5754 qemu_put_be32(f, u.l.lower);
5756 for (i = 0; i < 16; i++) {
5757 qemu_put_be32(f, env->vfp.xregs[i]);
5760 /* TODO: Should use proper FPSCR access functions. */
5761 qemu_put_be32(f, env->vfp.vec_len);
5762 qemu_put_be32(f, env->vfp.vec_stride);
5765 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5766 for (i = 0; i < 16; i++) {
5767 qemu_put_be64(f, env->iwmmxt.regs[i]);
5769 for (i = 0; i < 16; i++) {
5770 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5775 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5777 CPUARMState *env = (CPUARMState *)opaque;
5780 if (version_id != 0)
5783 for (i = 0; i < 16; i++) {
5784 env->regs[i] = qemu_get_be32(f);
5786 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5787 env->spsr = qemu_get_be32(f);
5788 for (i = 0; i < 6; i++) {
5789 env->banked_spsr[i] = qemu_get_be32(f);
5790 env->banked_r13[i] = qemu_get_be32(f);
5791 env->banked_r14[i] = qemu_get_be32(f);
5793 for (i = 0; i < 5; i++) {
5794 env->usr_regs[i] = qemu_get_be32(f);
5795 env->fiq_regs[i] = qemu_get_be32(f);
5797 env->cp15.c0_cpuid = qemu_get_be32(f);
5798 env->cp15.c0_cachetype = qemu_get_be32(f);
5799 env->cp15.c1_sys = qemu_get_be32(f);
5800 env->cp15.c1_coproc = qemu_get_be32(f);
5801 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5802 env->cp15.c2_base = qemu_get_be32(f);
5803 env->cp15.c2_data = qemu_get_be32(f);
5804 env->cp15.c2_insn = qemu_get_be32(f);
5805 env->cp15.c3 = qemu_get_be32(f);
5806 env->cp15.c5_insn = qemu_get_be32(f);
5807 env->cp15.c5_data = qemu_get_be32(f);
5808 for (i = 0; i < 8; i++) {
5809 env->cp15.c6_region[i] = qemu_get_be32(f);
5811 env->cp15.c6_insn = qemu_get_be32(f);
5812 env->cp15.c6_data = qemu_get_be32(f);
5813 env->cp15.c9_insn = qemu_get_be32(f);
5814 env->cp15.c9_data = qemu_get_be32(f);
5815 env->cp15.c13_fcse = qemu_get_be32(f);
5816 env->cp15.c13_context = qemu_get_be32(f);
5817 env->cp15.c15_cpar = qemu_get_be32(f);
5819 env->features = qemu_get_be32(f);
5821 if (arm_feature(env, ARM_FEATURE_VFP)) {
5822 for (i = 0; i < 16; i++) {
5824 u.l.upper = qemu_get_be32(f);
5825 u.l.lower = qemu_get_be32(f);
5826 env->vfp.regs[i] = u.d;
5828 for (i = 0; i < 16; i++) {
5829 env->vfp.xregs[i] = qemu_get_be32(f);
5832 /* TODO: Should use proper FPSCR access functions. */
5833 env->vfp.vec_len = qemu_get_be32(f);
5834 env->vfp.vec_stride = qemu_get_be32(f);
5837 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5838 for (i = 0; i < 16; i++) {
5839 env->iwmmxt.regs[i] = qemu_get_be64(f);
5841 for (i = 0; i < 16; i++) {
5842 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5851 #warning No CPU save/restore functions
5855 /***********************************************************/
5856 /* ram save/restore */
5858 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5862 v = qemu_get_byte(f);
5865 if (qemu_get_buffer(f, buf, len) != len)
5869 v = qemu_get_byte(f);
5870 memset(buf, v, len);
5878 static int ram_load_v1(QEMUFile *f, void *opaque)
5882 if (qemu_get_be32(f) != phys_ram_size)
5884 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5885 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5892 #define BDRV_HASH_BLOCK_SIZE 1024
5893 #define IOBUF_SIZE 4096
5894 #define RAM_CBLOCK_MAGIC 0xfabe
5896 typedef struct RamCompressState {
5899 uint8_t buf[IOBUF_SIZE];
5902 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5905 memset(s, 0, sizeof(*s));
5907 ret = deflateInit2(&s->zstream, 1,
5909 9, Z_DEFAULT_STRATEGY);
5912 s->zstream.avail_out = IOBUF_SIZE;
5913 s->zstream.next_out = s->buf;
5917 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5919 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5920 qemu_put_be16(s->f, len);
5921 qemu_put_buffer(s->f, buf, len);
5924 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5928 s->zstream.avail_in = len;
5929 s->zstream.next_in = (uint8_t *)buf;
5930 while (s->zstream.avail_in > 0) {
5931 ret = deflate(&s->zstream, Z_NO_FLUSH);
5934 if (s->zstream.avail_out == 0) {
5935 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5936 s->zstream.avail_out = IOBUF_SIZE;
5937 s->zstream.next_out = s->buf;
5943 static void ram_compress_close(RamCompressState *s)
5947 /* compress last bytes */
5949 ret = deflate(&s->zstream, Z_FINISH);
5950 if (ret == Z_OK || ret == Z_STREAM_END) {
5951 len = IOBUF_SIZE - s->zstream.avail_out;
5953 ram_put_cblock(s, s->buf, len);
5955 s->zstream.avail_out = IOBUF_SIZE;
5956 s->zstream.next_out = s->buf;
5957 if (ret == Z_STREAM_END)
5964 deflateEnd(&s->zstream);
5967 typedef struct RamDecompressState {
5970 uint8_t buf[IOBUF_SIZE];
5971 } RamDecompressState;
5973 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5976 memset(s, 0, sizeof(*s));
5978 ret = inflateInit(&s->zstream);
5984 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5988 s->zstream.avail_out = len;
5989 s->zstream.next_out = buf;
5990 while (s->zstream.avail_out > 0) {
5991 if (s->zstream.avail_in == 0) {
5992 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5994 clen = qemu_get_be16(s->f);
5995 if (clen > IOBUF_SIZE)
5997 qemu_get_buffer(s->f, s->buf, clen);
5998 s->zstream.avail_in = clen;
5999 s->zstream.next_in = s->buf;
6001 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6002 if (ret != Z_OK && ret != Z_STREAM_END) {
6009 static void ram_decompress_close(RamDecompressState *s)
6011 inflateEnd(&s->zstream);
6014 static void ram_save(QEMUFile *f, void *opaque)
6017 RamCompressState s1, *s = &s1;
6020 qemu_put_be32(f, phys_ram_size);
6021 if (ram_compress_open(s, f) < 0)
6023 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6025 if (tight_savevm_enabled) {
6029 /* find if the memory block is available on a virtual
6032 for(j = 0; j < MAX_DISKS; j++) {
6034 sector_num = bdrv_hash_find(bs_table[j],
6035 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6036 if (sector_num >= 0)
6041 goto normal_compress;
6044 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6045 ram_compress_buf(s, buf, 10);
6051 ram_compress_buf(s, buf, 1);
6052 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6055 ram_compress_close(s);
6058 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6060 RamDecompressState s1, *s = &s1;
6064 if (version_id == 1)
6065 return ram_load_v1(f, opaque);
6066 if (version_id != 2)
6068 if (qemu_get_be32(f) != phys_ram_size)
6070 if (ram_decompress_open(s, f) < 0)
6072 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6073 if (ram_decompress_buf(s, buf, 1) < 0) {
6074 fprintf(stderr, "Error while reading ram block header\n");
6078 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6079 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6088 ram_decompress_buf(s, buf + 1, 9);
6090 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6091 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6092 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6095 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6096 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6097 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6098 bs_index, sector_num);
6105 printf("Error block header\n");
6109 ram_decompress_close(s);
6113 /***********************************************************/
6114 /* bottom halves (can be seen as timers which expire ASAP) */
6123 static QEMUBH *first_bh = NULL;
6125 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6128 bh = qemu_mallocz(sizeof(QEMUBH));
6132 bh->opaque = opaque;
6136 int qemu_bh_poll(void)
6155 void qemu_bh_schedule(QEMUBH *bh)
6157 CPUState *env = cpu_single_env;
6161 bh->next = first_bh;
6164 /* stop the currently executing CPU to execute the BH ASAP */
6166 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6170 void qemu_bh_cancel(QEMUBH *bh)
6173 if (bh->scheduled) {
6176 pbh = &(*pbh)->next;
6182 void qemu_bh_delete(QEMUBH *bh)
6188 /***********************************************************/
6189 /* machine registration */
6191 QEMUMachine *first_machine = NULL;
6193 int qemu_register_machine(QEMUMachine *m)
6196 pm = &first_machine;
6204 QEMUMachine *find_machine(const char *name)
6208 for(m = first_machine; m != NULL; m = m->next) {
6209 if (!strcmp(m->name, name))
6215 /***********************************************************/
6216 /* main execution loop */
6218 void gui_update(void *opaque)
6220 DisplayState *ds = opaque;
6221 ds->dpy_refresh(ds);
6222 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6225 struct vm_change_state_entry {
6226 VMChangeStateHandler *cb;
6228 LIST_ENTRY (vm_change_state_entry) entries;
6231 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6233 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6236 VMChangeStateEntry *e;
6238 e = qemu_mallocz(sizeof (*e));
6244 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6248 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6250 LIST_REMOVE (e, entries);
6254 static void vm_state_notify(int running)
6256 VMChangeStateEntry *e;
6258 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6259 e->cb(e->opaque, running);
6263 /* XXX: support several handlers */
6264 static VMStopHandler *vm_stop_cb;
6265 static void *vm_stop_opaque;
6267 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6270 vm_stop_opaque = opaque;
6274 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6288 void vm_stop(int reason)
6291 cpu_disable_ticks();
6295 vm_stop_cb(vm_stop_opaque, reason);
6302 /* reset/shutdown handler */
6304 typedef struct QEMUResetEntry {
6305 QEMUResetHandler *func;
6307 struct QEMUResetEntry *next;
6310 static QEMUResetEntry *first_reset_entry;
6311 static int reset_requested;
6312 static int shutdown_requested;
6313 static int powerdown_requested;
6315 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6317 QEMUResetEntry **pre, *re;
6319 pre = &first_reset_entry;
6320 while (*pre != NULL)
6321 pre = &(*pre)->next;
6322 re = qemu_mallocz(sizeof(QEMUResetEntry));
6324 re->opaque = opaque;
6329 static void qemu_system_reset(void)
6333 /* reset all devices */
6334 for(re = first_reset_entry; re != NULL; re = re->next) {
6335 re->func(re->opaque);
6339 void qemu_system_reset_request(void)
6342 shutdown_requested = 1;
6344 reset_requested = 1;
6347 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6350 void qemu_system_shutdown_request(void)
6352 shutdown_requested = 1;
6354 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6357 void qemu_system_powerdown_request(void)
6359 powerdown_requested = 1;
6361 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6364 void main_loop_wait(int timeout)
6366 IOHandlerRecord *ioh;
6367 fd_set rfds, wfds, xfds;
6376 /* XXX: need to suppress polling by better using win32 events */
6378 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6379 ret |= pe->func(pe->opaque);
6384 WaitObjects *w = &wait_objects;
6386 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6387 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6388 if (w->func[ret - WAIT_OBJECT_0])
6389 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6391 /* Check for additional signaled events */
6392 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6394 /* Check if event is signaled */
6395 ret2 = WaitForSingleObject(w->events[i], 0);
6396 if(ret2 == WAIT_OBJECT_0) {
6398 w->func[i](w->opaque[i]);
6399 } else if (ret2 == WAIT_TIMEOUT) {
6401 err = GetLastError();
6402 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6405 } else if (ret == WAIT_TIMEOUT) {
6407 err = GetLastError();
6408 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6412 /* poll any events */
6413 /* XXX: separate device handlers from system ones */
6418 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6422 (!ioh->fd_read_poll ||
6423 ioh->fd_read_poll(ioh->opaque) != 0)) {
6424 FD_SET(ioh->fd, &rfds);
6428 if (ioh->fd_write) {
6429 FD_SET(ioh->fd, &wfds);
6439 tv.tv_usec = timeout * 1000;
6441 #if defined(CONFIG_SLIRP)
6443 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6446 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6448 IOHandlerRecord **pioh;
6450 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6453 if (FD_ISSET(ioh->fd, &rfds)) {
6454 ioh->fd_read(ioh->opaque);
6456 if (FD_ISSET(ioh->fd, &wfds)) {
6457 ioh->fd_write(ioh->opaque);
6461 /* remove deleted IO handlers */
6462 pioh = &first_io_handler;
6472 #if defined(CONFIG_SLIRP)
6479 slirp_select_poll(&rfds, &wfds, &xfds);
6485 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6486 qemu_get_clock(vm_clock));
6487 /* run dma transfers, if any */
6491 /* real time timers */
6492 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6493 qemu_get_clock(rt_clock));
6495 /* Check bottom-halves last in case any of the earlier events triggered
6501 static CPUState *cur_cpu;
6506 #ifdef CONFIG_PROFILER
6511 cur_cpu = first_cpu;
6518 env = env->next_cpu;
6521 #ifdef CONFIG_PROFILER
6522 ti = profile_getclock();
6524 ret = cpu_exec(env);
6525 #ifdef CONFIG_PROFILER
6526 qemu_time += profile_getclock() - ti;
6528 if (ret == EXCP_HLT) {
6529 /* Give the next CPU a chance to run. */
6533 if (ret != EXCP_HALTED)
6535 /* all CPUs are halted ? */
6541 if (shutdown_requested) {
6542 ret = EXCP_INTERRUPT;
6545 if (reset_requested) {
6546 reset_requested = 0;
6547 qemu_system_reset();
6548 ret = EXCP_INTERRUPT;
6550 if (powerdown_requested) {
6551 powerdown_requested = 0;
6552 qemu_system_powerdown();
6553 ret = EXCP_INTERRUPT;
6555 if (ret == EXCP_DEBUG) {
6556 vm_stop(EXCP_DEBUG);
6558 /* If all cpus are halted then wait until the next IRQ */
6559 /* XXX: use timeout computed from timers */
6560 if (ret == EXCP_HALTED)
6567 #ifdef CONFIG_PROFILER
6568 ti = profile_getclock();
6570 main_loop_wait(timeout);
6571 #ifdef CONFIG_PROFILER
6572 dev_time += profile_getclock() - ti;
6575 cpu_disable_ticks();
6579 static void help(int exitcode)
6581 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6582 "usage: %s [options] [disk_image]\n"
6584 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6586 "Standard options:\n"
6587 "-M machine select emulated machine (-M ? for list)\n"
6588 "-cpu cpu select CPU (-cpu ? for list)\n"
6589 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6590 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6591 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6592 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6593 "-mtdblock file use 'file' as on-board Flash memory image\n"
6594 "-sd file use 'file' as SecureDigital card image\n"
6595 "-pflash file use 'file' as a parallel flash image\n"
6596 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6597 "-snapshot write to temporary files instead of disk image files\n"
6599 "-no-frame open SDL window without a frame and window decorations\n"
6600 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6601 "-no-quit disable SDL window close capability\n"
6604 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6606 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6607 "-smp n set the number of CPUs to 'n' [default=1]\n"
6608 "-nographic disable graphical output and redirect serial I/Os to console\n"
6609 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6611 "-k language use keyboard layout (for example \"fr\" for French)\n"
6614 "-audio-help print list of audio drivers and their options\n"
6615 "-soundhw c1,... enable audio support\n"
6616 " and only specified sound cards (comma separated list)\n"
6617 " use -soundhw ? to get the list of supported cards\n"
6618 " use -soundhw all to enable all of them\n"
6620 "-localtime set the real time clock to local time [default=utc]\n"
6621 "-full-screen start in full screen\n"
6623 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6625 "-usb enable the USB driver (will be the default soon)\n"
6626 "-usbdevice name add the host or guest USB device 'name'\n"
6627 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6628 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6630 "-name string set the name of the guest\n"
6632 "Network options:\n"
6633 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6634 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6636 "-net user[,vlan=n][,hostname=host]\n"
6637 " connect the user mode network stack to VLAN 'n' and send\n"
6638 " hostname 'host' to DHCP clients\n"
6641 "-net tap[,vlan=n],ifname=name\n"
6642 " connect the host TAP network interface to VLAN 'n'\n"
6644 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6645 " connect the host TAP network interface to VLAN 'n' and use\n"
6646 " the network script 'file' (default=%s);\n"
6647 " use 'script=no' to disable script execution;\n"
6648 " use 'fd=h' to connect to an already opened TAP interface\n"
6650 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6651 " connect the vlan 'n' to another VLAN using a socket connection\n"
6652 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6653 " connect the vlan 'n' to multicast maddr and port\n"
6654 "-net none use it alone to have zero network devices; if no -net option\n"
6655 " is provided, the default is '-net nic -net user'\n"
6658 "-tftp dir allow tftp access to files in dir [-net user]\n"
6659 "-bootp file advertise file in BOOTP replies\n"
6661 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6663 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6664 " redirect TCP or UDP connections from host to guest [-net user]\n"
6667 "Linux boot specific:\n"
6668 "-kernel bzImage use 'bzImage' as kernel image\n"
6669 "-append cmdline use 'cmdline' as kernel command line\n"
6670 "-initrd file use 'file' as initial ram disk\n"
6672 "Debug/Expert options:\n"
6673 "-monitor dev redirect the monitor to char device 'dev'\n"
6674 "-serial dev redirect the serial port to char device 'dev'\n"
6675 "-parallel dev redirect the parallel port to char device 'dev'\n"
6676 "-pidfile file Write PID to 'file'\n"
6677 "-S freeze CPU at startup (use 'c' to start execution)\n"
6678 "-s wait gdb connection to port\n"
6679 "-p port set gdb connection port [default=%s]\n"
6680 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6681 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6682 " translation (t=none or lba) (usually qemu can guess them)\n"
6683 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6685 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6686 "-no-kqemu disable KQEMU kernel module usage\n"
6688 #ifdef USE_CODE_COPY
6689 "-no-code-copy disable code copy acceleration\n"
6692 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6693 " (default is CL-GD5446 PCI VGA)\n"
6694 "-no-acpi disable ACPI\n"
6696 "-no-reboot exit instead of rebooting\n"
6697 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6698 "-vnc display start a VNC server on display\n"
6700 "-daemonize daemonize QEMU after initializing\n"
6702 "-option-rom rom load a file, rom, into the option ROM space\n"
6704 "-prom-env variable=value set OpenBIOS nvram variables\n"
6707 "During emulation, the following keys are useful:\n"
6708 "ctrl-alt-f toggle full screen\n"
6709 "ctrl-alt-n switch to virtual console 'n'\n"
6710 "ctrl-alt toggle mouse and keyboard grab\n"
6712 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6717 DEFAULT_NETWORK_SCRIPT,
6719 DEFAULT_GDBSTUB_PORT,
6724 #define HAS_ARG 0x0001
6738 QEMU_OPTION_mtdblock,
6742 QEMU_OPTION_snapshot,
6744 QEMU_OPTION_no_fd_bootchk,
6747 QEMU_OPTION_nographic,
6748 QEMU_OPTION_portrait,
6750 QEMU_OPTION_audio_help,
6751 QEMU_OPTION_soundhw,
6770 QEMU_OPTION_no_code_copy,
6772 QEMU_OPTION_localtime,
6773 QEMU_OPTION_cirrusvga,
6776 QEMU_OPTION_std_vga,
6778 QEMU_OPTION_monitor,
6780 QEMU_OPTION_parallel,
6782 QEMU_OPTION_full_screen,
6783 QEMU_OPTION_no_frame,
6784 QEMU_OPTION_alt_grab,
6785 QEMU_OPTION_no_quit,
6786 QEMU_OPTION_pidfile,
6787 QEMU_OPTION_no_kqemu,
6788 QEMU_OPTION_kernel_kqemu,
6789 QEMU_OPTION_win2k_hack,
6791 QEMU_OPTION_usbdevice,
6794 QEMU_OPTION_no_acpi,
6795 QEMU_OPTION_no_reboot,
6796 QEMU_OPTION_show_cursor,
6797 QEMU_OPTION_daemonize,
6798 QEMU_OPTION_option_rom,
6799 QEMU_OPTION_semihosting,
6801 QEMU_OPTION_prom_env,
6804 typedef struct QEMUOption {
6810 const QEMUOption qemu_options[] = {
6811 { "h", 0, QEMU_OPTION_h },
6812 { "help", 0, QEMU_OPTION_h },
6814 { "M", HAS_ARG, QEMU_OPTION_M },
6815 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6816 { "fda", HAS_ARG, QEMU_OPTION_fda },
6817 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6818 { "hda", HAS_ARG, QEMU_OPTION_hda },
6819 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6820 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6821 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6822 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6823 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6824 { "sd", HAS_ARG, QEMU_OPTION_sd },
6825 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6826 { "boot", HAS_ARG, QEMU_OPTION_boot },
6827 { "snapshot", 0, QEMU_OPTION_snapshot },
6829 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6831 { "m", HAS_ARG, QEMU_OPTION_m },
6832 { "nographic", 0, QEMU_OPTION_nographic },
6833 { "portrait", 0, QEMU_OPTION_portrait },
6834 { "k", HAS_ARG, QEMU_OPTION_k },
6836 { "audio-help", 0, QEMU_OPTION_audio_help },
6837 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6840 { "net", HAS_ARG, QEMU_OPTION_net},
6842 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6843 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6845 { "smb", HAS_ARG, QEMU_OPTION_smb },
6847 { "redir", HAS_ARG, QEMU_OPTION_redir },
6850 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6851 { "append", HAS_ARG, QEMU_OPTION_append },
6852 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6854 { "S", 0, QEMU_OPTION_S },
6855 { "s", 0, QEMU_OPTION_s },
6856 { "p", HAS_ARG, QEMU_OPTION_p },
6857 { "d", HAS_ARG, QEMU_OPTION_d },
6858 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6859 { "L", HAS_ARG, QEMU_OPTION_L },
6860 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6862 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6863 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6865 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6866 { "g", 1, QEMU_OPTION_g },
6868 { "localtime", 0, QEMU_OPTION_localtime },
6869 { "std-vga", 0, QEMU_OPTION_std_vga },
6870 { "echr", HAS_ARG, QEMU_OPTION_echr },
6871 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6872 { "serial", HAS_ARG, QEMU_OPTION_serial },
6873 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6874 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6875 { "full-screen", 0, QEMU_OPTION_full_screen },
6877 { "no-frame", 0, QEMU_OPTION_no_frame },
6878 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6879 { "no-quit", 0, QEMU_OPTION_no_quit },
6881 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6882 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6883 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6884 { "smp", HAS_ARG, QEMU_OPTION_smp },
6885 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6887 /* temporary options */
6888 { "usb", 0, QEMU_OPTION_usb },
6889 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6890 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6891 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6892 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6893 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6894 { "daemonize", 0, QEMU_OPTION_daemonize },
6895 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6896 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6897 { "semihosting", 0, QEMU_OPTION_semihosting },
6899 { "name", HAS_ARG, QEMU_OPTION_name },
6900 #if defined(TARGET_SPARC)
6901 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6906 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6908 /* this stack is only used during signal handling */
6909 #define SIGNAL_STACK_SIZE 32768
6911 static uint8_t *signal_stack;
6915 /* password input */
6917 int qemu_key_check(BlockDriverState *bs, const char *name)
6922 if (!bdrv_is_encrypted(bs))
6925 term_printf("%s is encrypted.\n", name);
6926 for(i = 0; i < 3; i++) {
6927 monitor_readline("Password: ", 1, password, sizeof(password));
6928 if (bdrv_set_key(bs, password) == 0)
6930 term_printf("invalid password\n");
6935 static BlockDriverState *get_bdrv(int index)
6937 BlockDriverState *bs;
6940 bs = bs_table[index];
6941 } else if (index < 6) {
6942 bs = fd_table[index - 4];
6949 static void read_passwords(void)
6951 BlockDriverState *bs;
6954 for(i = 0; i < 6; i++) {
6957 qemu_key_check(bs, bdrv_get_device_name(bs));
6961 /* XXX: currently we cannot use simultaneously different CPUs */
6962 void register_machines(void)
6964 #if defined(TARGET_I386)
6965 qemu_register_machine(&pc_machine);
6966 qemu_register_machine(&isapc_machine);
6967 #elif defined(TARGET_PPC)
6968 qemu_register_machine(&heathrow_machine);
6969 qemu_register_machine(&core99_machine);
6970 qemu_register_machine(&prep_machine);
6971 qemu_register_machine(&ref405ep_machine);
6972 qemu_register_machine(&taihu_machine);
6973 #elif defined(TARGET_MIPS)
6974 qemu_register_machine(&mips_machine);
6975 qemu_register_machine(&mips_malta_machine);
6976 qemu_register_machine(&mips_pica61_machine);
6977 #elif defined(TARGET_SPARC)
6978 #ifdef TARGET_SPARC64
6979 qemu_register_machine(&sun4u_machine);
6981 qemu_register_machine(&ss5_machine);
6982 qemu_register_machine(&ss10_machine);
6984 #elif defined(TARGET_ARM)
6985 qemu_register_machine(&integratorcp_machine);
6986 qemu_register_machine(&versatilepb_machine);
6987 qemu_register_machine(&versatileab_machine);
6988 qemu_register_machine(&realview_machine);
6989 qemu_register_machine(&akitapda_machine);
6990 qemu_register_machine(&spitzpda_machine);
6991 qemu_register_machine(&borzoipda_machine);
6992 qemu_register_machine(&terrierpda_machine);
6993 #elif defined(TARGET_SH4)
6994 qemu_register_machine(&shix_machine);
6995 #elif defined(TARGET_ALPHA)
6997 #elif defined(TARGET_M68K)
6998 qemu_register_machine(&mcf5208evb_machine);
6999 qemu_register_machine(&an5206_machine);
7001 #error unsupported CPU
7006 struct soundhw soundhw[] = {
7007 #ifdef HAS_AUDIO_CHOICE
7014 { .init_isa = pcspk_audio_init }
7019 "Creative Sound Blaster 16",
7022 { .init_isa = SB16_init }
7029 "Yamaha YMF262 (OPL3)",
7031 "Yamaha YM3812 (OPL2)",
7035 { .init_isa = Adlib_init }
7042 "Gravis Ultrasound GF1",
7045 { .init_isa = GUS_init }
7051 "ENSONIQ AudioPCI ES1370",
7054 { .init_pci = es1370_init }
7058 { NULL, NULL, 0, 0, { NULL } }
7061 static void select_soundhw (const char *optarg)
7065 if (*optarg == '?') {
7068 printf ("Valid sound card names (comma separated):\n");
7069 for (c = soundhw; c->name; ++c) {
7070 printf ("%-11s %s\n", c->name, c->descr);
7072 printf ("\n-soundhw all will enable all of the above\n");
7073 exit (*optarg != '?');
7081 if (!strcmp (optarg, "all")) {
7082 for (c = soundhw; c->name; ++c) {
7090 e = strchr (p, ',');
7091 l = !e ? strlen (p) : (size_t) (e - p);
7093 for (c = soundhw; c->name; ++c) {
7094 if (!strncmp (c->name, p, l)) {
7103 "Unknown sound card name (too big to show)\n");
7106 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7111 p += l + (e != NULL);
7115 goto show_valid_cards;
7121 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7123 exit(STATUS_CONTROL_C_EXIT);
7128 #define MAX_NET_CLIENTS 32
7130 int main(int argc, char **argv)
7132 #ifdef CONFIG_GDBSTUB
7134 const char *gdbstub_port;
7136 int i, cdrom_index, pflash_index;
7137 int snapshot, linux_boot;
7138 const char *initrd_filename;
7139 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7140 const char *pflash_filename[MAX_PFLASH];
7141 const char *sd_filename;
7142 const char *mtd_filename;
7143 const char *kernel_filename, *kernel_cmdline;
7144 DisplayState *ds = &display_state;
7145 int cyls, heads, secs, translation;
7146 char net_clients[MAX_NET_CLIENTS][256];
7149 const char *r, *optarg;
7150 CharDriverState *monitor_hd;
7151 char monitor_device[128];
7152 char serial_devices[MAX_SERIAL_PORTS][128];
7153 int serial_device_index;
7154 char parallel_devices[MAX_PARALLEL_PORTS][128];
7155 int parallel_device_index;
7156 const char *loadvm = NULL;
7157 QEMUMachine *machine;
7158 const char *cpu_model;
7159 char usb_devices[MAX_USB_CMDLINE][128];
7160 int usb_devices_index;
7162 const char *pid_file = NULL;
7165 LIST_INIT (&vm_change_state_head);
7168 struct sigaction act;
7169 sigfillset(&act.sa_mask);
7171 act.sa_handler = SIG_IGN;
7172 sigaction(SIGPIPE, &act, NULL);
7175 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7176 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7177 QEMU to run on a single CPU */
7182 h = GetCurrentProcess();
7183 if (GetProcessAffinityMask(h, &mask, &smask)) {
7184 for(i = 0; i < 32; i++) {
7185 if (mask & (1 << i))
7190 SetProcessAffinityMask(h, mask);
7196 register_machines();
7197 machine = first_machine;
7199 initrd_filename = NULL;
7200 for(i = 0; i < MAX_FD; i++)
7201 fd_filename[i] = NULL;
7202 for(i = 0; i < MAX_DISKS; i++)
7203 hd_filename[i] = NULL;
7204 for(i = 0; i < MAX_PFLASH; i++)
7205 pflash_filename[i] = NULL;
7208 mtd_filename = NULL;
7209 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7210 vga_ram_size = VGA_RAM_SIZE;
7211 #ifdef CONFIG_GDBSTUB
7213 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7217 kernel_filename = NULL;
7218 kernel_cmdline = "";
7224 cyls = heads = secs = 0;
7225 translation = BIOS_ATA_TRANSLATION_AUTO;
7226 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7228 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7229 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7230 serial_devices[i][0] = '\0';
7231 serial_device_index = 0;
7233 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7234 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7235 parallel_devices[i][0] = '\0';
7236 parallel_device_index = 0;
7238 usb_devices_index = 0;
7243 /* default mac address of the first network interface */
7251 hd_filename[0] = argv[optind++];
7253 const QEMUOption *popt;
7256 /* Treat --foo the same as -foo. */
7259 popt = qemu_options;
7262 fprintf(stderr, "%s: invalid option -- '%s'\n",
7266 if (!strcmp(popt->name, r + 1))
7270 if (popt->flags & HAS_ARG) {
7271 if (optind >= argc) {
7272 fprintf(stderr, "%s: option '%s' requires an argument\n",
7276 optarg = argv[optind++];
7281 switch(popt->index) {
7283 machine = find_machine(optarg);
7286 printf("Supported machines are:\n");
7287 for(m = first_machine; m != NULL; m = m->next) {
7288 printf("%-10s %s%s\n",
7290 m == first_machine ? " (default)" : "");
7292 exit(*optarg != '?');
7295 case QEMU_OPTION_cpu:
7296 /* hw initialization will check this */
7297 if (*optarg == '?') {
7298 #if defined(TARGET_PPC)
7299 ppc_cpu_list(stdout, &fprintf);
7300 #elif defined(TARGET_ARM)
7302 #elif defined(TARGET_MIPS)
7303 mips_cpu_list(stdout, &fprintf);
7304 #elif defined(TARGET_SPARC)
7305 sparc_cpu_list(stdout, &fprintf);
7312 case QEMU_OPTION_initrd:
7313 initrd_filename = optarg;
7315 case QEMU_OPTION_hda:
7316 case QEMU_OPTION_hdb:
7317 case QEMU_OPTION_hdc:
7318 case QEMU_OPTION_hdd:
7321 hd_index = popt->index - QEMU_OPTION_hda;
7322 hd_filename[hd_index] = optarg;
7323 if (hd_index == cdrom_index)
7327 case QEMU_OPTION_mtdblock:
7328 mtd_filename = optarg;
7330 case QEMU_OPTION_sd:
7331 sd_filename = optarg;
7333 case QEMU_OPTION_pflash:
7334 if (pflash_index >= MAX_PFLASH) {
7335 fprintf(stderr, "qemu: too many parallel flash images\n");
7338 pflash_filename[pflash_index++] = optarg;
7340 case QEMU_OPTION_snapshot:
7343 case QEMU_OPTION_hdachs:
7347 cyls = strtol(p, (char **)&p, 0);
7348 if (cyls < 1 || cyls > 16383)
7353 heads = strtol(p, (char **)&p, 0);
7354 if (heads < 1 || heads > 16)
7359 secs = strtol(p, (char **)&p, 0);
7360 if (secs < 1 || secs > 63)
7364 if (!strcmp(p, "none"))
7365 translation = BIOS_ATA_TRANSLATION_NONE;
7366 else if (!strcmp(p, "lba"))
7367 translation = BIOS_ATA_TRANSLATION_LBA;
7368 else if (!strcmp(p, "auto"))
7369 translation = BIOS_ATA_TRANSLATION_AUTO;
7372 } else if (*p != '\0') {
7374 fprintf(stderr, "qemu: invalid physical CHS format\n");
7379 case QEMU_OPTION_nographic:
7380 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7381 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7382 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7385 case QEMU_OPTION_portrait:
7388 case QEMU_OPTION_kernel:
7389 kernel_filename = optarg;
7391 case QEMU_OPTION_append:
7392 kernel_cmdline = optarg;
7394 case QEMU_OPTION_cdrom:
7395 if (cdrom_index >= 0) {
7396 hd_filename[cdrom_index] = optarg;
7399 case QEMU_OPTION_boot:
7400 boot_device = optarg[0];
7401 if (boot_device != 'a' &&
7402 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7404 boot_device != 'n' &&
7406 boot_device != 'c' && boot_device != 'd') {
7407 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7411 case QEMU_OPTION_fda:
7412 fd_filename[0] = optarg;
7414 case QEMU_OPTION_fdb:
7415 fd_filename[1] = optarg;
7418 case QEMU_OPTION_no_fd_bootchk:
7422 case QEMU_OPTION_no_code_copy:
7423 code_copy_enabled = 0;
7425 case QEMU_OPTION_net:
7426 if (nb_net_clients >= MAX_NET_CLIENTS) {
7427 fprintf(stderr, "qemu: too many network clients\n");
7430 pstrcpy(net_clients[nb_net_clients],
7431 sizeof(net_clients[0]),
7436 case QEMU_OPTION_tftp:
7437 tftp_prefix = optarg;
7439 case QEMU_OPTION_bootp:
7440 bootp_filename = optarg;
7443 case QEMU_OPTION_smb:
7444 net_slirp_smb(optarg);
7447 case QEMU_OPTION_redir:
7448 net_slirp_redir(optarg);
7452 case QEMU_OPTION_audio_help:
7456 case QEMU_OPTION_soundhw:
7457 select_soundhw (optarg);
7464 ram_size = atoi(optarg) * 1024 * 1024;
7467 if (ram_size > PHYS_RAM_MAX_SIZE) {
7468 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7469 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7478 mask = cpu_str_to_log_mask(optarg);
7480 printf("Log items (comma separated):\n");
7481 for(item = cpu_log_items; item->mask != 0; item++) {
7482 printf("%-10s %s\n", item->name, item->help);
7489 #ifdef CONFIG_GDBSTUB
7494 gdbstub_port = optarg;
7504 keyboard_layout = optarg;
7506 case QEMU_OPTION_localtime:
7509 case QEMU_OPTION_cirrusvga:
7510 cirrus_vga_enabled = 1;
7513 case QEMU_OPTION_vmsvga:
7514 cirrus_vga_enabled = 0;
7517 case QEMU_OPTION_std_vga:
7518 cirrus_vga_enabled = 0;
7526 w = strtol(p, (char **)&p, 10);
7529 fprintf(stderr, "qemu: invalid resolution or depth\n");
7535 h = strtol(p, (char **)&p, 10);
7540 depth = strtol(p, (char **)&p, 10);
7541 if (depth != 8 && depth != 15 && depth != 16 &&
7542 depth != 24 && depth != 32)
7544 } else if (*p == '\0') {
7545 depth = graphic_depth;
7552 graphic_depth = depth;
7555 case QEMU_OPTION_echr:
7558 term_escape_char = strtol(optarg, &r, 0);
7560 printf("Bad argument to echr\n");
7563 case QEMU_OPTION_monitor:
7564 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7566 case QEMU_OPTION_serial:
7567 if (serial_device_index >= MAX_SERIAL_PORTS) {
7568 fprintf(stderr, "qemu: too many serial ports\n");
7571 pstrcpy(serial_devices[serial_device_index],
7572 sizeof(serial_devices[0]), optarg);
7573 serial_device_index++;
7575 case QEMU_OPTION_parallel:
7576 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7577 fprintf(stderr, "qemu: too many parallel ports\n");
7580 pstrcpy(parallel_devices[parallel_device_index],
7581 sizeof(parallel_devices[0]), optarg);
7582 parallel_device_index++;
7584 case QEMU_OPTION_loadvm:
7587 case QEMU_OPTION_full_screen:
7591 case QEMU_OPTION_no_frame:
7594 case QEMU_OPTION_alt_grab:
7597 case QEMU_OPTION_no_quit:
7601 case QEMU_OPTION_pidfile:
7605 case QEMU_OPTION_win2k_hack:
7606 win2k_install_hack = 1;
7610 case QEMU_OPTION_no_kqemu:
7613 case QEMU_OPTION_kernel_kqemu:
7617 case QEMU_OPTION_usb:
7620 case QEMU_OPTION_usbdevice:
7622 if (usb_devices_index >= MAX_USB_CMDLINE) {
7623 fprintf(stderr, "Too many USB devices\n");
7626 pstrcpy(usb_devices[usb_devices_index],
7627 sizeof(usb_devices[usb_devices_index]),
7629 usb_devices_index++;
7631 case QEMU_OPTION_smp:
7632 smp_cpus = atoi(optarg);
7633 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7634 fprintf(stderr, "Invalid number of CPUs\n");
7638 case QEMU_OPTION_vnc:
7639 vnc_display = optarg;
7641 case QEMU_OPTION_no_acpi:
7644 case QEMU_OPTION_no_reboot:
7647 case QEMU_OPTION_show_cursor:
7650 case QEMU_OPTION_daemonize:
7653 case QEMU_OPTION_option_rom:
7654 if (nb_option_roms >= MAX_OPTION_ROMS) {
7655 fprintf(stderr, "Too many option ROMs\n");
7658 option_rom[nb_option_roms] = optarg;
7661 case QEMU_OPTION_semihosting:
7662 semihosting_enabled = 1;
7664 case QEMU_OPTION_name:
7668 case QEMU_OPTION_prom_env:
7669 if (nb_prom_envs >= MAX_PROM_ENVS) {
7670 fprintf(stderr, "Too many prom variables\n");
7673 prom_envs[nb_prom_envs] = optarg;
7682 if (daemonize && !nographic && vnc_display == NULL) {
7683 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7690 if (pipe(fds) == -1)
7701 len = read(fds[0], &status, 1);
7702 if (len == -1 && (errno == EINTR))
7707 else if (status == 1) {
7708 fprintf(stderr, "Could not acquire pidfile\n");
7726 signal(SIGTSTP, SIG_IGN);
7727 signal(SIGTTOU, SIG_IGN);
7728 signal(SIGTTIN, SIG_IGN);
7732 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7735 write(fds[1], &status, 1);
7737 fprintf(stderr, "Could not acquire pid file\n");
7745 linux_boot = (kernel_filename != NULL);
7748 boot_device != 'n' &&
7749 hd_filename[0] == '\0' &&
7750 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7751 fd_filename[0] == '\0')
7754 /* boot to floppy or the default cd if no hard disk defined yet */
7755 if (hd_filename[0] == '\0' && boot_device == 'c') {
7756 if (fd_filename[0] != '\0')
7762 setvbuf(stdout, NULL, _IOLBF, 0);
7772 /* init network clients */
7773 if (nb_net_clients == 0) {
7774 /* if no clients, we use a default config */
7775 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7777 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7782 for(i = 0;i < nb_net_clients; i++) {
7783 if (net_client_init(net_clients[i]) < 0)
7786 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7787 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7789 if (vlan->nb_guest_devs == 0) {
7790 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7793 if (vlan->nb_host_devs == 0)
7795 "Warning: vlan %d is not connected to host network\n",
7800 if (boot_device == 'n') {
7801 for (i = 0; i < nb_nics; i++) {
7802 const char *model = nd_table[i].model;
7806 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7807 if (get_image_size(buf) > 0) {
7808 option_rom[nb_option_roms] = strdup(buf);
7814 fprintf(stderr, "No valid PXE rom found for network device\n");
7817 boot_device = 'c'; /* to prevent confusion by the BIOS */
7821 /* init the memory */
7822 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7824 phys_ram_base = qemu_vmalloc(phys_ram_size);
7825 if (!phys_ram_base) {
7826 fprintf(stderr, "Could not allocate physical memory\n");
7830 /* we always create the cdrom drive, even if no disk is there */
7832 if (cdrom_index >= 0) {
7833 bs_table[cdrom_index] = bdrv_new("cdrom");
7834 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7837 /* open the virtual block devices */
7838 for(i = 0; i < MAX_DISKS; i++) {
7839 if (hd_filename[i]) {
7842 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7843 bs_table[i] = bdrv_new(buf);
7845 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7846 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7850 if (i == 0 && cyls != 0) {
7851 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7852 bdrv_set_translation_hint(bs_table[i], translation);
7857 /* we always create at least one floppy disk */
7858 fd_table[0] = bdrv_new("fda");
7859 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7861 for(i = 0; i < MAX_FD; i++) {
7862 if (fd_filename[i]) {
7865 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7866 fd_table[i] = bdrv_new(buf);
7867 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7869 if (fd_filename[i][0] != '\0') {
7870 if (bdrv_open(fd_table[i], fd_filename[i],
7871 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7872 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7880 /* Open the virtual parallel flash block devices */
7881 for(i = 0; i < MAX_PFLASH; i++) {
7882 if (pflash_filename[i]) {
7883 if (!pflash_table[i]) {
7885 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7886 pflash_table[i] = bdrv_new(buf);
7888 if (bdrv_open(pflash_table[i], pflash_filename[i],
7889 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7890 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7891 pflash_filename[i]);
7897 sd_bdrv = bdrv_new ("sd");
7898 /* FIXME: This isn't really a floppy, but it's a reasonable
7900 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7902 if (bdrv_open(sd_bdrv, sd_filename,
7903 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7904 fprintf(stderr, "qemu: could not open SD card image %s\n",
7907 qemu_key_check(sd_bdrv, sd_filename);
7911 mtd_bdrv = bdrv_new ("mtd");
7912 if (bdrv_open(mtd_bdrv, mtd_filename,
7913 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7914 qemu_key_check(mtd_bdrv, mtd_filename)) {
7915 fprintf(stderr, "qemu: could not open Flash image %s\n",
7917 bdrv_delete(mtd_bdrv);
7922 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7923 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7928 memset(&display_state, 0, sizeof(display_state));
7930 /* nearly nothing to do */
7931 dumb_display_init(ds);
7932 } else if (vnc_display != NULL) {
7933 vnc_display_init(ds, vnc_display);
7935 #if defined(CONFIG_SDL)
7936 sdl_display_init(ds, full_screen, no_frame);
7937 #elif defined(CONFIG_COCOA)
7938 cocoa_display_init(ds, full_screen);
7942 /* Maintain compatibility with multiple stdio monitors */
7943 if (!strcmp(monitor_device,"stdio")) {
7944 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7945 if (!strcmp(serial_devices[i],"mon:stdio")) {
7946 monitor_device[0] = '\0';
7948 } else if (!strcmp(serial_devices[i],"stdio")) {
7949 monitor_device[0] = '\0';
7950 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7955 if (monitor_device[0] != '\0') {
7956 monitor_hd = qemu_chr_open(monitor_device);
7958 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7961 monitor_init(monitor_hd, !nographic);
7964 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7965 const char *devname = serial_devices[i];
7966 if (devname[0] != '\0' && strcmp(devname, "none")) {
7967 serial_hds[i] = qemu_chr_open(devname);
7968 if (!serial_hds[i]) {
7969 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7973 if (!strcmp(devname, "vc"))
7974 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7978 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7979 const char *devname = parallel_devices[i];
7980 if (devname[0] != '\0' && strcmp(devname, "none")) {
7981 parallel_hds[i] = qemu_chr_open(devname);
7982 if (!parallel_hds[i]) {
7983 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7987 if (!strcmp(devname, "vc"))
7988 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7992 machine->init(ram_size, vga_ram_size, boot_device,
7993 ds, fd_filename, snapshot,
7994 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7996 /* init USB devices */
7998 for(i = 0; i < usb_devices_index; i++) {
7999 if (usb_device_add(usb_devices[i]) < 0) {
8000 fprintf(stderr, "Warning: could not add USB device %s\n",
8006 if (display_state.dpy_refresh) {
8007 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8008 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8011 #ifdef CONFIG_GDBSTUB
8013 /* XXX: use standard host:port notation and modify options
8015 if (gdbserver_start(gdbstub_port) < 0) {
8016 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8027 /* XXX: simplify init */
8040 len = write(fds[1], &status, 1);
8041 if (len == -1 && (errno == EINTR))
8047 TFR(fd = open("/dev/null", O_RDWR));