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 *sd_bdrv;
142 /* point to the block driver where the snapshots are managed */
143 BlockDriverState *bs_snapshots;
145 static DisplayState display_state;
147 const char* keyboard_layout = NULL;
148 int64_t ticks_per_sec;
149 int boot_device = 'c';
151 int pit_min_timer_count = 0;
153 NICInfo nd_table[MAX_NICS];
154 QEMUTimer *gui_timer;
157 int cirrus_vga_enabled = 1;
158 int vmsvga_enabled = 0;
160 int graphic_width = 1024;
161 int graphic_height = 768;
162 int graphic_depth = 8;
164 int graphic_width = 800;
165 int graphic_height = 600;
166 int graphic_depth = 15;
171 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
172 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
174 int win2k_install_hack = 0;
177 static VLANState *first_vlan;
179 const char *vnc_display;
180 #if defined(TARGET_SPARC)
182 #elif defined(TARGET_I386)
187 int acpi_enabled = 1;
191 const char *option_rom[MAX_OPTION_ROMS];
193 int semihosting_enabled = 0;
195 const char *qemu_name;
197 /***********************************************************/
198 /* x86 ISA bus support */
200 target_phys_addr_t isa_mem_base = 0;
203 uint32_t default_ioport_readb(void *opaque, uint32_t address)
205 #ifdef DEBUG_UNUSED_IOPORT
206 fprintf(stderr, "unused inb: port=0x%04x\n", address);
211 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
213 #ifdef DEBUG_UNUSED_IOPORT
214 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
218 /* default is to make two byte accesses */
219 uint32_t default_ioport_readw(void *opaque, uint32_t address)
222 data = ioport_read_table[0][address](ioport_opaque[address], address);
223 address = (address + 1) & (MAX_IOPORTS - 1);
224 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
228 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
230 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
231 address = (address + 1) & (MAX_IOPORTS - 1);
232 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
235 uint32_t default_ioport_readl(void *opaque, uint32_t address)
237 #ifdef DEBUG_UNUSED_IOPORT
238 fprintf(stderr, "unused inl: port=0x%04x\n", address);
243 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
245 #ifdef DEBUG_UNUSED_IOPORT
246 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
250 void init_ioports(void)
254 for(i = 0; i < MAX_IOPORTS; i++) {
255 ioport_read_table[0][i] = default_ioport_readb;
256 ioport_write_table[0][i] = default_ioport_writeb;
257 ioport_read_table[1][i] = default_ioport_readw;
258 ioport_write_table[1][i] = default_ioport_writew;
259 ioport_read_table[2][i] = default_ioport_readl;
260 ioport_write_table[2][i] = default_ioport_writel;
264 /* size is the word size in byte */
265 int register_ioport_read(int start, int length, int size,
266 IOPortReadFunc *func, void *opaque)
272 } else if (size == 2) {
274 } else if (size == 4) {
277 hw_error("register_ioport_read: invalid size");
280 for(i = start; i < start + length; i += size) {
281 ioport_read_table[bsize][i] = func;
282 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
283 hw_error("register_ioport_read: invalid opaque");
284 ioport_opaque[i] = opaque;
289 /* size is the word size in byte */
290 int register_ioport_write(int start, int length, int size,
291 IOPortWriteFunc *func, void *opaque)
297 } else if (size == 2) {
299 } else if (size == 4) {
302 hw_error("register_ioport_write: invalid size");
305 for(i = start; i < start + length; i += size) {
306 ioport_write_table[bsize][i] = func;
307 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
308 hw_error("register_ioport_write: invalid opaque");
309 ioport_opaque[i] = opaque;
314 void isa_unassign_ioport(int start, int length)
318 for(i = start; i < start + length; i++) {
319 ioport_read_table[0][i] = default_ioport_readb;
320 ioport_read_table[1][i] = default_ioport_readw;
321 ioport_read_table[2][i] = default_ioport_readl;
323 ioport_write_table[0][i] = default_ioport_writeb;
324 ioport_write_table[1][i] = default_ioport_writew;
325 ioport_write_table[2][i] = default_ioport_writel;
329 /***********************************************************/
331 void cpu_outb(CPUState *env, int addr, int val)
334 if (loglevel & CPU_LOG_IOPORT)
335 fprintf(logfile, "outb: %04x %02x\n", addr, val);
337 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
340 env->last_io_time = cpu_get_time_fast();
344 void cpu_outw(CPUState *env, int addr, int val)
347 if (loglevel & CPU_LOG_IOPORT)
348 fprintf(logfile, "outw: %04x %04x\n", addr, val);
350 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
353 env->last_io_time = cpu_get_time_fast();
357 void cpu_outl(CPUState *env, int addr, int val)
360 if (loglevel & CPU_LOG_IOPORT)
361 fprintf(logfile, "outl: %04x %08x\n", addr, val);
363 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
366 env->last_io_time = cpu_get_time_fast();
370 int cpu_inb(CPUState *env, int addr)
373 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
375 if (loglevel & CPU_LOG_IOPORT)
376 fprintf(logfile, "inb : %04x %02x\n", addr, val);
380 env->last_io_time = cpu_get_time_fast();
385 int cpu_inw(CPUState *env, int addr)
388 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
390 if (loglevel & CPU_LOG_IOPORT)
391 fprintf(logfile, "inw : %04x %04x\n", addr, val);
395 env->last_io_time = cpu_get_time_fast();
400 int cpu_inl(CPUState *env, int addr)
403 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "inl : %04x %08x\n", addr, val);
410 env->last_io_time = cpu_get_time_fast();
415 /***********************************************************/
416 void hw_error(const char *fmt, ...)
422 fprintf(stderr, "qemu: hardware error: ");
423 vfprintf(stderr, fmt, ap);
424 fprintf(stderr, "\n");
425 for(env = first_cpu; env != NULL; env = env->next_cpu) {
426 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
428 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
430 cpu_dump_state(env, stderr, fprintf, 0);
437 /***********************************************************/
440 static QEMUPutKBDEvent *qemu_put_kbd_event;
441 static void *qemu_put_kbd_event_opaque;
442 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
443 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
445 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
447 qemu_put_kbd_event_opaque = opaque;
448 qemu_put_kbd_event = func;
451 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
452 void *opaque, int absolute,
455 QEMUPutMouseEntry *s, *cursor;
457 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
461 s->qemu_put_mouse_event = func;
462 s->qemu_put_mouse_event_opaque = opaque;
463 s->qemu_put_mouse_event_absolute = absolute;
464 s->qemu_put_mouse_event_name = qemu_strdup(name);
467 if (!qemu_put_mouse_event_head) {
468 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
472 cursor = qemu_put_mouse_event_head;
473 while (cursor->next != NULL)
474 cursor = cursor->next;
477 qemu_put_mouse_event_current = s;
482 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
484 QEMUPutMouseEntry *prev = NULL, *cursor;
486 if (!qemu_put_mouse_event_head || entry == NULL)
489 cursor = qemu_put_mouse_event_head;
490 while (cursor != NULL && cursor != entry) {
492 cursor = cursor->next;
495 if (cursor == NULL) // does not exist or list empty
497 else if (prev == NULL) { // entry is head
498 qemu_put_mouse_event_head = cursor->next;
499 if (qemu_put_mouse_event_current == entry)
500 qemu_put_mouse_event_current = cursor->next;
501 qemu_free(entry->qemu_put_mouse_event_name);
506 prev->next = entry->next;
508 if (qemu_put_mouse_event_current == entry)
509 qemu_put_mouse_event_current = prev;
511 qemu_free(entry->qemu_put_mouse_event_name);
515 void kbd_put_keycode(int keycode)
517 if (qemu_put_kbd_event) {
518 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
522 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
524 QEMUPutMouseEvent *mouse_event;
525 void *mouse_event_opaque;
527 if (!qemu_put_mouse_event_current) {
532 qemu_put_mouse_event_current->qemu_put_mouse_event;
534 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
537 mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
541 int kbd_mouse_is_absolute(void)
543 if (!qemu_put_mouse_event_current)
546 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
549 void (*kbd_mouse_set)(int x, int y, int on) = NULL;
550 void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
551 uint8_t *image, uint8_t *mask) = NULL;
553 void do_info_mice(void)
555 QEMUPutMouseEntry *cursor;
558 if (!qemu_put_mouse_event_head) {
559 term_printf("No mouse devices connected\n");
563 term_printf("Mouse devices available:\n");
564 cursor = qemu_put_mouse_event_head;
565 while (cursor != NULL) {
566 term_printf("%c Mouse #%d: %s\n",
567 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
568 index, cursor->qemu_put_mouse_event_name);
570 cursor = cursor->next;
574 void do_mouse_set(int index)
576 QEMUPutMouseEntry *cursor;
579 if (!qemu_put_mouse_event_head) {
580 term_printf("No mouse devices connected\n");
584 cursor = qemu_put_mouse_event_head;
585 while (cursor != NULL && index != i) {
587 cursor = cursor->next;
591 qemu_put_mouse_event_current = cursor;
593 term_printf("Mouse at given index not found\n");
596 /* compute with 96 bit intermediate result: (a*b)/c */
597 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
602 #ifdef WORDS_BIGENDIAN
612 rl = (uint64_t)u.l.low * (uint64_t)b;
613 rh = (uint64_t)u.l.high * (uint64_t)b;
616 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
620 /***********************************************************/
621 /* real time host monotonic timer */
623 #define QEMU_TIMER_BASE 1000000000LL
627 static int64_t clock_freq;
629 static void init_get_clock(void)
633 ret = QueryPerformanceFrequency(&freq);
635 fprintf(stderr, "Could not calibrate ticks\n");
638 clock_freq = freq.QuadPart;
641 static int64_t get_clock(void)
644 QueryPerformanceCounter(&ti);
645 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
650 static int use_rt_clock;
652 static void init_get_clock(void)
655 #if defined(__linux__)
658 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
665 static int64_t get_clock(void)
667 #if defined(__linux__)
670 clock_gettime(CLOCK_MONOTONIC, &ts);
671 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
675 /* XXX: using gettimeofday leads to problems if the date
676 changes, so it should be avoided. */
678 gettimeofday(&tv, NULL);
679 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
685 /***********************************************************/
686 /* guest cycle counter */
688 static int64_t cpu_ticks_prev;
689 static int64_t cpu_ticks_offset;
690 static int64_t cpu_clock_offset;
691 static int cpu_ticks_enabled;
693 /* return the host CPU cycle counter and handle stop/restart */
694 int64_t cpu_get_ticks(void)
696 if (!cpu_ticks_enabled) {
697 return cpu_ticks_offset;
700 ticks = cpu_get_real_ticks();
701 if (cpu_ticks_prev > ticks) {
702 /* Note: non increasing ticks may happen if the host uses
704 cpu_ticks_offset += cpu_ticks_prev - ticks;
706 cpu_ticks_prev = ticks;
707 return ticks + cpu_ticks_offset;
711 /* return the host CPU monotonic timer and handle stop/restart */
712 static int64_t cpu_get_clock(void)
715 if (!cpu_ticks_enabled) {
716 return cpu_clock_offset;
719 return ti + cpu_clock_offset;
723 /* enable cpu_get_ticks() */
724 void cpu_enable_ticks(void)
726 if (!cpu_ticks_enabled) {
727 cpu_ticks_offset -= cpu_get_real_ticks();
728 cpu_clock_offset -= get_clock();
729 cpu_ticks_enabled = 1;
733 /* disable cpu_get_ticks() : the clock is stopped. You must not call
734 cpu_get_ticks() after that. */
735 void cpu_disable_ticks(void)
737 if (cpu_ticks_enabled) {
738 cpu_ticks_offset = cpu_get_ticks();
739 cpu_clock_offset = cpu_get_clock();
740 cpu_ticks_enabled = 0;
744 /***********************************************************/
747 #define QEMU_TIMER_REALTIME 0
748 #define QEMU_TIMER_VIRTUAL 1
752 /* XXX: add frequency */
760 struct QEMUTimer *next;
766 static QEMUTimer *active_timers[2];
768 static MMRESULT timerID;
769 static HANDLE host_alarm = NULL;
770 static unsigned int period = 1;
772 /* frequency of the times() clock tick */
773 static int timer_freq;
776 QEMUClock *qemu_new_clock(int type)
779 clock = qemu_mallocz(sizeof(QEMUClock));
786 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
790 ts = qemu_mallocz(sizeof(QEMUTimer));
797 void qemu_free_timer(QEMUTimer *ts)
802 /* stop a timer, but do not dealloc it */
803 void qemu_del_timer(QEMUTimer *ts)
807 /* NOTE: this code must be signal safe because
808 qemu_timer_expired() can be called from a signal. */
809 pt = &active_timers[ts->clock->type];
822 /* modify the current timer so that it will be fired when current_time
823 >= expire_time. The corresponding callback will be called. */
824 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
830 /* add the timer in the sorted list */
831 /* NOTE: this code must be signal safe because
832 qemu_timer_expired() can be called from a signal. */
833 pt = &active_timers[ts->clock->type];
838 if (t->expire_time > expire_time)
842 ts->expire_time = expire_time;
847 int qemu_timer_pending(QEMUTimer *ts)
850 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
857 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
861 return (timer_head->expire_time <= current_time);
864 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
870 if (!ts || ts->expire_time > current_time)
872 /* remove timer from the list before calling the callback */
873 *ptimer_head = ts->next;
876 /* run the callback (the timer list can be modified) */
881 int64_t qemu_get_clock(QEMUClock *clock)
883 switch(clock->type) {
884 case QEMU_TIMER_REALTIME:
885 return get_clock() / 1000000;
887 case QEMU_TIMER_VIRTUAL:
888 return cpu_get_clock();
892 static void init_timers(void)
895 ticks_per_sec = QEMU_TIMER_BASE;
896 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
897 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
901 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
903 uint64_t expire_time;
905 if (qemu_timer_pending(ts)) {
906 expire_time = ts->expire_time;
910 qemu_put_be64(f, expire_time);
913 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
915 uint64_t expire_time;
917 expire_time = qemu_get_be64(f);
918 if (expire_time != -1) {
919 qemu_mod_timer(ts, expire_time);
925 static void timer_save(QEMUFile *f, void *opaque)
927 if (cpu_ticks_enabled) {
928 hw_error("cannot save state if virtual timers are running");
930 qemu_put_be64s(f, &cpu_ticks_offset);
931 qemu_put_be64s(f, &ticks_per_sec);
932 qemu_put_be64s(f, &cpu_clock_offset);
935 static int timer_load(QEMUFile *f, void *opaque, int version_id)
937 if (version_id != 1 && version_id != 2)
939 if (cpu_ticks_enabled) {
942 qemu_get_be64s(f, &cpu_ticks_offset);
943 qemu_get_be64s(f, &ticks_per_sec);
944 if (version_id == 2) {
945 qemu_get_be64s(f, &cpu_clock_offset);
951 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
952 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
954 static void host_alarm_handler(int host_signum)
958 #define DISP_FREQ 1000
960 static int64_t delta_min = INT64_MAX;
961 static int64_t delta_max, delta_cum, last_clock, delta, ti;
963 ti = qemu_get_clock(vm_clock);
964 if (last_clock != 0) {
965 delta = ti - last_clock;
966 if (delta < delta_min)
968 if (delta > delta_max)
971 if (++count == DISP_FREQ) {
972 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
973 muldiv64(delta_min, 1000000, ticks_per_sec),
974 muldiv64(delta_max, 1000000, ticks_per_sec),
975 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
976 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
978 delta_min = INT64_MAX;
986 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
987 qemu_get_clock(vm_clock)) ||
988 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
989 qemu_get_clock(rt_clock))) {
991 SetEvent(host_alarm);
993 CPUState *env = cpu_single_env;
995 /* stop the currently executing cpu because a timer occured */
996 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
998 if (env->kqemu_enabled) {
999 kqemu_cpu_interrupt(env);
1008 #if defined(__linux__)
1010 #define RTC_FREQ 1024
1014 static int start_rtc_timer(void)
1016 rtc_fd = open("/dev/rtc", O_RDONLY);
1019 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1020 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1021 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1022 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1025 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1030 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1036 static int start_rtc_timer(void)
1041 #endif /* !defined(__linux__) */
1043 #endif /* !defined(_WIN32) */
1045 static void init_timer_alarm(void)
1052 ZeroMemory(&tc, sizeof(TIMECAPS));
1053 timeGetDevCaps(&tc, sizeof(TIMECAPS));
1054 if (period < tc.wPeriodMin)
1055 period = tc.wPeriodMin;
1056 timeBeginPeriod(period);
1057 timerID = timeSetEvent(1, // interval (ms)
1058 period, // resolution
1059 host_alarm_handler, // function
1060 (DWORD)&count, // user parameter
1061 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1063 perror("failed timer alarm");
1066 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1068 perror("failed CreateEvent");
1071 qemu_add_wait_object(host_alarm, NULL, NULL);
1073 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1076 struct sigaction act;
1077 struct itimerval itv;
1079 /* get times() syscall frequency */
1080 timer_freq = sysconf(_SC_CLK_TCK);
1083 sigfillset(&act.sa_mask);
1085 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1086 act.sa_flags |= SA_ONSTACK;
1088 act.sa_handler = host_alarm_handler;
1089 sigaction(SIGALRM, &act, NULL);
1091 itv.it_interval.tv_sec = 0;
1092 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1093 itv.it_value.tv_sec = 0;
1094 itv.it_value.tv_usec = 10 * 1000;
1095 setitimer(ITIMER_REAL, &itv, NULL);
1096 /* we probe the tick duration of the kernel to inform the user if
1097 the emulated kernel requested a too high timer frequency */
1098 getitimer(ITIMER_REAL, &itv);
1100 #if defined(__linux__)
1101 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1102 have timers with 1 ms resolution. The correct solution will
1103 be to use the POSIX real time timers available in recent
1105 if (itv.it_interval.tv_usec > 1000 || 1) {
1106 /* try to use /dev/rtc to have a faster timer */
1107 if (start_rtc_timer() < 0)
1109 /* disable itimer */
1110 itv.it_interval.tv_sec = 0;
1111 itv.it_interval.tv_usec = 0;
1112 itv.it_value.tv_sec = 0;
1113 itv.it_value.tv_usec = 0;
1114 setitimer(ITIMER_REAL, &itv, NULL);
1117 sigaction(SIGIO, &act, NULL);
1118 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1119 fcntl(rtc_fd, F_SETOWN, getpid());
1121 #endif /* defined(__linux__) */
1124 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1125 PIT_FREQ) / 1000000;
1131 void quit_timers(void)
1134 timeKillEvent(timerID);
1135 timeEndPeriod(period);
1137 CloseHandle(host_alarm);
1143 /***********************************************************/
1144 /* character device */
1146 static void qemu_chr_event(CharDriverState *s, int event)
1150 s->chr_event(s->handler_opaque, event);
1153 static void qemu_chr_reset_bh(void *opaque)
1155 CharDriverState *s = opaque;
1156 qemu_chr_event(s, CHR_EVENT_RESET);
1157 qemu_bh_delete(s->bh);
1161 void qemu_chr_reset(CharDriverState *s)
1163 if (s->bh == NULL) {
1164 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1165 qemu_bh_schedule(s->bh);
1169 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1171 return s->chr_write(s, buf, len);
1174 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1178 return s->chr_ioctl(s, cmd, arg);
1181 int qemu_chr_can_read(CharDriverState *s)
1183 if (!s->chr_can_read)
1185 return s->chr_can_read(s->handler_opaque);
1188 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1190 s->chr_read(s->handler_opaque, buf, len);
1194 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1199 vsnprintf(buf, sizeof(buf), fmt, ap);
1200 qemu_chr_write(s, buf, strlen(buf));
1204 void qemu_chr_send_event(CharDriverState *s, int event)
1206 if (s->chr_send_event)
1207 s->chr_send_event(s, event);
1210 void qemu_chr_add_handlers(CharDriverState *s,
1211 IOCanRWHandler *fd_can_read,
1212 IOReadHandler *fd_read,
1213 IOEventHandler *fd_event,
1216 s->chr_can_read = fd_can_read;
1217 s->chr_read = fd_read;
1218 s->chr_event = fd_event;
1219 s->handler_opaque = opaque;
1220 if (s->chr_update_read_handler)
1221 s->chr_update_read_handler(s);
1224 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1229 static CharDriverState *qemu_chr_open_null(void)
1231 CharDriverState *chr;
1233 chr = qemu_mallocz(sizeof(CharDriverState));
1236 chr->chr_write = null_chr_write;
1240 /* MUX driver for serial I/O splitting */
1241 static int term_timestamps;
1242 static int64_t term_timestamps_start;
1245 IOCanRWHandler *chr_can_read[MAX_MUX];
1246 IOReadHandler *chr_read[MAX_MUX];
1247 IOEventHandler *chr_event[MAX_MUX];
1248 void *ext_opaque[MAX_MUX];
1249 CharDriverState *drv;
1251 int term_got_escape;
1256 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1258 MuxDriver *d = chr->opaque;
1260 if (!term_timestamps) {
1261 ret = d->drv->chr_write(d->drv, buf, len);
1266 for(i = 0; i < len; i++) {
1267 ret += d->drv->chr_write(d->drv, buf+i, 1);
1268 if (buf[i] == '\n') {
1274 if (term_timestamps_start == -1)
1275 term_timestamps_start = ti;
1276 ti -= term_timestamps_start;
1277 secs = ti / 1000000000;
1278 snprintf(buf1, sizeof(buf1),
1279 "[%02d:%02d:%02d.%03d] ",
1283 (int)((ti / 1000000) % 1000));
1284 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1291 static char *mux_help[] = {
1292 "% h print this help\n\r",
1293 "% x exit emulator\n\r",
1294 "% s save disk data back to file (if -snapshot)\n\r",
1295 "% t toggle console timestamps\n\r"
1296 "% b send break (magic sysrq)\n\r",
1297 "% c switch between console and monitor\n\r",
1302 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1303 static void mux_print_help(CharDriverState *chr)
1306 char ebuf[15] = "Escape-Char";
1307 char cbuf[50] = "\n\r";
1309 if (term_escape_char > 0 && term_escape_char < 26) {
1310 sprintf(cbuf,"\n\r");
1311 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1313 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1315 chr->chr_write(chr, cbuf, strlen(cbuf));
1316 for (i = 0; mux_help[i] != NULL; i++) {
1317 for (j=0; mux_help[i][j] != '\0'; j++) {
1318 if (mux_help[i][j] == '%')
1319 chr->chr_write(chr, ebuf, strlen(ebuf));
1321 chr->chr_write(chr, &mux_help[i][j], 1);
1326 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1328 if (d->term_got_escape) {
1329 d->term_got_escape = 0;
1330 if (ch == term_escape_char)
1335 mux_print_help(chr);
1339 char *term = "QEMU: Terminated\n\r";
1340 chr->chr_write(chr,term,strlen(term));
1347 for (i = 0; i < MAX_DISKS; i++) {
1349 bdrv_commit(bs_table[i]);
1355 chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1358 /* Switch to the next registered device */
1360 if (chr->focus >= d->mux_cnt)
1364 term_timestamps = !term_timestamps;
1365 term_timestamps_start = -1;
1368 } else if (ch == term_escape_char) {
1369 d->term_got_escape = 1;
1377 static int mux_chr_can_read(void *opaque)
1379 CharDriverState *chr = opaque;
1380 MuxDriver *d = chr->opaque;
1381 if (d->chr_can_read[chr->focus])
1382 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1386 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1388 CharDriverState *chr = opaque;
1389 MuxDriver *d = chr->opaque;
1391 for(i = 0; i < size; i++)
1392 if (mux_proc_byte(chr, d, buf[i]))
1393 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1396 static void mux_chr_event(void *opaque, int event)
1398 CharDriverState *chr = opaque;
1399 MuxDriver *d = chr->opaque;
1402 /* Send the event to all registered listeners */
1403 for (i = 0; i < d->mux_cnt; i++)
1404 if (d->chr_event[i])
1405 d->chr_event[i](d->ext_opaque[i], event);
1408 static void mux_chr_update_read_handler(CharDriverState *chr)
1410 MuxDriver *d = chr->opaque;
1412 if (d->mux_cnt >= MAX_MUX) {
1413 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1416 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1417 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1418 d->chr_read[d->mux_cnt] = chr->chr_read;
1419 d->chr_event[d->mux_cnt] = chr->chr_event;
1420 /* Fix up the real driver with mux routines */
1421 if (d->mux_cnt == 0) {
1422 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1423 mux_chr_event, chr);
1425 chr->focus = d->mux_cnt;
1429 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1431 CharDriverState *chr;
1434 chr = qemu_mallocz(sizeof(CharDriverState));
1437 d = qemu_mallocz(sizeof(MuxDriver));
1446 chr->chr_write = mux_chr_write;
1447 chr->chr_update_read_handler = mux_chr_update_read_handler;
1454 static void socket_cleanup(void)
1459 static int socket_init(void)
1464 ret = WSAStartup(MAKEWORD(2,2), &Data);
1466 err = WSAGetLastError();
1467 fprintf(stderr, "WSAStartup: %d\n", err);
1470 atexit(socket_cleanup);
1474 static int send_all(int fd, const uint8_t *buf, int len1)
1480 ret = send(fd, buf, len, 0);
1483 errno = WSAGetLastError();
1484 if (errno != WSAEWOULDBLOCK) {
1487 } else if (ret == 0) {
1497 void socket_set_nonblock(int fd)
1499 unsigned long opt = 1;
1500 ioctlsocket(fd, FIONBIO, &opt);
1505 static int unix_write(int fd, const uint8_t *buf, int len1)
1511 ret = write(fd, buf, len);
1513 if (errno != EINTR && errno != EAGAIN)
1515 } else if (ret == 0) {
1525 static inline int send_all(int fd, const uint8_t *buf, int len1)
1527 return unix_write(fd, buf, len1);
1530 void socket_set_nonblock(int fd)
1532 fcntl(fd, F_SETFL, O_NONBLOCK);
1534 #endif /* !_WIN32 */
1543 #define STDIO_MAX_CLIENTS 1
1544 static int stdio_nb_clients = 0;
1546 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1548 FDCharDriver *s = chr->opaque;
1549 return unix_write(s->fd_out, buf, len);
1552 static int fd_chr_read_poll(void *opaque)
1554 CharDriverState *chr = opaque;
1555 FDCharDriver *s = chr->opaque;
1557 s->max_size = qemu_chr_can_read(chr);
1561 static void fd_chr_read(void *opaque)
1563 CharDriverState *chr = opaque;
1564 FDCharDriver *s = chr->opaque;
1569 if (len > s->max_size)
1573 size = read(s->fd_in, buf, len);
1575 /* FD has been closed. Remove it from the active list. */
1576 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1580 qemu_chr_read(chr, buf, size);
1584 static void fd_chr_update_read_handler(CharDriverState *chr)
1586 FDCharDriver *s = chr->opaque;
1588 if (s->fd_in >= 0) {
1589 if (nographic && s->fd_in == 0) {
1591 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1592 fd_chr_read, NULL, chr);
1597 /* open a character device to a unix fd */
1598 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1600 CharDriverState *chr;
1603 chr = qemu_mallocz(sizeof(CharDriverState));
1606 s = qemu_mallocz(sizeof(FDCharDriver));
1614 chr->chr_write = fd_chr_write;
1615 chr->chr_update_read_handler = fd_chr_update_read_handler;
1617 qemu_chr_reset(chr);
1622 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1626 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1629 return qemu_chr_open_fd(-1, fd_out);
1632 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1635 char filename_in[256], filename_out[256];
1637 snprintf(filename_in, 256, "%s.in", filename);
1638 snprintf(filename_out, 256, "%s.out", filename);
1639 fd_in = open(filename_in, O_RDWR | O_BINARY);
1640 fd_out = open(filename_out, O_RDWR | O_BINARY);
1641 if (fd_in < 0 || fd_out < 0) {
1646 fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1650 return qemu_chr_open_fd(fd_in, fd_out);
1654 /* for STDIO, we handle the case where several clients use it
1657 #define TERM_FIFO_MAX_SIZE 1
1659 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1660 static int term_fifo_size;
1662 static int stdio_read_poll(void *opaque)
1664 CharDriverState *chr = opaque;
1666 /* try to flush the queue if needed */
1667 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1668 qemu_chr_read(chr, term_fifo, 1);
1671 /* see if we can absorb more chars */
1672 if (term_fifo_size == 0)
1678 static void stdio_read(void *opaque)
1682 CharDriverState *chr = opaque;
1684 size = read(0, buf, 1);
1686 /* stdin has been closed. Remove it from the active list. */
1687 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1691 if (qemu_chr_can_read(chr) > 0) {
1692 qemu_chr_read(chr, buf, 1);
1693 } else if (term_fifo_size == 0) {
1694 term_fifo[term_fifo_size++] = buf[0];
1699 /* init terminal so that we can grab keys */
1700 static struct termios oldtty;
1701 static int old_fd0_flags;
1703 static void term_exit(void)
1705 tcsetattr (0, TCSANOW, &oldtty);
1706 fcntl(0, F_SETFL, old_fd0_flags);
1709 static void term_init(void)
1713 tcgetattr (0, &tty);
1715 old_fd0_flags = fcntl(0, F_GETFL);
1717 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1718 |INLCR|IGNCR|ICRNL|IXON);
1719 tty.c_oflag |= OPOST;
1720 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1721 /* if graphical mode, we allow Ctrl-C handling */
1723 tty.c_lflag &= ~ISIG;
1724 tty.c_cflag &= ~(CSIZE|PARENB);
1727 tty.c_cc[VTIME] = 0;
1729 tcsetattr (0, TCSANOW, &tty);
1733 fcntl(0, F_SETFL, O_NONBLOCK);
1736 static CharDriverState *qemu_chr_open_stdio(void)
1738 CharDriverState *chr;
1740 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1742 chr = qemu_chr_open_fd(0, 1);
1743 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1750 #if defined(__linux__)
1751 static CharDriverState *qemu_chr_open_pty(void)
1754 char slave_name[1024];
1755 int master_fd, slave_fd;
1757 /* Not satisfying */
1758 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1762 /* Disabling local echo and line-buffered output */
1763 tcgetattr (master_fd, &tty);
1764 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1766 tty.c_cc[VTIME] = 0;
1767 tcsetattr (master_fd, TCSAFLUSH, &tty);
1769 fprintf(stderr, "char device redirected to %s\n", slave_name);
1770 return qemu_chr_open_fd(master_fd, master_fd);
1773 static void tty_serial_init(int fd, int speed,
1774 int parity, int data_bits, int stop_bits)
1780 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1781 speed, parity, data_bits, stop_bits);
1783 tcgetattr (fd, &tty);
1825 cfsetispeed(&tty, spd);
1826 cfsetospeed(&tty, spd);
1828 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1829 |INLCR|IGNCR|ICRNL|IXON);
1830 tty.c_oflag |= OPOST;
1831 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1832 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1853 tty.c_cflag |= PARENB;
1856 tty.c_cflag |= PARENB | PARODD;
1860 tty.c_cflag |= CSTOPB;
1862 tcsetattr (fd, TCSANOW, &tty);
1865 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1867 FDCharDriver *s = chr->opaque;
1870 case CHR_IOCTL_SERIAL_SET_PARAMS:
1872 QEMUSerialSetParams *ssp = arg;
1873 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1874 ssp->data_bits, ssp->stop_bits);
1877 case CHR_IOCTL_SERIAL_SET_BREAK:
1879 int enable = *(int *)arg;
1881 tcsendbreak(s->fd_in, 1);
1890 static CharDriverState *qemu_chr_open_tty(const char *filename)
1892 CharDriverState *chr;
1895 fd = open(filename, O_RDWR | O_NONBLOCK);
1898 fcntl(fd, F_SETFL, O_NONBLOCK);
1899 tty_serial_init(fd, 115200, 'N', 8, 1);
1900 chr = qemu_chr_open_fd(fd, fd);
1903 chr->chr_ioctl = tty_serial_ioctl;
1904 qemu_chr_reset(chr);
1911 } ParallelCharDriver;
1913 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1915 if (s->mode != mode) {
1917 if (ioctl(s->fd, PPSETMODE, &m) < 0)
1924 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1926 ParallelCharDriver *drv = chr->opaque;
1931 case CHR_IOCTL_PP_READ_DATA:
1932 if (ioctl(fd, PPRDATA, &b) < 0)
1934 *(uint8_t *)arg = b;
1936 case CHR_IOCTL_PP_WRITE_DATA:
1937 b = *(uint8_t *)arg;
1938 if (ioctl(fd, PPWDATA, &b) < 0)
1941 case CHR_IOCTL_PP_READ_CONTROL:
1942 if (ioctl(fd, PPRCONTROL, &b) < 0)
1944 /* Linux gives only the lowest bits, and no way to know data
1945 direction! For better compatibility set the fixed upper
1947 *(uint8_t *)arg = b | 0xc0;
1949 case CHR_IOCTL_PP_WRITE_CONTROL:
1950 b = *(uint8_t *)arg;
1951 if (ioctl(fd, PPWCONTROL, &b) < 0)
1954 case CHR_IOCTL_PP_READ_STATUS:
1955 if (ioctl(fd, PPRSTATUS, &b) < 0)
1957 *(uint8_t *)arg = b;
1959 case CHR_IOCTL_PP_EPP_READ_ADDR:
1960 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1961 struct ParallelIOArg *parg = arg;
1962 int n = read(fd, parg->buffer, parg->count);
1963 if (n != parg->count) {
1968 case CHR_IOCTL_PP_EPP_READ:
1969 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1970 struct ParallelIOArg *parg = arg;
1971 int n = read(fd, parg->buffer, parg->count);
1972 if (n != parg->count) {
1977 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1978 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1979 struct ParallelIOArg *parg = arg;
1980 int n = write(fd, parg->buffer, parg->count);
1981 if (n != parg->count) {
1986 case CHR_IOCTL_PP_EPP_WRITE:
1987 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1988 struct ParallelIOArg *parg = arg;
1989 int n = write(fd, parg->buffer, parg->count);
1990 if (n != parg->count) {
2001 static void pp_close(CharDriverState *chr)
2003 ParallelCharDriver *drv = chr->opaque;
2006 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2007 ioctl(fd, PPRELEASE);
2012 static CharDriverState *qemu_chr_open_pp(const char *filename)
2014 CharDriverState *chr;
2015 ParallelCharDriver *drv;
2018 fd = open(filename, O_RDWR);
2022 if (ioctl(fd, PPCLAIM) < 0) {
2027 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2033 drv->mode = IEEE1284_MODE_COMPAT;
2035 chr = qemu_mallocz(sizeof(CharDriverState));
2041 chr->chr_write = null_chr_write;
2042 chr->chr_ioctl = pp_ioctl;
2043 chr->chr_close = pp_close;
2046 qemu_chr_reset(chr);
2052 static CharDriverState *qemu_chr_open_pty(void)
2058 #endif /* !defined(_WIN32) */
2063 HANDLE hcom, hrecv, hsend;
2064 OVERLAPPED orecv, osend;
2069 #define NSENDBUF 2048
2070 #define NRECVBUF 2048
2071 #define MAXCONNECT 1
2072 #define NTIMEOUT 5000
2074 static int win_chr_poll(void *opaque);
2075 static int win_chr_pipe_poll(void *opaque);
2077 static void win_chr_close(CharDriverState *chr)
2079 WinCharState *s = chr->opaque;
2082 CloseHandle(s->hsend);
2086 CloseHandle(s->hrecv);
2090 CloseHandle(s->hcom);
2094 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2096 qemu_del_polling_cb(win_chr_poll, chr);
2099 static int win_chr_init(CharDriverState *chr, const char *filename)
2101 WinCharState *s = chr->opaque;
2103 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2108 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2110 fprintf(stderr, "Failed CreateEvent\n");
2113 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2115 fprintf(stderr, "Failed CreateEvent\n");
2119 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2120 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2121 if (s->hcom == INVALID_HANDLE_VALUE) {
2122 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2127 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2128 fprintf(stderr, "Failed SetupComm\n");
2132 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2133 size = sizeof(COMMCONFIG);
2134 GetDefaultCommConfig(filename, &comcfg, &size);
2135 comcfg.dcb.DCBlength = sizeof(DCB);
2136 CommConfigDialog(filename, NULL, &comcfg);
2138 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2139 fprintf(stderr, "Failed SetCommState\n");
2143 if (!SetCommMask(s->hcom, EV_ERR)) {
2144 fprintf(stderr, "Failed SetCommMask\n");
2148 cto.ReadIntervalTimeout = MAXDWORD;
2149 if (!SetCommTimeouts(s->hcom, &cto)) {
2150 fprintf(stderr, "Failed SetCommTimeouts\n");
2154 if (!ClearCommError(s->hcom, &err, &comstat)) {
2155 fprintf(stderr, "Failed ClearCommError\n");
2158 qemu_add_polling_cb(win_chr_poll, chr);
2166 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2168 WinCharState *s = chr->opaque;
2169 DWORD len, ret, size, err;
2172 ZeroMemory(&s->osend, sizeof(s->osend));
2173 s->osend.hEvent = s->hsend;
2176 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2178 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2180 err = GetLastError();
2181 if (err == ERROR_IO_PENDING) {
2182 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2200 static int win_chr_read_poll(CharDriverState *chr)
2202 WinCharState *s = chr->opaque;
2204 s->max_size = qemu_chr_can_read(chr);
2208 static void win_chr_readfile(CharDriverState *chr)
2210 WinCharState *s = chr->opaque;
2215 ZeroMemory(&s->orecv, sizeof(s->orecv));
2216 s->orecv.hEvent = s->hrecv;
2217 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2219 err = GetLastError();
2220 if (err == ERROR_IO_PENDING) {
2221 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2226 qemu_chr_read(chr, buf, size);
2230 static void win_chr_read(CharDriverState *chr)
2232 WinCharState *s = chr->opaque;
2234 if (s->len > s->max_size)
2235 s->len = s->max_size;
2239 win_chr_readfile(chr);
2242 static int win_chr_poll(void *opaque)
2244 CharDriverState *chr = opaque;
2245 WinCharState *s = chr->opaque;
2249 ClearCommError(s->hcom, &comerr, &status);
2250 if (status.cbInQue > 0) {
2251 s->len = status.cbInQue;
2252 win_chr_read_poll(chr);
2259 static CharDriverState *qemu_chr_open_win(const char *filename)
2261 CharDriverState *chr;
2264 chr = qemu_mallocz(sizeof(CharDriverState));
2267 s = qemu_mallocz(sizeof(WinCharState));
2273 chr->chr_write = win_chr_write;
2274 chr->chr_close = win_chr_close;
2276 if (win_chr_init(chr, filename) < 0) {
2281 qemu_chr_reset(chr);
2285 static int win_chr_pipe_poll(void *opaque)
2287 CharDriverState *chr = opaque;
2288 WinCharState *s = chr->opaque;
2291 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2294 win_chr_read_poll(chr);
2301 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2303 WinCharState *s = chr->opaque;
2311 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2313 fprintf(stderr, "Failed CreateEvent\n");
2316 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2318 fprintf(stderr, "Failed CreateEvent\n");
2322 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2323 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2324 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2326 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2327 if (s->hcom == INVALID_HANDLE_VALUE) {
2328 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2333 ZeroMemory(&ov, sizeof(ov));
2334 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2335 ret = ConnectNamedPipe(s->hcom, &ov);
2337 fprintf(stderr, "Failed ConnectNamedPipe\n");
2341 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2343 fprintf(stderr, "Failed GetOverlappedResult\n");
2345 CloseHandle(ov.hEvent);
2352 CloseHandle(ov.hEvent);
2355 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2364 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2366 CharDriverState *chr;
2369 chr = qemu_mallocz(sizeof(CharDriverState));
2372 s = qemu_mallocz(sizeof(WinCharState));
2378 chr->chr_write = win_chr_write;
2379 chr->chr_close = win_chr_close;
2381 if (win_chr_pipe_init(chr, filename) < 0) {
2386 qemu_chr_reset(chr);
2390 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2392 CharDriverState *chr;
2395 chr = qemu_mallocz(sizeof(CharDriverState));
2398 s = qemu_mallocz(sizeof(WinCharState));
2405 chr->chr_write = win_chr_write;
2406 qemu_chr_reset(chr);
2410 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2414 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2415 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2416 if (fd_out == INVALID_HANDLE_VALUE)
2419 return qemu_chr_open_win_file(fd_out);
2423 /***********************************************************/
2424 /* UDP Net console */
2428 struct sockaddr_in daddr;
2435 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2437 NetCharDriver *s = chr->opaque;
2439 return sendto(s->fd, buf, len, 0,
2440 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2443 static int udp_chr_read_poll(void *opaque)
2445 CharDriverState *chr = opaque;
2446 NetCharDriver *s = chr->opaque;
2448 s->max_size = qemu_chr_can_read(chr);
2450 /* If there were any stray characters in the queue process them
2453 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2454 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2456 s->max_size = qemu_chr_can_read(chr);
2461 static void udp_chr_read(void *opaque)
2463 CharDriverState *chr = opaque;
2464 NetCharDriver *s = chr->opaque;
2466 if (s->max_size == 0)
2468 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2469 s->bufptr = s->bufcnt;
2474 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2475 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2477 s->max_size = qemu_chr_can_read(chr);
2481 static void udp_chr_update_read_handler(CharDriverState *chr)
2483 NetCharDriver *s = chr->opaque;
2486 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2487 udp_chr_read, NULL, chr);
2491 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2493 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2495 int parse_host_src_port(struct sockaddr_in *haddr,
2496 struct sockaddr_in *saddr,
2499 static CharDriverState *qemu_chr_open_udp(const char *def)
2501 CharDriverState *chr = NULL;
2502 NetCharDriver *s = NULL;
2504 struct sockaddr_in saddr;
2506 chr = qemu_mallocz(sizeof(CharDriverState));
2509 s = qemu_mallocz(sizeof(NetCharDriver));
2513 fd = socket(PF_INET, SOCK_DGRAM, 0);
2515 perror("socket(PF_INET, SOCK_DGRAM)");
2519 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2520 printf("Could not parse: %s\n", def);
2524 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2534 chr->chr_write = udp_chr_write;
2535 chr->chr_update_read_handler = udp_chr_update_read_handler;
2548 /***********************************************************/
2549 /* TCP Net console */
2560 static void tcp_chr_accept(void *opaque);
2562 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2564 TCPCharDriver *s = chr->opaque;
2566 return send_all(s->fd, buf, len);
2568 /* XXX: indicate an error ? */
2573 static int tcp_chr_read_poll(void *opaque)
2575 CharDriverState *chr = opaque;
2576 TCPCharDriver *s = chr->opaque;
2579 s->max_size = qemu_chr_can_read(chr);
2584 #define IAC_BREAK 243
2585 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2587 char *buf, int *size)
2589 /* Handle any telnet client's basic IAC options to satisfy char by
2590 * char mode with no echo. All IAC options will be removed from
2591 * the buf and the do_telnetopt variable will be used to track the
2592 * state of the width of the IAC information.
2594 * IAC commands come in sets of 3 bytes with the exception of the
2595 * "IAC BREAK" command and the double IAC.
2601 for (i = 0; i < *size; i++) {
2602 if (s->do_telnetopt > 1) {
2603 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2604 /* Double IAC means send an IAC */
2608 s->do_telnetopt = 1;
2610 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2611 /* Handle IAC break commands by sending a serial break */
2612 qemu_chr_event(chr, CHR_EVENT_BREAK);
2617 if (s->do_telnetopt >= 4) {
2618 s->do_telnetopt = 1;
2621 if ((unsigned char)buf[i] == IAC) {
2622 s->do_telnetopt = 2;
2633 static void tcp_chr_read(void *opaque)
2635 CharDriverState *chr = opaque;
2636 TCPCharDriver *s = chr->opaque;
2640 if (!s->connected || s->max_size <= 0)
2643 if (len > s->max_size)
2645 size = recv(s->fd, buf, len, 0);
2647 /* connection closed */
2649 if (s->listen_fd >= 0) {
2650 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2652 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2655 } else if (size > 0) {
2656 if (s->do_telnetopt)
2657 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2659 qemu_chr_read(chr, buf, size);
2663 static void tcp_chr_connect(void *opaque)
2665 CharDriverState *chr = opaque;
2666 TCPCharDriver *s = chr->opaque;
2669 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2670 tcp_chr_read, NULL, chr);
2671 qemu_chr_reset(chr);
2674 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2675 static void tcp_chr_telnet_init(int fd)
2678 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2679 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2680 send(fd, (char *)buf, 3, 0);
2681 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2682 send(fd, (char *)buf, 3, 0);
2683 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2684 send(fd, (char *)buf, 3, 0);
2685 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2686 send(fd, (char *)buf, 3, 0);
2689 static void socket_set_nodelay(int fd)
2692 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2695 static void tcp_chr_accept(void *opaque)
2697 CharDriverState *chr = opaque;
2698 TCPCharDriver *s = chr->opaque;
2699 struct sockaddr_in saddr;
2701 struct sockaddr_un uaddr;
2703 struct sockaddr *addr;
2710 len = sizeof(uaddr);
2711 addr = (struct sockaddr *)&uaddr;
2715 len = sizeof(saddr);
2716 addr = (struct sockaddr *)&saddr;
2718 fd = accept(s->listen_fd, addr, &len);
2719 if (fd < 0 && errno != EINTR) {
2721 } else if (fd >= 0) {
2722 if (s->do_telnetopt)
2723 tcp_chr_telnet_init(fd);
2727 socket_set_nonblock(fd);
2729 socket_set_nodelay(fd);
2731 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2732 tcp_chr_connect(chr);
2735 static void tcp_chr_close(CharDriverState *chr)
2737 TCPCharDriver *s = chr->opaque;
2740 if (s->listen_fd >= 0)
2741 closesocket(s->listen_fd);
2745 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2749 CharDriverState *chr = NULL;
2750 TCPCharDriver *s = NULL;
2751 int fd = -1, ret, err, val;
2753 int is_waitconnect = 1;
2756 struct sockaddr_in saddr;
2758 struct sockaddr_un uaddr;
2760 struct sockaddr *addr;
2765 addr = (struct sockaddr *)&uaddr;
2766 addrlen = sizeof(uaddr);
2767 if (parse_unix_path(&uaddr, host_str) < 0)
2772 addr = (struct sockaddr *)&saddr;
2773 addrlen = sizeof(saddr);
2774 if (parse_host_port(&saddr, host_str) < 0)
2779 while((ptr = strchr(ptr,','))) {
2781 if (!strncmp(ptr,"server",6)) {
2783 } else if (!strncmp(ptr,"nowait",6)) {
2785 } else if (!strncmp(ptr,"nodelay",6)) {
2788 printf("Unknown option: %s\n", ptr);
2795 chr = qemu_mallocz(sizeof(CharDriverState));
2798 s = qemu_mallocz(sizeof(TCPCharDriver));
2804 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2807 fd = socket(PF_INET, SOCK_STREAM, 0);
2812 if (!is_waitconnect)
2813 socket_set_nonblock(fd);
2818 s->is_unix = is_unix;
2819 s->do_nodelay = do_nodelay && !is_unix;
2822 chr->chr_write = tcp_chr_write;
2823 chr->chr_close = tcp_chr_close;
2826 /* allow fast reuse */
2830 strncpy(path, uaddr.sun_path, 108);
2837 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2840 ret = bind(fd, addr, addrlen);
2844 ret = listen(fd, 0);
2849 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2851 s->do_telnetopt = 1;
2854 ret = connect(fd, addr, addrlen);
2856 err = socket_error();
2857 if (err == EINTR || err == EWOULDBLOCK) {
2858 } else if (err == EINPROGRESS) {
2861 } else if (err == WSAEALREADY) {
2873 socket_set_nodelay(fd);
2875 tcp_chr_connect(chr);
2877 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2880 if (is_listen && is_waitconnect) {
2881 printf("QEMU waiting for connection on: %s\n", host_str);
2882 tcp_chr_accept(chr);
2883 socket_set_nonblock(s->listen_fd);
2895 CharDriverState *qemu_chr_open(const char *filename)
2899 if (!strcmp(filename, "vc")) {
2900 return text_console_init(&display_state);
2901 } else if (!strcmp(filename, "null")) {
2902 return qemu_chr_open_null();
2904 if (strstart(filename, "tcp:", &p)) {
2905 return qemu_chr_open_tcp(p, 0, 0);
2907 if (strstart(filename, "telnet:", &p)) {
2908 return qemu_chr_open_tcp(p, 1, 0);
2910 if (strstart(filename, "udp:", &p)) {
2911 return qemu_chr_open_udp(p);
2913 if (strstart(filename, "mon:", &p)) {
2914 CharDriverState *drv = qemu_chr_open(p);
2916 drv = qemu_chr_open_mux(drv);
2917 monitor_init(drv, !nographic);
2920 printf("Unable to open driver: %s\n", p);
2924 if (strstart(filename, "unix:", &p)) {
2925 return qemu_chr_open_tcp(p, 0, 1);
2926 } else if (strstart(filename, "file:", &p)) {
2927 return qemu_chr_open_file_out(p);
2928 } else if (strstart(filename, "pipe:", &p)) {
2929 return qemu_chr_open_pipe(p);
2930 } else if (!strcmp(filename, "pty")) {
2931 return qemu_chr_open_pty();
2932 } else if (!strcmp(filename, "stdio")) {
2933 return qemu_chr_open_stdio();
2936 #if defined(__linux__)
2937 if (strstart(filename, "/dev/parport", NULL)) {
2938 return qemu_chr_open_pp(filename);
2940 if (strstart(filename, "/dev/", NULL)) {
2941 return qemu_chr_open_tty(filename);
2945 if (strstart(filename, "COM", NULL)) {
2946 return qemu_chr_open_win(filename);
2948 if (strstart(filename, "pipe:", &p)) {
2949 return qemu_chr_open_win_pipe(p);
2951 if (strstart(filename, "file:", &p)) {
2952 return qemu_chr_open_win_file_out(p);
2960 void qemu_chr_close(CharDriverState *chr)
2963 chr->chr_close(chr);
2966 /***********************************************************/
2967 /* network device redirectors */
2969 void hex_dump(FILE *f, const uint8_t *buf, int size)
2973 for(i=0;i<size;i+=16) {
2977 fprintf(f, "%08x ", i);
2980 fprintf(f, " %02x", buf[i+j]);
2985 for(j=0;j<len;j++) {
2987 if (c < ' ' || c > '~')
2989 fprintf(f, "%c", c);
2995 static int parse_macaddr(uint8_t *macaddr, const char *p)
2998 for(i = 0; i < 6; i++) {
2999 macaddr[i] = strtol(p, (char **)&p, 16);
3012 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3017 p1 = strchr(p, sep);
3023 if (len > buf_size - 1)
3025 memcpy(buf, p, len);
3032 int parse_host_src_port(struct sockaddr_in *haddr,
3033 struct sockaddr_in *saddr,
3034 const char *input_str)
3036 char *str = strdup(input_str);
3037 char *host_str = str;
3042 * Chop off any extra arguments at the end of the string which
3043 * would start with a comma, then fill in the src port information
3044 * if it was provided else use the "any address" and "any port".
3046 if ((ptr = strchr(str,',')))
3049 if ((src_str = strchr(input_str,'@'))) {
3054 if (parse_host_port(haddr, host_str) < 0)
3057 if (!src_str || *src_str == '\0')
3060 if (parse_host_port(saddr, src_str) < 0)
3071 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3079 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3081 saddr->sin_family = AF_INET;
3082 if (buf[0] == '\0') {
3083 saddr->sin_addr.s_addr = 0;
3085 if (isdigit(buf[0])) {
3086 if (!inet_aton(buf, &saddr->sin_addr))
3089 if ((he = gethostbyname(buf)) == NULL)
3091 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3094 port = strtol(p, (char **)&r, 0);
3097 saddr->sin_port = htons(port);
3102 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3107 len = MIN(108, strlen(str));
3108 p = strchr(str, ',');
3110 len = MIN(len, p - str);
3112 memset(uaddr, 0, sizeof(*uaddr));
3114 uaddr->sun_family = AF_UNIX;
3115 memcpy(uaddr->sun_path, str, len);
3121 /* find or alloc a new VLAN */
3122 VLANState *qemu_find_vlan(int id)
3124 VLANState **pvlan, *vlan;
3125 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3129 vlan = qemu_mallocz(sizeof(VLANState));
3134 pvlan = &first_vlan;
3135 while (*pvlan != NULL)
3136 pvlan = &(*pvlan)->next;
3141 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3142 IOReadHandler *fd_read,
3143 IOCanRWHandler *fd_can_read,
3146 VLANClientState *vc, **pvc;
3147 vc = qemu_mallocz(sizeof(VLANClientState));
3150 vc->fd_read = fd_read;
3151 vc->fd_can_read = fd_can_read;
3152 vc->opaque = opaque;
3156 pvc = &vlan->first_client;
3157 while (*pvc != NULL)
3158 pvc = &(*pvc)->next;
3163 int qemu_can_send_packet(VLANClientState *vc1)
3165 VLANState *vlan = vc1->vlan;
3166 VLANClientState *vc;
3168 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3170 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3177 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3179 VLANState *vlan = vc1->vlan;
3180 VLANClientState *vc;
3183 printf("vlan %d send:\n", vlan->id);
3184 hex_dump(stdout, buf, size);
3186 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3188 vc->fd_read(vc->opaque, buf, size);
3193 #if defined(CONFIG_SLIRP)
3195 /* slirp network adapter */
3197 static int slirp_inited;
3198 static VLANClientState *slirp_vc;
3200 int slirp_can_output(void)
3202 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3205 void slirp_output(const uint8_t *pkt, int pkt_len)
3208 printf("slirp output:\n");
3209 hex_dump(stdout, pkt, pkt_len);
3213 qemu_send_packet(slirp_vc, pkt, pkt_len);
3216 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3219 printf("slirp input:\n");
3220 hex_dump(stdout, buf, size);
3222 slirp_input(buf, size);
3225 static int net_slirp_init(VLANState *vlan)
3227 if (!slirp_inited) {
3231 slirp_vc = qemu_new_vlan_client(vlan,
3232 slirp_receive, NULL, NULL);
3233 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3237 static void net_slirp_redir(const char *redir_str)
3242 struct in_addr guest_addr;
3243 int host_port, guest_port;
3245 if (!slirp_inited) {
3251 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3253 if (!strcmp(buf, "tcp")) {
3255 } else if (!strcmp(buf, "udp")) {
3261 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3263 host_port = strtol(buf, &r, 0);
3267 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3269 if (buf[0] == '\0') {
3270 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3272 if (!inet_aton(buf, &guest_addr))
3275 guest_port = strtol(p, &r, 0);
3279 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3280 fprintf(stderr, "qemu: could not set up redirection\n");
3285 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3293 static void smb_exit(void)
3297 char filename[1024];
3299 /* erase all the files in the directory */
3300 d = opendir(smb_dir);
3305 if (strcmp(de->d_name, ".") != 0 &&
3306 strcmp(de->d_name, "..") != 0) {
3307 snprintf(filename, sizeof(filename), "%s/%s",
3308 smb_dir, de->d_name);
3316 /* automatic user mode samba server configuration */
3317 void net_slirp_smb(const char *exported_dir)
3319 char smb_conf[1024];
3320 char smb_cmdline[1024];
3323 if (!slirp_inited) {
3328 /* XXX: better tmp dir construction */
3329 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3330 if (mkdir(smb_dir, 0700) < 0) {
3331 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3334 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3336 f = fopen(smb_conf, "w");
3338 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3345 "socket address=127.0.0.1\n"
3346 "pid directory=%s\n"
3347 "lock directory=%s\n"
3348 "log file=%s/log.smbd\n"
3349 "smb passwd file=%s/smbpasswd\n"
3350 "security = share\n"
3365 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3366 SMBD_COMMAND, smb_conf);
3368 slirp_add_exec(0, smb_cmdline, 4, 139);
3371 #endif /* !defined(_WIN32) */
3373 #endif /* CONFIG_SLIRP */
3375 #if !defined(_WIN32)
3377 typedef struct TAPState {
3378 VLANClientState *vc;
3382 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3384 TAPState *s = opaque;
3387 ret = write(s->fd, buf, size);
3388 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3395 static void tap_send(void *opaque)
3397 TAPState *s = opaque;
3404 sbuf.maxlen = sizeof(buf);
3406 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3408 size = read(s->fd, buf, sizeof(buf));
3411 qemu_send_packet(s->vc, buf, size);
3417 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3421 s = qemu_mallocz(sizeof(TAPState));
3425 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3426 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3427 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3432 static int tap_open(char *ifname, int ifname_size)
3438 fd = open("/dev/tap", O_RDWR);
3440 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3445 dev = devname(s.st_rdev, S_IFCHR);
3446 pstrcpy(ifname, ifname_size, dev);
3448 fcntl(fd, F_SETFL, O_NONBLOCK);
3451 #elif defined(__sun__)
3452 #define TUNNEWPPA (('T'<<16) | 0x0001)
3454 * Allocate TAP device, returns opened fd.
3455 * Stores dev name in the first arg(must be large enough).
3457 int tap_alloc(char *dev)
3459 int tap_fd, if_fd, ppa = -1;
3460 static int ip_fd = 0;
3463 static int arp_fd = 0;
3464 int ip_muxid, arp_muxid;
3465 struct strioctl strioc_if, strioc_ppa;
3466 int link_type = I_PLINK;;
3468 char actual_name[32] = "";
3470 memset(&ifr, 0x0, sizeof(ifr));
3474 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3478 /* Check if IP device was opened */
3482 if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3483 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3487 if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3488 syslog(LOG_ERR, "Can't open /dev/tap");
3492 /* Assign a new PPA and get its unit number. */
3493 strioc_ppa.ic_cmd = TUNNEWPPA;
3494 strioc_ppa.ic_timout = 0;
3495 strioc_ppa.ic_len = sizeof(ppa);
3496 strioc_ppa.ic_dp = (char *)&ppa;
3497 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3498 syslog (LOG_ERR, "Can't assign new interface");
3500 if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3501 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3504 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3505 syslog(LOG_ERR, "Can't push IP module");
3509 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3510 syslog(LOG_ERR, "Can't get flags\n");
3512 snprintf (actual_name, 32, "tap%d", ppa);
3513 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3516 /* Assign ppa according to the unit number returned by tun device */
3518 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3519 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3520 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3521 syslog (LOG_ERR, "Can't get flags\n");
3522 /* Push arp module to if_fd */
3523 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3524 syslog (LOG_ERR, "Can't push ARP module (2)");
3526 /* Push arp module to ip_fd */
3527 if (ioctl (ip_fd, I_POP, NULL) < 0)
3528 syslog (LOG_ERR, "I_POP failed\n");
3529 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3530 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3532 if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3533 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3535 /* Set ifname to arp */
3536 strioc_if.ic_cmd = SIOCSLIFNAME;
3537 strioc_if.ic_timout = 0;
3538 strioc_if.ic_len = sizeof(ifr);
3539 strioc_if.ic_dp = (char *)𝔦
3540 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3541 syslog (LOG_ERR, "Can't set ifname to arp\n");
3544 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3545 syslog(LOG_ERR, "Can't link TAP device to IP");
3549 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3550 syslog (LOG_ERR, "Can't link TAP device to ARP");
3554 memset(&ifr, 0x0, sizeof(ifr));
3555 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3556 ifr.lifr_ip_muxid = ip_muxid;
3557 ifr.lifr_arp_muxid = arp_muxid;
3559 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3561 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3562 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3563 syslog (LOG_ERR, "Can't set multiplexor id");
3566 sprintf(dev, "tap%d", ppa);
3570 static int tap_open(char *ifname, int ifname_size)
3574 if( (fd = tap_alloc(dev)) < 0 ){
3575 fprintf(stderr, "Cannot allocate TAP device\n");
3578 pstrcpy(ifname, ifname_size, dev);
3579 fcntl(fd, F_SETFL, O_NONBLOCK);
3583 static int tap_open(char *ifname, int ifname_size)
3588 fd = open("/dev/net/tun", O_RDWR);
3590 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3593 memset(&ifr, 0, sizeof(ifr));
3594 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3595 if (ifname[0] != '\0')
3596 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3598 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3599 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3601 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3605 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3606 fcntl(fd, F_SETFL, O_NONBLOCK);
3611 static int net_tap_init(VLANState *vlan, const char *ifname1,
3612 const char *setup_script)
3615 int pid, status, fd;
3620 if (ifname1 != NULL)
3621 pstrcpy(ifname, sizeof(ifname), ifname1);
3624 fd = tap_open(ifname, sizeof(ifname));
3628 if (!setup_script || !strcmp(setup_script, "no"))
3630 if (setup_script[0] != '\0') {
3631 /* try to launch network init script */
3635 int open_max = sysconf (_SC_OPEN_MAX), i;
3636 for (i = 0; i < open_max; i++)
3637 if (i != STDIN_FILENO &&
3638 i != STDOUT_FILENO &&
3639 i != STDERR_FILENO &&
3644 *parg++ = (char *)setup_script;
3647 execv(setup_script, args);
3650 while (waitpid(pid, &status, 0) != pid);
3651 if (!WIFEXITED(status) ||
3652 WEXITSTATUS(status) != 0) {
3653 fprintf(stderr, "%s: could not launch network script\n",
3659 s = net_tap_fd_init(vlan, fd);
3662 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3663 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3667 #endif /* !_WIN32 */
3669 /* network connection */
3670 typedef struct NetSocketState {
3671 VLANClientState *vc;
3673 int state; /* 0 = getting length, 1 = getting data */
3677 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3680 typedef struct NetSocketListenState {
3683 } NetSocketListenState;
3685 /* XXX: we consider we can send the whole packet without blocking */
3686 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3688 NetSocketState *s = opaque;
3692 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3693 send_all(s->fd, buf, size);
3696 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3698 NetSocketState *s = opaque;
3699 sendto(s->fd, buf, size, 0,
3700 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3703 static void net_socket_send(void *opaque)
3705 NetSocketState *s = opaque;
3710 size = recv(s->fd, buf1, sizeof(buf1), 0);
3712 err = socket_error();
3713 if (err != EWOULDBLOCK)
3715 } else if (size == 0) {
3716 /* end of connection */
3718 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3724 /* reassemble a packet from the network */
3730 memcpy(s->buf + s->index, buf, l);
3734 if (s->index == 4) {
3736 s->packet_len = ntohl(*(uint32_t *)s->buf);
3742 l = s->packet_len - s->index;
3745 memcpy(s->buf + s->index, buf, l);
3749 if (s->index >= s->packet_len) {
3750 qemu_send_packet(s->vc, s->buf, s->packet_len);
3759 static void net_socket_send_dgram(void *opaque)
3761 NetSocketState *s = opaque;
3764 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3768 /* end of connection */
3769 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3772 qemu_send_packet(s->vc, s->buf, size);
3775 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3780 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3781 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3782 inet_ntoa(mcastaddr->sin_addr),
3783 (int)ntohl(mcastaddr->sin_addr.s_addr));
3787 fd = socket(PF_INET, SOCK_DGRAM, 0);
3789 perror("socket(PF_INET, SOCK_DGRAM)");
3794 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3795 (const char *)&val, sizeof(val));
3797 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3801 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3807 /* Add host to multicast group */
3808 imr.imr_multiaddr = mcastaddr->sin_addr;
3809 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3811 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3812 (const char *)&imr, sizeof(struct ip_mreq));
3814 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3818 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3820 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3821 (const char *)&val, sizeof(val));
3823 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3827 socket_set_nonblock(fd);
3835 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3838 struct sockaddr_in saddr;
3840 socklen_t saddr_len;
3843 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3844 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3845 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3849 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3851 if (saddr.sin_addr.s_addr==0) {
3852 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3856 /* clone dgram socket */
3857 newfd = net_socket_mcast_create(&saddr);
3859 /* error already reported by net_socket_mcast_create() */
3863 /* clone newfd to fd, close newfd */
3868 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3869 fd, strerror(errno));
3874 s = qemu_mallocz(sizeof(NetSocketState));
3879 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3880 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3882 /* mcast: save bound address as dst */
3883 if (is_connected) s->dgram_dst=saddr;
3885 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3886 "socket: fd=%d (%s mcast=%s:%d)",
3887 fd, is_connected? "cloned" : "",
3888 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3892 static void net_socket_connect(void *opaque)
3894 NetSocketState *s = opaque;
3895 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3898 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3902 s = qemu_mallocz(sizeof(NetSocketState));
3906 s->vc = qemu_new_vlan_client(vlan,
3907 net_socket_receive, NULL, s);
3908 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3909 "socket: fd=%d", fd);
3911 net_socket_connect(s);
3913 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3918 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3921 int so_type=-1, optlen=sizeof(so_type);
3923 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3924 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3929 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3931 return net_socket_fd_init_stream(vlan, fd, is_connected);
3933 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3934 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3935 return net_socket_fd_init_stream(vlan, fd, is_connected);
3940 static void net_socket_accept(void *opaque)
3942 NetSocketListenState *s = opaque;
3944 struct sockaddr_in saddr;
3949 len = sizeof(saddr);
3950 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3951 if (fd < 0 && errno != EINTR) {
3953 } else if (fd >= 0) {
3957 s1 = net_socket_fd_init(s->vlan, fd, 1);
3961 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3962 "socket: connection from %s:%d",
3963 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3967 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3969 NetSocketListenState *s;
3971 struct sockaddr_in saddr;
3973 if (parse_host_port(&saddr, host_str) < 0)
3976 s = qemu_mallocz(sizeof(NetSocketListenState));
3980 fd = socket(PF_INET, SOCK_STREAM, 0);
3985 socket_set_nonblock(fd);
3987 /* allow fast reuse */
3989 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3991 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3996 ret = listen(fd, 0);
4003 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4007 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4010 int fd, connected, ret, err;
4011 struct sockaddr_in saddr;
4013 if (parse_host_port(&saddr, host_str) < 0)
4016 fd = socket(PF_INET, SOCK_STREAM, 0);
4021 socket_set_nonblock(fd);
4025 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4027 err = socket_error();
4028 if (err == EINTR || err == EWOULDBLOCK) {
4029 } else if (err == EINPROGRESS) {
4032 } else if (err == WSAEALREADY) {
4045 s = net_socket_fd_init(vlan, fd, connected);
4048 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4049 "socket: connect to %s:%d",
4050 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4054 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4058 struct sockaddr_in saddr;
4060 if (parse_host_port(&saddr, host_str) < 0)
4064 fd = net_socket_mcast_create(&saddr);
4068 s = net_socket_fd_init(vlan, fd, 0);
4072 s->dgram_dst = saddr;
4074 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4075 "socket: mcast=%s:%d",
4076 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4081 static int get_param_value(char *buf, int buf_size,
4082 const char *tag, const char *str)
4091 while (*p != '\0' && *p != '=') {
4092 if ((q - option) < sizeof(option) - 1)
4100 if (!strcmp(tag, option)) {
4102 while (*p != '\0' && *p != ',') {
4103 if ((q - buf) < buf_size - 1)
4110 while (*p != '\0' && *p != ',') {
4121 static int net_client_init(const char *str)
4132 while (*p != '\0' && *p != ',') {
4133 if ((q - device) < sizeof(device) - 1)
4141 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4142 vlan_id = strtol(buf, NULL, 0);
4144 vlan = qemu_find_vlan(vlan_id);
4146 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4149 if (!strcmp(device, "nic")) {
4153 if (nb_nics >= MAX_NICS) {
4154 fprintf(stderr, "Too Many NICs\n");
4157 nd = &nd_table[nb_nics];
4158 macaddr = nd->macaddr;
4164 macaddr[5] = 0x56 + nb_nics;
4166 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4167 if (parse_macaddr(macaddr, buf) < 0) {
4168 fprintf(stderr, "invalid syntax for ethernet address\n");
4172 if (get_param_value(buf, sizeof(buf), "model", p)) {
4173 nd->model = strdup(buf);
4179 if (!strcmp(device, "none")) {
4180 /* does nothing. It is needed to signal that no network cards
4185 if (!strcmp(device, "user")) {
4186 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4187 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4189 ret = net_slirp_init(vlan);
4193 if (!strcmp(device, "tap")) {
4195 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4196 fprintf(stderr, "tap: no interface name\n");
4199 ret = tap_win32_init(vlan, ifname);
4202 if (!strcmp(device, "tap")) {
4204 char setup_script[1024];
4206 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4207 fd = strtol(buf, NULL, 0);
4209 if (net_tap_fd_init(vlan, fd))
4212 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4215 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4216 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4218 ret = net_tap_init(vlan, ifname, setup_script);
4222 if (!strcmp(device, "socket")) {
4223 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4225 fd = strtol(buf, NULL, 0);
4227 if (net_socket_fd_init(vlan, fd, 1))
4229 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4230 ret = net_socket_listen_init(vlan, buf);
4231 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4232 ret = net_socket_connect_init(vlan, buf);
4233 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4234 ret = net_socket_mcast_init(vlan, buf);
4236 fprintf(stderr, "Unknown socket options: %s\n", p);
4241 fprintf(stderr, "Unknown network device: %s\n", device);
4245 fprintf(stderr, "Could not initialize device '%s'\n", device);
4251 void do_info_network(void)
4254 VLANClientState *vc;
4256 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4257 term_printf("VLAN %d devices:\n", vlan->id);
4258 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4259 term_printf(" %s\n", vc->info_str);
4263 /***********************************************************/
4266 static USBPort *used_usb_ports;
4267 static USBPort *free_usb_ports;
4269 /* ??? Maybe change this to register a hub to keep track of the topology. */
4270 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4271 usb_attachfn attach)
4273 port->opaque = opaque;
4274 port->index = index;
4275 port->attach = attach;
4276 port->next = free_usb_ports;
4277 free_usb_ports = port;
4280 static int usb_device_add(const char *devname)
4286 if (!free_usb_ports)
4289 if (strstart(devname, "host:", &p)) {
4290 dev = usb_host_device_open(p);
4291 } else if (!strcmp(devname, "mouse")) {
4292 dev = usb_mouse_init();
4293 } else if (!strcmp(devname, "tablet")) {
4294 dev = usb_tablet_init();
4295 } else if (strstart(devname, "disk:", &p)) {
4296 dev = usb_msd_init(p);
4303 /* Find a USB port to add the device to. */
4304 port = free_usb_ports;
4308 /* Create a new hub and chain it on. */
4309 free_usb_ports = NULL;
4310 port->next = used_usb_ports;
4311 used_usb_ports = port;
4313 hub = usb_hub_init(VM_USB_HUB_SIZE);
4314 usb_attach(port, hub);
4315 port = free_usb_ports;
4318 free_usb_ports = port->next;
4319 port->next = used_usb_ports;
4320 used_usb_ports = port;
4321 usb_attach(port, dev);
4325 static int usb_device_del(const char *devname)
4333 if (!used_usb_ports)
4336 p = strchr(devname, '.');
4339 bus_num = strtoul(devname, NULL, 0);
4340 addr = strtoul(p + 1, NULL, 0);
4344 lastp = &used_usb_ports;
4345 port = used_usb_ports;
4346 while (port && port->dev->addr != addr) {
4347 lastp = &port->next;
4355 *lastp = port->next;
4356 usb_attach(port, NULL);
4357 dev->handle_destroy(dev);
4358 port->next = free_usb_ports;
4359 free_usb_ports = port;
4363 void do_usb_add(const char *devname)
4366 ret = usb_device_add(devname);
4368 term_printf("Could not add USB device '%s'\n", devname);
4371 void do_usb_del(const char *devname)
4374 ret = usb_device_del(devname);
4376 term_printf("Could not remove USB device '%s'\n", devname);
4383 const char *speed_str;
4386 term_printf("USB support not enabled\n");
4390 for (port = used_usb_ports; port; port = port->next) {
4394 switch(dev->speed) {
4398 case USB_SPEED_FULL:
4401 case USB_SPEED_HIGH:
4408 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4409 0, dev->addr, speed_str, dev->devname);
4413 /***********************************************************/
4416 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4420 static void dumb_resize(DisplayState *ds, int w, int h)
4424 static void dumb_refresh(DisplayState *ds)
4429 void dumb_display_init(DisplayState *ds)
4434 ds->dpy_update = dumb_update;
4435 ds->dpy_resize = dumb_resize;
4436 ds->dpy_refresh = dumb_refresh;
4439 /***********************************************************/
4442 #define MAX_IO_HANDLERS 64
4444 typedef struct IOHandlerRecord {
4446 IOCanRWHandler *fd_read_poll;
4448 IOHandler *fd_write;
4451 /* temporary data */
4453 struct IOHandlerRecord *next;
4456 static IOHandlerRecord *first_io_handler;
4458 /* XXX: fd_read_poll should be suppressed, but an API change is
4459 necessary in the character devices to suppress fd_can_read(). */
4460 int qemu_set_fd_handler2(int fd,
4461 IOCanRWHandler *fd_read_poll,
4463 IOHandler *fd_write,
4466 IOHandlerRecord **pioh, *ioh;
4468 if (!fd_read && !fd_write) {
4469 pioh = &first_io_handler;
4474 if (ioh->fd == fd) {
4481 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4485 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4488 ioh->next = first_io_handler;
4489 first_io_handler = ioh;
4492 ioh->fd_read_poll = fd_read_poll;
4493 ioh->fd_read = fd_read;
4494 ioh->fd_write = fd_write;
4495 ioh->opaque = opaque;
4501 int qemu_set_fd_handler(int fd,
4503 IOHandler *fd_write,
4506 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4509 /***********************************************************/
4510 /* Polling handling */
4512 typedef struct PollingEntry {
4515 struct PollingEntry *next;
4518 static PollingEntry *first_polling_entry;
4520 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4522 PollingEntry **ppe, *pe;
4523 pe = qemu_mallocz(sizeof(PollingEntry));
4527 pe->opaque = opaque;
4528 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4533 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4535 PollingEntry **ppe, *pe;
4536 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4538 if (pe->func == func && pe->opaque == opaque) {
4547 /***********************************************************/
4548 /* Wait objects support */
4549 typedef struct WaitObjects {
4551 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4552 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4553 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4556 static WaitObjects wait_objects = {0};
4558 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4560 WaitObjects *w = &wait_objects;
4562 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4564 w->events[w->num] = handle;
4565 w->func[w->num] = func;
4566 w->opaque[w->num] = opaque;
4571 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4574 WaitObjects *w = &wait_objects;
4577 for (i = 0; i < w->num; i++) {
4578 if (w->events[i] == handle)
4581 w->events[i] = w->events[i + 1];
4582 w->func[i] = w->func[i + 1];
4583 w->opaque[i] = w->opaque[i + 1];
4591 /***********************************************************/
4592 /* savevm/loadvm support */
4594 #define IO_BUF_SIZE 32768
4598 BlockDriverState *bs;
4601 int64_t base_offset;
4602 int64_t buf_offset; /* start of buffer when writing, end of buffer
4605 int buf_size; /* 0 when writing */
4606 uint8_t buf[IO_BUF_SIZE];
4609 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4613 f = qemu_mallocz(sizeof(QEMUFile));
4616 if (!strcmp(mode, "wb")) {
4618 } else if (!strcmp(mode, "rb")) {
4623 f->outfile = fopen(filename, mode);
4635 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4639 f = qemu_mallocz(sizeof(QEMUFile));
4644 f->is_writable = is_writable;
4645 f->base_offset = offset;
4649 void qemu_fflush(QEMUFile *f)
4651 if (!f->is_writable)
4653 if (f->buf_index > 0) {
4655 fseek(f->outfile, f->buf_offset, SEEK_SET);
4656 fwrite(f->buf, 1, f->buf_index, f->outfile);
4658 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4659 f->buf, f->buf_index);
4661 f->buf_offset += f->buf_index;
4666 static void qemu_fill_buffer(QEMUFile *f)
4673 fseek(f->outfile, f->buf_offset, SEEK_SET);
4674 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4678 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4679 f->buf, IO_BUF_SIZE);
4685 f->buf_offset += len;
4688 void qemu_fclose(QEMUFile *f)
4698 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4702 l = IO_BUF_SIZE - f->buf_index;
4705 memcpy(f->buf + f->buf_index, buf, l);
4709 if (f->buf_index >= IO_BUF_SIZE)
4714 void qemu_put_byte(QEMUFile *f, int v)
4716 f->buf[f->buf_index++] = v;
4717 if (f->buf_index >= IO_BUF_SIZE)
4721 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4727 l = f->buf_size - f->buf_index;
4729 qemu_fill_buffer(f);
4730 l = f->buf_size - f->buf_index;
4736 memcpy(buf, f->buf + f->buf_index, l);
4741 return size1 - size;
4744 int qemu_get_byte(QEMUFile *f)
4746 if (f->buf_index >= f->buf_size) {
4747 qemu_fill_buffer(f);
4748 if (f->buf_index >= f->buf_size)
4751 return f->buf[f->buf_index++];
4754 int64_t qemu_ftell(QEMUFile *f)
4756 return f->buf_offset - f->buf_size + f->buf_index;
4759 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4761 if (whence == SEEK_SET) {
4763 } else if (whence == SEEK_CUR) {
4764 pos += qemu_ftell(f);
4766 /* SEEK_END not supported */
4769 if (f->is_writable) {
4771 f->buf_offset = pos;
4773 f->buf_offset = pos;
4780 void qemu_put_be16(QEMUFile *f, unsigned int v)
4782 qemu_put_byte(f, v >> 8);
4783 qemu_put_byte(f, v);
4786 void qemu_put_be32(QEMUFile *f, unsigned int v)
4788 qemu_put_byte(f, v >> 24);
4789 qemu_put_byte(f, v >> 16);
4790 qemu_put_byte(f, v >> 8);
4791 qemu_put_byte(f, v);
4794 void qemu_put_be64(QEMUFile *f, uint64_t v)
4796 qemu_put_be32(f, v >> 32);
4797 qemu_put_be32(f, v);
4800 unsigned int qemu_get_be16(QEMUFile *f)
4803 v = qemu_get_byte(f) << 8;
4804 v |= qemu_get_byte(f);
4808 unsigned int qemu_get_be32(QEMUFile *f)
4811 v = qemu_get_byte(f) << 24;
4812 v |= qemu_get_byte(f) << 16;
4813 v |= qemu_get_byte(f) << 8;
4814 v |= qemu_get_byte(f);
4818 uint64_t qemu_get_be64(QEMUFile *f)
4821 v = (uint64_t)qemu_get_be32(f) << 32;
4822 v |= qemu_get_be32(f);
4826 typedef struct SaveStateEntry {
4830 SaveStateHandler *save_state;
4831 LoadStateHandler *load_state;
4833 struct SaveStateEntry *next;
4836 static SaveStateEntry *first_se;
4838 int register_savevm(const char *idstr,
4841 SaveStateHandler *save_state,
4842 LoadStateHandler *load_state,
4845 SaveStateEntry *se, **pse;
4847 se = qemu_malloc(sizeof(SaveStateEntry));
4850 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4851 se->instance_id = instance_id;
4852 se->version_id = version_id;
4853 se->save_state = save_state;
4854 se->load_state = load_state;
4855 se->opaque = opaque;
4858 /* add at the end of list */
4860 while (*pse != NULL)
4861 pse = &(*pse)->next;
4866 #define QEMU_VM_FILE_MAGIC 0x5145564d
4867 #define QEMU_VM_FILE_VERSION 0x00000002
4869 int qemu_savevm_state(QEMUFile *f)
4873 int64_t cur_pos, len_pos, total_len_pos;
4875 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4876 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4877 total_len_pos = qemu_ftell(f);
4878 qemu_put_be64(f, 0); /* total size */
4880 for(se = first_se; se != NULL; se = se->next) {
4882 len = strlen(se->idstr);
4883 qemu_put_byte(f, len);
4884 qemu_put_buffer(f, se->idstr, len);
4886 qemu_put_be32(f, se->instance_id);
4887 qemu_put_be32(f, se->version_id);
4889 /* record size: filled later */
4890 len_pos = qemu_ftell(f);
4891 qemu_put_be32(f, 0);
4893 se->save_state(f, se->opaque);
4895 /* fill record size */
4896 cur_pos = qemu_ftell(f);
4897 len = cur_pos - len_pos - 4;
4898 qemu_fseek(f, len_pos, SEEK_SET);
4899 qemu_put_be32(f, len);
4900 qemu_fseek(f, cur_pos, SEEK_SET);
4902 cur_pos = qemu_ftell(f);
4903 qemu_fseek(f, total_len_pos, SEEK_SET);
4904 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4905 qemu_fseek(f, cur_pos, SEEK_SET);
4911 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4915 for(se = first_se; se != NULL; se = se->next) {
4916 if (!strcmp(se->idstr, idstr) &&
4917 instance_id == se->instance_id)
4923 int qemu_loadvm_state(QEMUFile *f)
4926 int len, ret, instance_id, record_len, version_id;
4927 int64_t total_len, end_pos, cur_pos;
4931 v = qemu_get_be32(f);
4932 if (v != QEMU_VM_FILE_MAGIC)
4934 v = qemu_get_be32(f);
4935 if (v != QEMU_VM_FILE_VERSION) {
4940 total_len = qemu_get_be64(f);
4941 end_pos = total_len + qemu_ftell(f);
4943 if (qemu_ftell(f) >= end_pos)
4945 len = qemu_get_byte(f);
4946 qemu_get_buffer(f, idstr, len);
4948 instance_id = qemu_get_be32(f);
4949 version_id = qemu_get_be32(f);
4950 record_len = qemu_get_be32(f);
4952 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4953 idstr, instance_id, version_id, record_len);
4955 cur_pos = qemu_ftell(f);
4956 se = find_se(idstr, instance_id);
4958 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4959 instance_id, idstr);
4961 ret = se->load_state(f, se->opaque, version_id);
4963 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4964 instance_id, idstr);
4967 /* always seek to exact end of record */
4968 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4975 /* device can contain snapshots */
4976 static int bdrv_can_snapshot(BlockDriverState *bs)
4979 !bdrv_is_removable(bs) &&
4980 !bdrv_is_read_only(bs));
4983 /* device must be snapshots in order to have a reliable snapshot */
4984 static int bdrv_has_snapshot(BlockDriverState *bs)
4987 !bdrv_is_removable(bs) &&
4988 !bdrv_is_read_only(bs));
4991 static BlockDriverState *get_bs_snapshots(void)
4993 BlockDriverState *bs;
4997 return bs_snapshots;
4998 for(i = 0; i <= MAX_DISKS; i++) {
5000 if (bdrv_can_snapshot(bs))
5009 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5012 QEMUSnapshotInfo *sn_tab, *sn;
5016 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5019 for(i = 0; i < nb_sns; i++) {
5021 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5031 void do_savevm(const char *name)
5033 BlockDriverState *bs, *bs1;
5034 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5035 int must_delete, ret, i;
5036 BlockDriverInfo bdi1, *bdi = &bdi1;
5038 int saved_vm_running;
5045 bs = get_bs_snapshots();
5047 term_printf("No block device can accept snapshots\n");
5051 /* ??? Should this occur after vm_stop? */
5054 saved_vm_running = vm_running;
5059 ret = bdrv_snapshot_find(bs, old_sn, name);
5064 memset(sn, 0, sizeof(*sn));
5066 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5067 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5070 pstrcpy(sn->name, sizeof(sn->name), name);
5073 /* fill auxiliary fields */
5076 sn->date_sec = tb.time;
5077 sn->date_nsec = tb.millitm * 1000000;
5079 gettimeofday(&tv, NULL);
5080 sn->date_sec = tv.tv_sec;
5081 sn->date_nsec = tv.tv_usec * 1000;
5083 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5085 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5086 term_printf("Device %s does not support VM state snapshots\n",
5087 bdrv_get_device_name(bs));
5091 /* save the VM state */
5092 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5094 term_printf("Could not open VM state file\n");
5097 ret = qemu_savevm_state(f);
5098 sn->vm_state_size = qemu_ftell(f);
5101 term_printf("Error %d while writing VM\n", ret);
5105 /* create the snapshots */
5107 for(i = 0; i < MAX_DISKS; i++) {
5109 if (bdrv_has_snapshot(bs1)) {
5111 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5113 term_printf("Error while deleting snapshot on '%s'\n",
5114 bdrv_get_device_name(bs1));
5117 ret = bdrv_snapshot_create(bs1, sn);
5119 term_printf("Error while creating snapshot on '%s'\n",
5120 bdrv_get_device_name(bs1));
5126 if (saved_vm_running)
5130 void do_loadvm(const char *name)
5132 BlockDriverState *bs, *bs1;
5133 BlockDriverInfo bdi1, *bdi = &bdi1;
5136 int saved_vm_running;
5138 bs = get_bs_snapshots();
5140 term_printf("No block device supports snapshots\n");
5144 /* Flush all IO requests so they don't interfere with the new state. */
5147 saved_vm_running = vm_running;
5150 for(i = 0; i <= MAX_DISKS; i++) {
5152 if (bdrv_has_snapshot(bs1)) {
5153 ret = bdrv_snapshot_goto(bs1, name);
5156 term_printf("Warning: ");
5159 term_printf("Snapshots not supported on device '%s'\n",
5160 bdrv_get_device_name(bs1));
5163 term_printf("Could not find snapshot '%s' on device '%s'\n",
5164 name, bdrv_get_device_name(bs1));
5167 term_printf("Error %d while activating snapshot on '%s'\n",
5168 ret, bdrv_get_device_name(bs1));
5171 /* fatal on snapshot block device */
5178 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5179 term_printf("Device %s does not support VM state snapshots\n",
5180 bdrv_get_device_name(bs));
5184 /* restore the VM state */
5185 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5187 term_printf("Could not open VM state file\n");
5190 ret = qemu_loadvm_state(f);
5193 term_printf("Error %d while loading VM state\n", ret);
5196 if (saved_vm_running)
5200 void do_delvm(const char *name)
5202 BlockDriverState *bs, *bs1;
5205 bs = get_bs_snapshots();
5207 term_printf("No block device supports snapshots\n");
5211 for(i = 0; i <= MAX_DISKS; i++) {
5213 if (bdrv_has_snapshot(bs1)) {
5214 ret = bdrv_snapshot_delete(bs1, name);
5216 if (ret == -ENOTSUP)
5217 term_printf("Snapshots not supported on device '%s'\n",
5218 bdrv_get_device_name(bs1));
5220 term_printf("Error %d while deleting snapshot on '%s'\n",
5221 ret, bdrv_get_device_name(bs1));
5227 void do_info_snapshots(void)
5229 BlockDriverState *bs, *bs1;
5230 QEMUSnapshotInfo *sn_tab, *sn;
5234 bs = get_bs_snapshots();
5236 term_printf("No available block device supports snapshots\n");
5239 term_printf("Snapshot devices:");
5240 for(i = 0; i <= MAX_DISKS; i++) {
5242 if (bdrv_has_snapshot(bs1)) {
5244 term_printf(" %s", bdrv_get_device_name(bs1));
5249 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5251 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5254 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5255 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5256 for(i = 0; i < nb_sns; i++) {
5258 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5263 /***********************************************************/
5264 /* cpu save/restore */
5266 #if defined(TARGET_I386)
5268 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5270 qemu_put_be32(f, dt->selector);
5271 qemu_put_betl(f, dt->base);
5272 qemu_put_be32(f, dt->limit);
5273 qemu_put_be32(f, dt->flags);
5276 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5278 dt->selector = qemu_get_be32(f);
5279 dt->base = qemu_get_betl(f);
5280 dt->limit = qemu_get_be32(f);
5281 dt->flags = qemu_get_be32(f);
5284 void cpu_save(QEMUFile *f, void *opaque)
5286 CPUState *env = opaque;
5287 uint16_t fptag, fpus, fpuc, fpregs_format;
5291 for(i = 0; i < CPU_NB_REGS; i++)
5292 qemu_put_betls(f, &env->regs[i]);
5293 qemu_put_betls(f, &env->eip);
5294 qemu_put_betls(f, &env->eflags);
5295 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5296 qemu_put_be32s(f, &hflags);
5300 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5302 for(i = 0; i < 8; i++) {
5303 fptag |= ((!env->fptags[i]) << i);
5306 qemu_put_be16s(f, &fpuc);
5307 qemu_put_be16s(f, &fpus);
5308 qemu_put_be16s(f, &fptag);
5310 #ifdef USE_X86LDOUBLE
5315 qemu_put_be16s(f, &fpregs_format);
5317 for(i = 0; i < 8; i++) {
5318 #ifdef USE_X86LDOUBLE
5322 /* we save the real CPU data (in case of MMX usage only 'mant'
5323 contains the MMX register */
5324 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5325 qemu_put_be64(f, mant);
5326 qemu_put_be16(f, exp);
5329 /* if we use doubles for float emulation, we save the doubles to
5330 avoid losing information in case of MMX usage. It can give
5331 problems if the image is restored on a CPU where long
5332 doubles are used instead. */
5333 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5337 for(i = 0; i < 6; i++)
5338 cpu_put_seg(f, &env->segs[i]);
5339 cpu_put_seg(f, &env->ldt);
5340 cpu_put_seg(f, &env->tr);
5341 cpu_put_seg(f, &env->gdt);
5342 cpu_put_seg(f, &env->idt);
5344 qemu_put_be32s(f, &env->sysenter_cs);
5345 qemu_put_be32s(f, &env->sysenter_esp);
5346 qemu_put_be32s(f, &env->sysenter_eip);
5348 qemu_put_betls(f, &env->cr[0]);
5349 qemu_put_betls(f, &env->cr[2]);
5350 qemu_put_betls(f, &env->cr[3]);
5351 qemu_put_betls(f, &env->cr[4]);
5353 for(i = 0; i < 8; i++)
5354 qemu_put_betls(f, &env->dr[i]);
5357 qemu_put_be32s(f, &env->a20_mask);
5360 qemu_put_be32s(f, &env->mxcsr);
5361 for(i = 0; i < CPU_NB_REGS; i++) {
5362 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5363 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5366 #ifdef TARGET_X86_64
5367 qemu_put_be64s(f, &env->efer);
5368 qemu_put_be64s(f, &env->star);
5369 qemu_put_be64s(f, &env->lstar);
5370 qemu_put_be64s(f, &env->cstar);
5371 qemu_put_be64s(f, &env->fmask);
5372 qemu_put_be64s(f, &env->kernelgsbase);
5374 qemu_put_be32s(f, &env->smbase);
5377 #ifdef USE_X86LDOUBLE
5378 /* XXX: add that in a FPU generic layer */
5379 union x86_longdouble {
5384 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5385 #define EXPBIAS1 1023
5386 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5387 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5389 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5393 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5394 /* exponent + sign */
5395 e = EXPD1(temp) - EXPBIAS1 + 16383;
5396 e |= SIGND1(temp) >> 16;
5401 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5403 CPUState *env = opaque;
5406 uint16_t fpus, fpuc, fptag, fpregs_format;
5408 if (version_id != 3 && version_id != 4)
5410 for(i = 0; i < CPU_NB_REGS; i++)
5411 qemu_get_betls(f, &env->regs[i]);
5412 qemu_get_betls(f, &env->eip);
5413 qemu_get_betls(f, &env->eflags);
5414 qemu_get_be32s(f, &hflags);
5416 qemu_get_be16s(f, &fpuc);
5417 qemu_get_be16s(f, &fpus);
5418 qemu_get_be16s(f, &fptag);
5419 qemu_get_be16s(f, &fpregs_format);
5421 /* NOTE: we cannot always restore the FPU state if the image come
5422 from a host with a different 'USE_X86LDOUBLE' define. We guess
5423 if we are in an MMX state to restore correctly in that case. */
5424 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5425 for(i = 0; i < 8; i++) {
5429 switch(fpregs_format) {
5431 mant = qemu_get_be64(f);
5432 exp = qemu_get_be16(f);
5433 #ifdef USE_X86LDOUBLE
5434 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5436 /* difficult case */
5438 env->fpregs[i].mmx.MMX_Q(0) = mant;
5440 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5444 mant = qemu_get_be64(f);
5445 #ifdef USE_X86LDOUBLE
5447 union x86_longdouble *p;
5448 /* difficult case */
5449 p = (void *)&env->fpregs[i];
5454 fp64_to_fp80(p, mant);
5458 env->fpregs[i].mmx.MMX_Q(0) = mant;
5467 /* XXX: restore FPU round state */
5468 env->fpstt = (fpus >> 11) & 7;
5469 env->fpus = fpus & ~0x3800;
5471 for(i = 0; i < 8; i++) {
5472 env->fptags[i] = (fptag >> i) & 1;
5475 for(i = 0; i < 6; i++)
5476 cpu_get_seg(f, &env->segs[i]);
5477 cpu_get_seg(f, &env->ldt);
5478 cpu_get_seg(f, &env->tr);
5479 cpu_get_seg(f, &env->gdt);
5480 cpu_get_seg(f, &env->idt);
5482 qemu_get_be32s(f, &env->sysenter_cs);
5483 qemu_get_be32s(f, &env->sysenter_esp);
5484 qemu_get_be32s(f, &env->sysenter_eip);
5486 qemu_get_betls(f, &env->cr[0]);
5487 qemu_get_betls(f, &env->cr[2]);
5488 qemu_get_betls(f, &env->cr[3]);
5489 qemu_get_betls(f, &env->cr[4]);
5491 for(i = 0; i < 8; i++)
5492 qemu_get_betls(f, &env->dr[i]);
5495 qemu_get_be32s(f, &env->a20_mask);
5497 qemu_get_be32s(f, &env->mxcsr);
5498 for(i = 0; i < CPU_NB_REGS; i++) {
5499 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5500 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5503 #ifdef TARGET_X86_64
5504 qemu_get_be64s(f, &env->efer);
5505 qemu_get_be64s(f, &env->star);
5506 qemu_get_be64s(f, &env->lstar);
5507 qemu_get_be64s(f, &env->cstar);
5508 qemu_get_be64s(f, &env->fmask);
5509 qemu_get_be64s(f, &env->kernelgsbase);
5511 if (version_id >= 4)
5512 qemu_get_be32s(f, &env->smbase);
5514 /* XXX: compute hflags from scratch, except for CPL and IIF */
5515 env->hflags = hflags;
5520 #elif defined(TARGET_PPC)
5521 void cpu_save(QEMUFile *f, void *opaque)
5525 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5530 #elif defined(TARGET_MIPS)
5531 void cpu_save(QEMUFile *f, void *opaque)
5535 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5540 #elif defined(TARGET_SPARC)
5541 void cpu_save(QEMUFile *f, void *opaque)
5543 CPUState *env = opaque;
5547 for(i = 0; i < 8; i++)
5548 qemu_put_betls(f, &env->gregs[i]);
5549 for(i = 0; i < NWINDOWS * 16; i++)
5550 qemu_put_betls(f, &env->regbase[i]);
5553 for(i = 0; i < TARGET_FPREGS; i++) {
5559 qemu_put_be32(f, u.i);
5562 qemu_put_betls(f, &env->pc);
5563 qemu_put_betls(f, &env->npc);
5564 qemu_put_betls(f, &env->y);
5566 qemu_put_be32(f, tmp);
5567 qemu_put_betls(f, &env->fsr);
5568 qemu_put_betls(f, &env->tbr);
5569 #ifndef TARGET_SPARC64
5570 qemu_put_be32s(f, &env->wim);
5572 for(i = 0; i < 16; i++)
5573 qemu_put_be32s(f, &env->mmuregs[i]);
5577 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5579 CPUState *env = opaque;
5583 for(i = 0; i < 8; i++)
5584 qemu_get_betls(f, &env->gregs[i]);
5585 for(i = 0; i < NWINDOWS * 16; i++)
5586 qemu_get_betls(f, &env->regbase[i]);
5589 for(i = 0; i < TARGET_FPREGS; i++) {
5594 u.i = qemu_get_be32(f);
5598 qemu_get_betls(f, &env->pc);
5599 qemu_get_betls(f, &env->npc);
5600 qemu_get_betls(f, &env->y);
5601 tmp = qemu_get_be32(f);
5602 env->cwp = 0; /* needed to ensure that the wrapping registers are
5603 correctly updated */
5605 qemu_get_betls(f, &env->fsr);
5606 qemu_get_betls(f, &env->tbr);
5607 #ifndef TARGET_SPARC64
5608 qemu_get_be32s(f, &env->wim);
5610 for(i = 0; i < 16; i++)
5611 qemu_get_be32s(f, &env->mmuregs[i]);
5617 #elif defined(TARGET_ARM)
5619 /* ??? Need to implement these. */
5620 void cpu_save(QEMUFile *f, void *opaque)
5624 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5631 #warning No CPU save/restore functions
5635 /***********************************************************/
5636 /* ram save/restore */
5638 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5642 v = qemu_get_byte(f);
5645 if (qemu_get_buffer(f, buf, len) != len)
5649 v = qemu_get_byte(f);
5650 memset(buf, v, len);
5658 static int ram_load_v1(QEMUFile *f, void *opaque)
5662 if (qemu_get_be32(f) != phys_ram_size)
5664 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5665 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5672 #define BDRV_HASH_BLOCK_SIZE 1024
5673 #define IOBUF_SIZE 4096
5674 #define RAM_CBLOCK_MAGIC 0xfabe
5676 typedef struct RamCompressState {
5679 uint8_t buf[IOBUF_SIZE];
5682 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5685 memset(s, 0, sizeof(*s));
5687 ret = deflateInit2(&s->zstream, 1,
5689 9, Z_DEFAULT_STRATEGY);
5692 s->zstream.avail_out = IOBUF_SIZE;
5693 s->zstream.next_out = s->buf;
5697 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5699 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5700 qemu_put_be16(s->f, len);
5701 qemu_put_buffer(s->f, buf, len);
5704 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5708 s->zstream.avail_in = len;
5709 s->zstream.next_in = (uint8_t *)buf;
5710 while (s->zstream.avail_in > 0) {
5711 ret = deflate(&s->zstream, Z_NO_FLUSH);
5714 if (s->zstream.avail_out == 0) {
5715 ram_put_cblock(s, s->buf, IOBUF_SIZE);
5716 s->zstream.avail_out = IOBUF_SIZE;
5717 s->zstream.next_out = s->buf;
5723 static void ram_compress_close(RamCompressState *s)
5727 /* compress last bytes */
5729 ret = deflate(&s->zstream, Z_FINISH);
5730 if (ret == Z_OK || ret == Z_STREAM_END) {
5731 len = IOBUF_SIZE - s->zstream.avail_out;
5733 ram_put_cblock(s, s->buf, len);
5735 s->zstream.avail_out = IOBUF_SIZE;
5736 s->zstream.next_out = s->buf;
5737 if (ret == Z_STREAM_END)
5744 deflateEnd(&s->zstream);
5747 typedef struct RamDecompressState {
5750 uint8_t buf[IOBUF_SIZE];
5751 } RamDecompressState;
5753 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5756 memset(s, 0, sizeof(*s));
5758 ret = inflateInit(&s->zstream);
5764 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5768 s->zstream.avail_out = len;
5769 s->zstream.next_out = buf;
5770 while (s->zstream.avail_out > 0) {
5771 if (s->zstream.avail_in == 0) {
5772 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5774 clen = qemu_get_be16(s->f);
5775 if (clen > IOBUF_SIZE)
5777 qemu_get_buffer(s->f, s->buf, clen);
5778 s->zstream.avail_in = clen;
5779 s->zstream.next_in = s->buf;
5781 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5782 if (ret != Z_OK && ret != Z_STREAM_END) {
5789 static void ram_decompress_close(RamDecompressState *s)
5791 inflateEnd(&s->zstream);
5794 static void ram_save(QEMUFile *f, void *opaque)
5797 RamCompressState s1, *s = &s1;
5800 qemu_put_be32(f, phys_ram_size);
5801 if (ram_compress_open(s, f) < 0)
5803 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5805 if (tight_savevm_enabled) {
5809 /* find if the memory block is available on a virtual
5812 for(j = 0; j < MAX_DISKS; j++) {
5814 sector_num = bdrv_hash_find(bs_table[j],
5815 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5816 if (sector_num >= 0)
5821 goto normal_compress;
5824 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5825 ram_compress_buf(s, buf, 10);
5831 ram_compress_buf(s, buf, 1);
5832 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5835 ram_compress_close(s);
5838 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5840 RamDecompressState s1, *s = &s1;
5844 if (version_id == 1)
5845 return ram_load_v1(f, opaque);
5846 if (version_id != 2)
5848 if (qemu_get_be32(f) != phys_ram_size)
5850 if (ram_decompress_open(s, f) < 0)
5852 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5853 if (ram_decompress_buf(s, buf, 1) < 0) {
5854 fprintf(stderr, "Error while reading ram block header\n");
5858 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5859 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5868 ram_decompress_buf(s, buf + 1, 9);
5870 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5871 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5872 fprintf(stderr, "Invalid block device index %d\n", bs_index);
5875 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
5876 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5877 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
5878 bs_index, sector_num);
5885 printf("Error block header\n");
5889 ram_decompress_close(s);
5893 /***********************************************************/
5894 /* bottom halves (can be seen as timers which expire ASAP) */
5903 static QEMUBH *first_bh = NULL;
5905 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5908 bh = qemu_mallocz(sizeof(QEMUBH));
5912 bh->opaque = opaque;
5916 int qemu_bh_poll(void)
5935 void qemu_bh_schedule(QEMUBH *bh)
5937 CPUState *env = cpu_single_env;
5941 bh->next = first_bh;
5944 /* stop the currently executing CPU to execute the BH ASAP */
5946 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5950 void qemu_bh_cancel(QEMUBH *bh)
5953 if (bh->scheduled) {
5956 pbh = &(*pbh)->next;
5962 void qemu_bh_delete(QEMUBH *bh)
5968 /***********************************************************/
5969 /* machine registration */
5971 QEMUMachine *first_machine = NULL;
5973 int qemu_register_machine(QEMUMachine *m)
5976 pm = &first_machine;
5984 QEMUMachine *find_machine(const char *name)
5988 for(m = first_machine; m != NULL; m = m->next) {
5989 if (!strcmp(m->name, name))
5995 /***********************************************************/
5996 /* main execution loop */
5998 void gui_update(void *opaque)
6000 display_state.dpy_refresh(&display_state);
6001 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6004 struct vm_change_state_entry {
6005 VMChangeStateHandler *cb;
6007 LIST_ENTRY (vm_change_state_entry) entries;
6010 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6012 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6015 VMChangeStateEntry *e;
6017 e = qemu_mallocz(sizeof (*e));
6023 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6027 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6029 LIST_REMOVE (e, entries);
6033 static void vm_state_notify(int running)
6035 VMChangeStateEntry *e;
6037 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6038 e->cb(e->opaque, running);
6042 /* XXX: support several handlers */
6043 static VMStopHandler *vm_stop_cb;
6044 static void *vm_stop_opaque;
6046 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6049 vm_stop_opaque = opaque;
6053 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6067 void vm_stop(int reason)
6070 cpu_disable_ticks();
6074 vm_stop_cb(vm_stop_opaque, reason);
6081 /* reset/shutdown handler */
6083 typedef struct QEMUResetEntry {
6084 QEMUResetHandler *func;
6086 struct QEMUResetEntry *next;
6089 static QEMUResetEntry *first_reset_entry;
6090 static int reset_requested;
6091 static int shutdown_requested;
6092 static int powerdown_requested;
6094 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6096 QEMUResetEntry **pre, *re;
6098 pre = &first_reset_entry;
6099 while (*pre != NULL)
6100 pre = &(*pre)->next;
6101 re = qemu_mallocz(sizeof(QEMUResetEntry));
6103 re->opaque = opaque;
6108 static void qemu_system_reset(void)
6112 /* reset all devices */
6113 for(re = first_reset_entry; re != NULL; re = re->next) {
6114 re->func(re->opaque);
6118 void qemu_system_reset_request(void)
6121 shutdown_requested = 1;
6123 reset_requested = 1;
6126 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6129 void qemu_system_shutdown_request(void)
6131 shutdown_requested = 1;
6133 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6136 void qemu_system_powerdown_request(void)
6138 powerdown_requested = 1;
6140 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6143 void main_loop_wait(int timeout)
6145 IOHandlerRecord *ioh;
6146 fd_set rfds, wfds, xfds;
6155 /* XXX: need to suppress polling by better using win32 events */
6157 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6158 ret |= pe->func(pe->opaque);
6163 WaitObjects *w = &wait_objects;
6165 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6166 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6167 if (w->func[ret - WAIT_OBJECT_0])
6168 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6170 /* Check for additional signaled events */
6171 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6173 /* Check if event is signaled */
6174 ret2 = WaitForSingleObject(w->events[i], 0);
6175 if(ret2 == WAIT_OBJECT_0) {
6177 w->func[i](w->opaque[i]);
6178 } else if (ret2 == WAIT_TIMEOUT) {
6180 err = GetLastError();
6181 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6184 } else if (ret == WAIT_TIMEOUT) {
6186 err = GetLastError();
6187 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6191 /* poll any events */
6192 /* XXX: separate device handlers from system ones */
6197 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6201 (!ioh->fd_read_poll ||
6202 ioh->fd_read_poll(ioh->opaque) != 0)) {
6203 FD_SET(ioh->fd, &rfds);
6207 if (ioh->fd_write) {
6208 FD_SET(ioh->fd, &wfds);
6218 tv.tv_usec = timeout * 1000;
6220 #if defined(CONFIG_SLIRP)
6222 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6225 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6227 IOHandlerRecord **pioh;
6229 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6232 if (FD_ISSET(ioh->fd, &rfds)) {
6233 ioh->fd_read(ioh->opaque);
6235 if (FD_ISSET(ioh->fd, &wfds)) {
6236 ioh->fd_write(ioh->opaque);
6240 /* remove deleted IO handlers */
6241 pioh = &first_io_handler;
6251 #if defined(CONFIG_SLIRP)
6258 slirp_select_poll(&rfds, &wfds, &xfds);
6265 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6266 qemu_get_clock(vm_clock));
6267 /* run dma transfers, if any */
6271 /* real time timers */
6272 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6273 qemu_get_clock(rt_clock));
6276 static CPUState *cur_cpu;
6281 #ifdef CONFIG_PROFILER
6286 cur_cpu = first_cpu;
6293 env = env->next_cpu;
6296 #ifdef CONFIG_PROFILER
6297 ti = profile_getclock();
6299 ret = cpu_exec(env);
6300 #ifdef CONFIG_PROFILER
6301 qemu_time += profile_getclock() - ti;
6303 if (ret == EXCP_HLT) {
6304 /* Give the next CPU a chance to run. */
6308 if (ret != EXCP_HALTED)
6310 /* all CPUs are halted ? */
6316 if (shutdown_requested) {
6317 ret = EXCP_INTERRUPT;
6320 if (reset_requested) {
6321 reset_requested = 0;
6322 qemu_system_reset();
6323 ret = EXCP_INTERRUPT;
6325 if (powerdown_requested) {
6326 powerdown_requested = 0;
6327 qemu_system_powerdown();
6328 ret = EXCP_INTERRUPT;
6330 if (ret == EXCP_DEBUG) {
6331 vm_stop(EXCP_DEBUG);
6333 /* If all cpus are halted then wait until the next IRQ */
6334 /* XXX: use timeout computed from timers */
6335 if (ret == EXCP_HALTED)
6342 #ifdef CONFIG_PROFILER
6343 ti = profile_getclock();
6345 main_loop_wait(timeout);
6346 #ifdef CONFIG_PROFILER
6347 dev_time += profile_getclock() - ti;
6350 cpu_disable_ticks();
6356 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6357 "usage: %s [options] [disk_image]\n"
6359 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6361 "Standard options:\n"
6362 "-M machine select emulated machine (-M ? for list)\n"
6363 "-cpu cpu select CPU (-cpu ? for list)\n"
6364 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6365 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6366 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6367 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6368 "-sd file use 'file' as SecureDigital card image\n"
6369 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6370 "-snapshot write to temporary files instead of disk image files\n"
6372 "-no-frame open SDL window without a frame and window decorations\n"
6373 "-no-quit disable SDL window close capability\n"
6376 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6378 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6379 "-smp n set the number of CPUs to 'n' [default=1]\n"
6380 "-nographic disable graphical output and redirect serial I/Os to console\n"
6382 "-k language use keyboard layout (for example \"fr\" for French)\n"
6385 "-audio-help print list of audio drivers and their options\n"
6386 "-soundhw c1,... enable audio support\n"
6387 " and only specified sound cards (comma separated list)\n"
6388 " use -soundhw ? to get the list of supported cards\n"
6389 " use -soundhw all to enable all of them\n"
6391 "-localtime set the real time clock to local time [default=utc]\n"
6392 "-full-screen start in full screen\n"
6394 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6396 "-usb enable the USB driver (will be the default soon)\n"
6397 "-usbdevice name add the host or guest USB device 'name'\n"
6398 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6399 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6401 "-name string set the name of the guest\n"
6403 "Network options:\n"
6404 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6405 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6407 "-net user[,vlan=n][,hostname=host]\n"
6408 " connect the user mode network stack to VLAN 'n' and send\n"
6409 " hostname 'host' to DHCP clients\n"
6412 "-net tap[,vlan=n],ifname=name\n"
6413 " connect the host TAP network interface to VLAN 'n'\n"
6415 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6416 " connect the host TAP network interface to VLAN 'n' and use\n"
6417 " the network script 'file' (default=%s);\n"
6418 " use 'script=no' to disable script execution;\n"
6419 " use 'fd=h' to connect to an already opened TAP interface\n"
6421 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6422 " connect the vlan 'n' to another VLAN using a socket connection\n"
6423 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6424 " connect the vlan 'n' to multicast maddr and port\n"
6425 "-net none use it alone to have zero network devices; if no -net option\n"
6426 " is provided, the default is '-net nic -net user'\n"
6429 "-tftp dir allow tftp access to files in dir [-net user]\n"
6430 "-bootp file advertise file in BOOTP replies\n"
6432 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6434 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6435 " redirect TCP or UDP connections from host to guest [-net user]\n"
6438 "Linux boot specific:\n"
6439 "-kernel bzImage use 'bzImage' as kernel image\n"
6440 "-append cmdline use 'cmdline' as kernel command line\n"
6441 "-initrd file use 'file' as initial ram disk\n"
6443 "Debug/Expert options:\n"
6444 "-monitor dev redirect the monitor to char device 'dev'\n"
6445 "-serial dev redirect the serial port to char device 'dev'\n"
6446 "-parallel dev redirect the parallel port to char device 'dev'\n"
6447 "-pidfile file Write PID to 'file'\n"
6448 "-S freeze CPU at startup (use 'c' to start execution)\n"
6449 "-s wait gdb connection to port\n"
6450 "-p port set gdb connection port [default=%s]\n"
6451 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6452 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6453 " translation (t=none or lba) (usually qemu can guess them)\n"
6454 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6456 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6457 "-no-kqemu disable KQEMU kernel module usage\n"
6459 #ifdef USE_CODE_COPY
6460 "-no-code-copy disable code copy acceleration\n"
6463 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6464 " (default is CL-GD5446 PCI VGA)\n"
6465 "-no-acpi disable ACPI\n"
6467 "-no-reboot exit instead of rebooting\n"
6468 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6469 "-vnc display start a VNC server on display\n"
6471 "-daemonize daemonize QEMU after initializing\n"
6473 "-option-rom rom load a file, rom, into the option ROM space\n"
6475 "During emulation, the following keys are useful:\n"
6476 "ctrl-alt-f toggle full screen\n"
6477 "ctrl-alt-n switch to virtual console 'n'\n"
6478 "ctrl-alt toggle mouse and keyboard grab\n"
6480 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6485 DEFAULT_NETWORK_SCRIPT,
6487 DEFAULT_GDBSTUB_PORT,
6492 #define HAS_ARG 0x0001
6508 QEMU_OPTION_snapshot,
6510 QEMU_OPTION_no_fd_bootchk,
6513 QEMU_OPTION_nographic,
6515 QEMU_OPTION_audio_help,
6516 QEMU_OPTION_soundhw,
6535 QEMU_OPTION_no_code_copy,
6537 QEMU_OPTION_localtime,
6538 QEMU_OPTION_cirrusvga,
6541 QEMU_OPTION_std_vga,
6543 QEMU_OPTION_monitor,
6545 QEMU_OPTION_parallel,
6547 QEMU_OPTION_full_screen,
6548 QEMU_OPTION_no_frame,
6549 QEMU_OPTION_no_quit,
6550 QEMU_OPTION_pidfile,
6551 QEMU_OPTION_no_kqemu,
6552 QEMU_OPTION_kernel_kqemu,
6553 QEMU_OPTION_win2k_hack,
6555 QEMU_OPTION_usbdevice,
6558 QEMU_OPTION_no_acpi,
6559 QEMU_OPTION_no_reboot,
6560 QEMU_OPTION_daemonize,
6561 QEMU_OPTION_option_rom,
6562 QEMU_OPTION_semihosting,
6566 typedef struct QEMUOption {
6572 const QEMUOption qemu_options[] = {
6573 { "h", 0, QEMU_OPTION_h },
6574 { "help", 0, QEMU_OPTION_h },
6576 { "M", HAS_ARG, QEMU_OPTION_M },
6577 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6578 { "fda", HAS_ARG, QEMU_OPTION_fda },
6579 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6580 { "hda", HAS_ARG, QEMU_OPTION_hda },
6581 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6582 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6583 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6584 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6585 { "sd", HAS_ARG, QEMU_OPTION_sd },
6586 { "boot", HAS_ARG, QEMU_OPTION_boot },
6587 { "snapshot", 0, QEMU_OPTION_snapshot },
6589 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6591 { "m", HAS_ARG, QEMU_OPTION_m },
6592 { "nographic", 0, QEMU_OPTION_nographic },
6593 { "k", HAS_ARG, QEMU_OPTION_k },
6595 { "audio-help", 0, QEMU_OPTION_audio_help },
6596 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6599 { "net", HAS_ARG, QEMU_OPTION_net},
6601 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6602 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6604 { "smb", HAS_ARG, QEMU_OPTION_smb },
6606 { "redir", HAS_ARG, QEMU_OPTION_redir },
6609 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6610 { "append", HAS_ARG, QEMU_OPTION_append },
6611 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6613 { "S", 0, QEMU_OPTION_S },
6614 { "s", 0, QEMU_OPTION_s },
6615 { "p", HAS_ARG, QEMU_OPTION_p },
6616 { "d", HAS_ARG, QEMU_OPTION_d },
6617 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6618 { "L", HAS_ARG, QEMU_OPTION_L },
6619 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6621 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6622 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6624 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6625 { "g", 1, QEMU_OPTION_g },
6627 { "localtime", 0, QEMU_OPTION_localtime },
6628 { "std-vga", 0, QEMU_OPTION_std_vga },
6629 { "echr", 1, QEMU_OPTION_echr },
6630 { "monitor", 1, QEMU_OPTION_monitor },
6631 { "serial", 1, QEMU_OPTION_serial },
6632 { "parallel", 1, QEMU_OPTION_parallel },
6633 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6634 { "full-screen", 0, QEMU_OPTION_full_screen },
6636 { "no-frame", 0, QEMU_OPTION_no_frame },
6637 { "no-quit", 0, QEMU_OPTION_no_quit },
6639 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6640 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6641 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6642 { "smp", HAS_ARG, QEMU_OPTION_smp },
6643 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6645 /* temporary options */
6646 { "usb", 0, QEMU_OPTION_usb },
6647 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6648 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6649 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6650 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6651 { "daemonize", 0, QEMU_OPTION_daemonize },
6652 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6653 #if defined(TARGET_ARM)
6654 { "semihosting", 0, QEMU_OPTION_semihosting },
6656 { "name", HAS_ARG, QEMU_OPTION_name },
6660 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
6662 /* this stack is only used during signal handling */
6663 #define SIGNAL_STACK_SIZE 32768
6665 static uint8_t *signal_stack;
6669 /* password input */
6671 static BlockDriverState *get_bdrv(int index)
6673 BlockDriverState *bs;
6676 bs = bs_table[index];
6677 } else if (index < 6) {
6678 bs = fd_table[index - 4];
6685 static void read_passwords(void)
6687 BlockDriverState *bs;
6691 for(i = 0; i < 6; i++) {
6693 if (bs && bdrv_is_encrypted(bs)) {
6694 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6695 for(j = 0; j < 3; j++) {
6696 monitor_readline("Password: ",
6697 1, password, sizeof(password));
6698 if (bdrv_set_key(bs, password) == 0)
6700 term_printf("invalid password\n");
6706 /* XXX: currently we cannot use simultaneously different CPUs */
6707 void register_machines(void)
6709 #if defined(TARGET_I386)
6710 qemu_register_machine(&pc_machine);
6711 qemu_register_machine(&isapc_machine);
6712 #elif defined(TARGET_PPC)
6713 qemu_register_machine(&heathrow_machine);
6714 qemu_register_machine(&core99_machine);
6715 qemu_register_machine(&prep_machine);
6716 #elif defined(TARGET_MIPS)
6717 qemu_register_machine(&mips_machine);
6718 qemu_register_machine(&mips_malta_machine);
6719 qemu_register_machine(&mips_pica61_machine);
6720 #elif defined(TARGET_SPARC)
6721 #ifdef TARGET_SPARC64
6722 qemu_register_machine(&sun4u_machine);
6724 qemu_register_machine(&ss5_machine);
6725 qemu_register_machine(&ss10_machine);
6727 #elif defined(TARGET_ARM)
6728 qemu_register_machine(&integratorcp_machine);
6729 qemu_register_machine(&versatilepb_machine);
6730 qemu_register_machine(&versatileab_machine);
6731 qemu_register_machine(&realview_machine);
6732 #elif defined(TARGET_SH4)
6733 qemu_register_machine(&shix_machine);
6734 #elif defined(TARGET_ALPHA)
6737 #error unsupported CPU
6742 struct soundhw soundhw[] = {
6749 { .init_isa = pcspk_audio_init }
6754 "Creative Sound Blaster 16",
6757 { .init_isa = SB16_init }
6764 "Yamaha YMF262 (OPL3)",
6766 "Yamaha YM3812 (OPL2)",
6770 { .init_isa = Adlib_init }
6777 "Gravis Ultrasound GF1",
6780 { .init_isa = GUS_init }
6786 "ENSONIQ AudioPCI ES1370",
6789 { .init_pci = es1370_init }
6792 { NULL, NULL, 0, 0, { NULL } }
6795 static void select_soundhw (const char *optarg)
6799 if (*optarg == '?') {
6802 printf ("Valid sound card names (comma separated):\n");
6803 for (c = soundhw; c->name; ++c) {
6804 printf ("%-11s %s\n", c->name, c->descr);
6806 printf ("\n-soundhw all will enable all of the above\n");
6807 exit (*optarg != '?');
6815 if (!strcmp (optarg, "all")) {
6816 for (c = soundhw; c->name; ++c) {
6824 e = strchr (p, ',');
6825 l = !e ? strlen (p) : (size_t) (e - p);
6827 for (c = soundhw; c->name; ++c) {
6828 if (!strncmp (c->name, p, l)) {
6837 "Unknown sound card name (too big to show)\n");
6840 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6845 p += l + (e != NULL);
6849 goto show_valid_cards;
6855 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6857 exit(STATUS_CONTROL_C_EXIT);
6862 #define MAX_NET_CLIENTS 32
6864 int main(int argc, char **argv)
6866 #ifdef CONFIG_GDBSTUB
6868 const char *gdbstub_port;
6871 int snapshot, linux_boot;
6872 const char *initrd_filename;
6873 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6874 const char *sd_filename;
6875 const char *kernel_filename, *kernel_cmdline;
6876 DisplayState *ds = &display_state;
6877 int cyls, heads, secs, translation;
6878 char net_clients[MAX_NET_CLIENTS][256];
6881 const char *r, *optarg;
6882 CharDriverState *monitor_hd;
6883 char monitor_device[128];
6884 char serial_devices[MAX_SERIAL_PORTS][128];
6885 int serial_device_index;
6886 char parallel_devices[MAX_PARALLEL_PORTS][128];
6887 int parallel_device_index;
6888 const char *loadvm = NULL;
6889 QEMUMachine *machine;
6890 const char *cpu_model;
6891 char usb_devices[MAX_USB_CMDLINE][128];
6892 int usb_devices_index;
6894 const char *pid_file = NULL;
6896 LIST_INIT (&vm_change_state_head);
6899 struct sigaction act;
6900 sigfillset(&act.sa_mask);
6902 act.sa_handler = SIG_IGN;
6903 sigaction(SIGPIPE, &act, NULL);
6906 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6907 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6908 QEMU to run on a single CPU */
6913 h = GetCurrentProcess();
6914 if (GetProcessAffinityMask(h, &mask, &smask)) {
6915 for(i = 0; i < 32; i++) {
6916 if (mask & (1 << i))
6921 SetProcessAffinityMask(h, mask);
6927 register_machines();
6928 machine = first_machine;
6930 initrd_filename = NULL;
6931 for(i = 0; i < MAX_FD; i++)
6932 fd_filename[i] = NULL;
6933 for(i = 0; i < MAX_DISKS; i++)
6934 hd_filename[i] = NULL;
6936 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6937 vga_ram_size = VGA_RAM_SIZE;
6938 #ifdef CONFIG_GDBSTUB
6940 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6944 kernel_filename = NULL;
6945 kernel_cmdline = "";
6951 cyls = heads = secs = 0;
6952 translation = BIOS_ATA_TRANSLATION_AUTO;
6953 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6955 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6956 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6957 serial_devices[i][0] = '\0';
6958 serial_device_index = 0;
6960 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6961 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6962 parallel_devices[i][0] = '\0';
6963 parallel_device_index = 0;
6965 usb_devices_index = 0;
6970 /* default mac address of the first network interface */
6978 hd_filename[0] = argv[optind++];
6980 const QEMUOption *popt;
6983 /* Treat --foo the same as -foo. */
6986 popt = qemu_options;
6989 fprintf(stderr, "%s: invalid option -- '%s'\n",
6993 if (!strcmp(popt->name, r + 1))
6997 if (popt->flags & HAS_ARG) {
6998 if (optind >= argc) {
6999 fprintf(stderr, "%s: option '%s' requires an argument\n",
7003 optarg = argv[optind++];
7008 switch(popt->index) {
7010 machine = find_machine(optarg);
7013 printf("Supported machines are:\n");
7014 for(m = first_machine; m != NULL; m = m->next) {
7015 printf("%-10s %s%s\n",
7017 m == first_machine ? " (default)" : "");
7022 case QEMU_OPTION_cpu:
7023 /* hw initialization will check this */
7024 if (optarg[0] == '?') {
7025 #if defined(TARGET_PPC)
7026 ppc_cpu_list(stdout, &fprintf);
7027 #elif defined(TARGET_ARM)
7029 #elif defined(TARGET_MIPS)
7030 mips_cpu_list(stdout, &fprintf);
7031 #elif defined(TARGET_SPARC)
7032 sparc_cpu_list(stdout, &fprintf);
7039 case QEMU_OPTION_initrd:
7040 initrd_filename = optarg;
7042 case QEMU_OPTION_hda:
7043 case QEMU_OPTION_hdb:
7044 case QEMU_OPTION_hdc:
7045 case QEMU_OPTION_hdd:
7048 hd_index = popt->index - QEMU_OPTION_hda;
7049 hd_filename[hd_index] = optarg;
7050 if (hd_index == cdrom_index)
7054 case QEMU_OPTION_sd:
7055 sd_filename = optarg;
7057 case QEMU_OPTION_snapshot:
7060 case QEMU_OPTION_hdachs:
7064 cyls = strtol(p, (char **)&p, 0);
7065 if (cyls < 1 || cyls > 16383)
7070 heads = strtol(p, (char **)&p, 0);
7071 if (heads < 1 || heads > 16)
7076 secs = strtol(p, (char **)&p, 0);
7077 if (secs < 1 || secs > 63)
7081 if (!strcmp(p, "none"))
7082 translation = BIOS_ATA_TRANSLATION_NONE;
7083 else if (!strcmp(p, "lba"))
7084 translation = BIOS_ATA_TRANSLATION_LBA;
7085 else if (!strcmp(p, "auto"))
7086 translation = BIOS_ATA_TRANSLATION_AUTO;
7089 } else if (*p != '\0') {
7091 fprintf(stderr, "qemu: invalid physical CHS format\n");
7096 case QEMU_OPTION_nographic:
7097 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7098 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7099 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7102 case QEMU_OPTION_kernel:
7103 kernel_filename = optarg;
7105 case QEMU_OPTION_append:
7106 kernel_cmdline = optarg;
7108 case QEMU_OPTION_cdrom:
7109 if (cdrom_index >= 0) {
7110 hd_filename[cdrom_index] = optarg;
7113 case QEMU_OPTION_boot:
7114 boot_device = optarg[0];
7115 if (boot_device != 'a' &&
7116 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7118 boot_device != 'n' &&
7120 boot_device != 'c' && boot_device != 'd') {
7121 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7125 case QEMU_OPTION_fda:
7126 fd_filename[0] = optarg;
7128 case QEMU_OPTION_fdb:
7129 fd_filename[1] = optarg;
7132 case QEMU_OPTION_no_fd_bootchk:
7136 case QEMU_OPTION_no_code_copy:
7137 code_copy_enabled = 0;
7139 case QEMU_OPTION_net:
7140 if (nb_net_clients >= MAX_NET_CLIENTS) {
7141 fprintf(stderr, "qemu: too many network clients\n");
7144 pstrcpy(net_clients[nb_net_clients],
7145 sizeof(net_clients[0]),
7150 case QEMU_OPTION_tftp:
7151 tftp_prefix = optarg;
7153 case QEMU_OPTION_bootp:
7154 bootp_filename = optarg;
7157 case QEMU_OPTION_smb:
7158 net_slirp_smb(optarg);
7161 case QEMU_OPTION_redir:
7162 net_slirp_redir(optarg);
7166 case QEMU_OPTION_audio_help:
7170 case QEMU_OPTION_soundhw:
7171 select_soundhw (optarg);
7178 ram_size = atoi(optarg) * 1024 * 1024;
7181 if (ram_size > PHYS_RAM_MAX_SIZE) {
7182 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7183 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7192 mask = cpu_str_to_log_mask(optarg);
7194 printf("Log items (comma separated):\n");
7195 for(item = cpu_log_items; item->mask != 0; item++) {
7196 printf("%-10s %s\n", item->name, item->help);
7203 #ifdef CONFIG_GDBSTUB
7208 gdbstub_port = optarg;
7218 keyboard_layout = optarg;
7220 case QEMU_OPTION_localtime:
7223 case QEMU_OPTION_cirrusvga:
7224 cirrus_vga_enabled = 1;
7227 case QEMU_OPTION_vmsvga:
7228 cirrus_vga_enabled = 0;
7231 case QEMU_OPTION_std_vga:
7232 cirrus_vga_enabled = 0;
7240 w = strtol(p, (char **)&p, 10);
7243 fprintf(stderr, "qemu: invalid resolution or depth\n");
7249 h = strtol(p, (char **)&p, 10);
7254 depth = strtol(p, (char **)&p, 10);
7255 if (depth != 8 && depth != 15 && depth != 16 &&
7256 depth != 24 && depth != 32)
7258 } else if (*p == '\0') {
7259 depth = graphic_depth;
7266 graphic_depth = depth;
7269 case QEMU_OPTION_echr:
7272 term_escape_char = strtol(optarg, &r, 0);
7274 printf("Bad argument to echr\n");
7277 case QEMU_OPTION_monitor:
7278 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7280 case QEMU_OPTION_serial:
7281 if (serial_device_index >= MAX_SERIAL_PORTS) {
7282 fprintf(stderr, "qemu: too many serial ports\n");
7285 pstrcpy(serial_devices[serial_device_index],
7286 sizeof(serial_devices[0]), optarg);
7287 serial_device_index++;
7289 case QEMU_OPTION_parallel:
7290 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7291 fprintf(stderr, "qemu: too many parallel ports\n");
7294 pstrcpy(parallel_devices[parallel_device_index],
7295 sizeof(parallel_devices[0]), optarg);
7296 parallel_device_index++;
7298 case QEMU_OPTION_loadvm:
7301 case QEMU_OPTION_full_screen:
7305 case QEMU_OPTION_no_frame:
7308 case QEMU_OPTION_no_quit:
7312 case QEMU_OPTION_pidfile:
7316 case QEMU_OPTION_win2k_hack:
7317 win2k_install_hack = 1;
7321 case QEMU_OPTION_no_kqemu:
7324 case QEMU_OPTION_kernel_kqemu:
7328 case QEMU_OPTION_usb:
7331 case QEMU_OPTION_usbdevice:
7333 if (usb_devices_index >= MAX_USB_CMDLINE) {
7334 fprintf(stderr, "Too many USB devices\n");
7337 pstrcpy(usb_devices[usb_devices_index],
7338 sizeof(usb_devices[usb_devices_index]),
7340 usb_devices_index++;
7342 case QEMU_OPTION_smp:
7343 smp_cpus = atoi(optarg);
7344 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7345 fprintf(stderr, "Invalid number of CPUs\n");
7349 case QEMU_OPTION_vnc:
7350 vnc_display = optarg;
7352 case QEMU_OPTION_no_acpi:
7355 case QEMU_OPTION_no_reboot:
7358 case QEMU_OPTION_daemonize:
7361 case QEMU_OPTION_option_rom:
7362 if (nb_option_roms >= MAX_OPTION_ROMS) {
7363 fprintf(stderr, "Too many option ROMs\n");
7366 option_rom[nb_option_roms] = optarg;
7369 case QEMU_OPTION_semihosting:
7370 semihosting_enabled = 1;
7372 case QEMU_OPTION_name:
7380 if (daemonize && !nographic && vnc_display == NULL) {
7381 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7388 if (pipe(fds) == -1)
7399 len = read(fds[0], &status, 1);
7400 if (len == -1 && (errno == EINTR))
7405 else if (status == 1) {
7406 fprintf(stderr, "Could not acquire pidfile\n");
7424 signal(SIGTSTP, SIG_IGN);
7425 signal(SIGTTOU, SIG_IGN);
7426 signal(SIGTTIN, SIG_IGN);
7430 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7433 write(fds[1], &status, 1);
7435 fprintf(stderr, "Could not acquire pid file\n");
7443 linux_boot = (kernel_filename != NULL);
7446 boot_device != 'n' &&
7447 hd_filename[0] == '\0' &&
7448 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7449 fd_filename[0] == '\0')
7452 /* boot to floppy or the default cd if no hard disk defined yet */
7453 if (hd_filename[0] == '\0' && boot_device == 'c') {
7454 if (fd_filename[0] != '\0')
7460 setvbuf(stdout, NULL, _IOLBF, 0);
7470 /* init network clients */
7471 if (nb_net_clients == 0) {
7472 /* if no clients, we use a default config */
7473 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7475 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7480 for(i = 0;i < nb_net_clients; i++) {
7481 if (net_client_init(net_clients[i]) < 0)
7486 if (boot_device == 'n') {
7487 for (i = 0; i < nb_nics; i++) {
7488 const char *model = nd_table[i].model;
7492 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7493 if (get_image_size(buf) > 0) {
7494 option_rom[nb_option_roms] = strdup(buf);
7500 fprintf(stderr, "No valid PXE rom found for network device\n");
7503 boot_device = 'c'; /* to prevent confusion by the BIOS */
7507 /* init the memory */
7508 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7510 phys_ram_base = qemu_vmalloc(phys_ram_size);
7511 if (!phys_ram_base) {
7512 fprintf(stderr, "Could not allocate physical memory\n");
7516 /* we always create the cdrom drive, even if no disk is there */
7518 if (cdrom_index >= 0) {
7519 bs_table[cdrom_index] = bdrv_new("cdrom");
7520 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7523 /* open the virtual block devices */
7524 for(i = 0; i < MAX_DISKS; i++) {
7525 if (hd_filename[i]) {
7528 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7529 bs_table[i] = bdrv_new(buf);
7531 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7532 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7536 if (i == 0 && cyls != 0) {
7537 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7538 bdrv_set_translation_hint(bs_table[i], translation);
7543 /* we always create at least one floppy disk */
7544 fd_table[0] = bdrv_new("fda");
7545 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7547 for(i = 0; i < MAX_FD; i++) {
7548 if (fd_filename[i]) {
7551 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7552 fd_table[i] = bdrv_new(buf);
7553 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7555 if (fd_filename[i][0] != '\0') {
7556 if (bdrv_open(fd_table[i], fd_filename[i],
7557 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7558 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7566 sd_bdrv = bdrv_new ("sd");
7567 /* FIXME: This isn't really a floppy, but it's a reasonable
7569 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7571 if (bdrv_open(sd_bdrv, sd_filename,
7572 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7573 fprintf(stderr, "qemu: could not open SD card image %s\n",
7578 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7579 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7585 dumb_display_init(ds);
7586 } else if (vnc_display != NULL) {
7587 vnc_display_init(ds, vnc_display);
7589 #if defined(CONFIG_SDL)
7590 sdl_display_init(ds, full_screen, no_frame);
7591 #elif defined(CONFIG_COCOA)
7592 cocoa_display_init(ds, full_screen);
7594 dumb_display_init(ds);
7598 /* Maintain compatibility with multiple stdio monitors */
7599 if (!strcmp(monitor_device,"stdio")) {
7600 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7601 if (!strcmp(serial_devices[i],"mon:stdio")) {
7602 monitor_device[0] = '\0';
7604 } else if (!strcmp(serial_devices[i],"stdio")) {
7605 monitor_device[0] = '\0';
7606 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7611 if (monitor_device[0] != '\0') {
7612 monitor_hd = qemu_chr_open(monitor_device);
7614 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7617 monitor_init(monitor_hd, !nographic);
7620 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7621 const char *devname = serial_devices[i];
7622 if (devname[0] != '\0' && strcmp(devname, "none")) {
7623 serial_hds[i] = qemu_chr_open(devname);
7624 if (!serial_hds[i]) {
7625 fprintf(stderr, "qemu: could not open serial device '%s'\n",
7629 if (!strcmp(devname, "vc"))
7630 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7634 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7635 const char *devname = parallel_devices[i];
7636 if (devname[0] != '\0' && strcmp(devname, "none")) {
7637 parallel_hds[i] = qemu_chr_open(devname);
7638 if (!parallel_hds[i]) {
7639 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
7643 if (!strcmp(devname, "vc"))
7644 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7648 machine->init(ram_size, vga_ram_size, boot_device,
7649 ds, fd_filename, snapshot,
7650 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7652 /* init USB devices */
7654 for(i = 0; i < usb_devices_index; i++) {
7655 if (usb_device_add(usb_devices[i]) < 0) {
7656 fprintf(stderr, "Warning: could not add USB device %s\n",
7662 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7663 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7665 #ifdef CONFIG_GDBSTUB
7667 /* XXX: use standard host:port notation and modify options
7669 if (gdbserver_start(gdbstub_port) < 0) {
7670 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7680 /* XXX: simplify init */
7693 len = write(fds[1], &status, 1);
7694 if (len == -1 && (errno == EINTR))
7700 fd = open("/dev/null", O_RDWR);