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, 0);
2927 } else if (strstart(filename, "vc:", &p)) {
2928 return text_console_init(&display_state, p);
2929 } else if (!strcmp(filename, "null")) {
2930 return qemu_chr_open_null();
2932 if (strstart(filename, "tcp:", &p)) {
2933 return qemu_chr_open_tcp(p, 0, 0);
2935 if (strstart(filename, "telnet:", &p)) {
2936 return qemu_chr_open_tcp(p, 1, 0);
2938 if (strstart(filename, "udp:", &p)) {
2939 return qemu_chr_open_udp(p);
2941 if (strstart(filename, "mon:", &p)) {
2942 CharDriverState *drv = qemu_chr_open(p);
2944 drv = qemu_chr_open_mux(drv);
2945 monitor_init(drv, !nographic);
2948 printf("Unable to open driver: %s\n", p);
2952 if (strstart(filename, "unix:", &p)) {
2953 return qemu_chr_open_tcp(p, 0, 1);
2954 } else if (strstart(filename, "file:", &p)) {
2955 return qemu_chr_open_file_out(p);
2956 } else if (strstart(filename, "pipe:", &p)) {
2957 return qemu_chr_open_pipe(p);
2958 } else if (!strcmp(filename, "pty")) {
2959 return qemu_chr_open_pty();
2960 } else if (!strcmp(filename, "stdio")) {
2961 return qemu_chr_open_stdio();
2963 #if defined(__linux__)
2964 if (strstart(filename, "/dev/parport", NULL)) {
2965 return qemu_chr_open_pp(filename);
2968 #if defined(__linux__) || defined(__sun__)
2969 if (strstart(filename, "/dev/", NULL)) {
2970 return qemu_chr_open_tty(filename);
2974 if (strstart(filename, "COM", NULL)) {
2975 return qemu_chr_open_win(filename);
2977 if (strstart(filename, "pipe:", &p)) {
2978 return qemu_chr_open_win_pipe(p);
2980 if (strstart(filename, "con:", NULL)) {
2981 return qemu_chr_open_win_con(filename);
2983 if (strstart(filename, "file:", &p)) {
2984 return qemu_chr_open_win_file_out(p);
2992 void qemu_chr_close(CharDriverState *chr)
2995 chr->chr_close(chr);
2998 /***********************************************************/
2999 /* network device redirectors */
3001 void hex_dump(FILE *f, const uint8_t *buf, int size)
3005 for(i=0;i<size;i+=16) {
3009 fprintf(f, "%08x ", i);
3012 fprintf(f, " %02x", buf[i+j]);
3017 for(j=0;j<len;j++) {
3019 if (c < ' ' || c > '~')
3021 fprintf(f, "%c", c);
3027 static int parse_macaddr(uint8_t *macaddr, const char *p)
3030 for(i = 0; i < 6; i++) {
3031 macaddr[i] = strtol(p, (char **)&p, 16);
3044 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3049 p1 = strchr(p, sep);
3055 if (len > buf_size - 1)
3057 memcpy(buf, p, len);
3064 int parse_host_src_port(struct sockaddr_in *haddr,
3065 struct sockaddr_in *saddr,
3066 const char *input_str)
3068 char *str = strdup(input_str);
3069 char *host_str = str;
3074 * Chop off any extra arguments at the end of the string which
3075 * would start with a comma, then fill in the src port information
3076 * if it was provided else use the "any address" and "any port".
3078 if ((ptr = strchr(str,',')))
3081 if ((src_str = strchr(input_str,'@'))) {
3086 if (parse_host_port(haddr, host_str) < 0)
3089 if (!src_str || *src_str == '\0')
3092 if (parse_host_port(saddr, src_str) < 0)
3103 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3111 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3113 saddr->sin_family = AF_INET;
3114 if (buf[0] == '\0') {
3115 saddr->sin_addr.s_addr = 0;
3117 if (isdigit(buf[0])) {
3118 if (!inet_aton(buf, &saddr->sin_addr))
3121 if ((he = gethostbyname(buf)) == NULL)
3123 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3126 port = strtol(p, (char **)&r, 0);
3129 saddr->sin_port = htons(port);
3134 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3139 len = MIN(108, strlen(str));
3140 p = strchr(str, ',');
3142 len = MIN(len, p - str);
3144 memset(uaddr, 0, sizeof(*uaddr));
3146 uaddr->sun_family = AF_UNIX;
3147 memcpy(uaddr->sun_path, str, len);
3153 /* find or alloc a new VLAN */
3154 VLANState *qemu_find_vlan(int id)
3156 VLANState **pvlan, *vlan;
3157 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3161 vlan = qemu_mallocz(sizeof(VLANState));
3166 pvlan = &first_vlan;
3167 while (*pvlan != NULL)
3168 pvlan = &(*pvlan)->next;
3173 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3174 IOReadHandler *fd_read,
3175 IOCanRWHandler *fd_can_read,
3178 VLANClientState *vc, **pvc;
3179 vc = qemu_mallocz(sizeof(VLANClientState));
3182 vc->fd_read = fd_read;
3183 vc->fd_can_read = fd_can_read;
3184 vc->opaque = opaque;
3188 pvc = &vlan->first_client;
3189 while (*pvc != NULL)
3190 pvc = &(*pvc)->next;
3195 int qemu_can_send_packet(VLANClientState *vc1)
3197 VLANState *vlan = vc1->vlan;
3198 VLANClientState *vc;
3200 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3202 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3209 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3211 VLANState *vlan = vc1->vlan;
3212 VLANClientState *vc;
3215 printf("vlan %d send:\n", vlan->id);
3216 hex_dump(stdout, buf, size);
3218 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3220 vc->fd_read(vc->opaque, buf, size);
3225 #if defined(CONFIG_SLIRP)
3227 /* slirp network adapter */
3229 static int slirp_inited;
3230 static VLANClientState *slirp_vc;
3232 int slirp_can_output(void)
3234 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3237 void slirp_output(const uint8_t *pkt, int pkt_len)
3240 printf("slirp output:\n");
3241 hex_dump(stdout, pkt, pkt_len);
3245 qemu_send_packet(slirp_vc, pkt, pkt_len);
3248 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3251 printf("slirp input:\n");
3252 hex_dump(stdout, buf, size);
3254 slirp_input(buf, size);
3257 static int net_slirp_init(VLANState *vlan)
3259 if (!slirp_inited) {
3263 slirp_vc = qemu_new_vlan_client(vlan,
3264 slirp_receive, NULL, NULL);
3265 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3269 static void net_slirp_redir(const char *redir_str)
3274 struct in_addr guest_addr;
3275 int host_port, guest_port;
3277 if (!slirp_inited) {
3283 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3285 if (!strcmp(buf, "tcp")) {
3287 } else if (!strcmp(buf, "udp")) {
3293 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3295 host_port = strtol(buf, &r, 0);
3299 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3301 if (buf[0] == '\0') {
3302 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3304 if (!inet_aton(buf, &guest_addr))
3307 guest_port = strtol(p, &r, 0);
3311 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3312 fprintf(stderr, "qemu: could not set up redirection\n");
3317 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3325 static void smb_exit(void)
3329 char filename[1024];
3331 /* erase all the files in the directory */
3332 d = opendir(smb_dir);
3337 if (strcmp(de->d_name, ".") != 0 &&
3338 strcmp(de->d_name, "..") != 0) {
3339 snprintf(filename, sizeof(filename), "%s/%s",
3340 smb_dir, de->d_name);
3348 /* automatic user mode samba server configuration */
3349 void net_slirp_smb(const char *exported_dir)
3351 char smb_conf[1024];
3352 char smb_cmdline[1024];
3355 if (!slirp_inited) {
3360 /* XXX: better tmp dir construction */
3361 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3362 if (mkdir(smb_dir, 0700) < 0) {
3363 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3366 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3368 f = fopen(smb_conf, "w");
3370 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3377 "socket address=127.0.0.1\n"
3378 "pid directory=%s\n"
3379 "lock directory=%s\n"
3380 "log file=%s/log.smbd\n"
3381 "smb passwd file=%s/smbpasswd\n"
3382 "security = share\n"
3397 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3398 SMBD_COMMAND, smb_conf);
3400 slirp_add_exec(0, smb_cmdline, 4, 139);
3403 #endif /* !defined(_WIN32) */
3405 #endif /* CONFIG_SLIRP */
3407 #if !defined(_WIN32)
3409 typedef struct TAPState {
3410 VLANClientState *vc;
3414 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3416 TAPState *s = opaque;
3419 ret = write(s->fd, buf, size);
3420 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3427 static void tap_send(void *opaque)
3429 TAPState *s = opaque;
3436 sbuf.maxlen = sizeof(buf);
3438 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3440 size = read(s->fd, buf, sizeof(buf));
3443 qemu_send_packet(s->vc, buf, size);
3449 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3453 s = qemu_mallocz(sizeof(TAPState));
3457 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3458 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3459 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3463 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3464 static int tap_open(char *ifname, int ifname_size)
3470 TFR(fd = open("/dev/tap", O_RDWR));
3472 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3477 dev = devname(s.st_rdev, S_IFCHR);
3478 pstrcpy(ifname, ifname_size, dev);
3480 fcntl(fd, F_SETFL, O_NONBLOCK);
3483 #elif defined(__sun__)
3484 #define TUNNEWPPA (('T'<<16) | 0x0001)
3486 * Allocate TAP device, returns opened fd.
3487 * Stores dev name in the first arg(must be large enough).
3489 int tap_alloc(char *dev)
3491 int tap_fd, if_fd, ppa = -1;
3492 static int ip_fd = 0;
3495 static int arp_fd = 0;
3496 int ip_muxid, arp_muxid;
3497 struct strioctl strioc_if, strioc_ppa;
3498 int link_type = I_PLINK;;
3500 char actual_name[32] = "";
3502 memset(&ifr, 0x0, sizeof(ifr));
3506 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3510 /* Check if IP device was opened */
3514 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3516 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3520 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3522 syslog(LOG_ERR, "Can't open /dev/tap");
3526 /* Assign a new PPA and get its unit number. */
3527 strioc_ppa.ic_cmd = TUNNEWPPA;
3528 strioc_ppa.ic_timout = 0;
3529 strioc_ppa.ic_len = sizeof(ppa);
3530 strioc_ppa.ic_dp = (char *)&ppa;
3531 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3532 syslog (LOG_ERR, "Can't assign new interface");
3534 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3536 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3539 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3540 syslog(LOG_ERR, "Can't push IP module");
3544 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3545 syslog(LOG_ERR, "Can't get flags\n");
3547 snprintf (actual_name, 32, "tap%d", ppa);
3548 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3551 /* Assign ppa according to the unit number returned by tun device */
3553 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3554 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3555 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3556 syslog (LOG_ERR, "Can't get flags\n");
3557 /* Push arp module to if_fd */
3558 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3559 syslog (LOG_ERR, "Can't push ARP module (2)");
3561 /* Push arp module to ip_fd */
3562 if (ioctl (ip_fd, I_POP, NULL) < 0)
3563 syslog (LOG_ERR, "I_POP failed\n");
3564 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3565 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3567 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3569 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3571 /* Set ifname to arp */
3572 strioc_if.ic_cmd = SIOCSLIFNAME;
3573 strioc_if.ic_timout = 0;
3574 strioc_if.ic_len = sizeof(ifr);
3575 strioc_if.ic_dp = (char *)𝔦
3576 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3577 syslog (LOG_ERR, "Can't set ifname to arp\n");
3580 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3581 syslog(LOG_ERR, "Can't link TAP device to IP");
3585 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3586 syslog (LOG_ERR, "Can't link TAP device to ARP");
3590 memset(&ifr, 0x0, sizeof(ifr));
3591 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3592 ifr.lifr_ip_muxid = ip_muxid;
3593 ifr.lifr_arp_muxid = arp_muxid;
3595 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3597 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3598 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3599 syslog (LOG_ERR, "Can't set multiplexor id");
3602 sprintf(dev, "tap%d", ppa);
3606 static int tap_open(char *ifname, int ifname_size)
3610 if( (fd = tap_alloc(dev)) < 0 ){
3611 fprintf(stderr, "Cannot allocate TAP device\n");
3614 pstrcpy(ifname, ifname_size, dev);
3615 fcntl(fd, F_SETFL, O_NONBLOCK);
3619 static int tap_open(char *ifname, int ifname_size)
3624 TFR(fd = open("/dev/net/tun", O_RDWR));
3626 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3629 memset(&ifr, 0, sizeof(ifr));
3630 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3631 if (ifname[0] != '\0')
3632 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3634 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3635 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3637 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3641 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3642 fcntl(fd, F_SETFL, O_NONBLOCK);
3647 static int net_tap_init(VLANState *vlan, const char *ifname1,
3648 const char *setup_script)
3651 int pid, status, fd;
3656 if (ifname1 != NULL)
3657 pstrcpy(ifname, sizeof(ifname), ifname1);
3660 TFR(fd = tap_open(ifname, sizeof(ifname)));
3664 if (!setup_script || !strcmp(setup_script, "no"))
3666 if (setup_script[0] != '\0') {
3667 /* try to launch network init script */
3671 int open_max = sysconf (_SC_OPEN_MAX), i;
3672 for (i = 0; i < open_max; i++)
3673 if (i != STDIN_FILENO &&
3674 i != STDOUT_FILENO &&
3675 i != STDERR_FILENO &&
3680 *parg++ = (char *)setup_script;
3683 execv(setup_script, args);
3686 while (waitpid(pid, &status, 0) != pid);
3687 if (!WIFEXITED(status) ||
3688 WEXITSTATUS(status) != 0) {
3689 fprintf(stderr, "%s: could not launch network script\n",
3695 s = net_tap_fd_init(vlan, fd);
3698 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3699 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3703 #endif /* !_WIN32 */
3705 /* network connection */
3706 typedef struct NetSocketState {
3707 VLANClientState *vc;
3709 int state; /* 0 = getting length, 1 = getting data */
3713 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3716 typedef struct NetSocketListenState {
3719 } NetSocketListenState;
3721 /* XXX: we consider we can send the whole packet without blocking */
3722 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3724 NetSocketState *s = opaque;
3728 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3729 send_all(s->fd, buf, size);
3732 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3734 NetSocketState *s = opaque;
3735 sendto(s->fd, buf, size, 0,
3736 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3739 static void net_socket_send(void *opaque)
3741 NetSocketState *s = opaque;
3746 size = recv(s->fd, buf1, sizeof(buf1), 0);
3748 err = socket_error();
3749 if (err != EWOULDBLOCK)
3751 } else if (size == 0) {
3752 /* end of connection */
3754 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3760 /* reassemble a packet from the network */
3766 memcpy(s->buf + s->index, buf, l);
3770 if (s->index == 4) {
3772 s->packet_len = ntohl(*(uint32_t *)s->buf);
3778 l = s->packet_len - s->index;
3781 memcpy(s->buf + s->index, buf, l);
3785 if (s->index >= s->packet_len) {
3786 qemu_send_packet(s->vc, s->buf, s->packet_len);
3795 static void net_socket_send_dgram(void *opaque)
3797 NetSocketState *s = opaque;
3800 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3804 /* end of connection */
3805 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3808 qemu_send_packet(s->vc, s->buf, size);
3811 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3816 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3817 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3818 inet_ntoa(mcastaddr->sin_addr),
3819 (int)ntohl(mcastaddr->sin_addr.s_addr));
3823 fd = socket(PF_INET, SOCK_DGRAM, 0);
3825 perror("socket(PF_INET, SOCK_DGRAM)");
3830 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3831 (const char *)&val, sizeof(val));
3833 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3837 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3843 /* Add host to multicast group */
3844 imr.imr_multiaddr = mcastaddr->sin_addr;
3845 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3847 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3848 (const char *)&imr, sizeof(struct ip_mreq));
3850 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3854 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3856 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3857 (const char *)&val, sizeof(val));
3859 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3863 socket_set_nonblock(fd);
3871 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3874 struct sockaddr_in saddr;
3876 socklen_t saddr_len;
3879 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3880 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3881 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3885 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3887 if (saddr.sin_addr.s_addr==0) {
3888 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3892 /* clone dgram socket */
3893 newfd = net_socket_mcast_create(&saddr);
3895 /* error already reported by net_socket_mcast_create() */
3899 /* clone newfd to fd, close newfd */
3904 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3905 fd, strerror(errno));
3910 s = qemu_mallocz(sizeof(NetSocketState));
3915 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3916 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3918 /* mcast: save bound address as dst */
3919 if (is_connected) s->dgram_dst=saddr;
3921 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3922 "socket: fd=%d (%s mcast=%s:%d)",
3923 fd, is_connected? "cloned" : "",
3924 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3928 static void net_socket_connect(void *opaque)
3930 NetSocketState *s = opaque;
3931 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3934 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3938 s = qemu_mallocz(sizeof(NetSocketState));
3942 s->vc = qemu_new_vlan_client(vlan,
3943 net_socket_receive, NULL, s);
3944 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3945 "socket: fd=%d", fd);
3947 net_socket_connect(s);
3949 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3954 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3957 int so_type=-1, optlen=sizeof(so_type);
3959 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3960 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3965 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3967 return net_socket_fd_init_stream(vlan, fd, is_connected);
3969 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3970 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3971 return net_socket_fd_init_stream(vlan, fd, is_connected);
3976 static void net_socket_accept(void *opaque)
3978 NetSocketListenState *s = opaque;
3980 struct sockaddr_in saddr;
3985 len = sizeof(saddr);
3986 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3987 if (fd < 0 && errno != EINTR) {
3989 } else if (fd >= 0) {
3993 s1 = net_socket_fd_init(s->vlan, fd, 1);
3997 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3998 "socket: connection from %s:%d",
3999 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4003 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4005 NetSocketListenState *s;
4007 struct sockaddr_in saddr;
4009 if (parse_host_port(&saddr, host_str) < 0)
4012 s = qemu_mallocz(sizeof(NetSocketListenState));
4016 fd = socket(PF_INET, SOCK_STREAM, 0);
4021 socket_set_nonblock(fd);
4023 /* allow fast reuse */
4025 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4027 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4032 ret = listen(fd, 0);
4039 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4043 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4046 int fd, connected, ret, err;
4047 struct sockaddr_in saddr;
4049 if (parse_host_port(&saddr, host_str) < 0)
4052 fd = socket(PF_INET, SOCK_STREAM, 0);
4057 socket_set_nonblock(fd);
4061 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4063 err = socket_error();
4064 if (err == EINTR || err == EWOULDBLOCK) {
4065 } else if (err == EINPROGRESS) {
4068 } else if (err == WSAEALREADY) {
4081 s = net_socket_fd_init(vlan, fd, connected);
4084 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4085 "socket: connect to %s:%d",
4086 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4090 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4094 struct sockaddr_in saddr;
4096 if (parse_host_port(&saddr, host_str) < 0)
4100 fd = net_socket_mcast_create(&saddr);
4104 s = net_socket_fd_init(vlan, fd, 0);
4108 s->dgram_dst = saddr;
4110 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4111 "socket: mcast=%s:%d",
4112 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4117 static int get_param_value(char *buf, int buf_size,
4118 const char *tag, const char *str)
4127 while (*p != '\0' && *p != '=') {
4128 if ((q - option) < sizeof(option) - 1)
4136 if (!strcmp(tag, option)) {
4138 while (*p != '\0' && *p != ',') {
4139 if ((q - buf) < buf_size - 1)
4146 while (*p != '\0' && *p != ',') {
4157 static int net_client_init(const char *str)
4168 while (*p != '\0' && *p != ',') {
4169 if ((q - device) < sizeof(device) - 1)
4177 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4178 vlan_id = strtol(buf, NULL, 0);
4180 vlan = qemu_find_vlan(vlan_id);
4182 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4185 if (!strcmp(device, "nic")) {
4189 if (nb_nics >= MAX_NICS) {
4190 fprintf(stderr, "Too Many NICs\n");
4193 nd = &nd_table[nb_nics];
4194 macaddr = nd->macaddr;
4200 macaddr[5] = 0x56 + nb_nics;
4202 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4203 if (parse_macaddr(macaddr, buf) < 0) {
4204 fprintf(stderr, "invalid syntax for ethernet address\n");
4208 if (get_param_value(buf, sizeof(buf), "model", p)) {
4209 nd->model = strdup(buf);
4213 vlan->nb_guest_devs++;
4216 if (!strcmp(device, "none")) {
4217 /* does nothing. It is needed to signal that no network cards
4222 if (!strcmp(device, "user")) {
4223 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4224 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4226 vlan->nb_host_devs++;
4227 ret = net_slirp_init(vlan);
4231 if (!strcmp(device, "tap")) {
4233 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4234 fprintf(stderr, "tap: no interface name\n");
4237 vlan->nb_host_devs++;
4238 ret = tap_win32_init(vlan, ifname);
4241 if (!strcmp(device, "tap")) {
4243 char setup_script[1024];
4245 vlan->nb_host_devs++;
4246 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4247 fd = strtol(buf, NULL, 0);
4249 if (net_tap_fd_init(vlan, fd))
4252 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4255 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4256 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4258 ret = net_tap_init(vlan, ifname, setup_script);
4262 if (!strcmp(device, "socket")) {
4263 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4265 fd = strtol(buf, NULL, 0);
4267 if (net_socket_fd_init(vlan, fd, 1))
4269 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4270 ret = net_socket_listen_init(vlan, buf);
4271 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4272 ret = net_socket_connect_init(vlan, buf);
4273 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4274 ret = net_socket_mcast_init(vlan, buf);
4276 fprintf(stderr, "Unknown socket options: %s\n", p);
4279 vlan->nb_host_devs++;
4282 fprintf(stderr, "Unknown network device: %s\n", device);
4286 fprintf(stderr, "Could not initialize device '%s'\n", device);
4292 void do_info_network(void)
4295 VLANClientState *vc;
4297 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4298 term_printf("VLAN %d devices:\n", vlan->id);
4299 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4300 term_printf(" %s\n", vc->info_str);
4304 /***********************************************************/
4307 static USBPort *used_usb_ports;
4308 static USBPort *free_usb_ports;
4310 /* ??? Maybe change this to register a hub to keep track of the topology. */
4311 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4312 usb_attachfn attach)
4314 port->opaque = opaque;
4315 port->index = index;
4316 port->attach = attach;
4317 port->next = free_usb_ports;
4318 free_usb_ports = port;
4321 static int usb_device_add(const char *devname)
4327 if (!free_usb_ports)
4330 if (strstart(devname, "host:", &p)) {
4331 dev = usb_host_device_open(p);
4332 } else if (!strcmp(devname, "mouse")) {
4333 dev = usb_mouse_init();
4334 } else if (!strcmp(devname, "tablet")) {
4335 dev = usb_tablet_init();
4336 } else if (!strcmp(devname, "keyboard")) {
4337 dev = usb_keyboard_init();
4338 } else if (strstart(devname, "disk:", &p)) {
4339 dev = usb_msd_init(p);
4340 } else if (!strcmp(devname, "wacom-tablet")) {
4341 dev = usb_wacom_init();
4348 /* Find a USB port to add the device to. */
4349 port = free_usb_ports;
4353 /* Create a new hub and chain it on. */
4354 free_usb_ports = NULL;
4355 port->next = used_usb_ports;
4356 used_usb_ports = port;
4358 hub = usb_hub_init(VM_USB_HUB_SIZE);
4359 usb_attach(port, hub);
4360 port = free_usb_ports;
4363 free_usb_ports = port->next;
4364 port->next = used_usb_ports;
4365 used_usb_ports = port;
4366 usb_attach(port, dev);
4370 static int usb_device_del(const char *devname)
4378 if (!used_usb_ports)
4381 p = strchr(devname, '.');
4384 bus_num = strtoul(devname, NULL, 0);
4385 addr = strtoul(p + 1, NULL, 0);
4389 lastp = &used_usb_ports;
4390 port = used_usb_ports;
4391 while (port && port->dev->addr != addr) {
4392 lastp = &port->next;
4400 *lastp = port->next;
4401 usb_attach(port, NULL);
4402 dev->handle_destroy(dev);
4403 port->next = free_usb_ports;
4404 free_usb_ports = port;
4408 void do_usb_add(const char *devname)
4411 ret = usb_device_add(devname);
4413 term_printf("Could not add USB device '%s'\n", devname);
4416 void do_usb_del(const char *devname)
4419 ret = usb_device_del(devname);
4421 term_printf("Could not remove USB device '%s'\n", devname);
4428 const char *speed_str;
4431 term_printf("USB support not enabled\n");
4435 for (port = used_usb_ports; port; port = port->next) {
4439 switch(dev->speed) {
4443 case USB_SPEED_FULL:
4446 case USB_SPEED_HIGH:
4453 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4454 0, dev->addr, speed_str, dev->devname);
4458 /***********************************************************/
4459 /* PCMCIA/Cardbus */
4461 static struct pcmcia_socket_entry_s {
4462 struct pcmcia_socket_s *socket;
4463 struct pcmcia_socket_entry_s *next;
4464 } *pcmcia_sockets = 0;
4466 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4468 struct pcmcia_socket_entry_s *entry;
4470 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4471 entry->socket = socket;
4472 entry->next = pcmcia_sockets;
4473 pcmcia_sockets = entry;
4476 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4478 struct pcmcia_socket_entry_s *entry, **ptr;
4480 ptr = &pcmcia_sockets;
4481 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4482 if (entry->socket == socket) {
4488 void pcmcia_info(void)
4490 struct pcmcia_socket_entry_s *iter;
4491 if (!pcmcia_sockets)
4492 term_printf("No PCMCIA sockets\n");
4494 for (iter = pcmcia_sockets; iter; iter = iter->next)
4495 term_printf("%s: %s\n", iter->socket->slot_string,
4496 iter->socket->attached ? iter->socket->card_string :
4500 /***********************************************************/
4503 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4507 static void dumb_resize(DisplayState *ds, int w, int h)
4511 static void dumb_refresh(DisplayState *ds)
4513 #if defined(CONFIG_SDL)
4518 static void dumb_display_init(DisplayState *ds)
4523 ds->dpy_update = dumb_update;
4524 ds->dpy_resize = dumb_resize;
4525 ds->dpy_refresh = dumb_refresh;
4528 /***********************************************************/
4531 #define MAX_IO_HANDLERS 64
4533 typedef struct IOHandlerRecord {
4535 IOCanRWHandler *fd_read_poll;
4537 IOHandler *fd_write;
4540 /* temporary data */
4542 struct IOHandlerRecord *next;
4545 static IOHandlerRecord *first_io_handler;
4547 /* XXX: fd_read_poll should be suppressed, but an API change is
4548 necessary in the character devices to suppress fd_can_read(). */
4549 int qemu_set_fd_handler2(int fd,
4550 IOCanRWHandler *fd_read_poll,
4552 IOHandler *fd_write,
4555 IOHandlerRecord **pioh, *ioh;
4557 if (!fd_read && !fd_write) {
4558 pioh = &first_io_handler;
4563 if (ioh->fd == fd) {
4570 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4574 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4577 ioh->next = first_io_handler;
4578 first_io_handler = ioh;
4581 ioh->fd_read_poll = fd_read_poll;
4582 ioh->fd_read = fd_read;
4583 ioh->fd_write = fd_write;
4584 ioh->opaque = opaque;
4590 int qemu_set_fd_handler(int fd,
4592 IOHandler *fd_write,
4595 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4598 /***********************************************************/
4599 /* Polling handling */
4601 typedef struct PollingEntry {
4604 struct PollingEntry *next;
4607 static PollingEntry *first_polling_entry;
4609 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4611 PollingEntry **ppe, *pe;
4612 pe = qemu_mallocz(sizeof(PollingEntry));
4616 pe->opaque = opaque;
4617 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4622 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4624 PollingEntry **ppe, *pe;
4625 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4627 if (pe->func == func && pe->opaque == opaque) {
4636 /***********************************************************/
4637 /* Wait objects support */
4638 typedef struct WaitObjects {
4640 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4641 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4642 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4645 static WaitObjects wait_objects = {0};
4647 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4649 WaitObjects *w = &wait_objects;
4651 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4653 w->events[w->num] = handle;
4654 w->func[w->num] = func;
4655 w->opaque[w->num] = opaque;
4660 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4663 WaitObjects *w = &wait_objects;
4666 for (i = 0; i < w->num; i++) {
4667 if (w->events[i] == handle)
4670 w->events[i] = w->events[i + 1];
4671 w->func[i] = w->func[i + 1];
4672 w->opaque[i] = w->opaque[i + 1];
4680 /***********************************************************/
4681 /* savevm/loadvm support */
4683 #define IO_BUF_SIZE 32768
4687 BlockDriverState *bs;
4690 int64_t base_offset;
4691 int64_t buf_offset; /* start of buffer when writing, end of buffer
4694 int buf_size; /* 0 when writing */
4695 uint8_t buf[IO_BUF_SIZE];
4698 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4702 f = qemu_mallocz(sizeof(QEMUFile));
4705 if (!strcmp(mode, "wb")) {
4707 } else if (!strcmp(mode, "rb")) {
4712 f->outfile = fopen(filename, mode);
4724 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4728 f = qemu_mallocz(sizeof(QEMUFile));
4733 f->is_writable = is_writable;
4734 f->base_offset = offset;
4738 void qemu_fflush(QEMUFile *f)
4740 if (!f->is_writable)
4742 if (f->buf_index > 0) {
4744 fseek(f->outfile, f->buf_offset, SEEK_SET);
4745 fwrite(f->buf, 1, f->buf_index, f->outfile);
4747 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4748 f->buf, f->buf_index);
4750 f->buf_offset += f->buf_index;
4755 static void qemu_fill_buffer(QEMUFile *f)
4762 fseek(f->outfile, f->buf_offset, SEEK_SET);
4763 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4767 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4768 f->buf, IO_BUF_SIZE);
4774 f->buf_offset += len;
4777 void qemu_fclose(QEMUFile *f)
4787 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4791 l = IO_BUF_SIZE - f->buf_index;
4794 memcpy(f->buf + f->buf_index, buf, l);
4798 if (f->buf_index >= IO_BUF_SIZE)
4803 void qemu_put_byte(QEMUFile *f, int v)
4805 f->buf[f->buf_index++] = v;
4806 if (f->buf_index >= IO_BUF_SIZE)
4810 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4816 l = f->buf_size - f->buf_index;
4818 qemu_fill_buffer(f);
4819 l = f->buf_size - f->buf_index;
4825 memcpy(buf, f->buf + f->buf_index, l);
4830 return size1 - size;
4833 int qemu_get_byte(QEMUFile *f)
4835 if (f->buf_index >= f->buf_size) {
4836 qemu_fill_buffer(f);
4837 if (f->buf_index >= f->buf_size)
4840 return f->buf[f->buf_index++];
4843 int64_t qemu_ftell(QEMUFile *f)
4845 return f->buf_offset - f->buf_size + f->buf_index;
4848 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4850 if (whence == SEEK_SET) {
4852 } else if (whence == SEEK_CUR) {
4853 pos += qemu_ftell(f);
4855 /* SEEK_END not supported */
4858 if (f->is_writable) {
4860 f->buf_offset = pos;
4862 f->buf_offset = pos;
4869 void qemu_put_be16(QEMUFile *f, unsigned int v)
4871 qemu_put_byte(f, v >> 8);
4872 qemu_put_byte(f, v);
4875 void qemu_put_be32(QEMUFile *f, unsigned int v)
4877 qemu_put_byte(f, v >> 24);
4878 qemu_put_byte(f, v >> 16);
4879 qemu_put_byte(f, v >> 8);
4880 qemu_put_byte(f, v);
4883 void qemu_put_be64(QEMUFile *f, uint64_t v)
4885 qemu_put_be32(f, v >> 32);
4886 qemu_put_be32(f, v);
4889 unsigned int qemu_get_be16(QEMUFile *f)
4892 v = qemu_get_byte(f) << 8;
4893 v |= qemu_get_byte(f);
4897 unsigned int qemu_get_be32(QEMUFile *f)
4900 v = qemu_get_byte(f) << 24;
4901 v |= qemu_get_byte(f) << 16;
4902 v |= qemu_get_byte(f) << 8;
4903 v |= qemu_get_byte(f);
4907 uint64_t qemu_get_be64(QEMUFile *f)
4910 v = (uint64_t)qemu_get_be32(f) << 32;
4911 v |= qemu_get_be32(f);
4915 typedef struct SaveStateEntry {
4919 SaveStateHandler *save_state;
4920 LoadStateHandler *load_state;
4922 struct SaveStateEntry *next;
4925 static SaveStateEntry *first_se;
4927 int register_savevm(const char *idstr,
4930 SaveStateHandler *save_state,
4931 LoadStateHandler *load_state,
4934 SaveStateEntry *se, **pse;
4936 se = qemu_malloc(sizeof(SaveStateEntry));
4939 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4940 se->instance_id = instance_id;
4941 se->version_id = version_id;
4942 se->save_state = save_state;
4943 se->load_state = load_state;
4944 se->opaque = opaque;
4947 /* add at the end of list */
4949 while (*pse != NULL)
4950 pse = &(*pse)->next;
4955 #define QEMU_VM_FILE_MAGIC 0x5145564d
4956 #define QEMU_VM_FILE_VERSION 0x00000002
4958 int qemu_savevm_state(QEMUFile *f)
4962 int64_t cur_pos, len_pos, total_len_pos;
4964 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4965 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4966 total_len_pos = qemu_ftell(f);
4967 qemu_put_be64(f, 0); /* total size */
4969 for(se = first_se; se != NULL; se = se->next) {
4971 len = strlen(se->idstr);
4972 qemu_put_byte(f, len);
4973 qemu_put_buffer(f, se->idstr, len);
4975 qemu_put_be32(f, se->instance_id);
4976 qemu_put_be32(f, se->version_id);
4978 /* record size: filled later */
4979 len_pos = qemu_ftell(f);
4980 qemu_put_be32(f, 0);
4982 se->save_state(f, se->opaque);
4984 /* fill record size */
4985 cur_pos = qemu_ftell(f);
4986 len = cur_pos - len_pos - 4;
4987 qemu_fseek(f, len_pos, SEEK_SET);
4988 qemu_put_be32(f, len);
4989 qemu_fseek(f, cur_pos, SEEK_SET);
4991 cur_pos = qemu_ftell(f);
4992 qemu_fseek(f, total_len_pos, SEEK_SET);
4993 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4994 qemu_fseek(f, cur_pos, SEEK_SET);
5000 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5004 for(se = first_se; se != NULL; se = se->next) {
5005 if (!strcmp(se->idstr, idstr) &&
5006 instance_id == se->instance_id)
5012 int qemu_loadvm_state(QEMUFile *f)
5015 int len, ret, instance_id, record_len, version_id;
5016 int64_t total_len, end_pos, cur_pos;
5020 v = qemu_get_be32(f);
5021 if (v != QEMU_VM_FILE_MAGIC)
5023 v = qemu_get_be32(f);
5024 if (v != QEMU_VM_FILE_VERSION) {
5029 total_len = qemu_get_be64(f);
5030 end_pos = total_len + qemu_ftell(f);
5032 if (qemu_ftell(f) >= end_pos)
5034 len = qemu_get_byte(f);
5035 qemu_get_buffer(f, idstr, len);
5037 instance_id = qemu_get_be32(f);
5038 version_id = qemu_get_be32(f);
5039 record_len = qemu_get_be32(f);
5041 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5042 idstr, instance_id, version_id, record_len);
5044 cur_pos = qemu_ftell(f);
5045 se = find_se(idstr, instance_id);
5047 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5048 instance_id, idstr);
5050 ret = se->load_state(f, se->opaque, version_id);
5052 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5053 instance_id, idstr);
5056 /* always seek to exact end of record */
5057 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5064 /* device can contain snapshots */
5065 static int bdrv_can_snapshot(BlockDriverState *bs)
5068 !bdrv_is_removable(bs) &&
5069 !bdrv_is_read_only(bs));
5072 /* device must be snapshots in order to have a reliable snapshot */
5073 static int bdrv_has_snapshot(BlockDriverState *bs)
5076 !bdrv_is_removable(bs) &&
5077 !bdrv_is_read_only(bs));
5080 static BlockDriverState *get_bs_snapshots(void)
5082 BlockDriverState *bs;
5086 return bs_snapshots;
5087 for(i = 0; i <= MAX_DISKS; i++) {
5089 if (bdrv_can_snapshot(bs))
5098 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5101 QEMUSnapshotInfo *sn_tab, *sn;
5105 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5108 for(i = 0; i < nb_sns; i++) {
5110 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5120 void do_savevm(const char *name)
5122 BlockDriverState *bs, *bs1;
5123 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5124 int must_delete, ret, i;
5125 BlockDriverInfo bdi1, *bdi = &bdi1;
5127 int saved_vm_running;
5134 bs = get_bs_snapshots();
5136 term_printf("No block device can accept snapshots\n");
5140 /* ??? Should this occur after vm_stop? */
5143 saved_vm_running = vm_running;
5148 ret = bdrv_snapshot_find(bs, old_sn, name);
5153 memset(sn, 0, sizeof(*sn));
5155 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5156 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5159 pstrcpy(sn->name, sizeof(sn->name), name);
5162 /* fill auxiliary fields */
5165 sn->date_sec = tb.time;
5166 sn->date_nsec = tb.millitm * 1000000;
5168 gettimeofday(&tv, NULL);
5169 sn->date_sec = tv.tv_sec;
5170 sn->date_nsec = tv.tv_usec * 1000;
5172 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5174 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5175 term_printf("Device %s does not support VM state snapshots\n",
5176 bdrv_get_device_name(bs));
5180 /* save the VM state */
5181 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5183 term_printf("Could not open VM state file\n");
5186 ret = qemu_savevm_state(f);
5187 sn->vm_state_size = qemu_ftell(f);
5190 term_printf("Error %d while writing VM\n", ret);
5194 /* create the snapshots */
5196 for(i = 0; i < MAX_DISKS; i++) {
5198 if (bdrv_has_snapshot(bs1)) {
5200 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5202 term_printf("Error while deleting snapshot on '%s'\n",
5203 bdrv_get_device_name(bs1));
5206 ret = bdrv_snapshot_create(bs1, sn);
5208 term_printf("Error while creating snapshot on '%s'\n",
5209 bdrv_get_device_name(bs1));
5215 if (saved_vm_running)
5219 void do_loadvm(const char *name)
5221 BlockDriverState *bs, *bs1;
5222 BlockDriverInfo bdi1, *bdi = &bdi1;
5225 int saved_vm_running;
5227 bs = get_bs_snapshots();
5229 term_printf("No block device supports snapshots\n");
5233 /* Flush all IO requests so they don't interfere with the new state. */
5236 saved_vm_running = vm_running;
5239 for(i = 0; i <= MAX_DISKS; i++) {
5241 if (bdrv_has_snapshot(bs1)) {
5242 ret = bdrv_snapshot_goto(bs1, name);
5245 term_printf("Warning: ");
5248 term_printf("Snapshots not supported on device '%s'\n",
5249 bdrv_get_device_name(bs1));
5252 term_printf("Could not find snapshot '%s' on device '%s'\n",
5253 name, bdrv_get_device_name(bs1));
5256 term_printf("Error %d while activating snapshot on '%s'\n",
5257 ret, bdrv_get_device_name(bs1));
5260 /* fatal on snapshot block device */
5267 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5268 term_printf("Device %s does not support VM state snapshots\n",
5269 bdrv_get_device_name(bs));
5273 /* restore the VM state */
5274 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5276 term_printf("Could not open VM state file\n");
5279 ret = qemu_loadvm_state(f);
5282 term_printf("Error %d while loading VM state\n", ret);
5285 if (saved_vm_running)
5289 void do_delvm(const char *name)
5291 BlockDriverState *bs, *bs1;
5294 bs = get_bs_snapshots();
5296 term_printf("No block device supports snapshots\n");
5300 for(i = 0; i <= MAX_DISKS; i++) {
5302 if (bdrv_has_snapshot(bs1)) {
5303 ret = bdrv_snapshot_delete(bs1, name);
5305 if (ret == -ENOTSUP)
5306 term_printf("Snapshots not supported on device '%s'\n",
5307 bdrv_get_device_name(bs1));
5309 term_printf("Error %d while deleting snapshot on '%s'\n",
5310 ret, bdrv_get_device_name(bs1));
5316 void do_info_snapshots(void)
5318 BlockDriverState *bs, *bs1;
5319 QEMUSnapshotInfo *sn_tab, *sn;
5323 bs = get_bs_snapshots();
5325 term_printf("No available block device supports snapshots\n");
5328 term_printf("Snapshot devices:");
5329 for(i = 0; i <= MAX_DISKS; i++) {
5331 if (bdrv_has_snapshot(bs1)) {
5333 term_printf(" %s", bdrv_get_device_name(bs1));
5338 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5340 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5343 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5344 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5345 for(i = 0; i < nb_sns; i++) {
5347 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5352 /***********************************************************/
5353 /* cpu save/restore */
5355 #if defined(TARGET_I386)
5357 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5359 qemu_put_be32(f, dt->selector);
5360 qemu_put_betl(f, dt->base);
5361 qemu_put_be32(f, dt->limit);
5362 qemu_put_be32(f, dt->flags);
5365 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5367 dt->selector = qemu_get_be32(f);
5368 dt->base = qemu_get_betl(f);
5369 dt->limit = qemu_get_be32(f);
5370 dt->flags = qemu_get_be32(f);
5373 void cpu_save(QEMUFile *f, void *opaque)
5375 CPUState *env = opaque;
5376 uint16_t fptag, fpus, fpuc, fpregs_format;
5380 for(i = 0; i < CPU_NB_REGS; i++)
5381 qemu_put_betls(f, &env->regs[i]);
5382 qemu_put_betls(f, &env->eip);
5383 qemu_put_betls(f, &env->eflags);
5384 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5385 qemu_put_be32s(f, &hflags);
5389 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5391 for(i = 0; i < 8; i++) {
5392 fptag |= ((!env->fptags[i]) << i);
5395 qemu_put_be16s(f, &fpuc);
5396 qemu_put_be16s(f, &fpus);
5397 qemu_put_be16s(f, &fptag);
5399 #ifdef USE_X86LDOUBLE
5404 qemu_put_be16s(f, &fpregs_format);
5406 for(i = 0; i < 8; i++) {
5407 #ifdef USE_X86LDOUBLE
5411 /* we save the real CPU data (in case of MMX usage only 'mant'
5412 contains the MMX register */
5413 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5414 qemu_put_be64(f, mant);
5415 qemu_put_be16(f, exp);
5418 /* if we use doubles for float emulation, we save the doubles to
5419 avoid losing information in case of MMX usage. It can give
5420 problems if the image is restored on a CPU where long
5421 doubles are used instead. */
5422 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5426 for(i = 0; i < 6; i++)
5427 cpu_put_seg(f, &env->segs[i]);
5428 cpu_put_seg(f, &env->ldt);
5429 cpu_put_seg(f, &env->tr);
5430 cpu_put_seg(f, &env->gdt);
5431 cpu_put_seg(f, &env->idt);
5433 qemu_put_be32s(f, &env->sysenter_cs);
5434 qemu_put_be32s(f, &env->sysenter_esp);
5435 qemu_put_be32s(f, &env->sysenter_eip);
5437 qemu_put_betls(f, &env->cr[0]);
5438 qemu_put_betls(f, &env->cr[2]);
5439 qemu_put_betls(f, &env->cr[3]);
5440 qemu_put_betls(f, &env->cr[4]);
5442 for(i = 0; i < 8; i++)
5443 qemu_put_betls(f, &env->dr[i]);
5446 qemu_put_be32s(f, &env->a20_mask);
5449 qemu_put_be32s(f, &env->mxcsr);
5450 for(i = 0; i < CPU_NB_REGS; i++) {
5451 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5452 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5455 #ifdef TARGET_X86_64
5456 qemu_put_be64s(f, &env->efer);
5457 qemu_put_be64s(f, &env->star);
5458 qemu_put_be64s(f, &env->lstar);
5459 qemu_put_be64s(f, &env->cstar);
5460 qemu_put_be64s(f, &env->fmask);
5461 qemu_put_be64s(f, &env->kernelgsbase);
5463 qemu_put_be32s(f, &env->smbase);
5466 #ifdef USE_X86LDOUBLE
5467 /* XXX: add that in a FPU generic layer */
5468 union x86_longdouble {
5473 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5474 #define EXPBIAS1 1023
5475 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5476 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5478 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5482 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5483 /* exponent + sign */
5484 e = EXPD1(temp) - EXPBIAS1 + 16383;
5485 e |= SIGND1(temp) >> 16;
5490 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5492 CPUState *env = opaque;
5495 uint16_t fpus, fpuc, fptag, fpregs_format;
5497 if (version_id != 3 && version_id != 4)
5499 for(i = 0; i < CPU_NB_REGS; i++)
5500 qemu_get_betls(f, &env->regs[i]);
5501 qemu_get_betls(f, &env->eip);
5502 qemu_get_betls(f, &env->eflags);
5503 qemu_get_be32s(f, &hflags);
5505 qemu_get_be16s(f, &fpuc);
5506 qemu_get_be16s(f, &fpus);
5507 qemu_get_be16s(f, &fptag);
5508 qemu_get_be16s(f, &fpregs_format);
5510 /* NOTE: we cannot always restore the FPU state if the image come
5511 from a host with a different 'USE_X86LDOUBLE' define. We guess
5512 if we are in an MMX state to restore correctly in that case. */
5513 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5514 for(i = 0; i < 8; i++) {
5518 switch(fpregs_format) {
5520 mant = qemu_get_be64(f);
5521 exp = qemu_get_be16(f);
5522 #ifdef USE_X86LDOUBLE
5523 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5525 /* difficult case */
5527 env->fpregs[i].mmx.MMX_Q(0) = mant;
5529 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5533 mant = qemu_get_be64(f);
5534 #ifdef USE_X86LDOUBLE
5536 union x86_longdouble *p;
5537 /* difficult case */
5538 p = (void *)&env->fpregs[i];
5543 fp64_to_fp80(p, mant);
5547 env->fpregs[i].mmx.MMX_Q(0) = mant;
5556 /* XXX: restore FPU round state */
5557 env->fpstt = (fpus >> 11) & 7;
5558 env->fpus = fpus & ~0x3800;
5560 for(i = 0; i < 8; i++) {
5561 env->fptags[i] = (fptag >> i) & 1;
5564 for(i = 0; i < 6; i++)
5565 cpu_get_seg(f, &env->segs[i]);
5566 cpu_get_seg(f, &env->ldt);
5567 cpu_get_seg(f, &env->tr);
5568 cpu_get_seg(f, &env->gdt);
5569 cpu_get_seg(f, &env->idt);
5571 qemu_get_be32s(f, &env->sysenter_cs);
5572 qemu_get_be32s(f, &env->sysenter_esp);
5573 qemu_get_be32s(f, &env->sysenter_eip);
5575 qemu_get_betls(f, &env->cr[0]);
5576 qemu_get_betls(f, &env->cr[2]);
5577 qemu_get_betls(f, &env->cr[3]);
5578 qemu_get_betls(f, &env->cr[4]);
5580 for(i = 0; i < 8; i++)
5581 qemu_get_betls(f, &env->dr[i]);
5584 qemu_get_be32s(f, &env->a20_mask);
5586 qemu_get_be32s(f, &env->mxcsr);
5587 for(i = 0; i < CPU_NB_REGS; i++) {
5588 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5589 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5592 #ifdef TARGET_X86_64
5593 qemu_get_be64s(f, &env->efer);
5594 qemu_get_be64s(f, &env->star);
5595 qemu_get_be64s(f, &env->lstar);
5596 qemu_get_be64s(f, &env->cstar);
5597 qemu_get_be64s(f, &env->fmask);
5598 qemu_get_be64s(f, &env->kernelgsbase);
5600 if (version_id >= 4)
5601 qemu_get_be32s(f, &env->smbase);
5603 /* XXX: compute hflags from scratch, except for CPL and IIF */
5604 env->hflags = hflags;
5609 #elif defined(TARGET_PPC)
5610 void cpu_save(QEMUFile *f, void *opaque)
5614 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5619 #elif defined(TARGET_MIPS)
5620 void cpu_save(QEMUFile *f, void *opaque)
5624 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5629 #elif defined(TARGET_SPARC)
5630 void cpu_save(QEMUFile *f, void *opaque)
5632 CPUState *env = opaque;
5636 for(i = 0; i < 8; i++)
5637 qemu_put_betls(f, &env->gregs[i]);
5638 for(i = 0; i < NWINDOWS * 16; i++)
5639 qemu_put_betls(f, &env->regbase[i]);
5642 for(i = 0; i < TARGET_FPREGS; i++) {
5648 qemu_put_be32(f, u.i);
5651 qemu_put_betls(f, &env->pc);
5652 qemu_put_betls(f, &env->npc);
5653 qemu_put_betls(f, &env->y);
5655 qemu_put_be32(f, tmp);
5656 qemu_put_betls(f, &env->fsr);
5657 qemu_put_betls(f, &env->tbr);
5658 #ifndef TARGET_SPARC64
5659 qemu_put_be32s(f, &env->wim);
5661 for(i = 0; i < 16; i++)
5662 qemu_put_be32s(f, &env->mmuregs[i]);
5666 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5668 CPUState *env = opaque;
5672 for(i = 0; i < 8; i++)
5673 qemu_get_betls(f, &env->gregs[i]);
5674 for(i = 0; i < NWINDOWS * 16; i++)
5675 qemu_get_betls(f, &env->regbase[i]);
5678 for(i = 0; i < TARGET_FPREGS; i++) {
5683 u.i = qemu_get_be32(f);
5687 qemu_get_betls(f, &env->pc);
5688 qemu_get_betls(f, &env->npc);
5689 qemu_get_betls(f, &env->y);
5690 tmp = qemu_get_be32(f);
5691 env->cwp = 0; /* needed to ensure that the wrapping registers are
5692 correctly updated */
5694 qemu_get_betls(f, &env->fsr);
5695 qemu_get_betls(f, &env->tbr);
5696 #ifndef TARGET_SPARC64
5697 qemu_get_be32s(f, &env->wim);
5699 for(i = 0; i < 16; i++)
5700 qemu_get_be32s(f, &env->mmuregs[i]);
5706 #elif defined(TARGET_ARM)
5708 void cpu_save(QEMUFile *f, void *opaque)
5711 CPUARMState *env = (CPUARMState *)opaque;
5713 for (i = 0; i < 16; i++) {
5714 qemu_put_be32(f, env->regs[i]);
5716 qemu_put_be32(f, cpsr_read(env));
5717 qemu_put_be32(f, env->spsr);
5718 for (i = 0; i < 6; i++) {
5719 qemu_put_be32(f, env->banked_spsr[i]);
5720 qemu_put_be32(f, env->banked_r13[i]);
5721 qemu_put_be32(f, env->banked_r14[i]);
5723 for (i = 0; i < 5; i++) {
5724 qemu_put_be32(f, env->usr_regs[i]);
5725 qemu_put_be32(f, env->fiq_regs[i]);
5727 qemu_put_be32(f, env->cp15.c0_cpuid);
5728 qemu_put_be32(f, env->cp15.c0_cachetype);
5729 qemu_put_be32(f, env->cp15.c1_sys);
5730 qemu_put_be32(f, env->cp15.c1_coproc);
5731 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5732 qemu_put_be32(f, env->cp15.c2_base);
5733 qemu_put_be32(f, env->cp15.c2_data);
5734 qemu_put_be32(f, env->cp15.c2_insn);
5735 qemu_put_be32(f, env->cp15.c3);
5736 qemu_put_be32(f, env->cp15.c5_insn);
5737 qemu_put_be32(f, env->cp15.c5_data);
5738 for (i = 0; i < 8; i++) {
5739 qemu_put_be32(f, env->cp15.c6_region[i]);
5741 qemu_put_be32(f, env->cp15.c6_insn);
5742 qemu_put_be32(f, env->cp15.c6_data);
5743 qemu_put_be32(f, env->cp15.c9_insn);
5744 qemu_put_be32(f, env->cp15.c9_data);
5745 qemu_put_be32(f, env->cp15.c13_fcse);
5746 qemu_put_be32(f, env->cp15.c13_context);
5747 qemu_put_be32(f, env->cp15.c15_cpar);
5749 qemu_put_be32(f, env->features);
5751 if (arm_feature(env, ARM_FEATURE_VFP)) {
5752 for (i = 0; i < 16; i++) {
5754 u.d = env->vfp.regs[i];
5755 qemu_put_be32(f, u.l.upper);
5756 qemu_put_be32(f, u.l.lower);
5758 for (i = 0; i < 16; i++) {
5759 qemu_put_be32(f, env->vfp.xregs[i]);
5762 /* TODO: Should use proper FPSCR access functions. */
5763 qemu_put_be32(f, env->vfp.vec_len);
5764 qemu_put_be32(f, env->vfp.vec_stride);
5767 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5768 for (i = 0; i < 16; i++) {
5769 qemu_put_be64(f, env->iwmmxt.regs[i]);
5771 for (i = 0; i < 16; i++) {
5772 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5777 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5779 CPUARMState *env = (CPUARMState *)opaque;
5782 if (version_id != 0)
5785 for (i = 0; i < 16; i++) {
5786 env->regs[i] = qemu_get_be32(f);
5788 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5789 env->spsr = qemu_get_be32(f);
5790 for (i = 0; i < 6; i++) {
5791 env->banked_spsr[i] = qemu_get_be32(f);
5792 env->banked_r13[i] = qemu_get_be32(f);
5793 env->banked_r14[i] = qemu_get_be32(f);
5795 for (i = 0; i < 5; i++) {
5796 env->usr_regs[i] = qemu_get_be32(f);
5797 env->fiq_regs[i] = qemu_get_be32(f);
5799 env->cp15.c0_cpuid = qemu_get_be32(f);
5800 env->cp15.c0_cachetype = qemu_get_be32(f);
5801 env->cp15.c1_sys = qemu_get_be32(f);
5802 env->cp15.c1_coproc = qemu_get_be32(f);
5803 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5804 env->cp15.c2_base = qemu_get_be32(f);
5805 env->cp15.c2_data = qemu_get_be32(f);
5806 env->cp15.c2_insn = qemu_get_be32(f);
5807 env->cp15.c3 = qemu_get_be32(f);
5808 env->cp15.c5_insn = qemu_get_be32(f);
5809 env->cp15.c5_data = qemu_get_be32(f);
5810 for (i = 0; i < 8; i++) {
5811 env->cp15.c6_region[i] = qemu_get_be32(f);
5813 env->cp15.c6_insn = qemu_get_be32(f);
5814 env->cp15.c6_data = qemu_get_be32(f);
5815 env->cp15.c9_insn = qemu_get_be32(f);
5816 env->cp15.c9_data = qemu_get_be32(f);
5817 env->cp15.c13_fcse = qemu_get_be32(f);
5818 env->cp15.c13_context = qemu_get_be32(f);
5819 env->cp15.c15_cpar = qemu_get_be32(f);
5821 env->features = qemu_get_be32(f);
5823 if (arm_feature(env, ARM_FEATURE_VFP)) {
5824 for (i = 0; i < 16; i++) {
5826 u.l.upper = qemu_get_be32(f);
5827 u.l.lower = qemu_get_be32(f);
5828 env->vfp.regs[i] = u.d;
5830 for (i = 0; i < 16; i++) {
5831 env->vfp.xregs[i] = qemu_get_be32(f);
5834 /* TODO: Should use proper FPSCR access functions. */
5835 env->vfp.vec_len = qemu_get_be32(f);
5836 env->vfp.vec_stride = qemu_get_be32(f);
5839 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5840 for (i = 0; i < 16; i++) {
5841 env->iwmmxt.regs[i] = qemu_get_be64(f);
5843 for (i = 0; i < 16; i++) {
5844 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5853 #warning No CPU save/restore functions
5857 /***********************************************************/
5858 /* ram save/restore */
5860 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5864 v = qemu_get_byte(f);
5867 if (qemu_get_buffer(f, buf, len) != len)
5871 v = qemu_get_byte(f);
5872 memset(buf, v, len);
5880 static int ram_load_v1(QEMUFile *f, void *opaque)
5884 if (qemu_get_be32(f) != phys_ram_size)
5886 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5887 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5894 #define BDRV_HASH_BLOCK_SIZE 1024
5895 #define IOBUF_SIZE 4096
5896 #define RAM_CBLOCK_MAGIC 0xfabe
5898 typedef struct RamCompressState {
5901 uint8_t buf[IOBUF_SIZE];
5904 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5907 memset(s, 0, sizeof(*s));
5909 ret = deflateInit2(&s->zstream, 1,
5911 9, Z_DEFAULT_STRATEGY);
5914 s->zstream.avail_out = IOBUF_SIZE;
5915 s->zstream.next_out = s->buf;
5919 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5921 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5922 qemu_put_be16(s->f, len);
5923 qemu_put_buffer(s->f, buf, len);
5926 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5930 s->zstream.avail_in = len;
5931 s->zstream.next_in = (uint8_t *)buf;
5932 while (s->zstream.avail_in > 0) {
5933 ret = deflate(&s->zstream, Z_NO_FLUSH);
5936 if (s->zstream.avail_out == 0) {
5937 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5938 s->zstream.avail_out = IOBUF_SIZE;
5939 s->zstream.next_out = s->buf;
5945 static void ram_compress_close(RamCompressState *s)
5949 /* compress last bytes */
5951 ret = deflate(&s->zstream, Z_FINISH);
5952 if (ret == Z_OK || ret == Z_STREAM_END) {
5953 len = IOBUF_SIZE - s->zstream.avail_out;
5955 ram_put_cblock(s, s->buf, len);
5957 s->zstream.avail_out = IOBUF_SIZE;
5958 s->zstream.next_out = s->buf;
5959 if (ret == Z_STREAM_END)
5966 deflateEnd(&s->zstream);
5969 typedef struct RamDecompressState {
5972 uint8_t buf[IOBUF_SIZE];
5973 } RamDecompressState;
5975 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5978 memset(s, 0, sizeof(*s));
5980 ret = inflateInit(&s->zstream);
5986 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5990 s->zstream.avail_out = len;
5991 s->zstream.next_out = buf;
5992 while (s->zstream.avail_out > 0) {
5993 if (s->zstream.avail_in == 0) {
5994 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5996 clen = qemu_get_be16(s->f);
5997 if (clen > IOBUF_SIZE)
5999 qemu_get_buffer(s->f, s->buf, clen);
6000 s->zstream.avail_in = clen;
6001 s->zstream.next_in = s->buf;
6003 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6004 if (ret != Z_OK && ret != Z_STREAM_END) {
6011 static void ram_decompress_close(RamDecompressState *s)
6013 inflateEnd(&s->zstream);
6016 static void ram_save(QEMUFile *f, void *opaque)
6019 RamCompressState s1, *s = &s1;
6022 qemu_put_be32(f, phys_ram_size);
6023 if (ram_compress_open(s, f) < 0)
6025 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6027 if (tight_savevm_enabled) {
6031 /* find if the memory block is available on a virtual
6034 for(j = 0; j < MAX_DISKS; j++) {
6036 sector_num = bdrv_hash_find(bs_table[j],
6037 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6038 if (sector_num >= 0)
6043 goto normal_compress;
6046 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6047 ram_compress_buf(s, buf, 10);
6053 ram_compress_buf(s, buf, 1);
6054 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6057 ram_compress_close(s);
6060 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6062 RamDecompressState s1, *s = &s1;
6066 if (version_id == 1)
6067 return ram_load_v1(f, opaque);
6068 if (version_id != 2)
6070 if (qemu_get_be32(f) != phys_ram_size)
6072 if (ram_decompress_open(s, f) < 0)
6074 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6075 if (ram_decompress_buf(s, buf, 1) < 0) {
6076 fprintf(stderr, "Error while reading ram block header\n");
6080 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6081 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6090 ram_decompress_buf(s, buf + 1, 9);
6092 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6093 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6094 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6097 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6098 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6099 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6100 bs_index, sector_num);
6107 printf("Error block header\n");
6111 ram_decompress_close(s);
6115 /***********************************************************/
6116 /* bottom halves (can be seen as timers which expire ASAP) */
6125 static QEMUBH *first_bh = NULL;
6127 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6130 bh = qemu_mallocz(sizeof(QEMUBH));
6134 bh->opaque = opaque;
6138 int qemu_bh_poll(void)
6157 void qemu_bh_schedule(QEMUBH *bh)
6159 CPUState *env = cpu_single_env;
6163 bh->next = first_bh;
6166 /* stop the currently executing CPU to execute the BH ASAP */
6168 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6172 void qemu_bh_cancel(QEMUBH *bh)
6175 if (bh->scheduled) {
6178 pbh = &(*pbh)->next;
6184 void qemu_bh_delete(QEMUBH *bh)
6190 /***********************************************************/
6191 /* machine registration */
6193 QEMUMachine *first_machine = NULL;
6195 int qemu_register_machine(QEMUMachine *m)
6198 pm = &first_machine;
6206 QEMUMachine *find_machine(const char *name)
6210 for(m = first_machine; m != NULL; m = m->next) {
6211 if (!strcmp(m->name, name))
6217 /***********************************************************/
6218 /* main execution loop */
6220 void gui_update(void *opaque)
6222 DisplayState *ds = opaque;
6223 ds->dpy_refresh(ds);
6224 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6227 struct vm_change_state_entry {
6228 VMChangeStateHandler *cb;
6230 LIST_ENTRY (vm_change_state_entry) entries;
6233 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6235 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6238 VMChangeStateEntry *e;
6240 e = qemu_mallocz(sizeof (*e));
6246 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6250 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6252 LIST_REMOVE (e, entries);
6256 static void vm_state_notify(int running)
6258 VMChangeStateEntry *e;
6260 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6261 e->cb(e->opaque, running);
6265 /* XXX: support several handlers */
6266 static VMStopHandler *vm_stop_cb;
6267 static void *vm_stop_opaque;
6269 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6272 vm_stop_opaque = opaque;
6276 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6290 void vm_stop(int reason)
6293 cpu_disable_ticks();
6297 vm_stop_cb(vm_stop_opaque, reason);
6304 /* reset/shutdown handler */
6306 typedef struct QEMUResetEntry {
6307 QEMUResetHandler *func;
6309 struct QEMUResetEntry *next;
6312 static QEMUResetEntry *first_reset_entry;
6313 static int reset_requested;
6314 static int shutdown_requested;
6315 static int powerdown_requested;
6317 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6319 QEMUResetEntry **pre, *re;
6321 pre = &first_reset_entry;
6322 while (*pre != NULL)
6323 pre = &(*pre)->next;
6324 re = qemu_mallocz(sizeof(QEMUResetEntry));
6326 re->opaque = opaque;
6331 static void qemu_system_reset(void)
6335 /* reset all devices */
6336 for(re = first_reset_entry; re != NULL; re = re->next) {
6337 re->func(re->opaque);
6341 void qemu_system_reset_request(void)
6344 shutdown_requested = 1;
6346 reset_requested = 1;
6349 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6352 void qemu_system_shutdown_request(void)
6354 shutdown_requested = 1;
6356 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6359 void qemu_system_powerdown_request(void)
6361 powerdown_requested = 1;
6363 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6366 void main_loop_wait(int timeout)
6368 IOHandlerRecord *ioh;
6369 fd_set rfds, wfds, xfds;
6378 /* XXX: need to suppress polling by better using win32 events */
6380 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6381 ret |= pe->func(pe->opaque);
6386 WaitObjects *w = &wait_objects;
6388 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6389 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6390 if (w->func[ret - WAIT_OBJECT_0])
6391 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6393 /* Check for additional signaled events */
6394 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6396 /* Check if event is signaled */
6397 ret2 = WaitForSingleObject(w->events[i], 0);
6398 if(ret2 == WAIT_OBJECT_0) {
6400 w->func[i](w->opaque[i]);
6401 } else if (ret2 == WAIT_TIMEOUT) {
6403 err = GetLastError();
6404 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6407 } else if (ret == WAIT_TIMEOUT) {
6409 err = GetLastError();
6410 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6414 /* poll any events */
6415 /* XXX: separate device handlers from system ones */
6420 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6424 (!ioh->fd_read_poll ||
6425 ioh->fd_read_poll(ioh->opaque) != 0)) {
6426 FD_SET(ioh->fd, &rfds);
6430 if (ioh->fd_write) {
6431 FD_SET(ioh->fd, &wfds);
6441 tv.tv_usec = timeout * 1000;
6443 #if defined(CONFIG_SLIRP)
6445 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6448 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6450 IOHandlerRecord **pioh;
6452 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6455 if (FD_ISSET(ioh->fd, &rfds)) {
6456 ioh->fd_read(ioh->opaque);
6458 if (FD_ISSET(ioh->fd, &wfds)) {
6459 ioh->fd_write(ioh->opaque);
6463 /* remove deleted IO handlers */
6464 pioh = &first_io_handler;
6474 #if defined(CONFIG_SLIRP)
6481 slirp_select_poll(&rfds, &wfds, &xfds);
6487 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6488 qemu_get_clock(vm_clock));
6489 /* run dma transfers, if any */
6493 /* real time timers */
6494 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6495 qemu_get_clock(rt_clock));
6497 /* Check bottom-halves last in case any of the earlier events triggered
6503 static CPUState *cur_cpu;
6508 #ifdef CONFIG_PROFILER
6513 cur_cpu = first_cpu;
6520 env = env->next_cpu;
6523 #ifdef CONFIG_PROFILER
6524 ti = profile_getclock();
6526 ret = cpu_exec(env);
6527 #ifdef CONFIG_PROFILER
6528 qemu_time += profile_getclock() - ti;
6530 if (ret == EXCP_HLT) {
6531 /* Give the next CPU a chance to run. */
6535 if (ret != EXCP_HALTED)
6537 /* all CPUs are halted ? */
6543 if (shutdown_requested) {
6544 ret = EXCP_INTERRUPT;
6547 if (reset_requested) {
6548 reset_requested = 0;
6549 qemu_system_reset();
6550 ret = EXCP_INTERRUPT;
6552 if (powerdown_requested) {
6553 powerdown_requested = 0;
6554 qemu_system_powerdown();
6555 ret = EXCP_INTERRUPT;
6557 if (ret == EXCP_DEBUG) {
6558 vm_stop(EXCP_DEBUG);
6560 /* If all cpus are halted then wait until the next IRQ */
6561 /* XXX: use timeout computed from timers */
6562 if (ret == EXCP_HALTED)
6569 #ifdef CONFIG_PROFILER
6570 ti = profile_getclock();
6572 main_loop_wait(timeout);
6573 #ifdef CONFIG_PROFILER
6574 dev_time += profile_getclock() - ti;
6577 cpu_disable_ticks();
6581 static void help(int exitcode)
6583 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6584 "usage: %s [options] [disk_image]\n"
6586 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6588 "Standard options:\n"
6589 "-M machine select emulated machine (-M ? for list)\n"
6590 "-cpu cpu select CPU (-cpu ? for list)\n"
6591 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6592 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6593 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6594 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6595 "-mtdblock file use 'file' as on-board Flash memory image\n"
6596 "-sd file use 'file' as SecureDigital card image\n"
6597 "-pflash file use 'file' as a parallel flash image\n"
6598 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6599 "-snapshot write to temporary files instead of disk image files\n"
6601 "-no-frame open SDL window without a frame and window decorations\n"
6602 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6603 "-no-quit disable SDL window close capability\n"
6606 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6608 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6609 "-smp n set the number of CPUs to 'n' [default=1]\n"
6610 "-nographic disable graphical output and redirect serial I/Os to console\n"
6611 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6613 "-k language use keyboard layout (for example \"fr\" for French)\n"
6616 "-audio-help print list of audio drivers and their options\n"
6617 "-soundhw c1,... enable audio support\n"
6618 " and only specified sound cards (comma separated list)\n"
6619 " use -soundhw ? to get the list of supported cards\n"
6620 " use -soundhw all to enable all of them\n"
6622 "-localtime set the real time clock to local time [default=utc]\n"
6623 "-full-screen start in full screen\n"
6625 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6627 "-usb enable the USB driver (will be the default soon)\n"
6628 "-usbdevice name add the host or guest USB device 'name'\n"
6629 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6630 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6632 "-name string set the name of the guest\n"
6634 "Network options:\n"
6635 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6636 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6638 "-net user[,vlan=n][,hostname=host]\n"
6639 " connect the user mode network stack to VLAN 'n' and send\n"
6640 " hostname 'host' to DHCP clients\n"
6643 "-net tap[,vlan=n],ifname=name\n"
6644 " connect the host TAP network interface to VLAN 'n'\n"
6646 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6647 " connect the host TAP network interface to VLAN 'n' and use\n"
6648 " the network script 'file' (default=%s);\n"
6649 " use 'script=no' to disable script execution;\n"
6650 " use 'fd=h' to connect to an already opened TAP interface\n"
6652 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6653 " connect the vlan 'n' to another VLAN using a socket connection\n"
6654 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6655 " connect the vlan 'n' to multicast maddr and port\n"
6656 "-net none use it alone to have zero network devices; if no -net option\n"
6657 " is provided, the default is '-net nic -net user'\n"
6660 "-tftp dir allow tftp access to files in dir [-net user]\n"
6661 "-bootp file advertise file in BOOTP replies\n"
6663 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6665 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6666 " redirect TCP or UDP connections from host to guest [-net user]\n"
6669 "Linux boot specific:\n"
6670 "-kernel bzImage use 'bzImage' as kernel image\n"
6671 "-append cmdline use 'cmdline' as kernel command line\n"
6672 "-initrd file use 'file' as initial ram disk\n"
6674 "Debug/Expert options:\n"
6675 "-monitor dev redirect the monitor to char device 'dev'\n"
6676 "-serial dev redirect the serial port to char device 'dev'\n"
6677 "-parallel dev redirect the parallel port to char device 'dev'\n"
6678 "-pidfile file Write PID to 'file'\n"
6679 "-S freeze CPU at startup (use 'c' to start execution)\n"
6680 "-s wait gdb connection to port\n"
6681 "-p port set gdb connection port [default=%s]\n"
6682 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6683 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6684 " translation (t=none or lba) (usually qemu can guess them)\n"
6685 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6687 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6688 "-no-kqemu disable KQEMU kernel module usage\n"
6690 #ifdef USE_CODE_COPY
6691 "-no-code-copy disable code copy acceleration\n"
6694 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6695 " (default is CL-GD5446 PCI VGA)\n"
6696 "-no-acpi disable ACPI\n"
6698 "-no-reboot exit instead of rebooting\n"
6699 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6700 "-vnc display start a VNC server on display\n"
6702 "-daemonize daemonize QEMU after initializing\n"
6704 "-option-rom rom load a file, rom, into the option ROM space\n"
6706 "-prom-env variable=value set OpenBIOS nvram variables\n"
6709 "During emulation, the following keys are useful:\n"
6710 "ctrl-alt-f toggle full screen\n"
6711 "ctrl-alt-n switch to virtual console 'n'\n"
6712 "ctrl-alt toggle mouse and keyboard grab\n"
6714 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6719 DEFAULT_NETWORK_SCRIPT,
6721 DEFAULT_GDBSTUB_PORT,
6726 #define HAS_ARG 0x0001
6740 QEMU_OPTION_mtdblock,
6744 QEMU_OPTION_snapshot,
6746 QEMU_OPTION_no_fd_bootchk,
6749 QEMU_OPTION_nographic,
6750 QEMU_OPTION_portrait,
6752 QEMU_OPTION_audio_help,
6753 QEMU_OPTION_soundhw,
6772 QEMU_OPTION_no_code_copy,
6774 QEMU_OPTION_localtime,
6775 QEMU_OPTION_cirrusvga,
6778 QEMU_OPTION_std_vga,
6780 QEMU_OPTION_monitor,
6782 QEMU_OPTION_parallel,
6784 QEMU_OPTION_full_screen,
6785 QEMU_OPTION_no_frame,
6786 QEMU_OPTION_alt_grab,
6787 QEMU_OPTION_no_quit,
6788 QEMU_OPTION_pidfile,
6789 QEMU_OPTION_no_kqemu,
6790 QEMU_OPTION_kernel_kqemu,
6791 QEMU_OPTION_win2k_hack,
6793 QEMU_OPTION_usbdevice,
6796 QEMU_OPTION_no_acpi,
6797 QEMU_OPTION_no_reboot,
6798 QEMU_OPTION_show_cursor,
6799 QEMU_OPTION_daemonize,
6800 QEMU_OPTION_option_rom,
6801 QEMU_OPTION_semihosting,
6803 QEMU_OPTION_prom_env,
6806 typedef struct QEMUOption {
6812 const QEMUOption qemu_options[] = {
6813 { "h", 0, QEMU_OPTION_h },
6814 { "help", 0, QEMU_OPTION_h },
6816 { "M", HAS_ARG, QEMU_OPTION_M },
6817 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6818 { "fda", HAS_ARG, QEMU_OPTION_fda },
6819 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6820 { "hda", HAS_ARG, QEMU_OPTION_hda },
6821 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6822 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6823 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6824 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6825 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6826 { "sd", HAS_ARG, QEMU_OPTION_sd },
6827 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6828 { "boot", HAS_ARG, QEMU_OPTION_boot },
6829 { "snapshot", 0, QEMU_OPTION_snapshot },
6831 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6833 { "m", HAS_ARG, QEMU_OPTION_m },
6834 { "nographic", 0, QEMU_OPTION_nographic },
6835 { "portrait", 0, QEMU_OPTION_portrait },
6836 { "k", HAS_ARG, QEMU_OPTION_k },
6838 { "audio-help", 0, QEMU_OPTION_audio_help },
6839 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6842 { "net", HAS_ARG, QEMU_OPTION_net},
6844 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6845 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6847 { "smb", HAS_ARG, QEMU_OPTION_smb },
6849 { "redir", HAS_ARG, QEMU_OPTION_redir },
6852 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6853 { "append", HAS_ARG, QEMU_OPTION_append },
6854 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6856 { "S", 0, QEMU_OPTION_S },
6857 { "s", 0, QEMU_OPTION_s },
6858 { "p", HAS_ARG, QEMU_OPTION_p },
6859 { "d", HAS_ARG, QEMU_OPTION_d },
6860 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6861 { "L", HAS_ARG, QEMU_OPTION_L },
6862 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6864 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6865 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6867 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6868 { "g", 1, QEMU_OPTION_g },
6870 { "localtime", 0, QEMU_OPTION_localtime },
6871 { "std-vga", 0, QEMU_OPTION_std_vga },
6872 { "echr", HAS_ARG, QEMU_OPTION_echr },
6873 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6874 { "serial", HAS_ARG, QEMU_OPTION_serial },
6875 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6876 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6877 { "full-screen", 0, QEMU_OPTION_full_screen },
6879 { "no-frame", 0, QEMU_OPTION_no_frame },
6880 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6881 { "no-quit", 0, QEMU_OPTION_no_quit },
6883 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6884 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6885 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6886 { "smp", HAS_ARG, QEMU_OPTION_smp },
6887 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6889 /* temporary options */
6890 { "usb", 0, QEMU_OPTION_usb },
6891 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6892 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6893 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6894 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6895 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6896 { "daemonize", 0, QEMU_OPTION_daemonize },
6897 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6898 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6899 { "semihosting", 0, QEMU_OPTION_semihosting },
6901 { "name", HAS_ARG, QEMU_OPTION_name },
6902 #if defined(TARGET_SPARC)
6903 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6908 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6910 /* this stack is only used during signal handling */
6911 #define SIGNAL_STACK_SIZE 32768
6913 static uint8_t *signal_stack;
6917 /* password input */
6919 int qemu_key_check(BlockDriverState *bs, const char *name)
6924 if (!bdrv_is_encrypted(bs))
6927 term_printf("%s is encrypted.\n", name);
6928 for(i = 0; i < 3; i++) {
6929 monitor_readline("Password: ", 1, password, sizeof(password));
6930 if (bdrv_set_key(bs, password) == 0)
6932 term_printf("invalid password\n");
6937 static BlockDriverState *get_bdrv(int index)
6939 BlockDriverState *bs;
6942 bs = bs_table[index];
6943 } else if (index < 6) {
6944 bs = fd_table[index - 4];
6951 static void read_passwords(void)
6953 BlockDriverState *bs;
6956 for(i = 0; i < 6; i++) {
6959 qemu_key_check(bs, bdrv_get_device_name(bs));
6963 /* XXX: currently we cannot use simultaneously different CPUs */
6964 void register_machines(void)
6966 #if defined(TARGET_I386)
6967 qemu_register_machine(&pc_machine);
6968 qemu_register_machine(&isapc_machine);
6969 #elif defined(TARGET_PPC)
6970 qemu_register_machine(&heathrow_machine);
6971 qemu_register_machine(&core99_machine);
6972 qemu_register_machine(&prep_machine);
6973 qemu_register_machine(&ref405ep_machine);
6974 qemu_register_machine(&taihu_machine);
6975 #elif defined(TARGET_MIPS)
6976 qemu_register_machine(&mips_machine);
6977 qemu_register_machine(&mips_malta_machine);
6978 qemu_register_machine(&mips_pica61_machine);
6979 #elif defined(TARGET_SPARC)
6980 #ifdef TARGET_SPARC64
6981 qemu_register_machine(&sun4u_machine);
6983 qemu_register_machine(&ss5_machine);
6984 qemu_register_machine(&ss10_machine);
6986 #elif defined(TARGET_ARM)
6987 qemu_register_machine(&integratorcp_machine);
6988 qemu_register_machine(&versatilepb_machine);
6989 qemu_register_machine(&versatileab_machine);
6990 qemu_register_machine(&realview_machine);
6991 qemu_register_machine(&akitapda_machine);
6992 qemu_register_machine(&spitzpda_machine);
6993 qemu_register_machine(&borzoipda_machine);
6994 qemu_register_machine(&terrierpda_machine);
6995 #elif defined(TARGET_SH4)
6996 qemu_register_machine(&shix_machine);
6997 #elif defined(TARGET_ALPHA)
6999 #elif defined(TARGET_M68K)
7000 qemu_register_machine(&mcf5208evb_machine);
7001 qemu_register_machine(&an5206_machine);
7003 #error unsupported CPU
7008 struct soundhw soundhw[] = {
7009 #ifdef HAS_AUDIO_CHOICE
7016 { .init_isa = pcspk_audio_init }
7021 "Creative Sound Blaster 16",
7024 { .init_isa = SB16_init }
7031 "Yamaha YMF262 (OPL3)",
7033 "Yamaha YM3812 (OPL2)",
7037 { .init_isa = Adlib_init }
7044 "Gravis Ultrasound GF1",
7047 { .init_isa = GUS_init }
7053 "ENSONIQ AudioPCI ES1370",
7056 { .init_pci = es1370_init }
7060 { NULL, NULL, 0, 0, { NULL } }
7063 static void select_soundhw (const char *optarg)
7067 if (*optarg == '?') {
7070 printf ("Valid sound card names (comma separated):\n");
7071 for (c = soundhw; c->name; ++c) {
7072 printf ("%-11s %s\n", c->name, c->descr);
7074 printf ("\n-soundhw all will enable all of the above\n");
7075 exit (*optarg != '?');
7083 if (!strcmp (optarg, "all")) {
7084 for (c = soundhw; c->name; ++c) {
7092 e = strchr (p, ',');
7093 l = !e ? strlen (p) : (size_t) (e - p);
7095 for (c = soundhw; c->name; ++c) {
7096 if (!strncmp (c->name, p, l)) {
7105 "Unknown sound card name (too big to show)\n");
7108 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7113 p += l + (e != NULL);
7117 goto show_valid_cards;
7123 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7125 exit(STATUS_CONTROL_C_EXIT);
7130 #define MAX_NET_CLIENTS 32
7132 int main(int argc, char **argv)
7134 #ifdef CONFIG_GDBSTUB
7136 const char *gdbstub_port;
7138 int i, cdrom_index, pflash_index;
7139 int snapshot, linux_boot;
7140 const char *initrd_filename;
7141 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7142 const char *pflash_filename[MAX_PFLASH];
7143 const char *sd_filename;
7144 const char *mtd_filename;
7145 const char *kernel_filename, *kernel_cmdline;
7146 DisplayState *ds = &display_state;
7147 int cyls, heads, secs, translation;
7148 char net_clients[MAX_NET_CLIENTS][256];
7151 const char *r, *optarg;
7152 CharDriverState *monitor_hd;
7153 char monitor_device[128];
7154 char serial_devices[MAX_SERIAL_PORTS][128];
7155 int serial_device_index;
7156 char parallel_devices[MAX_PARALLEL_PORTS][128];
7157 int parallel_device_index;
7158 const char *loadvm = NULL;
7159 QEMUMachine *machine;
7160 const char *cpu_model;
7161 char usb_devices[MAX_USB_CMDLINE][128];
7162 int usb_devices_index;
7164 const char *pid_file = NULL;
7167 LIST_INIT (&vm_change_state_head);
7170 struct sigaction act;
7171 sigfillset(&act.sa_mask);
7173 act.sa_handler = SIG_IGN;
7174 sigaction(SIGPIPE, &act, NULL);
7177 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7178 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7179 QEMU to run on a single CPU */
7184 h = GetCurrentProcess();
7185 if (GetProcessAffinityMask(h, &mask, &smask)) {
7186 for(i = 0; i < 32; i++) {
7187 if (mask & (1 << i))
7192 SetProcessAffinityMask(h, mask);
7198 register_machines();
7199 machine = first_machine;
7201 initrd_filename = NULL;
7202 for(i = 0; i < MAX_FD; i++)
7203 fd_filename[i] = NULL;
7204 for(i = 0; i < MAX_DISKS; i++)
7205 hd_filename[i] = NULL;
7206 for(i = 0; i < MAX_PFLASH; i++)
7207 pflash_filename[i] = NULL;
7210 mtd_filename = NULL;
7211 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7212 vga_ram_size = VGA_RAM_SIZE;
7213 #ifdef CONFIG_GDBSTUB
7215 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7219 kernel_filename = NULL;
7220 kernel_cmdline = "";
7226 cyls = heads = secs = 0;
7227 translation = BIOS_ATA_TRANSLATION_AUTO;
7228 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7230 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7231 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7232 serial_devices[i][0] = '\0';
7233 serial_device_index = 0;
7235 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7236 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7237 parallel_devices[i][0] = '\0';
7238 parallel_device_index = 0;
7240 usb_devices_index = 0;
7245 /* default mac address of the first network interface */
7253 hd_filename[0] = argv[optind++];
7255 const QEMUOption *popt;
7258 /* Treat --foo the same as -foo. */
7261 popt = qemu_options;
7264 fprintf(stderr, "%s: invalid option -- '%s'\n",
7268 if (!strcmp(popt->name, r + 1))
7272 if (popt->flags & HAS_ARG) {
7273 if (optind >= argc) {
7274 fprintf(stderr, "%s: option '%s' requires an argument\n",
7278 optarg = argv[optind++];
7283 switch(popt->index) {
7285 machine = find_machine(optarg);
7288 printf("Supported machines are:\n");
7289 for(m = first_machine; m != NULL; m = m->next) {
7290 printf("%-10s %s%s\n",
7292 m == first_machine ? " (default)" : "");
7294 exit(*optarg != '?');
7297 case QEMU_OPTION_cpu:
7298 /* hw initialization will check this */
7299 if (*optarg == '?') {
7300 #if defined(TARGET_PPC)
7301 ppc_cpu_list(stdout, &fprintf);
7302 #elif defined(TARGET_ARM)
7304 #elif defined(TARGET_MIPS)
7305 mips_cpu_list(stdout, &fprintf);
7306 #elif defined(TARGET_SPARC)
7307 sparc_cpu_list(stdout, &fprintf);
7314 case QEMU_OPTION_initrd:
7315 initrd_filename = optarg;
7317 case QEMU_OPTION_hda:
7318 case QEMU_OPTION_hdb:
7319 case QEMU_OPTION_hdc:
7320 case QEMU_OPTION_hdd:
7323 hd_index = popt->index - QEMU_OPTION_hda;
7324 hd_filename[hd_index] = optarg;
7325 if (hd_index == cdrom_index)
7329 case QEMU_OPTION_mtdblock:
7330 mtd_filename = optarg;
7332 case QEMU_OPTION_sd:
7333 sd_filename = optarg;
7335 case QEMU_OPTION_pflash:
7336 if (pflash_index >= MAX_PFLASH) {
7337 fprintf(stderr, "qemu: too many parallel flash images\n");
7340 pflash_filename[pflash_index++] = optarg;
7342 case QEMU_OPTION_snapshot:
7345 case QEMU_OPTION_hdachs:
7349 cyls = strtol(p, (char **)&p, 0);
7350 if (cyls < 1 || cyls > 16383)
7355 heads = strtol(p, (char **)&p, 0);
7356 if (heads < 1 || heads > 16)
7361 secs = strtol(p, (char **)&p, 0);
7362 if (secs < 1 || secs > 63)
7366 if (!strcmp(p, "none"))
7367 translation = BIOS_ATA_TRANSLATION_NONE;
7368 else if (!strcmp(p, "lba"))
7369 translation = BIOS_ATA_TRANSLATION_LBA;
7370 else if (!strcmp(p, "auto"))
7371 translation = BIOS_ATA_TRANSLATION_AUTO;
7374 } else if (*p != '\0') {
7376 fprintf(stderr, "qemu: invalid physical CHS format\n");
7381 case QEMU_OPTION_nographic:
7382 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7383 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7384 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7387 case QEMU_OPTION_portrait:
7390 case QEMU_OPTION_kernel:
7391 kernel_filename = optarg;
7393 case QEMU_OPTION_append:
7394 kernel_cmdline = optarg;
7396 case QEMU_OPTION_cdrom:
7397 if (cdrom_index >= 0) {
7398 hd_filename[cdrom_index] = optarg;
7401 case QEMU_OPTION_boot:
7402 boot_device = optarg[0];
7403 if (boot_device != 'a' &&
7404 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7406 boot_device != 'n' &&
7408 boot_device != 'c' && boot_device != 'd') {
7409 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7413 case QEMU_OPTION_fda:
7414 fd_filename[0] = optarg;
7416 case QEMU_OPTION_fdb:
7417 fd_filename[1] = optarg;
7420 case QEMU_OPTION_no_fd_bootchk:
7424 case QEMU_OPTION_no_code_copy:
7425 code_copy_enabled = 0;
7427 case QEMU_OPTION_net:
7428 if (nb_net_clients >= MAX_NET_CLIENTS) {
7429 fprintf(stderr, "qemu: too many network clients\n");
7432 pstrcpy(net_clients[nb_net_clients],
7433 sizeof(net_clients[0]),
7438 case QEMU_OPTION_tftp:
7439 tftp_prefix = optarg;
7441 case QEMU_OPTION_bootp:
7442 bootp_filename = optarg;
7445 case QEMU_OPTION_smb:
7446 net_slirp_smb(optarg);
7449 case QEMU_OPTION_redir:
7450 net_slirp_redir(optarg);
7454 case QEMU_OPTION_audio_help:
7458 case QEMU_OPTION_soundhw:
7459 select_soundhw (optarg);
7466 ram_size = atoi(optarg) * 1024 * 1024;
7469 if (ram_size > PHYS_RAM_MAX_SIZE) {
7470 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7471 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7480 mask = cpu_str_to_log_mask(optarg);
7482 printf("Log items (comma separated):\n");
7483 for(item = cpu_log_items; item->mask != 0; item++) {
7484 printf("%-10s %s\n", item->name, item->help);
7491 #ifdef CONFIG_GDBSTUB
7496 gdbstub_port = optarg;
7506 keyboard_layout = optarg;
7508 case QEMU_OPTION_localtime:
7511 case QEMU_OPTION_cirrusvga:
7512 cirrus_vga_enabled = 1;
7515 case QEMU_OPTION_vmsvga:
7516 cirrus_vga_enabled = 0;
7519 case QEMU_OPTION_std_vga:
7520 cirrus_vga_enabled = 0;
7528 w = strtol(p, (char **)&p, 10);
7531 fprintf(stderr, "qemu: invalid resolution or depth\n");
7537 h = strtol(p, (char **)&p, 10);
7542 depth = strtol(p, (char **)&p, 10);
7543 if (depth != 8 && depth != 15 && depth != 16 &&
7544 depth != 24 && depth != 32)
7546 } else if (*p == '\0') {
7547 depth = graphic_depth;
7554 graphic_depth = depth;
7557 case QEMU_OPTION_echr:
7560 term_escape_char = strtol(optarg, &r, 0);
7562 printf("Bad argument to echr\n");
7565 case QEMU_OPTION_monitor:
7566 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7568 case QEMU_OPTION_serial:
7569 if (serial_device_index >= MAX_SERIAL_PORTS) {
7570 fprintf(stderr, "qemu: too many serial ports\n");
7573 pstrcpy(serial_devices[serial_device_index],
7574 sizeof(serial_devices[0]), optarg);
7575 serial_device_index++;
7577 case QEMU_OPTION_parallel:
7578 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7579 fprintf(stderr, "qemu: too many parallel ports\n");
7582 pstrcpy(parallel_devices[parallel_device_index],
7583 sizeof(parallel_devices[0]), optarg);
7584 parallel_device_index++;
7586 case QEMU_OPTION_loadvm:
7589 case QEMU_OPTION_full_screen:
7593 case QEMU_OPTION_no_frame:
7596 case QEMU_OPTION_alt_grab:
7599 case QEMU_OPTION_no_quit:
7603 case QEMU_OPTION_pidfile:
7607 case QEMU_OPTION_win2k_hack:
7608 win2k_install_hack = 1;
7612 case QEMU_OPTION_no_kqemu:
7615 case QEMU_OPTION_kernel_kqemu:
7619 case QEMU_OPTION_usb:
7622 case QEMU_OPTION_usbdevice:
7624 if (usb_devices_index >= MAX_USB_CMDLINE) {
7625 fprintf(stderr, "Too many USB devices\n");
7628 pstrcpy(usb_devices[usb_devices_index],
7629 sizeof(usb_devices[usb_devices_index]),
7631 usb_devices_index++;
7633 case QEMU_OPTION_smp:
7634 smp_cpus = atoi(optarg);
7635 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7636 fprintf(stderr, "Invalid number of CPUs\n");
7640 case QEMU_OPTION_vnc:
7641 vnc_display = optarg;
7643 case QEMU_OPTION_no_acpi:
7646 case QEMU_OPTION_no_reboot:
7649 case QEMU_OPTION_show_cursor:
7652 case QEMU_OPTION_daemonize:
7655 case QEMU_OPTION_option_rom:
7656 if (nb_option_roms >= MAX_OPTION_ROMS) {
7657 fprintf(stderr, "Too many option ROMs\n");
7660 option_rom[nb_option_roms] = optarg;
7663 case QEMU_OPTION_semihosting:
7664 semihosting_enabled = 1;
7666 case QEMU_OPTION_name:
7670 case QEMU_OPTION_prom_env:
7671 if (nb_prom_envs >= MAX_PROM_ENVS) {
7672 fprintf(stderr, "Too many prom variables\n");
7675 prom_envs[nb_prom_envs] = optarg;
7684 if (daemonize && !nographic && vnc_display == NULL) {
7685 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7692 if (pipe(fds) == -1)
7703 len = read(fds[0], &status, 1);
7704 if (len == -1 && (errno == EINTR))
7709 else if (status == 1) {
7710 fprintf(stderr, "Could not acquire pidfile\n");
7728 signal(SIGTSTP, SIG_IGN);
7729 signal(SIGTTOU, SIG_IGN);
7730 signal(SIGTTIN, SIG_IGN);
7734 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7737 write(fds[1], &status, 1);
7739 fprintf(stderr, "Could not acquire pid file\n");
7747 linux_boot = (kernel_filename != NULL);
7750 boot_device != 'n' &&
7751 hd_filename[0] == '\0' &&
7752 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7753 fd_filename[0] == '\0')
7756 /* boot to floppy or the default cd if no hard disk defined yet */
7757 if (hd_filename[0] == '\0' && boot_device == 'c') {
7758 if (fd_filename[0] != '\0')
7764 setvbuf(stdout, NULL, _IOLBF, 0);
7774 /* init network clients */
7775 if (nb_net_clients == 0) {
7776 /* if no clients, we use a default config */
7777 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7779 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7784 for(i = 0;i < nb_net_clients; i++) {
7785 if (net_client_init(net_clients[i]) < 0)
7788 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7789 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7791 if (vlan->nb_guest_devs == 0) {
7792 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7795 if (vlan->nb_host_devs == 0)
7797 "Warning: vlan %d is not connected to host network\n",
7802 if (boot_device == 'n') {
7803 for (i = 0; i < nb_nics; i++) {
7804 const char *model = nd_table[i].model;
7808 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7809 if (get_image_size(buf) > 0) {
7810 option_rom[nb_option_roms] = strdup(buf);
7816 fprintf(stderr, "No valid PXE rom found for network device\n");
7819 boot_device = 'c'; /* to prevent confusion by the BIOS */
7823 /* init the memory */
7824 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7826 phys_ram_base = qemu_vmalloc(phys_ram_size);
7827 if (!phys_ram_base) {
7828 fprintf(stderr, "Could not allocate physical memory\n");
7832 /* we always create the cdrom drive, even if no disk is there */
7834 if (cdrom_index >= 0) {
7835 bs_table[cdrom_index] = bdrv_new("cdrom");
7836 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7839 /* open the virtual block devices */
7840 for(i = 0; i < MAX_DISKS; i++) {
7841 if (hd_filename[i]) {
7844 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7845 bs_table[i] = bdrv_new(buf);
7847 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7848 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7852 if (i == 0 && cyls != 0) {
7853 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7854 bdrv_set_translation_hint(bs_table[i], translation);
7859 /* we always create at least one floppy disk */
7860 fd_table[0] = bdrv_new("fda");
7861 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7863 for(i = 0; i < MAX_FD; i++) {
7864 if (fd_filename[i]) {
7867 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7868 fd_table[i] = bdrv_new(buf);
7869 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7871 if (fd_filename[i][0] != '\0') {
7872 if (bdrv_open(fd_table[i], fd_filename[i],
7873 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7874 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7882 /* Open the virtual parallel flash block devices */
7883 for(i = 0; i < MAX_PFLASH; i++) {
7884 if (pflash_filename[i]) {
7885 if (!pflash_table[i]) {
7887 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7888 pflash_table[i] = bdrv_new(buf);
7890 if (bdrv_open(pflash_table[i], pflash_filename[i],
7891 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7892 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7893 pflash_filename[i]);
7899 sd_bdrv = bdrv_new ("sd");
7900 /* FIXME: This isn't really a floppy, but it's a reasonable
7902 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7904 if (bdrv_open(sd_bdrv, sd_filename,
7905 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7906 fprintf(stderr, "qemu: could not open SD card image %s\n",
7909 qemu_key_check(sd_bdrv, sd_filename);
7913 mtd_bdrv = bdrv_new ("mtd");
7914 if (bdrv_open(mtd_bdrv, mtd_filename,
7915 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7916 qemu_key_check(mtd_bdrv, mtd_filename)) {
7917 fprintf(stderr, "qemu: could not open Flash image %s\n",
7919 bdrv_delete(mtd_bdrv);
7924 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7925 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7930 memset(&display_state, 0, sizeof(display_state));
7932 /* nearly nothing to do */
7933 dumb_display_init(ds);
7934 } else if (vnc_display != NULL) {
7935 vnc_display_init(ds, vnc_display);
7937 #if defined(CONFIG_SDL)
7938 sdl_display_init(ds, full_screen, no_frame);
7939 #elif defined(CONFIG_COCOA)
7940 cocoa_display_init(ds, full_screen);
7944 /* Maintain compatibility with multiple stdio monitors */
7945 if (!strcmp(monitor_device,"stdio")) {
7946 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7947 if (!strcmp(serial_devices[i],"mon:stdio")) {
7948 monitor_device[0] = '\0';
7950 } else if (!strcmp(serial_devices[i],"stdio")) {
7951 monitor_device[0] = '\0';
7952 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7957 if (monitor_device[0] != '\0') {
7958 monitor_hd = qemu_chr_open(monitor_device);
7960 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7963 monitor_init(monitor_hd, !nographic);
7966 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7967 const char *devname = serial_devices[i];
7968 if (devname[0] != '\0' && strcmp(devname, "none")) {
7969 serial_hds[i] = qemu_chr_open(devname);
7970 if (!serial_hds[i]) {
7971 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7975 if (strstart(devname, "vc", 0))
7976 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7980 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7981 const char *devname = parallel_devices[i];
7982 if (devname[0] != '\0' && strcmp(devname, "none")) {
7983 parallel_hds[i] = qemu_chr_open(devname);
7984 if (!parallel_hds[i]) {
7985 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7989 if (strstart(devname, "vc", 0))
7990 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7994 machine->init(ram_size, vga_ram_size, boot_device,
7995 ds, fd_filename, snapshot,
7996 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7998 /* init USB devices */
8000 for(i = 0; i < usb_devices_index; i++) {
8001 if (usb_device_add(usb_devices[i]) < 0) {
8002 fprintf(stderr, "Warning: could not add USB device %s\n",
8008 if (display_state.dpy_refresh) {
8009 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8010 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8013 #ifdef CONFIG_GDBSTUB
8015 /* XXX: use standard host:port notation and modify options
8017 if (gdbserver_start(gdbstub_port) < 0) {
8018 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8029 /* XXX: simplify init */
8042 len = write(fds[1], &status, 1);
8043 if (len == -1 && (errno == EINTR))
8049 TFR(fd = open("/dev/null", O_RDWR));