4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
53 #include <linux/if_tun.h>
56 #include <linux/rtc.h>
57 #include <linux/ppdev.h>
58 #include <linux/parport.h>
61 #include <sys/ethernet.h>
62 #include <sys/sockio.h>
63 #include <arpa/inet.h>
64 #include <netinet/arp.h>
65 #include <netinet/in.h>
66 #include <netinet/in_systm.h>
67 #include <netinet/ip.h>
68 #include <netinet/ip_icmp.h> // must come after ip.h
69 #include <netinet/udp.h>
70 #include <netinet/tcp.h>
78 #if defined(CONFIG_SLIRP)
84 #include <sys/timeb.h>
86 #define getopt_long_only getopt_long
87 #define memalign(align, size) malloc(size)
90 #include "qemu_socket.h"
96 #endif /* CONFIG_SDL */
100 #define main qemu_main
101 #endif /* CONFIG_COCOA */
105 #include "exec-all.h"
107 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
109 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
111 #define SMBD_COMMAND "/usr/sbin/smbd"
114 //#define DEBUG_UNUSED_IOPORT
115 //#define DEBUG_IOPORT
117 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
120 #define DEFAULT_RAM_SIZE 144
122 #define DEFAULT_RAM_SIZE 128
125 #define GUI_REFRESH_INTERVAL 30
127 /* Max number of USB devices that can be specified on the commandline. */
128 #define MAX_USB_CMDLINE 8
130 /* XXX: use a two level table to limit memory usage */
131 #define MAX_IOPORTS 65536
133 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134 char phys_ram_file[1024];
135 void *ioport_opaque[MAX_IOPORTS];
136 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139 to store the VM snapshots */
140 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141 BlockDriverState *pflash_table[MAX_PFLASH];
142 BlockDriverState *sd_bdrv;
143 BlockDriverState *mtd_bdrv;
144 /* point to the block driver where the snapshots are managed */
145 BlockDriverState *bs_snapshots;
147 static DisplayState display_state;
149 const char* keyboard_layout = NULL;
150 int64_t ticks_per_sec;
151 int boot_device = 'c';
153 int pit_min_timer_count = 0;
155 NICInfo nd_table[MAX_NICS];
156 QEMUTimer *gui_timer;
159 int cirrus_vga_enabled = 1;
160 int vmsvga_enabled = 0;
162 int graphic_width = 1024;
163 int graphic_height = 768;
164 int graphic_depth = 8;
166 int graphic_width = 800;
167 int graphic_height = 600;
168 int graphic_depth = 15;
173 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
174 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
176 int win2k_install_hack = 0;
179 static VLANState *first_vlan;
181 const char *vnc_display;
182 #if defined(TARGET_SPARC)
184 #elif defined(TARGET_I386)
189 int acpi_enabled = 1;
193 int graphic_rotate = 0;
195 const char *option_rom[MAX_OPTION_ROMS];
197 int semihosting_enabled = 0;
199 const char *qemu_name;
201 unsigned int nb_prom_envs = 0;
202 const char *prom_envs[MAX_PROM_ENVS];
205 /***********************************************************/
206 /* x86 ISA bus support */
208 target_phys_addr_t isa_mem_base = 0;
211 uint32_t default_ioport_readb(void *opaque, uint32_t address)
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "unused inb: port=0x%04x\n", address);
219 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
226 /* default is to make two byte accesses */
227 uint32_t default_ioport_readw(void *opaque, uint32_t address)
230 data = ioport_read_table[0][address](ioport_opaque[address], address);
231 address = (address + 1) & (MAX_IOPORTS - 1);
232 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
236 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
238 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
239 address = (address + 1) & (MAX_IOPORTS - 1);
240 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
243 uint32_t default_ioport_readl(void *opaque, uint32_t address)
245 #ifdef DEBUG_UNUSED_IOPORT
246 fprintf(stderr, "unused inl: port=0x%04x\n", address);
251 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
258 void init_ioports(void)
262 for(i = 0; i < MAX_IOPORTS; i++) {
263 ioport_read_table[0][i] = default_ioport_readb;
264 ioport_write_table[0][i] = default_ioport_writeb;
265 ioport_read_table[1][i] = default_ioport_readw;
266 ioport_write_table[1][i] = default_ioport_writew;
267 ioport_read_table[2][i] = default_ioport_readl;
268 ioport_write_table[2][i] = default_ioport_writel;
272 /* size is the word size in byte */
273 int register_ioport_read(int start, int length, int size,
274 IOPortReadFunc *func, void *opaque)
280 } else if (size == 2) {
282 } else if (size == 4) {
285 hw_error("register_ioport_read: invalid size");
288 for(i = start; i < start + length; i += size) {
289 ioport_read_table[bsize][i] = func;
290 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
291 hw_error("register_ioport_read: invalid opaque");
292 ioport_opaque[i] = opaque;
297 /* size is the word size in byte */
298 int register_ioport_write(int start, int length, int size,
299 IOPortWriteFunc *func, void *opaque)
305 } else if (size == 2) {
307 } else if (size == 4) {
310 hw_error("register_ioport_write: invalid size");
313 for(i = start; i < start + length; i += size) {
314 ioport_write_table[bsize][i] = func;
315 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
316 hw_error("register_ioport_write: invalid opaque");
317 ioport_opaque[i] = opaque;
322 void isa_unassign_ioport(int start, int length)
326 for(i = start; i < start + length; i++) {
327 ioport_read_table[0][i] = default_ioport_readb;
328 ioport_read_table[1][i] = default_ioport_readw;
329 ioport_read_table[2][i] = default_ioport_readl;
331 ioport_write_table[0][i] = default_ioport_writeb;
332 ioport_write_table[1][i] = default_ioport_writew;
333 ioport_write_table[2][i] = default_ioport_writel;
337 /***********************************************************/
339 void cpu_outb(CPUState *env, int addr, int val)
342 if (loglevel & CPU_LOG_IOPORT)
343 fprintf(logfile, "outb: %04x %02x\n", addr, val);
345 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
348 env->last_io_time = cpu_get_time_fast();
352 void cpu_outw(CPUState *env, int addr, int val)
355 if (loglevel & CPU_LOG_IOPORT)
356 fprintf(logfile, "outw: %04x %04x\n", addr, val);
358 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
361 env->last_io_time = cpu_get_time_fast();
365 void cpu_outl(CPUState *env, int addr, int val)
368 if (loglevel & CPU_LOG_IOPORT)
369 fprintf(logfile, "outl: %04x %08x\n", addr, val);
371 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
374 env->last_io_time = cpu_get_time_fast();
378 int cpu_inb(CPUState *env, int addr)
381 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "inb : %04x %02x\n", addr, val);
388 env->last_io_time = cpu_get_time_fast();
393 int cpu_inw(CPUState *env, int addr)
396 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
398 if (loglevel & CPU_LOG_IOPORT)
399 fprintf(logfile, "inw : %04x %04x\n", addr, val);
403 env->last_io_time = cpu_get_time_fast();
408 int cpu_inl(CPUState *env, int addr)
411 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
413 if (loglevel & CPU_LOG_IOPORT)
414 fprintf(logfile, "inl : %04x %08x\n", addr, val);
418 env->last_io_time = cpu_get_time_fast();
423 /***********************************************************/
424 void hw_error(const char *fmt, ...)
430 fprintf(stderr, "qemu: hardware error: ");
431 vfprintf(stderr, fmt, ap);
432 fprintf(stderr, "\n");
433 for(env = first_cpu; env != NULL; env = env->next_cpu) {
434 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
436 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
438 cpu_dump_state(env, stderr, fprintf, 0);
445 /***********************************************************/
448 static QEMUPutKBDEvent *qemu_put_kbd_event;
449 static void *qemu_put_kbd_event_opaque;
450 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
451 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
453 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
455 qemu_put_kbd_event_opaque = opaque;
456 qemu_put_kbd_event = func;
459 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
460 void *opaque, int absolute,
463 QEMUPutMouseEntry *s, *cursor;
465 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
469 s->qemu_put_mouse_event = func;
470 s->qemu_put_mouse_event_opaque = opaque;
471 s->qemu_put_mouse_event_absolute = absolute;
472 s->qemu_put_mouse_event_name = qemu_strdup(name);
475 if (!qemu_put_mouse_event_head) {
476 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
480 cursor = qemu_put_mouse_event_head;
481 while (cursor->next != NULL)
482 cursor = cursor->next;
485 qemu_put_mouse_event_current = s;
490 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
492 QEMUPutMouseEntry *prev = NULL, *cursor;
494 if (!qemu_put_mouse_event_head || entry == NULL)
497 cursor = qemu_put_mouse_event_head;
498 while (cursor != NULL && cursor != entry) {
500 cursor = cursor->next;
503 if (cursor == NULL) // does not exist or list empty
505 else if (prev == NULL) { // entry is head
506 qemu_put_mouse_event_head = cursor->next;
507 if (qemu_put_mouse_event_current == entry)
508 qemu_put_mouse_event_current = cursor->next;
509 qemu_free(entry->qemu_put_mouse_event_name);
514 prev->next = entry->next;
516 if (qemu_put_mouse_event_current == entry)
517 qemu_put_mouse_event_current = prev;
519 qemu_free(entry->qemu_put_mouse_event_name);
523 void kbd_put_keycode(int keycode)
525 if (qemu_put_kbd_event) {
526 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
530 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
532 QEMUPutMouseEvent *mouse_event;
533 void *mouse_event_opaque;
536 if (!qemu_put_mouse_event_current) {
541 qemu_put_mouse_event_current->qemu_put_mouse_event;
543 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
546 if (graphic_rotate) {
547 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
550 width = graphic_width;
551 mouse_event(mouse_event_opaque,
552 width - dy, dx, dz, buttons_state);
554 mouse_event(mouse_event_opaque,
555 dx, dy, dz, buttons_state);
559 int kbd_mouse_is_absolute(void)
561 if (!qemu_put_mouse_event_current)
564 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
567 void (*kbd_mouse_set)(int x, int y, int on) = NULL;
568 void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
569 uint8_t *image, uint8_t *mask) = NULL;
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 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]);
1373 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1376 /* Switch to the next registered device */
1378 if (chr->focus >= d->mux_cnt)
1382 term_timestamps = !term_timestamps;
1383 term_timestamps_start = -1;
1386 } else if (ch == term_escape_char) {
1387 d->term_got_escape = 1;
1395 static int mux_chr_can_read(void *opaque)
1397 CharDriverState *chr = opaque;
1398 MuxDriver *d = chr->opaque;
1399 if (d->chr_can_read[chr->focus])
1400 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1404 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1406 CharDriverState *chr = opaque;
1407 MuxDriver *d = chr->opaque;
1409 for(i = 0; i < size; i++)
1410 if (mux_proc_byte(chr, d, buf[i]))
1411 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1414 static void mux_chr_event(void *opaque, int event)
1416 CharDriverState *chr = opaque;
1417 MuxDriver *d = chr->opaque;
1420 /* Send the event to all registered listeners */
1421 for (i = 0; i < d->mux_cnt; i++)
1422 if (d->chr_event[i])
1423 d->chr_event[i](d->ext_opaque[i], event);
1426 static void mux_chr_update_read_handler(CharDriverState *chr)
1428 MuxDriver *d = chr->opaque;
1430 if (d->mux_cnt >= MAX_MUX) {
1431 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1434 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1435 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1436 d->chr_read[d->mux_cnt] = chr->chr_read;
1437 d->chr_event[d->mux_cnt] = chr->chr_event;
1438 /* Fix up the real driver with mux routines */
1439 if (d->mux_cnt == 0) {
1440 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1441 mux_chr_event, chr);
1443 chr->focus = d->mux_cnt;
1447 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1449 CharDriverState *chr;
1452 chr = qemu_mallocz(sizeof(CharDriverState));
1455 d = qemu_mallocz(sizeof(MuxDriver));
1464 chr->chr_write = mux_chr_write;
1465 chr->chr_update_read_handler = mux_chr_update_read_handler;
1472 static void socket_cleanup(void)
1477 static int socket_init(void)
1482 ret = WSAStartup(MAKEWORD(2,2), &Data);
1484 err = WSAGetLastError();
1485 fprintf(stderr, "WSAStartup: %d\n", err);
1488 atexit(socket_cleanup);
1492 static int send_all(int fd, const uint8_t *buf, int len1)
1498 ret = send(fd, buf, len, 0);
1501 errno = WSAGetLastError();
1502 if (errno != WSAEWOULDBLOCK) {
1505 } else if (ret == 0) {
1515 void socket_set_nonblock(int fd)
1517 unsigned long opt = 1;
1518 ioctlsocket(fd, FIONBIO, &opt);
1523 static int unix_write(int fd, const uint8_t *buf, int len1)
1529 ret = write(fd, buf, len);
1531 if (errno != EINTR && errno != EAGAIN)
1533 } else if (ret == 0) {
1543 static inline int send_all(int fd, const uint8_t *buf, int len1)
1545 return unix_write(fd, buf, len1);
1548 void socket_set_nonblock(int fd)
1550 fcntl(fd, F_SETFL, O_NONBLOCK);
1552 #endif /* !_WIN32 */
1561 #define STDIO_MAX_CLIENTS 1
1562 static int stdio_nb_clients = 0;
1564 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1566 FDCharDriver *s = chr->opaque;
1567 return unix_write(s->fd_out, buf, len);
1570 static int fd_chr_read_poll(void *opaque)
1572 CharDriverState *chr = opaque;
1573 FDCharDriver *s = chr->opaque;
1575 s->max_size = qemu_chr_can_read(chr);
1579 static void fd_chr_read(void *opaque)
1581 CharDriverState *chr = opaque;
1582 FDCharDriver *s = chr->opaque;
1587 if (len > s->max_size)
1591 size = read(s->fd_in, buf, len);
1593 /* FD has been closed. Remove it from the active list. */
1594 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1598 qemu_chr_read(chr, buf, size);
1602 static void fd_chr_update_read_handler(CharDriverState *chr)
1604 FDCharDriver *s = chr->opaque;
1606 if (s->fd_in >= 0) {
1607 if (nographic && s->fd_in == 0) {
1609 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1610 fd_chr_read, NULL, chr);
1615 /* open a character device to a unix fd */
1616 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1618 CharDriverState *chr;
1621 chr = qemu_mallocz(sizeof(CharDriverState));
1624 s = qemu_mallocz(sizeof(FDCharDriver));
1632 chr->chr_write = fd_chr_write;
1633 chr->chr_update_read_handler = fd_chr_update_read_handler;
1635 qemu_chr_reset(chr);
1640 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1644 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1647 return qemu_chr_open_fd(-1, fd_out);
1650 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1653 char filename_in[256], filename_out[256];
1655 snprintf(filename_in, 256, "%s.in", filename);
1656 snprintf(filename_out, 256, "%s.out", filename);
1657 fd_in = open(filename_in, O_RDWR | O_BINARY);
1658 fd_out = open(filename_out, O_RDWR | O_BINARY);
1659 if (fd_in < 0 || fd_out < 0) {
1664 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1668 return qemu_chr_open_fd(fd_in, fd_out);
1672 /* for STDIO, we handle the case where several clients use it
1675 #define TERM_FIFO_MAX_SIZE 1
1677 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1678 static int term_fifo_size;
1680 static int stdio_read_poll(void *opaque)
1682 CharDriverState *chr = opaque;
1684 /* try to flush the queue if needed */
1685 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1686 qemu_chr_read(chr, term_fifo, 1);
1689 /* see if we can absorb more chars */
1690 if (term_fifo_size == 0)
1696 static void stdio_read(void *opaque)
1700 CharDriverState *chr = opaque;
1702 size = read(0, buf, 1);
1704 /* stdin has been closed. Remove it from the active list. */
1705 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1709 if (qemu_chr_can_read(chr) > 0) {
1710 qemu_chr_read(chr, buf, 1);
1711 } else if (term_fifo_size == 0) {
1712 term_fifo[term_fifo_size++] = buf[0];
1717 /* init terminal so that we can grab keys */
1718 static struct termios oldtty;
1719 static int old_fd0_flags;
1721 static void term_exit(void)
1723 tcsetattr (0, TCSANOW, &oldtty);
1724 fcntl(0, F_SETFL, old_fd0_flags);
1727 static void term_init(void)
1731 tcgetattr (0, &tty);
1733 old_fd0_flags = fcntl(0, F_GETFL);
1735 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1736 |INLCR|IGNCR|ICRNL|IXON);
1737 tty.c_oflag |= OPOST;
1738 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1739 /* if graphical mode, we allow Ctrl-C handling */
1741 tty.c_lflag &= ~ISIG;
1742 tty.c_cflag &= ~(CSIZE|PARENB);
1745 tty.c_cc[VTIME] = 0;
1747 tcsetattr (0, TCSANOW, &tty);
1751 fcntl(0, F_SETFL, O_NONBLOCK);
1754 static CharDriverState *qemu_chr_open_stdio(void)
1756 CharDriverState *chr;
1758 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1760 chr = qemu_chr_open_fd(0, 1);
1761 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1768 #if defined(__linux__)
1769 static CharDriverState *qemu_chr_open_pty(void)
1772 char slave_name[1024];
1773 int master_fd, slave_fd;
1775 /* Not satisfying */
1776 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1780 /* Disabling local echo and line-buffered output */
1781 tcgetattr (master_fd, &tty);
1782 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1784 tty.c_cc[VTIME] = 0;
1785 tcsetattr (master_fd, TCSAFLUSH, &tty);
1787 fprintf(stderr, "char device redirected to %s\n", slave_name);
1788 return qemu_chr_open_fd(master_fd, master_fd);
1791 static void tty_serial_init(int fd, int speed,
1792 int parity, int data_bits, int stop_bits)
1798 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1799 speed, parity, data_bits, stop_bits);
1801 tcgetattr (fd, &tty);
1843 cfsetispeed(&tty, spd);
1844 cfsetospeed(&tty, spd);
1846 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1847 |INLCR|IGNCR|ICRNL|IXON);
1848 tty.c_oflag |= OPOST;
1849 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1850 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1871 tty.c_cflag |= PARENB;
1874 tty.c_cflag |= PARENB | PARODD;
1878 tty.c_cflag |= CSTOPB;
1880 tcsetattr (fd, TCSANOW, &tty);
1883 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1885 FDCharDriver *s = chr->opaque;
1888 case CHR_IOCTL_SERIAL_SET_PARAMS:
1890 QEMUSerialSetParams *ssp = arg;
1891 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1892 ssp->data_bits, ssp->stop_bits);
1895 case CHR_IOCTL_SERIAL_SET_BREAK:
1897 int enable = *(int *)arg;
1899 tcsendbreak(s->fd_in, 1);
1908 static CharDriverState *qemu_chr_open_tty(const char *filename)
1910 CharDriverState *chr;
1913 fd = open(filename, O_RDWR | O_NONBLOCK);
1916 fcntl(fd, F_SETFL, O_NONBLOCK);
1917 tty_serial_init(fd, 115200, 'N', 8, 1);
1918 chr = qemu_chr_open_fd(fd, fd);
1921 chr->chr_ioctl = tty_serial_ioctl;
1922 qemu_chr_reset(chr);
1929 } ParallelCharDriver;
1931 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1933 if (s->mode != mode) {
1935 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1942 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1944 ParallelCharDriver *drv = chr->opaque;
1949 case CHR_IOCTL_PP_READ_DATA:
1950 if (ioctl(fd, PPRDATA, &b) < 0)
1952 *(uint8_t *)arg = b;
1954 case CHR_IOCTL_PP_WRITE_DATA:
1955 b = *(uint8_t *)arg;
1956 if (ioctl(fd, PPWDATA, &b) < 0)
1959 case CHR_IOCTL_PP_READ_CONTROL:
1960 if (ioctl(fd, PPRCONTROL, &b) < 0)
1962 /* Linux gives only the lowest bits, and no way to know data
1963 direction! For better compatibility set the fixed upper
1965 *(uint8_t *)arg = b | 0xc0;
1967 case CHR_IOCTL_PP_WRITE_CONTROL:
1968 b = *(uint8_t *)arg;
1969 if (ioctl(fd, PPWCONTROL, &b) < 0)
1972 case CHR_IOCTL_PP_READ_STATUS:
1973 if (ioctl(fd, PPRSTATUS, &b) < 0)
1975 *(uint8_t *)arg = b;
1977 case CHR_IOCTL_PP_EPP_READ_ADDR:
1978 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1979 struct ParallelIOArg *parg = arg;
1980 int n = read(fd, parg->buffer, parg->count);
1981 if (n != parg->count) {
1986 case CHR_IOCTL_PP_EPP_READ:
1987 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1988 struct ParallelIOArg *parg = arg;
1989 int n = read(fd, parg->buffer, parg->count);
1990 if (n != parg->count) {
1995 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1996 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1997 struct ParallelIOArg *parg = arg;
1998 int n = write(fd, parg->buffer, parg->count);
1999 if (n != parg->count) {
2004 case CHR_IOCTL_PP_EPP_WRITE:
2005 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2006 struct ParallelIOArg *parg = arg;
2007 int n = write(fd, parg->buffer, parg->count);
2008 if (n != parg->count) {
2019 static void pp_close(CharDriverState *chr)
2021 ParallelCharDriver *drv = chr->opaque;
2024 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2025 ioctl(fd, PPRELEASE);
2030 static CharDriverState *qemu_chr_open_pp(const char *filename)
2032 CharDriverState *chr;
2033 ParallelCharDriver *drv;
2036 fd = open(filename, O_RDWR);
2040 if (ioctl(fd, PPCLAIM) < 0) {
2045 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2051 drv->mode = IEEE1284_MODE_COMPAT;
2053 chr = qemu_mallocz(sizeof(CharDriverState));
2059 chr->chr_write = null_chr_write;
2060 chr->chr_ioctl = pp_ioctl;
2061 chr->chr_close = pp_close;
2064 qemu_chr_reset(chr);
2070 static CharDriverState *qemu_chr_open_pty(void)
2076 #endif /* !defined(_WIN32) */
2081 HANDLE hcom, hrecv, hsend;
2082 OVERLAPPED orecv, osend;
2087 #define NSENDBUF 2048
2088 #define NRECVBUF 2048
2089 #define MAXCONNECT 1
2090 #define NTIMEOUT 5000
2092 static int win_chr_poll(void *opaque);
2093 static int win_chr_pipe_poll(void *opaque);
2095 static void win_chr_close(CharDriverState *chr)
2097 WinCharState *s = chr->opaque;
2100 CloseHandle(s->hsend);
2104 CloseHandle(s->hrecv);
2108 CloseHandle(s->hcom);
2112 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2114 qemu_del_polling_cb(win_chr_poll, chr);
2117 static int win_chr_init(CharDriverState *chr, const char *filename)
2119 WinCharState *s = chr->opaque;
2121 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2126 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2128 fprintf(stderr, "Failed CreateEvent\n");
2131 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2133 fprintf(stderr, "Failed CreateEvent\n");
2137 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2138 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2139 if (s->hcom == INVALID_HANDLE_VALUE) {
2140 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2145 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2146 fprintf(stderr, "Failed SetupComm\n");
2150 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2151 size = sizeof(COMMCONFIG);
2152 GetDefaultCommConfig(filename, &comcfg, &size);
2153 comcfg.dcb.DCBlength = sizeof(DCB);
2154 CommConfigDialog(filename, NULL, &comcfg);
2156 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2157 fprintf(stderr, "Failed SetCommState\n");
2161 if (!SetCommMask(s->hcom, EV_ERR)) {
2162 fprintf(stderr, "Failed SetCommMask\n");
2166 cto.ReadIntervalTimeout = MAXDWORD;
2167 if (!SetCommTimeouts(s->hcom, &cto)) {
2168 fprintf(stderr, "Failed SetCommTimeouts\n");
2172 if (!ClearCommError(s->hcom, &err, &comstat)) {
2173 fprintf(stderr, "Failed ClearCommError\n");
2176 qemu_add_polling_cb(win_chr_poll, chr);
2184 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2186 WinCharState *s = chr->opaque;
2187 DWORD len, ret, size, err;
2190 ZeroMemory(&s->osend, sizeof(s->osend));
2191 s->osend.hEvent = s->hsend;
2194 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2196 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2198 err = GetLastError();
2199 if (err == ERROR_IO_PENDING) {
2200 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2218 static int win_chr_read_poll(CharDriverState *chr)
2220 WinCharState *s = chr->opaque;
2222 s->max_size = qemu_chr_can_read(chr);
2226 static void win_chr_readfile(CharDriverState *chr)
2228 WinCharState *s = chr->opaque;
2233 ZeroMemory(&s->orecv, sizeof(s->orecv));
2234 s->orecv.hEvent = s->hrecv;
2235 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2237 err = GetLastError();
2238 if (err == ERROR_IO_PENDING) {
2239 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2244 qemu_chr_read(chr, buf, size);
2248 static void win_chr_read(CharDriverState *chr)
2250 WinCharState *s = chr->opaque;
2252 if (s->len > s->max_size)
2253 s->len = s->max_size;
2257 win_chr_readfile(chr);
2260 static int win_chr_poll(void *opaque)
2262 CharDriverState *chr = opaque;
2263 WinCharState *s = chr->opaque;
2267 ClearCommError(s->hcom, &comerr, &status);
2268 if (status.cbInQue > 0) {
2269 s->len = status.cbInQue;
2270 win_chr_read_poll(chr);
2277 static CharDriverState *qemu_chr_open_win(const char *filename)
2279 CharDriverState *chr;
2282 chr = qemu_mallocz(sizeof(CharDriverState));
2285 s = qemu_mallocz(sizeof(WinCharState));
2291 chr->chr_write = win_chr_write;
2292 chr->chr_close = win_chr_close;
2294 if (win_chr_init(chr, filename) < 0) {
2299 qemu_chr_reset(chr);
2303 static int win_chr_pipe_poll(void *opaque)
2305 CharDriverState *chr = opaque;
2306 WinCharState *s = chr->opaque;
2309 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2312 win_chr_read_poll(chr);
2319 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2321 WinCharState *s = chr->opaque;
2329 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2331 fprintf(stderr, "Failed CreateEvent\n");
2334 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2336 fprintf(stderr, "Failed CreateEvent\n");
2340 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2341 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2342 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2344 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2345 if (s->hcom == INVALID_HANDLE_VALUE) {
2346 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2351 ZeroMemory(&ov, sizeof(ov));
2352 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2353 ret = ConnectNamedPipe(s->hcom, &ov);
2355 fprintf(stderr, "Failed ConnectNamedPipe\n");
2359 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2361 fprintf(stderr, "Failed GetOverlappedResult\n");
2363 CloseHandle(ov.hEvent);
2370 CloseHandle(ov.hEvent);
2373 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2382 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2384 CharDriverState *chr;
2387 chr = qemu_mallocz(sizeof(CharDriverState));
2390 s = qemu_mallocz(sizeof(WinCharState));
2396 chr->chr_write = win_chr_write;
2397 chr->chr_close = win_chr_close;
2399 if (win_chr_pipe_init(chr, filename) < 0) {
2404 qemu_chr_reset(chr);
2408 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2410 CharDriverState *chr;
2413 chr = qemu_mallocz(sizeof(CharDriverState));
2416 s = qemu_mallocz(sizeof(WinCharState));
2423 chr->chr_write = win_chr_write;
2424 qemu_chr_reset(chr);
2428 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2432 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2433 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2434 if (fd_out == INVALID_HANDLE_VALUE)
2437 return qemu_chr_open_win_file(fd_out);
2441 /***********************************************************/
2442 /* UDP Net console */
2446 struct sockaddr_in daddr;
2453 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2455 NetCharDriver *s = chr->opaque;
2457 return sendto(s->fd, buf, len, 0,
2458 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2461 static int udp_chr_read_poll(void *opaque)
2463 CharDriverState *chr = opaque;
2464 NetCharDriver *s = chr->opaque;
2466 s->max_size = qemu_chr_can_read(chr);
2468 /* If there were any stray characters in the queue process them
2471 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2472 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2474 s->max_size = qemu_chr_can_read(chr);
2479 static void udp_chr_read(void *opaque)
2481 CharDriverState *chr = opaque;
2482 NetCharDriver *s = chr->opaque;
2484 if (s->max_size == 0)
2486 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2487 s->bufptr = s->bufcnt;
2492 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2493 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2495 s->max_size = qemu_chr_can_read(chr);
2499 static void udp_chr_update_read_handler(CharDriverState *chr)
2501 NetCharDriver *s = chr->opaque;
2504 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2505 udp_chr_read, NULL, chr);
2509 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2511 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2513 int parse_host_src_port(struct sockaddr_in *haddr,
2514 struct sockaddr_in *saddr,
2517 static CharDriverState *qemu_chr_open_udp(const char *def)
2519 CharDriverState *chr = NULL;
2520 NetCharDriver *s = NULL;
2522 struct sockaddr_in saddr;
2524 chr = qemu_mallocz(sizeof(CharDriverState));
2527 s = qemu_mallocz(sizeof(NetCharDriver));
2531 fd = socket(PF_INET, SOCK_DGRAM, 0);
2533 perror("socket(PF_INET, SOCK_DGRAM)");
2537 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2538 printf("Could not parse: %s\n", def);
2542 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2552 chr->chr_write = udp_chr_write;
2553 chr->chr_update_read_handler = udp_chr_update_read_handler;
2566 /***********************************************************/
2567 /* TCP Net console */
2578 static void tcp_chr_accept(void *opaque);
2580 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2582 TCPCharDriver *s = chr->opaque;
2584 return send_all(s->fd, buf, len);
2586 /* XXX: indicate an error ? */
2591 static int tcp_chr_read_poll(void *opaque)
2593 CharDriverState *chr = opaque;
2594 TCPCharDriver *s = chr->opaque;
2597 s->max_size = qemu_chr_can_read(chr);
2602 #define IAC_BREAK 243
2603 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2605 char *buf, int *size)
2607 /* Handle any telnet client's basic IAC options to satisfy char by
2608 * char mode with no echo. All IAC options will be removed from
2609 * the buf and the do_telnetopt variable will be used to track the
2610 * state of the width of the IAC information.
2612 * IAC commands come in sets of 3 bytes with the exception of the
2613 * "IAC BREAK" command and the double IAC.
2619 for (i = 0; i < *size; i++) {
2620 if (s->do_telnetopt > 1) {
2621 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2622 /* Double IAC means send an IAC */
2626 s->do_telnetopt = 1;
2628 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2629 /* Handle IAC break commands by sending a serial break */
2630 qemu_chr_event(chr, CHR_EVENT_BREAK);
2635 if (s->do_telnetopt >= 4) {
2636 s->do_telnetopt = 1;
2639 if ((unsigned char)buf[i] == IAC) {
2640 s->do_telnetopt = 2;
2651 static void tcp_chr_read(void *opaque)
2653 CharDriverState *chr = opaque;
2654 TCPCharDriver *s = chr->opaque;
2658 if (!s->connected || s->max_size <= 0)
2661 if (len > s->max_size)
2663 size = recv(s->fd, buf, len, 0);
2665 /* connection closed */
2667 if (s->listen_fd >= 0) {
2668 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2670 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2673 } else if (size > 0) {
2674 if (s->do_telnetopt)
2675 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2677 qemu_chr_read(chr, buf, size);
2681 static void tcp_chr_connect(void *opaque)
2683 CharDriverState *chr = opaque;
2684 TCPCharDriver *s = chr->opaque;
2687 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2688 tcp_chr_read, NULL, chr);
2689 qemu_chr_reset(chr);
2692 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2693 static void tcp_chr_telnet_init(int fd)
2696 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2697 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2698 send(fd, (char *)buf, 3, 0);
2699 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2700 send(fd, (char *)buf, 3, 0);
2701 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2702 send(fd, (char *)buf, 3, 0);
2703 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2704 send(fd, (char *)buf, 3, 0);
2707 static void socket_set_nodelay(int fd)
2710 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2713 static void tcp_chr_accept(void *opaque)
2715 CharDriverState *chr = opaque;
2716 TCPCharDriver *s = chr->opaque;
2717 struct sockaddr_in saddr;
2719 struct sockaddr_un uaddr;
2721 struct sockaddr *addr;
2728 len = sizeof(uaddr);
2729 addr = (struct sockaddr *)&uaddr;
2733 len = sizeof(saddr);
2734 addr = (struct sockaddr *)&saddr;
2736 fd = accept(s->listen_fd, addr, &len);
2737 if (fd < 0 && errno != EINTR) {
2739 } else if (fd >= 0) {
2740 if (s->do_telnetopt)
2741 tcp_chr_telnet_init(fd);
2745 socket_set_nonblock(fd);
2747 socket_set_nodelay(fd);
2749 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2750 tcp_chr_connect(chr);
2753 static void tcp_chr_close(CharDriverState *chr)
2755 TCPCharDriver *s = chr->opaque;
2758 if (s->listen_fd >= 0)
2759 closesocket(s->listen_fd);
2763 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2767 CharDriverState *chr = NULL;
2768 TCPCharDriver *s = NULL;
2769 int fd = -1, ret, err, val;
2771 int is_waitconnect = 1;
2774 struct sockaddr_in saddr;
2776 struct sockaddr_un uaddr;
2778 struct sockaddr *addr;
2783 addr = (struct sockaddr *)&uaddr;
2784 addrlen = sizeof(uaddr);
2785 if (parse_unix_path(&uaddr, host_str) < 0)
2790 addr = (struct sockaddr *)&saddr;
2791 addrlen = sizeof(saddr);
2792 if (parse_host_port(&saddr, host_str) < 0)
2797 while((ptr = strchr(ptr,','))) {
2799 if (!strncmp(ptr,"server",6)) {
2801 } else if (!strncmp(ptr,"nowait",6)) {
2803 } else if (!strncmp(ptr,"nodelay",6)) {
2806 printf("Unknown option: %s\n", ptr);
2813 chr = qemu_mallocz(sizeof(CharDriverState));
2816 s = qemu_mallocz(sizeof(TCPCharDriver));
2822 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2825 fd = socket(PF_INET, SOCK_STREAM, 0);
2830 if (!is_waitconnect)
2831 socket_set_nonblock(fd);
2836 s->is_unix = is_unix;
2837 s->do_nodelay = do_nodelay && !is_unix;
2840 chr->chr_write = tcp_chr_write;
2841 chr->chr_close = tcp_chr_close;
2844 /* allow fast reuse */
2848 strncpy(path, uaddr.sun_path, 108);
2855 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2858 ret = bind(fd, addr, addrlen);
2862 ret = listen(fd, 0);
2867 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2869 s->do_telnetopt = 1;
2872 ret = connect(fd, addr, addrlen);
2874 err = socket_error();
2875 if (err == EINTR || err == EWOULDBLOCK) {
2876 } else if (err == EINPROGRESS) {
2879 } else if (err == WSAEALREADY) {
2891 socket_set_nodelay(fd);
2893 tcp_chr_connect(chr);
2895 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2898 if (is_listen && is_waitconnect) {
2899 printf("QEMU waiting for connection on: %s\n", host_str);
2900 tcp_chr_accept(chr);
2901 socket_set_nonblock(s->listen_fd);
2913 CharDriverState *qemu_chr_open(const char *filename)
2917 if (!strcmp(filename, "vc")) {
2918 return text_console_init(&display_state);
2919 } else if (!strcmp(filename, "null")) {
2920 return qemu_chr_open_null();
2922 if (strstart(filename, "tcp:", &p)) {
2923 return qemu_chr_open_tcp(p, 0, 0);
2925 if (strstart(filename, "telnet:", &p)) {
2926 return qemu_chr_open_tcp(p, 1, 0);
2928 if (strstart(filename, "udp:", &p)) {
2929 return qemu_chr_open_udp(p);
2931 if (strstart(filename, "mon:", &p)) {
2932 CharDriverState *drv = qemu_chr_open(p);
2934 drv = qemu_chr_open_mux(drv);
2935 monitor_init(drv, !nographic);
2938 printf("Unable to open driver: %s\n", p);
2942 if (strstart(filename, "unix:", &p)) {
2943 return qemu_chr_open_tcp(p, 0, 1);
2944 } else if (strstart(filename, "file:", &p)) {
2945 return qemu_chr_open_file_out(p);
2946 } else if (strstart(filename, "pipe:", &p)) {
2947 return qemu_chr_open_pipe(p);
2948 } else if (!strcmp(filename, "pty")) {
2949 return qemu_chr_open_pty();
2950 } else if (!strcmp(filename, "stdio")) {
2951 return qemu_chr_open_stdio();
2954 #if defined(__linux__)
2955 if (strstart(filename, "/dev/parport", NULL)) {
2956 return qemu_chr_open_pp(filename);
2958 if (strstart(filename, "/dev/", NULL)) {
2959 return qemu_chr_open_tty(filename);
2963 if (strstart(filename, "COM", NULL)) {
2964 return qemu_chr_open_win(filename);
2966 if (strstart(filename, "pipe:", &p)) {
2967 return qemu_chr_open_win_pipe(p);
2969 if (strstart(filename, "file:", &p)) {
2970 return qemu_chr_open_win_file_out(p);
2978 void qemu_chr_close(CharDriverState *chr)
2981 chr->chr_close(chr);
2984 /***********************************************************/
2985 /* network device redirectors */
2987 void hex_dump(FILE *f, const uint8_t *buf, int size)
2991 for(i=0;i<size;i+=16) {
2995 fprintf(f, "%08x ", i);
2998 fprintf(f, " %02x", buf[i+j]);
3003 for(j=0;j<len;j++) {
3005 if (c < ' ' || c > '~')
3007 fprintf(f, "%c", c);
3013 static int parse_macaddr(uint8_t *macaddr, const char *p)
3016 for(i = 0; i < 6; i++) {
3017 macaddr[i] = strtol(p, (char **)&p, 16);
3030 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3035 p1 = strchr(p, sep);
3041 if (len > buf_size - 1)
3043 memcpy(buf, p, len);
3050 int parse_host_src_port(struct sockaddr_in *haddr,
3051 struct sockaddr_in *saddr,
3052 const char *input_str)
3054 char *str = strdup(input_str);
3055 char *host_str = str;
3060 * Chop off any extra arguments at the end of the string which
3061 * would start with a comma, then fill in the src port information
3062 * if it was provided else use the "any address" and "any port".
3064 if ((ptr = strchr(str,',')))
3067 if ((src_str = strchr(input_str,'@'))) {
3072 if (parse_host_port(haddr, host_str) < 0)
3075 if (!src_str || *src_str == '\0')
3078 if (parse_host_port(saddr, src_str) < 0)
3089 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3097 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3099 saddr->sin_family = AF_INET;
3100 if (buf[0] == '\0') {
3101 saddr->sin_addr.s_addr = 0;
3103 if (isdigit(buf[0])) {
3104 if (!inet_aton(buf, &saddr->sin_addr))
3107 if ((he = gethostbyname(buf)) == NULL)
3109 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3112 port = strtol(p, (char **)&r, 0);
3115 saddr->sin_port = htons(port);
3120 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3125 len = MIN(108, strlen(str));
3126 p = strchr(str, ',');
3128 len = MIN(len, p - str);
3130 memset(uaddr, 0, sizeof(*uaddr));
3132 uaddr->sun_family = AF_UNIX;
3133 memcpy(uaddr->sun_path, str, len);
3139 /* find or alloc a new VLAN */
3140 VLANState *qemu_find_vlan(int id)
3142 VLANState **pvlan, *vlan;
3143 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3147 vlan = qemu_mallocz(sizeof(VLANState));
3152 pvlan = &first_vlan;
3153 while (*pvlan != NULL)
3154 pvlan = &(*pvlan)->next;
3159 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3160 IOReadHandler *fd_read,
3161 IOCanRWHandler *fd_can_read,
3164 VLANClientState *vc, **pvc;
3165 vc = qemu_mallocz(sizeof(VLANClientState));
3168 vc->fd_read = fd_read;
3169 vc->fd_can_read = fd_can_read;
3170 vc->opaque = opaque;
3174 pvc = &vlan->first_client;
3175 while (*pvc != NULL)
3176 pvc = &(*pvc)->next;
3181 int qemu_can_send_packet(VLANClientState *vc1)
3183 VLANState *vlan = vc1->vlan;
3184 VLANClientState *vc;
3186 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3188 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3195 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3197 VLANState *vlan = vc1->vlan;
3198 VLANClientState *vc;
3201 printf("vlan %d send:\n", vlan->id);
3202 hex_dump(stdout, buf, size);
3204 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3206 vc->fd_read(vc->opaque, buf, size);
3211 #if defined(CONFIG_SLIRP)
3213 /* slirp network adapter */
3215 static int slirp_inited;
3216 static VLANClientState *slirp_vc;
3218 int slirp_can_output(void)
3220 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3223 void slirp_output(const uint8_t *pkt, int pkt_len)
3226 printf("slirp output:\n");
3227 hex_dump(stdout, pkt, pkt_len);
3231 qemu_send_packet(slirp_vc, pkt, pkt_len);
3234 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3237 printf("slirp input:\n");
3238 hex_dump(stdout, buf, size);
3240 slirp_input(buf, size);
3243 static int net_slirp_init(VLANState *vlan)
3245 if (!slirp_inited) {
3249 slirp_vc = qemu_new_vlan_client(vlan,
3250 slirp_receive, NULL, NULL);
3251 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3255 static void net_slirp_redir(const char *redir_str)
3260 struct in_addr guest_addr;
3261 int host_port, guest_port;
3263 if (!slirp_inited) {
3269 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3271 if (!strcmp(buf, "tcp")) {
3273 } else if (!strcmp(buf, "udp")) {
3279 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3281 host_port = strtol(buf, &r, 0);
3285 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3287 if (buf[0] == '\0') {
3288 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3290 if (!inet_aton(buf, &guest_addr))
3293 guest_port = strtol(p, &r, 0);
3297 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3298 fprintf(stderr, "qemu: could not set up redirection\n");
3303 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3311 static void smb_exit(void)
3315 char filename[1024];
3317 /* erase all the files in the directory */
3318 d = opendir(smb_dir);
3323 if (strcmp(de->d_name, ".") != 0 &&
3324 strcmp(de->d_name, "..") != 0) {
3325 snprintf(filename, sizeof(filename), "%s/%s",
3326 smb_dir, de->d_name);
3334 /* automatic user mode samba server configuration */
3335 void net_slirp_smb(const char *exported_dir)
3337 char smb_conf[1024];
3338 char smb_cmdline[1024];
3341 if (!slirp_inited) {
3346 /* XXX: better tmp dir construction */
3347 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3348 if (mkdir(smb_dir, 0700) < 0) {
3349 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3352 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3354 f = fopen(smb_conf, "w");
3356 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3363 "socket address=127.0.0.1\n"
3364 "pid directory=%s\n"
3365 "lock directory=%s\n"
3366 "log file=%s/log.smbd\n"
3367 "smb passwd file=%s/smbpasswd\n"
3368 "security = share\n"
3383 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3384 SMBD_COMMAND, smb_conf);
3386 slirp_add_exec(0, smb_cmdline, 4, 139);
3389 #endif /* !defined(_WIN32) */
3391 #endif /* CONFIG_SLIRP */
3393 #if !defined(_WIN32)
3395 typedef struct TAPState {
3396 VLANClientState *vc;
3400 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3402 TAPState *s = opaque;
3405 ret = write(s->fd, buf, size);
3406 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3413 static void tap_send(void *opaque)
3415 TAPState *s = opaque;
3422 sbuf.maxlen = sizeof(buf);
3424 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3426 size = read(s->fd, buf, sizeof(buf));
3429 qemu_send_packet(s->vc, buf, size);
3435 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3439 s = qemu_mallocz(sizeof(TAPState));
3443 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3444 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3445 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3450 static int tap_open(char *ifname, int ifname_size)
3456 fd = open("/dev/tap", O_RDWR);
3458 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3463 dev = devname(s.st_rdev, S_IFCHR);
3464 pstrcpy(ifname, ifname_size, dev);
3466 fcntl(fd, F_SETFL, O_NONBLOCK);
3469 #elif defined(__sun__)
3470 #define TUNNEWPPA (('T'<<16) | 0x0001)
3472 * Allocate TAP device, returns opened fd.
3473 * Stores dev name in the first arg(must be large enough).
3475 int tap_alloc(char *dev)
3477 int tap_fd, if_fd, ppa = -1;
3478 static int ip_fd = 0;
3481 static int arp_fd = 0;
3482 int ip_muxid, arp_muxid;
3483 struct strioctl strioc_if, strioc_ppa;
3484 int link_type = I_PLINK;;
3486 char actual_name[32] = "";
3488 memset(&ifr, 0x0, sizeof(ifr));
3492 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3496 /* Check if IP device was opened */
3500 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3501 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3505 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3506 syslog(LOG_ERR, "Can't open /dev/tap");
3510 /* Assign a new PPA and get its unit number. */
3511 strioc_ppa.ic_cmd = TUNNEWPPA;
3512 strioc_ppa.ic_timout = 0;
3513 strioc_ppa.ic_len = sizeof(ppa);
3514 strioc_ppa.ic_dp = (char *)&ppa;
3515 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3516 syslog (LOG_ERR, "Can't assign new interface");
3518 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3519 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3522 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3523 syslog(LOG_ERR, "Can't push IP module");
3527 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3528 syslog(LOG_ERR, "Can't get flags\n");
3530 snprintf (actual_name, 32, "tap%d", ppa);
3531 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3534 /* Assign ppa according to the unit number returned by tun device */
3536 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3537 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3538 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3539 syslog (LOG_ERR, "Can't get flags\n");
3540 /* Push arp module to if_fd */
3541 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3542 syslog (LOG_ERR, "Can't push ARP module (2)");
3544 /* Push arp module to ip_fd */
3545 if (ioctl (ip_fd, I_POP, NULL) < 0)
3546 syslog (LOG_ERR, "I_POP failed\n");
3547 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3548 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3550 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3551 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3553 /* Set ifname to arp */
3554 strioc_if.ic_cmd = SIOCSLIFNAME;
3555 strioc_if.ic_timout = 0;
3556 strioc_if.ic_len = sizeof(ifr);
3557 strioc_if.ic_dp = (char *)𝔦
3558 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3559 syslog (LOG_ERR, "Can't set ifname to arp\n");
3562 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3563 syslog(LOG_ERR, "Can't link TAP device to IP");
3567 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3568 syslog (LOG_ERR, "Can't link TAP device to ARP");
3572 memset(&ifr, 0x0, sizeof(ifr));
3573 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3574 ifr.lifr_ip_muxid = ip_muxid;
3575 ifr.lifr_arp_muxid = arp_muxid;
3577 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3579 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3580 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3581 syslog (LOG_ERR, "Can't set multiplexor id");
3584 sprintf(dev, "tap%d", ppa);
3588 static int tap_open(char *ifname, int ifname_size)
3592 if( (fd = tap_alloc(dev)) < 0 ){
3593 fprintf(stderr, "Cannot allocate TAP device\n");
3596 pstrcpy(ifname, ifname_size, dev);
3597 fcntl(fd, F_SETFL, O_NONBLOCK);
3601 static int tap_open(char *ifname, int ifname_size)
3606 fd = open("/dev/net/tun", O_RDWR);
3608 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3611 memset(&ifr, 0, sizeof(ifr));
3612 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3613 if (ifname[0] != '\0')
3614 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3616 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3617 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3619 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3623 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3624 fcntl(fd, F_SETFL, O_NONBLOCK);
3629 static int net_tap_init(VLANState *vlan, const char *ifname1,
3630 const char *setup_script)
3633 int pid, status, fd;
3638 if (ifname1 != NULL)
3639 pstrcpy(ifname, sizeof(ifname), ifname1);
3642 fd = tap_open(ifname, sizeof(ifname));
3646 if (!setup_script || !strcmp(setup_script, "no"))
3648 if (setup_script[0] != '\0') {
3649 /* try to launch network init script */
3653 int open_max = sysconf (_SC_OPEN_MAX), i;
3654 for (i = 0; i < open_max; i++)
3655 if (i != STDIN_FILENO &&
3656 i != STDOUT_FILENO &&
3657 i != STDERR_FILENO &&
3662 *parg++ = (char *)setup_script;
3665 execv(setup_script, args);
3668 while (waitpid(pid, &status, 0) != pid);
3669 if (!WIFEXITED(status) ||
3670 WEXITSTATUS(status) != 0) {
3671 fprintf(stderr, "%s: could not launch network script\n",
3677 s = net_tap_fd_init(vlan, fd);
3680 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3681 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3685 #endif /* !_WIN32 */
3687 /* network connection */
3688 typedef struct NetSocketState {
3689 VLANClientState *vc;
3691 int state; /* 0 = getting length, 1 = getting data */
3695 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3698 typedef struct NetSocketListenState {
3701 } NetSocketListenState;
3703 /* XXX: we consider we can send the whole packet without blocking */
3704 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3706 NetSocketState *s = opaque;
3710 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3711 send_all(s->fd, buf, size);
3714 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3716 NetSocketState *s = opaque;
3717 sendto(s->fd, buf, size, 0,
3718 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3721 static void net_socket_send(void *opaque)
3723 NetSocketState *s = opaque;
3728 size = recv(s->fd, buf1, sizeof(buf1), 0);
3730 err = socket_error();
3731 if (err != EWOULDBLOCK)
3733 } else if (size == 0) {
3734 /* end of connection */
3736 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3742 /* reassemble a packet from the network */
3748 memcpy(s->buf + s->index, buf, l);
3752 if (s->index == 4) {
3754 s->packet_len = ntohl(*(uint32_t *)s->buf);
3760 l = s->packet_len - s->index;
3763 memcpy(s->buf + s->index, buf, l);
3767 if (s->index >= s->packet_len) {
3768 qemu_send_packet(s->vc, s->buf, s->packet_len);
3777 static void net_socket_send_dgram(void *opaque)
3779 NetSocketState *s = opaque;
3782 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3786 /* end of connection */
3787 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3790 qemu_send_packet(s->vc, s->buf, size);
3793 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3798 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3799 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3800 inet_ntoa(mcastaddr->sin_addr),
3801 (int)ntohl(mcastaddr->sin_addr.s_addr));
3805 fd = socket(PF_INET, SOCK_DGRAM, 0);
3807 perror("socket(PF_INET, SOCK_DGRAM)");
3812 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3813 (const char *)&val, sizeof(val));
3815 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3819 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3825 /* Add host to multicast group */
3826 imr.imr_multiaddr = mcastaddr->sin_addr;
3827 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3829 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3830 (const char *)&imr, sizeof(struct ip_mreq));
3832 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3836 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3838 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3839 (const char *)&val, sizeof(val));
3841 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3845 socket_set_nonblock(fd);
3853 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3856 struct sockaddr_in saddr;
3858 socklen_t saddr_len;
3861 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3862 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3863 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3867 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3869 if (saddr.sin_addr.s_addr==0) {
3870 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3874 /* clone dgram socket */
3875 newfd = net_socket_mcast_create(&saddr);
3877 /* error already reported by net_socket_mcast_create() */
3881 /* clone newfd to fd, close newfd */
3886 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3887 fd, strerror(errno));
3892 s = qemu_mallocz(sizeof(NetSocketState));
3897 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3898 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3900 /* mcast: save bound address as dst */
3901 if (is_connected) s->dgram_dst=saddr;
3903 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3904 "socket: fd=%d (%s mcast=%s:%d)",
3905 fd, is_connected? "cloned" : "",
3906 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3910 static void net_socket_connect(void *opaque)
3912 NetSocketState *s = opaque;
3913 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3916 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3920 s = qemu_mallocz(sizeof(NetSocketState));
3924 s->vc = qemu_new_vlan_client(vlan,
3925 net_socket_receive, NULL, s);
3926 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3927 "socket: fd=%d", fd);
3929 net_socket_connect(s);
3931 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3936 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3939 int so_type=-1, optlen=sizeof(so_type);
3941 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3942 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3947 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3949 return net_socket_fd_init_stream(vlan, fd, is_connected);
3951 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3952 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3953 return net_socket_fd_init_stream(vlan, fd, is_connected);
3958 static void net_socket_accept(void *opaque)
3960 NetSocketListenState *s = opaque;
3962 struct sockaddr_in saddr;
3967 len = sizeof(saddr);
3968 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3969 if (fd < 0 && errno != EINTR) {
3971 } else if (fd >= 0) {
3975 s1 = net_socket_fd_init(s->vlan, fd, 1);
3979 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3980 "socket: connection from %s:%d",
3981 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3985 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3987 NetSocketListenState *s;
3989 struct sockaddr_in saddr;
3991 if (parse_host_port(&saddr, host_str) < 0)
3994 s = qemu_mallocz(sizeof(NetSocketListenState));
3998 fd = socket(PF_INET, SOCK_STREAM, 0);
4003 socket_set_nonblock(fd);
4005 /* allow fast reuse */
4007 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4009 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4014 ret = listen(fd, 0);
4021 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4025 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4028 int fd, connected, ret, err;
4029 struct sockaddr_in saddr;
4031 if (parse_host_port(&saddr, host_str) < 0)
4034 fd = socket(PF_INET, SOCK_STREAM, 0);
4039 socket_set_nonblock(fd);
4043 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4045 err = socket_error();
4046 if (err == EINTR || err == EWOULDBLOCK) {
4047 } else if (err == EINPROGRESS) {
4050 } else if (err == WSAEALREADY) {
4063 s = net_socket_fd_init(vlan, fd, connected);
4066 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4067 "socket: connect to %s:%d",
4068 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4072 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4076 struct sockaddr_in saddr;
4078 if (parse_host_port(&saddr, host_str) < 0)
4082 fd = net_socket_mcast_create(&saddr);
4086 s = net_socket_fd_init(vlan, fd, 0);
4090 s->dgram_dst = saddr;
4092 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4093 "socket: mcast=%s:%d",
4094 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4099 static int get_param_value(char *buf, int buf_size,
4100 const char *tag, const char *str)
4109 while (*p != '\0' && *p != '=') {
4110 if ((q - option) < sizeof(option) - 1)
4118 if (!strcmp(tag, option)) {
4120 while (*p != '\0' && *p != ',') {
4121 if ((q - buf) < buf_size - 1)
4128 while (*p != '\0' && *p != ',') {
4139 static int net_client_init(const char *str)
4150 while (*p != '\0' && *p != ',') {
4151 if ((q - device) < sizeof(device) - 1)
4159 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4160 vlan_id = strtol(buf, NULL, 0);
4162 vlan = qemu_find_vlan(vlan_id);
4164 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4167 if (!strcmp(device, "nic")) {
4171 if (nb_nics >= MAX_NICS) {
4172 fprintf(stderr, "Too Many NICs\n");
4175 nd = &nd_table[nb_nics];
4176 macaddr = nd->macaddr;
4182 macaddr[5] = 0x56 + nb_nics;
4184 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4185 if (parse_macaddr(macaddr, buf) < 0) {
4186 fprintf(stderr, "invalid syntax for ethernet address\n");
4190 if (get_param_value(buf, sizeof(buf), "model", p)) {
4191 nd->model = strdup(buf);
4197 if (!strcmp(device, "none")) {
4198 /* does nothing. It is needed to signal that no network cards
4203 if (!strcmp(device, "user")) {
4204 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4205 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4207 ret = net_slirp_init(vlan);
4211 if (!strcmp(device, "tap")) {
4213 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4214 fprintf(stderr, "tap: no interface name\n");
4217 ret = tap_win32_init(vlan, ifname);
4220 if (!strcmp(device, "tap")) {
4222 char setup_script[1024];
4224 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4225 fd = strtol(buf, NULL, 0);
4227 if (net_tap_fd_init(vlan, fd))
4230 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4233 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4234 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4236 ret = net_tap_init(vlan, ifname, setup_script);
4240 if (!strcmp(device, "socket")) {
4241 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4243 fd = strtol(buf, NULL, 0);
4245 if (net_socket_fd_init(vlan, fd, 1))
4247 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4248 ret = net_socket_listen_init(vlan, buf);
4249 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4250 ret = net_socket_connect_init(vlan, buf);
4251 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4252 ret = net_socket_mcast_init(vlan, buf);
4254 fprintf(stderr, "Unknown socket options: %s\n", p);
4259 fprintf(stderr, "Unknown network device: %s\n", device);
4263 fprintf(stderr, "Could not initialize device '%s'\n", device);
4269 void do_info_network(void)
4272 VLANClientState *vc;
4274 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4275 term_printf("VLAN %d devices:\n", vlan->id);
4276 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4277 term_printf(" %s\n", vc->info_str);
4281 /***********************************************************/
4284 static USBPort *used_usb_ports;
4285 static USBPort *free_usb_ports;
4287 /* ??? Maybe change this to register a hub to keep track of the topology. */
4288 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4289 usb_attachfn attach)
4291 port->opaque = opaque;
4292 port->index = index;
4293 port->attach = attach;
4294 port->next = free_usb_ports;
4295 free_usb_ports = port;
4298 static int usb_device_add(const char *devname)
4304 if (!free_usb_ports)
4307 if (strstart(devname, "host:", &p)) {
4308 dev = usb_host_device_open(p);
4309 } else if (!strcmp(devname, "mouse")) {
4310 dev = usb_mouse_init();
4311 } else if (!strcmp(devname, "tablet")) {
4312 dev = usb_tablet_init();
4313 } else if (strstart(devname, "disk:", &p)) {
4314 dev = usb_msd_init(p);
4321 /* Find a USB port to add the device to. */
4322 port = free_usb_ports;
4326 /* Create a new hub and chain it on. */
4327 free_usb_ports = NULL;
4328 port->next = used_usb_ports;
4329 used_usb_ports = port;
4331 hub = usb_hub_init(VM_USB_HUB_SIZE);
4332 usb_attach(port, hub);
4333 port = free_usb_ports;
4336 free_usb_ports = port->next;
4337 port->next = used_usb_ports;
4338 used_usb_ports = port;
4339 usb_attach(port, dev);
4343 static int usb_device_del(const char *devname)
4351 if (!used_usb_ports)
4354 p = strchr(devname, '.');
4357 bus_num = strtoul(devname, NULL, 0);
4358 addr = strtoul(p + 1, NULL, 0);
4362 lastp = &used_usb_ports;
4363 port = used_usb_ports;
4364 while (port && port->dev->addr != addr) {
4365 lastp = &port->next;
4373 *lastp = port->next;
4374 usb_attach(port, NULL);
4375 dev->handle_destroy(dev);
4376 port->next = free_usb_ports;
4377 free_usb_ports = port;
4381 void do_usb_add(const char *devname)
4384 ret = usb_device_add(devname);
4386 term_printf("Could not add USB device '%s'\n", devname);
4389 void do_usb_del(const char *devname)
4392 ret = usb_device_del(devname);
4394 term_printf("Could not remove USB device '%s'\n", devname);
4401 const char *speed_str;
4404 term_printf("USB support not enabled\n");
4408 for (port = used_usb_ports; port; port = port->next) {
4412 switch(dev->speed) {
4416 case USB_SPEED_FULL:
4419 case USB_SPEED_HIGH:
4426 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4427 0, dev->addr, speed_str, dev->devname);
4431 /***********************************************************/
4432 /* PCMCIA/Cardbus */
4434 static struct pcmcia_socket_entry_s {
4435 struct pcmcia_socket_s *socket;
4436 struct pcmcia_socket_entry_s *next;
4437 } *pcmcia_sockets = 0;
4439 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4441 struct pcmcia_socket_entry_s *entry;
4443 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4444 entry->socket = socket;
4445 entry->next = pcmcia_sockets;
4446 pcmcia_sockets = entry;
4449 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4451 struct pcmcia_socket_entry_s *entry, **ptr;
4453 ptr = &pcmcia_sockets;
4454 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4455 if (entry->socket == socket) {
4461 void pcmcia_info(void)
4463 struct pcmcia_socket_entry_s *iter;
4464 if (!pcmcia_sockets)
4465 term_printf("No PCMCIA sockets\n");
4467 for (iter = pcmcia_sockets; iter; iter = iter->next)
4468 term_printf("%s: %s\n", iter->socket->slot_string,
4469 iter->socket->attached ? iter->socket->card_string :
4473 /***********************************************************/
4476 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4480 static void dumb_resize(DisplayState *ds, int w, int h)
4484 static void dumb_refresh(DisplayState *ds)
4489 void dumb_display_init(DisplayState *ds)
4494 ds->dpy_update = dumb_update;
4495 ds->dpy_resize = dumb_resize;
4496 ds->dpy_refresh = dumb_refresh;
4499 /***********************************************************/
4502 #define MAX_IO_HANDLERS 64
4504 typedef struct IOHandlerRecord {
4506 IOCanRWHandler *fd_read_poll;
4508 IOHandler *fd_write;
4511 /* temporary data */
4513 struct IOHandlerRecord *next;
4516 static IOHandlerRecord *first_io_handler;
4518 /* XXX: fd_read_poll should be suppressed, but an API change is
4519 necessary in the character devices to suppress fd_can_read(). */
4520 int qemu_set_fd_handler2(int fd,
4521 IOCanRWHandler *fd_read_poll,
4523 IOHandler *fd_write,
4526 IOHandlerRecord **pioh, *ioh;
4528 if (!fd_read && !fd_write) {
4529 pioh = &first_io_handler;
4534 if (ioh->fd == fd) {
4541 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4545 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4548 ioh->next = first_io_handler;
4549 first_io_handler = ioh;
4552 ioh->fd_read_poll = fd_read_poll;
4553 ioh->fd_read = fd_read;
4554 ioh->fd_write = fd_write;
4555 ioh->opaque = opaque;
4561 int qemu_set_fd_handler(int fd,
4563 IOHandler *fd_write,
4566 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4569 /***********************************************************/
4570 /* Polling handling */
4572 typedef struct PollingEntry {
4575 struct PollingEntry *next;
4578 static PollingEntry *first_polling_entry;
4580 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4582 PollingEntry **ppe, *pe;
4583 pe = qemu_mallocz(sizeof(PollingEntry));
4587 pe->opaque = opaque;
4588 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4593 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4595 PollingEntry **ppe, *pe;
4596 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4598 if (pe->func == func && pe->opaque == opaque) {
4607 /***********************************************************/
4608 /* Wait objects support */
4609 typedef struct WaitObjects {
4611 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4612 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4613 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4616 static WaitObjects wait_objects = {0};
4618 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4620 WaitObjects *w = &wait_objects;
4622 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4624 w->events[w->num] = handle;
4625 w->func[w->num] = func;
4626 w->opaque[w->num] = opaque;
4631 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4634 WaitObjects *w = &wait_objects;
4637 for (i = 0; i < w->num; i++) {
4638 if (w->events[i] == handle)
4641 w->events[i] = w->events[i + 1];
4642 w->func[i] = w->func[i + 1];
4643 w->opaque[i] = w->opaque[i + 1];
4651 /***********************************************************/
4652 /* savevm/loadvm support */
4654 #define IO_BUF_SIZE 32768
4658 BlockDriverState *bs;
4661 int64_t base_offset;
4662 int64_t buf_offset; /* start of buffer when writing, end of buffer
4665 int buf_size; /* 0 when writing */
4666 uint8_t buf[IO_BUF_SIZE];
4669 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4673 f = qemu_mallocz(sizeof(QEMUFile));
4676 if (!strcmp(mode, "wb")) {
4678 } else if (!strcmp(mode, "rb")) {
4683 f->outfile = fopen(filename, mode);
4695 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4699 f = qemu_mallocz(sizeof(QEMUFile));
4704 f->is_writable = is_writable;
4705 f->base_offset = offset;
4709 void qemu_fflush(QEMUFile *f)
4711 if (!f->is_writable)
4713 if (f->buf_index > 0) {
4715 fseek(f->outfile, f->buf_offset, SEEK_SET);
4716 fwrite(f->buf, 1, f->buf_index, f->outfile);
4718 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4719 f->buf, f->buf_index);
4721 f->buf_offset += f->buf_index;
4726 static void qemu_fill_buffer(QEMUFile *f)
4733 fseek(f->outfile, f->buf_offset, SEEK_SET);
4734 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4738 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4739 f->buf, IO_BUF_SIZE);
4745 f->buf_offset += len;
4748 void qemu_fclose(QEMUFile *f)
4758 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4762 l = IO_BUF_SIZE - f->buf_index;
4765 memcpy(f->buf + f->buf_index, buf, l);
4769 if (f->buf_index >= IO_BUF_SIZE)
4774 void qemu_put_byte(QEMUFile *f, int v)
4776 f->buf[f->buf_index++] = v;
4777 if (f->buf_index >= IO_BUF_SIZE)
4781 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4787 l = f->buf_size - f->buf_index;
4789 qemu_fill_buffer(f);
4790 l = f->buf_size - f->buf_index;
4796 memcpy(buf, f->buf + f->buf_index, l);
4801 return size1 - size;
4804 int qemu_get_byte(QEMUFile *f)
4806 if (f->buf_index >= f->buf_size) {
4807 qemu_fill_buffer(f);
4808 if (f->buf_index >= f->buf_size)
4811 return f->buf[f->buf_index++];
4814 int64_t qemu_ftell(QEMUFile *f)
4816 return f->buf_offset - f->buf_size + f->buf_index;
4819 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4821 if (whence == SEEK_SET) {
4823 } else if (whence == SEEK_CUR) {
4824 pos += qemu_ftell(f);
4826 /* SEEK_END not supported */
4829 if (f->is_writable) {
4831 f->buf_offset = pos;
4833 f->buf_offset = pos;
4840 void qemu_put_be16(QEMUFile *f, unsigned int v)
4842 qemu_put_byte(f, v >> 8);
4843 qemu_put_byte(f, v);
4846 void qemu_put_be32(QEMUFile *f, unsigned int v)
4848 qemu_put_byte(f, v >> 24);
4849 qemu_put_byte(f, v >> 16);
4850 qemu_put_byte(f, v >> 8);
4851 qemu_put_byte(f, v);
4854 void qemu_put_be64(QEMUFile *f, uint64_t v)
4856 qemu_put_be32(f, v >> 32);
4857 qemu_put_be32(f, v);
4860 unsigned int qemu_get_be16(QEMUFile *f)
4863 v = qemu_get_byte(f) << 8;
4864 v |= qemu_get_byte(f);
4868 unsigned int qemu_get_be32(QEMUFile *f)
4871 v = qemu_get_byte(f) << 24;
4872 v |= qemu_get_byte(f) << 16;
4873 v |= qemu_get_byte(f) << 8;
4874 v |= qemu_get_byte(f);
4878 uint64_t qemu_get_be64(QEMUFile *f)
4881 v = (uint64_t)qemu_get_be32(f) << 32;
4882 v |= qemu_get_be32(f);
4886 typedef struct SaveStateEntry {
4890 SaveStateHandler *save_state;
4891 LoadStateHandler *load_state;
4893 struct SaveStateEntry *next;
4896 static SaveStateEntry *first_se;
4898 int register_savevm(const char *idstr,
4901 SaveStateHandler *save_state,
4902 LoadStateHandler *load_state,
4905 SaveStateEntry *se, **pse;
4907 se = qemu_malloc(sizeof(SaveStateEntry));
4910 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4911 se->instance_id = instance_id;
4912 se->version_id = version_id;
4913 se->save_state = save_state;
4914 se->load_state = load_state;
4915 se->opaque = opaque;
4918 /* add at the end of list */
4920 while (*pse != NULL)
4921 pse = &(*pse)->next;
4926 #define QEMU_VM_FILE_MAGIC 0x5145564d
4927 #define QEMU_VM_FILE_VERSION 0x00000002
4929 int qemu_savevm_state(QEMUFile *f)
4933 int64_t cur_pos, len_pos, total_len_pos;
4935 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4936 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4937 total_len_pos = qemu_ftell(f);
4938 qemu_put_be64(f, 0); /* total size */
4940 for(se = first_se; se != NULL; se = se->next) {
4942 len = strlen(se->idstr);
4943 qemu_put_byte(f, len);
4944 qemu_put_buffer(f, se->idstr, len);
4946 qemu_put_be32(f, se->instance_id);
4947 qemu_put_be32(f, se->version_id);
4949 /* record size: filled later */
4950 len_pos = qemu_ftell(f);
4951 qemu_put_be32(f, 0);
4953 se->save_state(f, se->opaque);
4955 /* fill record size */
4956 cur_pos = qemu_ftell(f);
4957 len = cur_pos - len_pos - 4;
4958 qemu_fseek(f, len_pos, SEEK_SET);
4959 qemu_put_be32(f, len);
4960 qemu_fseek(f, cur_pos, SEEK_SET);
4962 cur_pos = qemu_ftell(f);
4963 qemu_fseek(f, total_len_pos, SEEK_SET);
4964 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4965 qemu_fseek(f, cur_pos, SEEK_SET);
4971 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4975 for(se = first_se; se != NULL; se = se->next) {
4976 if (!strcmp(se->idstr, idstr) &&
4977 instance_id == se->instance_id)
4983 int qemu_loadvm_state(QEMUFile *f)
4986 int len, ret, instance_id, record_len, version_id;
4987 int64_t total_len, end_pos, cur_pos;
4991 v = qemu_get_be32(f);
4992 if (v != QEMU_VM_FILE_MAGIC)
4994 v = qemu_get_be32(f);
4995 if (v != QEMU_VM_FILE_VERSION) {
5000 total_len = qemu_get_be64(f);
5001 end_pos = total_len + qemu_ftell(f);
5003 if (qemu_ftell(f) >= end_pos)
5005 len = qemu_get_byte(f);
5006 qemu_get_buffer(f, idstr, len);
5008 instance_id = qemu_get_be32(f);
5009 version_id = qemu_get_be32(f);
5010 record_len = qemu_get_be32(f);
5012 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5013 idstr, instance_id, version_id, record_len);
5015 cur_pos = qemu_ftell(f);
5016 se = find_se(idstr, instance_id);
5018 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5019 instance_id, idstr);
5021 ret = se->load_state(f, se->opaque, version_id);
5023 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5024 instance_id, idstr);
5027 /* always seek to exact end of record */
5028 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5035 /* device can contain snapshots */
5036 static int bdrv_can_snapshot(BlockDriverState *bs)
5039 !bdrv_is_removable(bs) &&
5040 !bdrv_is_read_only(bs));
5043 /* device must be snapshots in order to have a reliable snapshot */
5044 static int bdrv_has_snapshot(BlockDriverState *bs)
5047 !bdrv_is_removable(bs) &&
5048 !bdrv_is_read_only(bs));
5051 static BlockDriverState *get_bs_snapshots(void)
5053 BlockDriverState *bs;
5057 return bs_snapshots;
5058 for(i = 0; i <= MAX_DISKS; i++) {
5060 if (bdrv_can_snapshot(bs))
5069 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5072 QEMUSnapshotInfo *sn_tab, *sn;
5076 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5079 for(i = 0; i < nb_sns; i++) {
5081 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5091 void do_savevm(const char *name)
5093 BlockDriverState *bs, *bs1;
5094 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5095 int must_delete, ret, i;
5096 BlockDriverInfo bdi1, *bdi = &bdi1;
5098 int saved_vm_running;
5105 bs = get_bs_snapshots();
5107 term_printf("No block device can accept snapshots\n");
5111 /* ??? Should this occur after vm_stop? */
5114 saved_vm_running = vm_running;
5119 ret = bdrv_snapshot_find(bs, old_sn, name);
5124 memset(sn, 0, sizeof(*sn));
5126 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5127 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5130 pstrcpy(sn->name, sizeof(sn->name), name);
5133 /* fill auxiliary fields */
5136 sn->date_sec = tb.time;
5137 sn->date_nsec = tb.millitm * 1000000;
5139 gettimeofday(&tv, NULL);
5140 sn->date_sec = tv.tv_sec;
5141 sn->date_nsec = tv.tv_usec * 1000;
5143 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5145 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5146 term_printf("Device %s does not support VM state snapshots\n",
5147 bdrv_get_device_name(bs));
5151 /* save the VM state */
5152 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5154 term_printf("Could not open VM state file\n");
5157 ret = qemu_savevm_state(f);
5158 sn->vm_state_size = qemu_ftell(f);
5161 term_printf("Error %d while writing VM\n", ret);
5165 /* create the snapshots */
5167 for(i = 0; i < MAX_DISKS; i++) {
5169 if (bdrv_has_snapshot(bs1)) {
5171 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5173 term_printf("Error while deleting snapshot on '%s'\n",
5174 bdrv_get_device_name(bs1));
5177 ret = bdrv_snapshot_create(bs1, sn);
5179 term_printf("Error while creating snapshot on '%s'\n",
5180 bdrv_get_device_name(bs1));
5186 if (saved_vm_running)
5190 void do_loadvm(const char *name)
5192 BlockDriverState *bs, *bs1;
5193 BlockDriverInfo bdi1, *bdi = &bdi1;
5196 int saved_vm_running;
5198 bs = get_bs_snapshots();
5200 term_printf("No block device supports snapshots\n");
5204 /* Flush all IO requests so they don't interfere with the new state. */
5207 saved_vm_running = vm_running;
5210 for(i = 0; i <= MAX_DISKS; i++) {
5212 if (bdrv_has_snapshot(bs1)) {
5213 ret = bdrv_snapshot_goto(bs1, name);
5216 term_printf("Warning: ");
5219 term_printf("Snapshots not supported on device '%s'\n",
5220 bdrv_get_device_name(bs1));
5223 term_printf("Could not find snapshot '%s' on device '%s'\n",
5224 name, bdrv_get_device_name(bs1));
5227 term_printf("Error %d while activating snapshot on '%s'\n",
5228 ret, bdrv_get_device_name(bs1));
5231 /* fatal on snapshot block device */
5238 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5239 term_printf("Device %s does not support VM state snapshots\n",
5240 bdrv_get_device_name(bs));
5244 /* restore the VM state */
5245 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5247 term_printf("Could not open VM state file\n");
5250 ret = qemu_loadvm_state(f);
5253 term_printf("Error %d while loading VM state\n", ret);
5256 if (saved_vm_running)
5260 void do_delvm(const char *name)
5262 BlockDriverState *bs, *bs1;
5265 bs = get_bs_snapshots();
5267 term_printf("No block device supports snapshots\n");
5271 for(i = 0; i <= MAX_DISKS; i++) {
5273 if (bdrv_has_snapshot(bs1)) {
5274 ret = bdrv_snapshot_delete(bs1, name);
5276 if (ret == -ENOTSUP)
5277 term_printf("Snapshots not supported on device '%s'\n",
5278 bdrv_get_device_name(bs1));
5280 term_printf("Error %d while deleting snapshot on '%s'\n",
5281 ret, bdrv_get_device_name(bs1));
5287 void do_info_snapshots(void)
5289 BlockDriverState *bs, *bs1;
5290 QEMUSnapshotInfo *sn_tab, *sn;
5294 bs = get_bs_snapshots();
5296 term_printf("No available block device supports snapshots\n");
5299 term_printf("Snapshot devices:");
5300 for(i = 0; i <= MAX_DISKS; i++) {
5302 if (bdrv_has_snapshot(bs1)) {
5304 term_printf(" %s", bdrv_get_device_name(bs1));
5309 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5311 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5314 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5315 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5316 for(i = 0; i < nb_sns; i++) {
5318 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5323 /***********************************************************/
5324 /* cpu save/restore */
5326 #if defined(TARGET_I386)
5328 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5330 qemu_put_be32(f, dt->selector);
5331 qemu_put_betl(f, dt->base);
5332 qemu_put_be32(f, dt->limit);
5333 qemu_put_be32(f, dt->flags);
5336 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5338 dt->selector = qemu_get_be32(f);
5339 dt->base = qemu_get_betl(f);
5340 dt->limit = qemu_get_be32(f);
5341 dt->flags = qemu_get_be32(f);
5344 void cpu_save(QEMUFile *f, void *opaque)
5346 CPUState *env = opaque;
5347 uint16_t fptag, fpus, fpuc, fpregs_format;
5351 for(i = 0; i < CPU_NB_REGS; i++)
5352 qemu_put_betls(f, &env->regs[i]);
5353 qemu_put_betls(f, &env->eip);
5354 qemu_put_betls(f, &env->eflags);
5355 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5356 qemu_put_be32s(f, &hflags);
5360 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5362 for(i = 0; i < 8; i++) {
5363 fptag |= ((!env->fptags[i]) << i);
5366 qemu_put_be16s(f, &fpuc);
5367 qemu_put_be16s(f, &fpus);
5368 qemu_put_be16s(f, &fptag);
5370 #ifdef USE_X86LDOUBLE
5375 qemu_put_be16s(f, &fpregs_format);
5377 for(i = 0; i < 8; i++) {
5378 #ifdef USE_X86LDOUBLE
5382 /* we save the real CPU data (in case of MMX usage only 'mant'
5383 contains the MMX register */
5384 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5385 qemu_put_be64(f, mant);
5386 qemu_put_be16(f, exp);
5389 /* if we use doubles for float emulation, we save the doubles to
5390 avoid losing information in case of MMX usage. It can give
5391 problems if the image is restored on a CPU where long
5392 doubles are used instead. */
5393 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5397 for(i = 0; i < 6; i++)
5398 cpu_put_seg(f, &env->segs[i]);
5399 cpu_put_seg(f, &env->ldt);
5400 cpu_put_seg(f, &env->tr);
5401 cpu_put_seg(f, &env->gdt);
5402 cpu_put_seg(f, &env->idt);
5404 qemu_put_be32s(f, &env->sysenter_cs);
5405 qemu_put_be32s(f, &env->sysenter_esp);
5406 qemu_put_be32s(f, &env->sysenter_eip);
5408 qemu_put_betls(f, &env->cr[0]);
5409 qemu_put_betls(f, &env->cr[2]);
5410 qemu_put_betls(f, &env->cr[3]);
5411 qemu_put_betls(f, &env->cr[4]);
5413 for(i = 0; i < 8; i++)
5414 qemu_put_betls(f, &env->dr[i]);
5417 qemu_put_be32s(f, &env->a20_mask);
5420 qemu_put_be32s(f, &env->mxcsr);
5421 for(i = 0; i < CPU_NB_REGS; i++) {
5422 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5423 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5426 #ifdef TARGET_X86_64
5427 qemu_put_be64s(f, &env->efer);
5428 qemu_put_be64s(f, &env->star);
5429 qemu_put_be64s(f, &env->lstar);
5430 qemu_put_be64s(f, &env->cstar);
5431 qemu_put_be64s(f, &env->fmask);
5432 qemu_put_be64s(f, &env->kernelgsbase);
5434 qemu_put_be32s(f, &env->smbase);
5437 #ifdef USE_X86LDOUBLE
5438 /* XXX: add that in a FPU generic layer */
5439 union x86_longdouble {
5444 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5445 #define EXPBIAS1 1023
5446 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5447 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5449 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5453 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5454 /* exponent + sign */
5455 e = EXPD1(temp) - EXPBIAS1 + 16383;
5456 e |= SIGND1(temp) >> 16;
5461 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5463 CPUState *env = opaque;
5466 uint16_t fpus, fpuc, fptag, fpregs_format;
5468 if (version_id != 3 && version_id != 4)
5470 for(i = 0; i < CPU_NB_REGS; i++)
5471 qemu_get_betls(f, &env->regs[i]);
5472 qemu_get_betls(f, &env->eip);
5473 qemu_get_betls(f, &env->eflags);
5474 qemu_get_be32s(f, &hflags);
5476 qemu_get_be16s(f, &fpuc);
5477 qemu_get_be16s(f, &fpus);
5478 qemu_get_be16s(f, &fptag);
5479 qemu_get_be16s(f, &fpregs_format);
5481 /* NOTE: we cannot always restore the FPU state if the image come
5482 from a host with a different 'USE_X86LDOUBLE' define. We guess
5483 if we are in an MMX state to restore correctly in that case. */
5484 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5485 for(i = 0; i < 8; i++) {
5489 switch(fpregs_format) {
5491 mant = qemu_get_be64(f);
5492 exp = qemu_get_be16(f);
5493 #ifdef USE_X86LDOUBLE
5494 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5496 /* difficult case */
5498 env->fpregs[i].mmx.MMX_Q(0) = mant;
5500 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5504 mant = qemu_get_be64(f);
5505 #ifdef USE_X86LDOUBLE
5507 union x86_longdouble *p;
5508 /* difficult case */
5509 p = (void *)&env->fpregs[i];
5514 fp64_to_fp80(p, mant);
5518 env->fpregs[i].mmx.MMX_Q(0) = mant;
5527 /* XXX: restore FPU round state */
5528 env->fpstt = (fpus >> 11) & 7;
5529 env->fpus = fpus & ~0x3800;
5531 for(i = 0; i < 8; i++) {
5532 env->fptags[i] = (fptag >> i) & 1;
5535 for(i = 0; i < 6; i++)
5536 cpu_get_seg(f, &env->segs[i]);
5537 cpu_get_seg(f, &env->ldt);
5538 cpu_get_seg(f, &env->tr);
5539 cpu_get_seg(f, &env->gdt);
5540 cpu_get_seg(f, &env->idt);
5542 qemu_get_be32s(f, &env->sysenter_cs);
5543 qemu_get_be32s(f, &env->sysenter_esp);
5544 qemu_get_be32s(f, &env->sysenter_eip);
5546 qemu_get_betls(f, &env->cr[0]);
5547 qemu_get_betls(f, &env->cr[2]);
5548 qemu_get_betls(f, &env->cr[3]);
5549 qemu_get_betls(f, &env->cr[4]);
5551 for(i = 0; i < 8; i++)
5552 qemu_get_betls(f, &env->dr[i]);
5555 qemu_get_be32s(f, &env->a20_mask);
5557 qemu_get_be32s(f, &env->mxcsr);
5558 for(i = 0; i < CPU_NB_REGS; i++) {
5559 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5560 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5563 #ifdef TARGET_X86_64
5564 qemu_get_be64s(f, &env->efer);
5565 qemu_get_be64s(f, &env->star);
5566 qemu_get_be64s(f, &env->lstar);
5567 qemu_get_be64s(f, &env->cstar);
5568 qemu_get_be64s(f, &env->fmask);
5569 qemu_get_be64s(f, &env->kernelgsbase);
5571 if (version_id >= 4)
5572 qemu_get_be32s(f, &env->smbase);
5574 /* XXX: compute hflags from scratch, except for CPL and IIF */
5575 env->hflags = hflags;
5580 #elif defined(TARGET_PPC)
5581 void cpu_save(QEMUFile *f, void *opaque)
5585 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5590 #elif defined(TARGET_MIPS)
5591 void cpu_save(QEMUFile *f, void *opaque)
5595 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5600 #elif defined(TARGET_SPARC)
5601 void cpu_save(QEMUFile *f, void *opaque)
5603 CPUState *env = opaque;
5607 for(i = 0; i < 8; i++)
5608 qemu_put_betls(f, &env->gregs[i]);
5609 for(i = 0; i < NWINDOWS * 16; i++)
5610 qemu_put_betls(f, &env->regbase[i]);
5613 for(i = 0; i < TARGET_FPREGS; i++) {
5619 qemu_put_be32(f, u.i);
5622 qemu_put_betls(f, &env->pc);
5623 qemu_put_betls(f, &env->npc);
5624 qemu_put_betls(f, &env->y);
5626 qemu_put_be32(f, tmp);
5627 qemu_put_betls(f, &env->fsr);
5628 qemu_put_betls(f, &env->tbr);
5629 #ifndef TARGET_SPARC64
5630 qemu_put_be32s(f, &env->wim);
5632 for(i = 0; i < 16; i++)
5633 qemu_put_be32s(f, &env->mmuregs[i]);
5637 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5639 CPUState *env = opaque;
5643 for(i = 0; i < 8; i++)
5644 qemu_get_betls(f, &env->gregs[i]);
5645 for(i = 0; i < NWINDOWS * 16; i++)
5646 qemu_get_betls(f, &env->regbase[i]);
5649 for(i = 0; i < TARGET_FPREGS; i++) {
5654 u.i = qemu_get_be32(f);
5658 qemu_get_betls(f, &env->pc);
5659 qemu_get_betls(f, &env->npc);
5660 qemu_get_betls(f, &env->y);
5661 tmp = qemu_get_be32(f);
5662 env->cwp = 0; /* needed to ensure that the wrapping registers are
5663 correctly updated */
5665 qemu_get_betls(f, &env->fsr);
5666 qemu_get_betls(f, &env->tbr);
5667 #ifndef TARGET_SPARC64
5668 qemu_get_be32s(f, &env->wim);
5670 for(i = 0; i < 16; i++)
5671 qemu_get_be32s(f, &env->mmuregs[i]);
5677 #elif defined(TARGET_ARM)
5679 /* ??? Need to implement these. */
5680 void cpu_save(QEMUFile *f, void *opaque)
5684 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5691 #warning No CPU save/restore functions
5695 /***********************************************************/
5696 /* ram save/restore */
5698 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5702 v = qemu_get_byte(f);
5705 if (qemu_get_buffer(f, buf, len) != len)
5709 v = qemu_get_byte(f);
5710 memset(buf, v, len);
5718 static int ram_load_v1(QEMUFile *f, void *opaque)
5722 if (qemu_get_be32(f) != phys_ram_size)
5724 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5725 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5732 #define BDRV_HASH_BLOCK_SIZE 1024
5733 #define IOBUF_SIZE 4096
5734 #define RAM_CBLOCK_MAGIC 0xfabe
5736 typedef struct RamCompressState {
5739 uint8_t buf[IOBUF_SIZE];
5742 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5745 memset(s, 0, sizeof(*s));
5747 ret = deflateInit2(&s->zstream, 1,
5749 9, Z_DEFAULT_STRATEGY);
5752 s->zstream.avail_out = IOBUF_SIZE;
5753 s->zstream.next_out = s->buf;
5757 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5759 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5760 qemu_put_be16(s->f, len);
5761 qemu_put_buffer(s->f, buf, len);
5764 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5768 s->zstream.avail_in = len;
5769 s->zstream.next_in = (uint8_t *)buf;
5770 while (s->zstream.avail_in > 0) {
5771 ret = deflate(&s->zstream, Z_NO_FLUSH);
5774 if (s->zstream.avail_out == 0) {
5775 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5776 s->zstream.avail_out = IOBUF_SIZE;
5777 s->zstream.next_out = s->buf;
5783 static void ram_compress_close(RamCompressState *s)
5787 /* compress last bytes */
5789 ret = deflate(&s->zstream, Z_FINISH);
5790 if (ret == Z_OK || ret == Z_STREAM_END) {
5791 len = IOBUF_SIZE - s->zstream.avail_out;
5793 ram_put_cblock(s, s->buf, len);
5795 s->zstream.avail_out = IOBUF_SIZE;
5796 s->zstream.next_out = s->buf;
5797 if (ret == Z_STREAM_END)
5804 deflateEnd(&s->zstream);
5807 typedef struct RamDecompressState {
5810 uint8_t buf[IOBUF_SIZE];
5811 } RamDecompressState;
5813 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5816 memset(s, 0, sizeof(*s));
5818 ret = inflateInit(&s->zstream);
5824 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5828 s->zstream.avail_out = len;
5829 s->zstream.next_out = buf;
5830 while (s->zstream.avail_out > 0) {
5831 if (s->zstream.avail_in == 0) {
5832 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5834 clen = qemu_get_be16(s->f);
5835 if (clen > IOBUF_SIZE)
5837 qemu_get_buffer(s->f, s->buf, clen);
5838 s->zstream.avail_in = clen;
5839 s->zstream.next_in = s->buf;
5841 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5842 if (ret != Z_OK && ret != Z_STREAM_END) {
5849 static void ram_decompress_close(RamDecompressState *s)
5851 inflateEnd(&s->zstream);
5854 static void ram_save(QEMUFile *f, void *opaque)
5857 RamCompressState s1, *s = &s1;
5860 qemu_put_be32(f, phys_ram_size);
5861 if (ram_compress_open(s, f) < 0)
5863 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5865 if (tight_savevm_enabled) {
5869 /* find if the memory block is available on a virtual
5872 for(j = 0; j < MAX_DISKS; j++) {
5874 sector_num = bdrv_hash_find(bs_table[j],
5875 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5876 if (sector_num >= 0)
5881 goto normal_compress;
5884 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5885 ram_compress_buf(s, buf, 10);
5891 ram_compress_buf(s, buf, 1);
5892 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5895 ram_compress_close(s);
5898 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5900 RamDecompressState s1, *s = &s1;
5904 if (version_id == 1)
5905 return ram_load_v1(f, opaque);
5906 if (version_id != 2)
5908 if (qemu_get_be32(f) != phys_ram_size)
5910 if (ram_decompress_open(s, f) < 0)
5912 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5913 if (ram_decompress_buf(s, buf, 1) < 0) {
5914 fprintf(stderr, "Error while reading ram block header\n");
5918 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5919 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5928 ram_decompress_buf(s, buf + 1, 9);
5930 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5931 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5932 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5935 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5936 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5937 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5938 bs_index, sector_num);
5945 printf("Error block header\n");
5949 ram_decompress_close(s);
5953 /***********************************************************/
5954 /* bottom halves (can be seen as timers which expire ASAP) */
5963 static QEMUBH *first_bh = NULL;
5965 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5968 bh = qemu_mallocz(sizeof(QEMUBH));
5972 bh->opaque = opaque;
5976 int qemu_bh_poll(void)
5995 void qemu_bh_schedule(QEMUBH *bh)
5997 CPUState *env = cpu_single_env;
6001 bh->next = first_bh;
6004 /* stop the currently executing CPU to execute the BH ASAP */
6006 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6010 void qemu_bh_cancel(QEMUBH *bh)
6013 if (bh->scheduled) {
6016 pbh = &(*pbh)->next;
6022 void qemu_bh_delete(QEMUBH *bh)
6028 /***********************************************************/
6029 /* machine registration */
6031 QEMUMachine *first_machine = NULL;
6033 int qemu_register_machine(QEMUMachine *m)
6036 pm = &first_machine;
6044 QEMUMachine *find_machine(const char *name)
6048 for(m = first_machine; m != NULL; m = m->next) {
6049 if (!strcmp(m->name, name))
6055 /***********************************************************/
6056 /* main execution loop */
6058 void gui_update(void *opaque)
6060 display_state.dpy_refresh(&display_state);
6061 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6064 struct vm_change_state_entry {
6065 VMChangeStateHandler *cb;
6067 LIST_ENTRY (vm_change_state_entry) entries;
6070 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6072 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6075 VMChangeStateEntry *e;
6077 e = qemu_mallocz(sizeof (*e));
6083 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6087 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6089 LIST_REMOVE (e, entries);
6093 static void vm_state_notify(int running)
6095 VMChangeStateEntry *e;
6097 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6098 e->cb(e->opaque, running);
6102 /* XXX: support several handlers */
6103 static VMStopHandler *vm_stop_cb;
6104 static void *vm_stop_opaque;
6106 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6109 vm_stop_opaque = opaque;
6113 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6127 void vm_stop(int reason)
6130 cpu_disable_ticks();
6134 vm_stop_cb(vm_stop_opaque, reason);
6141 /* reset/shutdown handler */
6143 typedef struct QEMUResetEntry {
6144 QEMUResetHandler *func;
6146 struct QEMUResetEntry *next;
6149 static QEMUResetEntry *first_reset_entry;
6150 static int reset_requested;
6151 static int shutdown_requested;
6152 static int powerdown_requested;
6154 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6156 QEMUResetEntry **pre, *re;
6158 pre = &first_reset_entry;
6159 while (*pre != NULL)
6160 pre = &(*pre)->next;
6161 re = qemu_mallocz(sizeof(QEMUResetEntry));
6163 re->opaque = opaque;
6168 static void qemu_system_reset(void)
6172 /* reset all devices */
6173 for(re = first_reset_entry; re != NULL; re = re->next) {
6174 re->func(re->opaque);
6178 void qemu_system_reset_request(void)
6181 shutdown_requested = 1;
6183 reset_requested = 1;
6186 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6189 void qemu_system_shutdown_request(void)
6191 shutdown_requested = 1;
6193 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6196 void qemu_system_powerdown_request(void)
6198 powerdown_requested = 1;
6200 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6203 void main_loop_wait(int timeout)
6205 IOHandlerRecord *ioh;
6206 fd_set rfds, wfds, xfds;
6215 /* XXX: need to suppress polling by better using win32 events */
6217 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6218 ret |= pe->func(pe->opaque);
6223 WaitObjects *w = &wait_objects;
6225 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6226 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6227 if (w->func[ret - WAIT_OBJECT_0])
6228 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6230 /* Check for additional signaled events */
6231 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6233 /* Check if event is signaled */
6234 ret2 = WaitForSingleObject(w->events[i], 0);
6235 if(ret2 == WAIT_OBJECT_0) {
6237 w->func[i](w->opaque[i]);
6238 } else if (ret2 == WAIT_TIMEOUT) {
6240 err = GetLastError();
6241 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6244 } else if (ret == WAIT_TIMEOUT) {
6246 err = GetLastError();
6247 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6251 /* poll any events */
6252 /* XXX: separate device handlers from system ones */
6257 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6261 (!ioh->fd_read_poll ||
6262 ioh->fd_read_poll(ioh->opaque) != 0)) {
6263 FD_SET(ioh->fd, &rfds);
6267 if (ioh->fd_write) {
6268 FD_SET(ioh->fd, &wfds);
6278 tv.tv_usec = timeout * 1000;
6280 #if defined(CONFIG_SLIRP)
6282 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6285 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6287 IOHandlerRecord **pioh;
6289 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6292 if (FD_ISSET(ioh->fd, &rfds)) {
6293 ioh->fd_read(ioh->opaque);
6295 if (FD_ISSET(ioh->fd, &wfds)) {
6296 ioh->fd_write(ioh->opaque);
6300 /* remove deleted IO handlers */
6301 pioh = &first_io_handler;
6311 #if defined(CONFIG_SLIRP)
6318 slirp_select_poll(&rfds, &wfds, &xfds);
6325 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6326 qemu_get_clock(vm_clock));
6327 /* run dma transfers, if any */
6331 /* real time timers */
6332 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6333 qemu_get_clock(rt_clock));
6336 static CPUState *cur_cpu;
6341 #ifdef CONFIG_PROFILER
6346 cur_cpu = first_cpu;
6353 env = env->next_cpu;
6356 #ifdef CONFIG_PROFILER
6357 ti = profile_getclock();
6359 ret = cpu_exec(env);
6360 #ifdef CONFIG_PROFILER
6361 qemu_time += profile_getclock() - ti;
6363 if (ret == EXCP_HLT) {
6364 /* Give the next CPU a chance to run. */
6368 if (ret != EXCP_HALTED)
6370 /* all CPUs are halted ? */
6376 if (shutdown_requested) {
6377 ret = EXCP_INTERRUPT;
6380 if (reset_requested) {
6381 reset_requested = 0;
6382 qemu_system_reset();
6383 ret = EXCP_INTERRUPT;
6385 if (powerdown_requested) {
6386 powerdown_requested = 0;
6387 qemu_system_powerdown();
6388 ret = EXCP_INTERRUPT;
6390 if (ret == EXCP_DEBUG) {
6391 vm_stop(EXCP_DEBUG);
6393 /* If all cpus are halted then wait until the next IRQ */
6394 /* XXX: use timeout computed from timers */
6395 if (ret == EXCP_HALTED)
6402 #ifdef CONFIG_PROFILER
6403 ti = profile_getclock();
6405 main_loop_wait(timeout);
6406 #ifdef CONFIG_PROFILER
6407 dev_time += profile_getclock() - ti;
6410 cpu_disable_ticks();
6416 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6417 "usage: %s [options] [disk_image]\n"
6419 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6421 "Standard options:\n"
6422 "-M machine select emulated machine (-M ? for list)\n"
6423 "-cpu cpu select CPU (-cpu ? for list)\n"
6424 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6425 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6426 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6427 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6428 "-mtdblock file use 'file' as on-board Flash memory image\n"
6429 "-sd file use 'file' as SecureDigital card image\n"
6430 "-pflash file use 'file' as a parallel flash image\n"
6431 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6432 "-snapshot write to temporary files instead of disk image files\n"
6434 "-no-frame open SDL window without a frame and window decorations\n"
6435 "-no-quit disable SDL window close capability\n"
6438 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6440 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6441 "-smp n set the number of CPUs to 'n' [default=1]\n"
6442 "-nographic disable graphical output and redirect serial I/Os to console\n"
6443 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6445 "-k language use keyboard layout (for example \"fr\" for French)\n"
6448 "-audio-help print list of audio drivers and their options\n"
6449 "-soundhw c1,... enable audio support\n"
6450 " and only specified sound cards (comma separated list)\n"
6451 " use -soundhw ? to get the list of supported cards\n"
6452 " use -soundhw all to enable all of them\n"
6454 "-localtime set the real time clock to local time [default=utc]\n"
6455 "-full-screen start in full screen\n"
6457 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6459 "-usb enable the USB driver (will be the default soon)\n"
6460 "-usbdevice name add the host or guest USB device 'name'\n"
6461 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6462 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6464 "-name string set the name of the guest\n"
6466 "Network options:\n"
6467 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6468 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6470 "-net user[,vlan=n][,hostname=host]\n"
6471 " connect the user mode network stack to VLAN 'n' and send\n"
6472 " hostname 'host' to DHCP clients\n"
6475 "-net tap[,vlan=n],ifname=name\n"
6476 " connect the host TAP network interface to VLAN 'n'\n"
6478 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6479 " connect the host TAP network interface to VLAN 'n' and use\n"
6480 " the network script 'file' (default=%s);\n"
6481 " use 'script=no' to disable script execution;\n"
6482 " use 'fd=h' to connect to an already opened TAP interface\n"
6484 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6485 " connect the vlan 'n' to another VLAN using a socket connection\n"
6486 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6487 " connect the vlan 'n' to multicast maddr and port\n"
6488 "-net none use it alone to have zero network devices; if no -net option\n"
6489 " is provided, the default is '-net nic -net user'\n"
6492 "-tftp dir allow tftp access to files in dir [-net user]\n"
6493 "-bootp file advertise file in BOOTP replies\n"
6495 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6497 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6498 " redirect TCP or UDP connections from host to guest [-net user]\n"
6501 "Linux boot specific:\n"
6502 "-kernel bzImage use 'bzImage' as kernel image\n"
6503 "-append cmdline use 'cmdline' as kernel command line\n"
6504 "-initrd file use 'file' as initial ram disk\n"
6506 "Debug/Expert options:\n"
6507 "-monitor dev redirect the monitor to char device 'dev'\n"
6508 "-serial dev redirect the serial port to char device 'dev'\n"
6509 "-parallel dev redirect the parallel port to char device 'dev'\n"
6510 "-pidfile file Write PID to 'file'\n"
6511 "-S freeze CPU at startup (use 'c' to start execution)\n"
6512 "-s wait gdb connection to port\n"
6513 "-p port set gdb connection port [default=%s]\n"
6514 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6515 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6516 " translation (t=none or lba) (usually qemu can guess them)\n"
6517 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6519 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6520 "-no-kqemu disable KQEMU kernel module usage\n"
6522 #ifdef USE_CODE_COPY
6523 "-no-code-copy disable code copy acceleration\n"
6526 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6527 " (default is CL-GD5446 PCI VGA)\n"
6528 "-no-acpi disable ACPI\n"
6530 "-no-reboot exit instead of rebooting\n"
6531 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6532 "-vnc display start a VNC server on display\n"
6534 "-daemonize daemonize QEMU after initializing\n"
6536 "-option-rom rom load a file, rom, into the option ROM space\n"
6538 "-prom-env variable=value set OpenBIOS nvram variables\n"
6541 "During emulation, the following keys are useful:\n"
6542 "ctrl-alt-f toggle full screen\n"
6543 "ctrl-alt-n switch to virtual console 'n'\n"
6544 "ctrl-alt toggle mouse and keyboard grab\n"
6546 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6551 DEFAULT_NETWORK_SCRIPT,
6553 DEFAULT_GDBSTUB_PORT,
6558 #define HAS_ARG 0x0001
6572 QEMU_OPTION_mtdblock,
6576 QEMU_OPTION_snapshot,
6578 QEMU_OPTION_no_fd_bootchk,
6581 QEMU_OPTION_nographic,
6582 QEMU_OPTION_portrait,
6584 QEMU_OPTION_audio_help,
6585 QEMU_OPTION_soundhw,
6604 QEMU_OPTION_no_code_copy,
6606 QEMU_OPTION_localtime,
6607 QEMU_OPTION_cirrusvga,
6610 QEMU_OPTION_std_vga,
6612 QEMU_OPTION_monitor,
6614 QEMU_OPTION_parallel,
6616 QEMU_OPTION_full_screen,
6617 QEMU_OPTION_no_frame,
6618 QEMU_OPTION_no_quit,
6619 QEMU_OPTION_pidfile,
6620 QEMU_OPTION_no_kqemu,
6621 QEMU_OPTION_kernel_kqemu,
6622 QEMU_OPTION_win2k_hack,
6624 QEMU_OPTION_usbdevice,
6627 QEMU_OPTION_no_acpi,
6628 QEMU_OPTION_no_reboot,
6629 QEMU_OPTION_show_cursor,
6630 QEMU_OPTION_daemonize,
6631 QEMU_OPTION_option_rom,
6632 QEMU_OPTION_semihosting,
6634 QEMU_OPTION_prom_env,
6637 typedef struct QEMUOption {
6643 const QEMUOption qemu_options[] = {
6644 { "h", 0, QEMU_OPTION_h },
6645 { "help", 0, QEMU_OPTION_h },
6647 { "M", HAS_ARG, QEMU_OPTION_M },
6648 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6649 { "fda", HAS_ARG, QEMU_OPTION_fda },
6650 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6651 { "hda", HAS_ARG, QEMU_OPTION_hda },
6652 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6653 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6654 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6655 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6656 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6657 { "sd", HAS_ARG, QEMU_OPTION_sd },
6658 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6659 { "boot", HAS_ARG, QEMU_OPTION_boot },
6660 { "snapshot", 0, QEMU_OPTION_snapshot },
6662 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6664 { "m", HAS_ARG, QEMU_OPTION_m },
6665 { "nographic", 0, QEMU_OPTION_nographic },
6666 { "portrait", 0, QEMU_OPTION_portrait },
6667 { "k", HAS_ARG, QEMU_OPTION_k },
6669 { "audio-help", 0, QEMU_OPTION_audio_help },
6670 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6673 { "net", HAS_ARG, QEMU_OPTION_net},
6675 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6676 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6678 { "smb", HAS_ARG, QEMU_OPTION_smb },
6680 { "redir", HAS_ARG, QEMU_OPTION_redir },
6683 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6684 { "append", HAS_ARG, QEMU_OPTION_append },
6685 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6687 { "S", 0, QEMU_OPTION_S },
6688 { "s", 0, QEMU_OPTION_s },
6689 { "p", HAS_ARG, QEMU_OPTION_p },
6690 { "d", HAS_ARG, QEMU_OPTION_d },
6691 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6692 { "L", HAS_ARG, QEMU_OPTION_L },
6693 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6695 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6696 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6698 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6699 { "g", 1, QEMU_OPTION_g },
6701 { "localtime", 0, QEMU_OPTION_localtime },
6702 { "std-vga", 0, QEMU_OPTION_std_vga },
6703 { "echr", 1, QEMU_OPTION_echr },
6704 { "monitor", 1, QEMU_OPTION_monitor },
6705 { "serial", 1, QEMU_OPTION_serial },
6706 { "parallel", 1, QEMU_OPTION_parallel },
6707 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6708 { "full-screen", 0, QEMU_OPTION_full_screen },
6710 { "no-frame", 0, QEMU_OPTION_no_frame },
6711 { "no-quit", 0, QEMU_OPTION_no_quit },
6713 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6714 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6715 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6716 { "smp", HAS_ARG, QEMU_OPTION_smp },
6717 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6719 /* temporary options */
6720 { "usb", 0, QEMU_OPTION_usb },
6721 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6722 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6723 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6724 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6725 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6726 { "daemonize", 0, QEMU_OPTION_daemonize },
6727 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6728 #if defined(TARGET_ARM)
6729 { "semihosting", 0, QEMU_OPTION_semihosting },
6731 { "name", HAS_ARG, QEMU_OPTION_name },
6732 #if defined(TARGET_SPARC)
6733 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6738 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6740 /* this stack is only used during signal handling */
6741 #define SIGNAL_STACK_SIZE 32768
6743 static uint8_t *signal_stack;
6747 /* password input */
6749 int qemu_key_check(BlockDriverState *bs, const char *name)
6754 if (!bdrv_is_encrypted(bs))
6757 term_printf("%s is encrypted.\n", name);
6758 for(i = 0; i < 3; i++) {
6759 monitor_readline("Password: ", 1, password, sizeof(password));
6760 if (bdrv_set_key(bs, password) == 0)
6762 term_printf("invalid password\n");
6767 static BlockDriverState *get_bdrv(int index)
6769 BlockDriverState *bs;
6772 bs = bs_table[index];
6773 } else if (index < 6) {
6774 bs = fd_table[index - 4];
6781 static void read_passwords(void)
6783 BlockDriverState *bs;
6786 for(i = 0; i < 6; i++) {
6789 qemu_key_check(bs, bdrv_get_device_name(bs));
6793 /* XXX: currently we cannot use simultaneously different CPUs */
6794 void register_machines(void)
6796 #if defined(TARGET_I386)
6797 qemu_register_machine(&pc_machine);
6798 qemu_register_machine(&isapc_machine);
6799 #elif defined(TARGET_PPC)
6800 qemu_register_machine(&heathrow_machine);
6801 qemu_register_machine(&core99_machine);
6802 qemu_register_machine(&prep_machine);
6803 qemu_register_machine(&ref405ep_machine);
6804 qemu_register_machine(&taihu_machine);
6805 #elif defined(TARGET_MIPS)
6806 qemu_register_machine(&mips_machine);
6807 qemu_register_machine(&mips_malta_machine);
6808 qemu_register_machine(&mips_pica61_machine);
6809 #elif defined(TARGET_SPARC)
6810 #ifdef TARGET_SPARC64
6811 qemu_register_machine(&sun4u_machine);
6813 qemu_register_machine(&ss5_machine);
6814 qemu_register_machine(&ss10_machine);
6816 #elif defined(TARGET_ARM)
6817 qemu_register_machine(&integratorcp_machine);
6818 qemu_register_machine(&versatilepb_machine);
6819 qemu_register_machine(&versatileab_machine);
6820 qemu_register_machine(&realview_machine);
6821 qemu_register_machine(&akitapda_machine);
6822 qemu_register_machine(&spitzpda_machine);
6823 qemu_register_machine(&borzoipda_machine);
6824 qemu_register_machine(&terrierpda_machine);
6825 #elif defined(TARGET_SH4)
6826 qemu_register_machine(&shix_machine);
6827 #elif defined(TARGET_ALPHA)
6830 #error unsupported CPU
6835 struct soundhw soundhw[] = {
6836 #ifdef HAS_AUDIO_CHOICE
6843 { .init_isa = pcspk_audio_init }
6848 "Creative Sound Blaster 16",
6851 { .init_isa = SB16_init }
6858 "Yamaha YMF262 (OPL3)",
6860 "Yamaha YM3812 (OPL2)",
6864 { .init_isa = Adlib_init }
6871 "Gravis Ultrasound GF1",
6874 { .init_isa = GUS_init }
6880 "ENSONIQ AudioPCI ES1370",
6883 { .init_pci = es1370_init }
6887 { NULL, NULL, 0, 0, { NULL } }
6890 static void select_soundhw (const char *optarg)
6894 if (*optarg == '?') {
6897 printf ("Valid sound card names (comma separated):\n");
6898 for (c = soundhw; c->name; ++c) {
6899 printf ("%-11s %s\n", c->name, c->descr);
6901 printf ("\n-soundhw all will enable all of the above\n");
6902 exit (*optarg != '?');
6910 if (!strcmp (optarg, "all")) {
6911 for (c = soundhw; c->name; ++c) {
6919 e = strchr (p, ',');
6920 l = !e ? strlen (p) : (size_t) (e - p);
6922 for (c = soundhw; c->name; ++c) {
6923 if (!strncmp (c->name, p, l)) {
6932 "Unknown sound card name (too big to show)\n");
6935 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6940 p += l + (e != NULL);
6944 goto show_valid_cards;
6950 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6952 exit(STATUS_CONTROL_C_EXIT);
6957 #define MAX_NET_CLIENTS 32
6959 int main(int argc, char **argv)
6961 #ifdef CONFIG_GDBSTUB
6963 const char *gdbstub_port;
6965 int i, cdrom_index, pflash_index;
6966 int snapshot, linux_boot;
6967 const char *initrd_filename;
6968 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6969 const char *pflash_filename[MAX_PFLASH];
6970 const char *sd_filename;
6971 const char *mtd_filename;
6972 const char *kernel_filename, *kernel_cmdline;
6973 DisplayState *ds = &display_state;
6974 int cyls, heads, secs, translation;
6975 char net_clients[MAX_NET_CLIENTS][256];
6978 const char *r, *optarg;
6979 CharDriverState *monitor_hd;
6980 char monitor_device[128];
6981 char serial_devices[MAX_SERIAL_PORTS][128];
6982 int serial_device_index;
6983 char parallel_devices[MAX_PARALLEL_PORTS][128];
6984 int parallel_device_index;
6985 const char *loadvm = NULL;
6986 QEMUMachine *machine;
6987 const char *cpu_model;
6988 char usb_devices[MAX_USB_CMDLINE][128];
6989 int usb_devices_index;
6991 const char *pid_file = NULL;
6993 LIST_INIT (&vm_change_state_head);
6996 struct sigaction act;
6997 sigfillset(&act.sa_mask);
6999 act.sa_handler = SIG_IGN;
7000 sigaction(SIGPIPE, &act, NULL);
7003 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7004 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7005 QEMU to run on a single CPU */
7010 h = GetCurrentProcess();
7011 if (GetProcessAffinityMask(h, &mask, &smask)) {
7012 for(i = 0; i < 32; i++) {
7013 if (mask & (1 << i))
7018 SetProcessAffinityMask(h, mask);
7024 register_machines();
7025 machine = first_machine;
7027 initrd_filename = NULL;
7028 for(i = 0; i < MAX_FD; i++)
7029 fd_filename[i] = NULL;
7030 for(i = 0; i < MAX_DISKS; i++)
7031 hd_filename[i] = NULL;
7032 for(i = 0; i < MAX_PFLASH; i++)
7033 pflash_filename[i] = NULL;
7036 mtd_filename = NULL;
7037 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7038 vga_ram_size = VGA_RAM_SIZE;
7039 #ifdef CONFIG_GDBSTUB
7041 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7045 kernel_filename = NULL;
7046 kernel_cmdline = "";
7052 cyls = heads = secs = 0;
7053 translation = BIOS_ATA_TRANSLATION_AUTO;
7054 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7056 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7057 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7058 serial_devices[i][0] = '\0';
7059 serial_device_index = 0;
7061 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7062 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7063 parallel_devices[i][0] = '\0';
7064 parallel_device_index = 0;
7066 usb_devices_index = 0;
7071 /* default mac address of the first network interface */
7079 hd_filename[0] = argv[optind++];
7081 const QEMUOption *popt;
7084 /* Treat --foo the same as -foo. */
7087 popt = qemu_options;
7090 fprintf(stderr, "%s: invalid option -- '%s'\n",
7094 if (!strcmp(popt->name, r + 1))
7098 if (popt->flags & HAS_ARG) {
7099 if (optind >= argc) {
7100 fprintf(stderr, "%s: option '%s' requires an argument\n",
7104 optarg = argv[optind++];
7109 switch(popt->index) {
7111 machine = find_machine(optarg);
7114 printf("Supported machines are:\n");
7115 for(m = first_machine; m != NULL; m = m->next) {
7116 printf("%-10s %s%s\n",
7118 m == first_machine ? " (default)" : "");
7123 case QEMU_OPTION_cpu:
7124 /* hw initialization will check this */
7125 if (optarg[0] == '?') {
7126 #if defined(TARGET_PPC)
7127 ppc_cpu_list(stdout, &fprintf);
7128 #elif defined(TARGET_ARM)
7130 #elif defined(TARGET_MIPS)
7131 mips_cpu_list(stdout, &fprintf);
7132 #elif defined(TARGET_SPARC)
7133 sparc_cpu_list(stdout, &fprintf);
7140 case QEMU_OPTION_initrd:
7141 initrd_filename = optarg;
7143 case QEMU_OPTION_hda:
7144 case QEMU_OPTION_hdb:
7145 case QEMU_OPTION_hdc:
7146 case QEMU_OPTION_hdd:
7149 hd_index = popt->index - QEMU_OPTION_hda;
7150 hd_filename[hd_index] = optarg;
7151 if (hd_index == cdrom_index)
7155 case QEMU_OPTION_mtdblock:
7156 mtd_filename = optarg;
7158 case QEMU_OPTION_sd:
7159 sd_filename = optarg;
7161 case QEMU_OPTION_pflash:
7162 if (pflash_index >= MAX_PFLASH) {
7163 fprintf(stderr, "qemu: too many parallel flash images\n");
7166 pflash_filename[pflash_index++] = optarg;
7168 case QEMU_OPTION_snapshot:
7171 case QEMU_OPTION_hdachs:
7175 cyls = strtol(p, (char **)&p, 0);
7176 if (cyls < 1 || cyls > 16383)
7181 heads = strtol(p, (char **)&p, 0);
7182 if (heads < 1 || heads > 16)
7187 secs = strtol(p, (char **)&p, 0);
7188 if (secs < 1 || secs > 63)
7192 if (!strcmp(p, "none"))
7193 translation = BIOS_ATA_TRANSLATION_NONE;
7194 else if (!strcmp(p, "lba"))
7195 translation = BIOS_ATA_TRANSLATION_LBA;
7196 else if (!strcmp(p, "auto"))
7197 translation = BIOS_ATA_TRANSLATION_AUTO;
7200 } else if (*p != '\0') {
7202 fprintf(stderr, "qemu: invalid physical CHS format\n");
7207 case QEMU_OPTION_nographic:
7208 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7209 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7210 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7213 case QEMU_OPTION_portrait:
7216 case QEMU_OPTION_kernel:
7217 kernel_filename = optarg;
7219 case QEMU_OPTION_append:
7220 kernel_cmdline = optarg;
7222 case QEMU_OPTION_cdrom:
7223 if (cdrom_index >= 0) {
7224 hd_filename[cdrom_index] = optarg;
7227 case QEMU_OPTION_boot:
7228 boot_device = optarg[0];
7229 if (boot_device != 'a' &&
7230 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7232 boot_device != 'n' &&
7234 boot_device != 'c' && boot_device != 'd') {
7235 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7239 case QEMU_OPTION_fda:
7240 fd_filename[0] = optarg;
7242 case QEMU_OPTION_fdb:
7243 fd_filename[1] = optarg;
7246 case QEMU_OPTION_no_fd_bootchk:
7250 case QEMU_OPTION_no_code_copy:
7251 code_copy_enabled = 0;
7253 case QEMU_OPTION_net:
7254 if (nb_net_clients >= MAX_NET_CLIENTS) {
7255 fprintf(stderr, "qemu: too many network clients\n");
7258 pstrcpy(net_clients[nb_net_clients],
7259 sizeof(net_clients[0]),
7264 case QEMU_OPTION_tftp:
7265 tftp_prefix = optarg;
7267 case QEMU_OPTION_bootp:
7268 bootp_filename = optarg;
7271 case QEMU_OPTION_smb:
7272 net_slirp_smb(optarg);
7275 case QEMU_OPTION_redir:
7276 net_slirp_redir(optarg);
7280 case QEMU_OPTION_audio_help:
7284 case QEMU_OPTION_soundhw:
7285 select_soundhw (optarg);
7292 ram_size = atoi(optarg) * 1024 * 1024;
7295 if (ram_size > PHYS_RAM_MAX_SIZE) {
7296 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7297 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7306 mask = cpu_str_to_log_mask(optarg);
7308 printf("Log items (comma separated):\n");
7309 for(item = cpu_log_items; item->mask != 0; item++) {
7310 printf("%-10s %s\n", item->name, item->help);
7317 #ifdef CONFIG_GDBSTUB
7322 gdbstub_port = optarg;
7332 keyboard_layout = optarg;
7334 case QEMU_OPTION_localtime:
7337 case QEMU_OPTION_cirrusvga:
7338 cirrus_vga_enabled = 1;
7341 case QEMU_OPTION_vmsvga:
7342 cirrus_vga_enabled = 0;
7345 case QEMU_OPTION_std_vga:
7346 cirrus_vga_enabled = 0;
7354 w = strtol(p, (char **)&p, 10);
7357 fprintf(stderr, "qemu: invalid resolution or depth\n");
7363 h = strtol(p, (char **)&p, 10);
7368 depth = strtol(p, (char **)&p, 10);
7369 if (depth != 8 && depth != 15 && depth != 16 &&
7370 depth != 24 && depth != 32)
7372 } else if (*p == '\0') {
7373 depth = graphic_depth;
7380 graphic_depth = depth;
7383 case QEMU_OPTION_echr:
7386 term_escape_char = strtol(optarg, &r, 0);
7388 printf("Bad argument to echr\n");
7391 case QEMU_OPTION_monitor:
7392 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7394 case QEMU_OPTION_serial:
7395 if (serial_device_index >= MAX_SERIAL_PORTS) {
7396 fprintf(stderr, "qemu: too many serial ports\n");
7399 pstrcpy(serial_devices[serial_device_index],
7400 sizeof(serial_devices[0]), optarg);
7401 serial_device_index++;
7403 case QEMU_OPTION_parallel:
7404 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7405 fprintf(stderr, "qemu: too many parallel ports\n");
7408 pstrcpy(parallel_devices[parallel_device_index],
7409 sizeof(parallel_devices[0]), optarg);
7410 parallel_device_index++;
7412 case QEMU_OPTION_loadvm:
7415 case QEMU_OPTION_full_screen:
7419 case QEMU_OPTION_no_frame:
7422 case QEMU_OPTION_no_quit:
7426 case QEMU_OPTION_pidfile:
7430 case QEMU_OPTION_win2k_hack:
7431 win2k_install_hack = 1;
7435 case QEMU_OPTION_no_kqemu:
7438 case QEMU_OPTION_kernel_kqemu:
7442 case QEMU_OPTION_usb:
7445 case QEMU_OPTION_usbdevice:
7447 if (usb_devices_index >= MAX_USB_CMDLINE) {
7448 fprintf(stderr, "Too many USB devices\n");
7451 pstrcpy(usb_devices[usb_devices_index],
7452 sizeof(usb_devices[usb_devices_index]),
7454 usb_devices_index++;
7456 case QEMU_OPTION_smp:
7457 smp_cpus = atoi(optarg);
7458 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7459 fprintf(stderr, "Invalid number of CPUs\n");
7463 case QEMU_OPTION_vnc:
7464 vnc_display = optarg;
7466 case QEMU_OPTION_no_acpi:
7469 case QEMU_OPTION_no_reboot:
7472 case QEMU_OPTION_show_cursor:
7475 case QEMU_OPTION_daemonize:
7478 case QEMU_OPTION_option_rom:
7479 if (nb_option_roms >= MAX_OPTION_ROMS) {
7480 fprintf(stderr, "Too many option ROMs\n");
7483 option_rom[nb_option_roms] = optarg;
7486 case QEMU_OPTION_semihosting:
7487 semihosting_enabled = 1;
7489 case QEMU_OPTION_name:
7493 case QEMU_OPTION_prom_env:
7494 if (nb_prom_envs >= MAX_PROM_ENVS) {
7495 fprintf(stderr, "Too many prom variables\n");
7498 prom_envs[nb_prom_envs] = optarg;
7507 if (daemonize && !nographic && vnc_display == NULL) {
7508 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7515 if (pipe(fds) == -1)
7526 len = read(fds[0], &status, 1);
7527 if (len == -1 && (errno == EINTR))
7532 else if (status == 1) {
7533 fprintf(stderr, "Could not acquire pidfile\n");
7551 signal(SIGTSTP, SIG_IGN);
7552 signal(SIGTTOU, SIG_IGN);
7553 signal(SIGTTIN, SIG_IGN);
7557 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7560 write(fds[1], &status, 1);
7562 fprintf(stderr, "Could not acquire pid file\n");
7570 linux_boot = (kernel_filename != NULL);
7573 boot_device != 'n' &&
7574 hd_filename[0] == '\0' &&
7575 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7576 fd_filename[0] == '\0')
7579 /* boot to floppy or the default cd if no hard disk defined yet */
7580 if (hd_filename[0] == '\0' && boot_device == 'c') {
7581 if (fd_filename[0] != '\0')
7587 setvbuf(stdout, NULL, _IOLBF, 0);
7597 /* init network clients */
7598 if (nb_net_clients == 0) {
7599 /* if no clients, we use a default config */
7600 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7602 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7607 for(i = 0;i < nb_net_clients; i++) {
7608 if (net_client_init(net_clients[i]) < 0)
7613 if (boot_device == 'n') {
7614 for (i = 0; i < nb_nics; i++) {
7615 const char *model = nd_table[i].model;
7619 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7620 if (get_image_size(buf) > 0) {
7621 option_rom[nb_option_roms] = strdup(buf);
7627 fprintf(stderr, "No valid PXE rom found for network device\n");
7630 boot_device = 'c'; /* to prevent confusion by the BIOS */
7634 /* init the memory */
7635 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7637 phys_ram_base = qemu_vmalloc(phys_ram_size);
7638 if (!phys_ram_base) {
7639 fprintf(stderr, "Could not allocate physical memory\n");
7643 /* we always create the cdrom drive, even if no disk is there */
7645 if (cdrom_index >= 0) {
7646 bs_table[cdrom_index] = bdrv_new("cdrom");
7647 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7650 /* open the virtual block devices */
7651 for(i = 0; i < MAX_DISKS; i++) {
7652 if (hd_filename[i]) {
7655 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7656 bs_table[i] = bdrv_new(buf);
7658 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7659 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7663 if (i == 0 && cyls != 0) {
7664 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7665 bdrv_set_translation_hint(bs_table[i], translation);
7670 /* we always create at least one floppy disk */
7671 fd_table[0] = bdrv_new("fda");
7672 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7674 for(i = 0; i < MAX_FD; i++) {
7675 if (fd_filename[i]) {
7678 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7679 fd_table[i] = bdrv_new(buf);
7680 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7682 if (fd_filename[i][0] != '\0') {
7683 if (bdrv_open(fd_table[i], fd_filename[i],
7684 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7685 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7693 /* Open the virtual parallel flash block devices */
7694 for(i = 0; i < MAX_PFLASH; i++) {
7695 if (pflash_filename[i]) {
7696 if (!pflash_table[i]) {
7698 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7699 pflash_table[i] = bdrv_new(buf);
7701 if (bdrv_open(pflash_table[i], pflash_filename[i],
7702 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7703 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7704 pflash_filename[i]);
7710 sd_bdrv = bdrv_new ("sd");
7711 /* FIXME: This isn't really a floppy, but it's a reasonable
7713 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7715 if (bdrv_open(sd_bdrv, sd_filename,
7716 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7717 fprintf(stderr, "qemu: could not open SD card image %s\n",
7720 qemu_key_check(sd_bdrv, sd_filename);
7724 mtd_bdrv = bdrv_new ("mtd");
7725 if (bdrv_open(mtd_bdrv, mtd_filename,
7726 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
7727 qemu_key_check(mtd_bdrv, mtd_filename)) {
7728 fprintf(stderr, "qemu: could not open Flash image %s\n",
7730 bdrv_delete(mtd_bdrv);
7735 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7736 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7742 dumb_display_init(ds);
7743 } else if (vnc_display != NULL) {
7744 vnc_display_init(ds, vnc_display);
7746 #if defined(CONFIG_SDL)
7747 sdl_display_init(ds, full_screen, no_frame);
7748 #elif defined(CONFIG_COCOA)
7749 cocoa_display_init(ds, full_screen);
7751 dumb_display_init(ds);
7755 /* Maintain compatibility with multiple stdio monitors */
7756 if (!strcmp(monitor_device,"stdio")) {
7757 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7758 if (!strcmp(serial_devices[i],"mon:stdio")) {
7759 monitor_device[0] = '\0';
7761 } else if (!strcmp(serial_devices[i],"stdio")) {
7762 monitor_device[0] = '\0';
7763 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7768 if (monitor_device[0] != '\0') {
7769 monitor_hd = qemu_chr_open(monitor_device);
7771 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7774 monitor_init(monitor_hd, !nographic);
7777 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7778 const char *devname = serial_devices[i];
7779 if (devname[0] != '\0' && strcmp(devname, "none")) {
7780 serial_hds[i] = qemu_chr_open(devname);
7781 if (!serial_hds[i]) {
7782 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7786 if (!strcmp(devname, "vc"))
7787 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7791 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7792 const char *devname = parallel_devices[i];
7793 if (devname[0] != '\0' && strcmp(devname, "none")) {
7794 parallel_hds[i] = qemu_chr_open(devname);
7795 if (!parallel_hds[i]) {
7796 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7800 if (!strcmp(devname, "vc"))
7801 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7805 machine->init(ram_size, vga_ram_size, boot_device,
7806 ds, fd_filename, snapshot,
7807 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7809 /* init USB devices */
7811 for(i = 0; i < usb_devices_index; i++) {
7812 if (usb_device_add(usb_devices[i]) < 0) {
7813 fprintf(stderr, "Warning: could not add USB device %s\n",
7819 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7820 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7822 #ifdef CONFIG_GDBSTUB
7824 /* XXX: use standard host:port notation and modify options
7826 if (gdbserver_start(gdbstub_port) < 0) {
7827 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7837 /* XXX: simplify init */
7850 len = write(fds[1], &status, 1);
7851 if (len == -1 && (errno == EINTR))
7857 fd = open("/dev/null", O_RDWR);