4 * Copyright (c) 2003-2005 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
34 #include <sys/times.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
52 #include <linux/if_tun.h>
55 #include <linux/rtc.h>
56 #include <linux/ppdev.h>
61 #if defined(CONFIG_SLIRP)
67 #include <sys/timeb.h>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
73 #include "qemu_socket.h"
79 #endif /* CONFIG_SDL */
83 #define main qemu_main
84 #endif /* CONFIG_COCOA */
90 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 //#define DEBUG_UNUSED_IOPORT
93 //#define DEBUG_IOPORT
95 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
98 #define DEFAULT_RAM_SIZE 144
100 #define DEFAULT_RAM_SIZE 128
103 #define GUI_REFRESH_INTERVAL 30
105 /* Max number of USB devices that can be specified on the commandline. */
106 #define MAX_USB_CMDLINE 8
108 /* XXX: use a two level table to limit memory usage */
109 #define MAX_IOPORTS 65536
111 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
112 char phys_ram_file[1024];
113 void *ioport_opaque[MAX_IOPORTS];
114 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
115 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
116 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
117 to store the VM snapshots */
118 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
119 /* point to the block driver where the snapshots are managed */
120 BlockDriverState *bs_snapshots;
123 static DisplayState display_state;
125 const char* keyboard_layout = NULL;
126 int64_t ticks_per_sec;
127 int boot_device = 'c';
129 int pit_min_timer_count = 0;
131 NICInfo nd_table[MAX_NICS];
132 QEMUTimer *gui_timer;
135 int cirrus_vga_enabled = 1;
137 int graphic_width = 1024;
138 int graphic_height = 768;
140 int graphic_width = 800;
141 int graphic_height = 600;
143 int graphic_depth = 15;
145 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
146 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
148 int win2k_install_hack = 0;
151 static VLANState *first_vlan;
153 int vnc_display = -1;
154 #if defined(TARGET_SPARC)
156 #elif defined(TARGET_I386)
161 int acpi_enabled = 1;
164 /***********************************************************/
165 /* x86 ISA bus support */
167 target_phys_addr_t isa_mem_base = 0;
170 uint32_t default_ioport_readb(void *opaque, uint32_t address)
172 #ifdef DEBUG_UNUSED_IOPORT
173 fprintf(stderr, "inb: port=0x%04x\n", address);
178 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
180 #ifdef DEBUG_UNUSED_IOPORT
181 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
185 /* default is to make two byte accesses */
186 uint32_t default_ioport_readw(void *opaque, uint32_t address)
189 data = ioport_read_table[0][address](ioport_opaque[address], address);
190 address = (address + 1) & (MAX_IOPORTS - 1);
191 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
195 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
197 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
198 address = (address + 1) & (MAX_IOPORTS - 1);
199 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
202 uint32_t default_ioport_readl(void *opaque, uint32_t address)
204 #ifdef DEBUG_UNUSED_IOPORT
205 fprintf(stderr, "inl: port=0x%04x\n", address);
210 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
212 #ifdef DEBUG_UNUSED_IOPORT
213 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
217 void init_ioports(void)
221 for(i = 0; i < MAX_IOPORTS; i++) {
222 ioport_read_table[0][i] = default_ioport_readb;
223 ioport_write_table[0][i] = default_ioport_writeb;
224 ioport_read_table[1][i] = default_ioport_readw;
225 ioport_write_table[1][i] = default_ioport_writew;
226 ioport_read_table[2][i] = default_ioport_readl;
227 ioport_write_table[2][i] = default_ioport_writel;
231 /* size is the word size in byte */
232 int register_ioport_read(int start, int length, int size,
233 IOPortReadFunc *func, void *opaque)
239 } else if (size == 2) {
241 } else if (size == 4) {
244 hw_error("register_ioport_read: invalid size");
247 for(i = start; i < start + length; i += size) {
248 ioport_read_table[bsize][i] = func;
249 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
250 hw_error("register_ioport_read: invalid opaque");
251 ioport_opaque[i] = opaque;
256 /* size is the word size in byte */
257 int register_ioport_write(int start, int length, int size,
258 IOPortWriteFunc *func, void *opaque)
264 } else if (size == 2) {
266 } else if (size == 4) {
269 hw_error("register_ioport_write: invalid size");
272 for(i = start; i < start + length; i += size) {
273 ioport_write_table[bsize][i] = func;
274 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
275 hw_error("register_ioport_read: invalid opaque");
276 ioport_opaque[i] = opaque;
281 void isa_unassign_ioport(int start, int length)
285 for(i = start; i < start + length; i++) {
286 ioport_read_table[0][i] = default_ioport_readb;
287 ioport_read_table[1][i] = default_ioport_readw;
288 ioport_read_table[2][i] = default_ioport_readl;
290 ioport_write_table[0][i] = default_ioport_writeb;
291 ioport_write_table[1][i] = default_ioport_writew;
292 ioport_write_table[2][i] = default_ioport_writel;
296 /***********************************************************/
298 void pstrcpy(char *buf, int buf_size, const char *str)
308 if (c == 0 || q >= buf + buf_size - 1)
315 /* strcat and truncate. */
316 char *pstrcat(char *buf, int buf_size, const char *s)
321 pstrcpy(buf + len, buf_size - len, s);
325 int strstart(const char *str, const char *val, const char **ptr)
341 void cpu_outb(CPUState *env, int addr, int val)
344 if (loglevel & CPU_LOG_IOPORT)
345 fprintf(logfile, "outb: %04x %02x\n", addr, val);
347 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
350 env->last_io_time = cpu_get_time_fast();
354 void cpu_outw(CPUState *env, int addr, int val)
357 if (loglevel & CPU_LOG_IOPORT)
358 fprintf(logfile, "outw: %04x %04x\n", addr, val);
360 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
363 env->last_io_time = cpu_get_time_fast();
367 void cpu_outl(CPUState *env, int addr, int val)
370 if (loglevel & CPU_LOG_IOPORT)
371 fprintf(logfile, "outl: %04x %08x\n", addr, val);
373 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
376 env->last_io_time = cpu_get_time_fast();
380 int cpu_inb(CPUState *env, int addr)
383 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
385 if (loglevel & CPU_LOG_IOPORT)
386 fprintf(logfile, "inb : %04x %02x\n", addr, val);
390 env->last_io_time = cpu_get_time_fast();
395 int cpu_inw(CPUState *env, int addr)
398 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
400 if (loglevel & CPU_LOG_IOPORT)
401 fprintf(logfile, "inw : %04x %04x\n", addr, val);
405 env->last_io_time = cpu_get_time_fast();
410 int cpu_inl(CPUState *env, int addr)
413 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
415 if (loglevel & CPU_LOG_IOPORT)
416 fprintf(logfile, "inl : %04x %08x\n", addr, val);
420 env->last_io_time = cpu_get_time_fast();
425 /***********************************************************/
426 void hw_error(const char *fmt, ...)
432 fprintf(stderr, "qemu: hardware error: ");
433 vfprintf(stderr, fmt, ap);
434 fprintf(stderr, "\n");
435 for(env = first_cpu; env != NULL; env = env->next_cpu) {
436 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
438 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
440 cpu_dump_state(env, stderr, fprintf, 0);
447 /***********************************************************/
450 static QEMUPutKBDEvent *qemu_put_kbd_event;
451 static void *qemu_put_kbd_event_opaque;
452 static QEMUPutMouseEvent *qemu_put_mouse_event;
453 static void *qemu_put_mouse_event_opaque;
454 static int qemu_put_mouse_event_absolute;
456 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
458 qemu_put_kbd_event_opaque = opaque;
459 qemu_put_kbd_event = func;
462 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
464 qemu_put_mouse_event_opaque = opaque;
465 qemu_put_mouse_event = func;
466 qemu_put_mouse_event_absolute = absolute;
469 void kbd_put_keycode(int keycode)
471 if (qemu_put_kbd_event) {
472 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
476 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
478 if (qemu_put_mouse_event) {
479 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
480 dx, dy, dz, buttons_state);
484 int kbd_mouse_is_absolute(void)
486 return qemu_put_mouse_event_absolute;
489 /* compute with 96 bit intermediate result: (a*b)/c */
490 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
495 #ifdef WORDS_BIGENDIAN
505 rl = (uint64_t)u.l.low * (uint64_t)b;
506 rh = (uint64_t)u.l.high * (uint64_t)b;
509 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
513 /***********************************************************/
514 /* real time host monotonic timer */
516 #define QEMU_TIMER_BASE 1000000000LL
520 static int64_t clock_freq;
522 static void init_get_clock(void)
526 ret = QueryPerformanceFrequency(&freq);
528 fprintf(stderr, "Could not calibrate ticks\n");
531 clock_freq = freq.QuadPart;
534 static int64_t get_clock(void)
537 QueryPerformanceCounter(&ti);
538 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
543 static int use_rt_clock;
545 static void init_get_clock(void)
548 #if defined(__linux__)
551 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
558 static int64_t get_clock(void)
560 #if defined(__linux__)
563 clock_gettime(CLOCK_MONOTONIC, &ts);
564 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
568 /* XXX: using gettimeofday leads to problems if the date
569 changes, so it should be avoided. */
571 gettimeofday(&tv, NULL);
572 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
578 /***********************************************************/
579 /* guest cycle counter */
581 static int64_t cpu_ticks_prev;
582 static int64_t cpu_ticks_offset;
583 static int64_t cpu_clock_offset;
584 static int cpu_ticks_enabled;
586 /* return the host CPU cycle counter and handle stop/restart */
587 int64_t cpu_get_ticks(void)
589 if (!cpu_ticks_enabled) {
590 return cpu_ticks_offset;
593 ticks = cpu_get_real_ticks();
594 if (cpu_ticks_prev > ticks) {
595 /* Note: non increasing ticks may happen if the host uses
597 cpu_ticks_offset += cpu_ticks_prev - ticks;
599 cpu_ticks_prev = ticks;
600 return ticks + cpu_ticks_offset;
604 /* return the host CPU monotonic timer and handle stop/restart */
605 static int64_t cpu_get_clock(void)
608 if (!cpu_ticks_enabled) {
609 return cpu_clock_offset;
612 return ti + cpu_clock_offset;
616 /* enable cpu_get_ticks() */
617 void cpu_enable_ticks(void)
619 if (!cpu_ticks_enabled) {
620 cpu_ticks_offset -= cpu_get_real_ticks();
621 cpu_clock_offset -= get_clock();
622 cpu_ticks_enabled = 1;
626 /* disable cpu_get_ticks() : the clock is stopped. You must not call
627 cpu_get_ticks() after that. */
628 void cpu_disable_ticks(void)
630 if (cpu_ticks_enabled) {
631 cpu_ticks_offset = cpu_get_ticks();
632 cpu_clock_offset = cpu_get_clock();
633 cpu_ticks_enabled = 0;
637 /***********************************************************/
640 #define QEMU_TIMER_REALTIME 0
641 #define QEMU_TIMER_VIRTUAL 1
645 /* XXX: add frequency */
653 struct QEMUTimer *next;
659 static QEMUTimer *active_timers[2];
661 static MMRESULT timerID;
662 static HANDLE host_alarm = NULL;
663 static unsigned int period = 1;
665 /* frequency of the times() clock tick */
666 static int timer_freq;
669 QEMUClock *qemu_new_clock(int type)
672 clock = qemu_mallocz(sizeof(QEMUClock));
679 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
683 ts = qemu_mallocz(sizeof(QEMUTimer));
690 void qemu_free_timer(QEMUTimer *ts)
695 /* stop a timer, but do not dealloc it */
696 void qemu_del_timer(QEMUTimer *ts)
700 /* NOTE: this code must be signal safe because
701 qemu_timer_expired() can be called from a signal. */
702 pt = &active_timers[ts->clock->type];
715 /* modify the current timer so that it will be fired when current_time
716 >= expire_time. The corresponding callback will be called. */
717 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
723 /* add the timer in the sorted list */
724 /* NOTE: this code must be signal safe because
725 qemu_timer_expired() can be called from a signal. */
726 pt = &active_timers[ts->clock->type];
731 if (t->expire_time > expire_time)
735 ts->expire_time = expire_time;
740 int qemu_timer_pending(QEMUTimer *ts)
743 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
750 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
754 return (timer_head->expire_time <= current_time);
757 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
763 if (!ts || ts->expire_time > current_time)
765 /* remove timer from the list before calling the callback */
766 *ptimer_head = ts->next;
769 /* run the callback (the timer list can be modified) */
774 int64_t qemu_get_clock(QEMUClock *clock)
776 switch(clock->type) {
777 case QEMU_TIMER_REALTIME:
778 return get_clock() / 1000000;
780 case QEMU_TIMER_VIRTUAL:
781 return cpu_get_clock();
785 static void init_timers(void)
788 ticks_per_sec = QEMU_TIMER_BASE;
789 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
790 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
794 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
796 uint64_t expire_time;
798 if (qemu_timer_pending(ts)) {
799 expire_time = ts->expire_time;
803 qemu_put_be64(f, expire_time);
806 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
808 uint64_t expire_time;
810 expire_time = qemu_get_be64(f);
811 if (expire_time != -1) {
812 qemu_mod_timer(ts, expire_time);
818 static void timer_save(QEMUFile *f, void *opaque)
820 if (cpu_ticks_enabled) {
821 hw_error("cannot save state if virtual timers are running");
823 qemu_put_be64s(f, &cpu_ticks_offset);
824 qemu_put_be64s(f, &ticks_per_sec);
827 static int timer_load(QEMUFile *f, void *opaque, int version_id)
831 if (cpu_ticks_enabled) {
834 qemu_get_be64s(f, &cpu_ticks_offset);
835 qemu_get_be64s(f, &ticks_per_sec);
840 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
841 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
843 static void host_alarm_handler(int host_signum)
847 #define DISP_FREQ 1000
849 static int64_t delta_min = INT64_MAX;
850 static int64_t delta_max, delta_cum, last_clock, delta, ti;
852 ti = qemu_get_clock(vm_clock);
853 if (last_clock != 0) {
854 delta = ti - last_clock;
855 if (delta < delta_min)
857 if (delta > delta_max)
860 if (++count == DISP_FREQ) {
861 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
862 muldiv64(delta_min, 1000000, ticks_per_sec),
863 muldiv64(delta_max, 1000000, ticks_per_sec),
864 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
865 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
867 delta_min = INT64_MAX;
875 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
876 qemu_get_clock(vm_clock)) ||
877 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
878 qemu_get_clock(rt_clock))) {
880 SetEvent(host_alarm);
882 CPUState *env = cpu_single_env;
884 /* stop the currently executing cpu because a timer occured */
885 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
887 if (env->kqemu_enabled) {
888 kqemu_cpu_interrupt(env);
897 #if defined(__linux__)
899 #define RTC_FREQ 1024
903 static int start_rtc_timer(void)
905 rtc_fd = open("/dev/rtc", O_RDONLY);
908 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
909 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
910 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
911 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
914 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
919 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
925 static int start_rtc_timer(void)
930 #endif /* !defined(__linux__) */
932 #endif /* !defined(_WIN32) */
934 static void init_timer_alarm(void)
941 ZeroMemory(&tc, sizeof(TIMECAPS));
942 timeGetDevCaps(&tc, sizeof(TIMECAPS));
943 if (period < tc.wPeriodMin)
944 period = tc.wPeriodMin;
945 timeBeginPeriod(period);
946 timerID = timeSetEvent(1, // interval (ms)
947 period, // resolution
948 host_alarm_handler, // function
949 (DWORD)&count, // user parameter
950 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
952 perror("failed timer alarm");
955 host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
957 perror("failed CreateEvent");
960 qemu_add_wait_object(host_alarm, NULL, NULL);
962 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
965 struct sigaction act;
966 struct itimerval itv;
968 /* get times() syscall frequency */
969 timer_freq = sysconf(_SC_CLK_TCK);
972 sigfillset(&act.sa_mask);
974 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
975 act.sa_flags |= SA_ONSTACK;
977 act.sa_handler = host_alarm_handler;
978 sigaction(SIGALRM, &act, NULL);
980 itv.it_interval.tv_sec = 0;
981 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
982 itv.it_value.tv_sec = 0;
983 itv.it_value.tv_usec = 10 * 1000;
984 setitimer(ITIMER_REAL, &itv, NULL);
985 /* we probe the tick duration of the kernel to inform the user if
986 the emulated kernel requested a too high timer frequency */
987 getitimer(ITIMER_REAL, &itv);
989 #if defined(__linux__)
990 /* XXX: force /dev/rtc usage because even 2.6 kernels may not
991 have timers with 1 ms resolution. The correct solution will
992 be to use the POSIX real time timers available in recent
994 if (itv.it_interval.tv_usec > 1000 || 1) {
995 /* try to use /dev/rtc to have a faster timer */
996 if (start_rtc_timer() < 0)
999 itv.it_interval.tv_sec = 0;
1000 itv.it_interval.tv_usec = 0;
1001 itv.it_value.tv_sec = 0;
1002 itv.it_value.tv_usec = 0;
1003 setitimer(ITIMER_REAL, &itv, NULL);
1006 sigaction(SIGIO, &act, NULL);
1007 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1008 fcntl(rtc_fd, F_SETOWN, getpid());
1010 #endif /* defined(__linux__) */
1013 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1014 PIT_FREQ) / 1000000;
1020 void quit_timers(void)
1023 timeKillEvent(timerID);
1024 timeEndPeriod(period);
1026 CloseHandle(host_alarm);
1032 /***********************************************************/
1033 /* character device */
1035 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1037 return s->chr_write(s, buf, len);
1040 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1044 return s->chr_ioctl(s, cmd, arg);
1047 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1052 vsnprintf(buf, sizeof(buf), fmt, ap);
1053 qemu_chr_write(s, buf, strlen(buf));
1057 void qemu_chr_send_event(CharDriverState *s, int event)
1059 if (s->chr_send_event)
1060 s->chr_send_event(s, event);
1063 void qemu_chr_add_read_handler(CharDriverState *s,
1064 IOCanRWHandler *fd_can_read,
1065 IOReadHandler *fd_read, void *opaque)
1067 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1070 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1072 s->chr_event = chr_event;
1075 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1080 static void null_chr_add_read_handler(CharDriverState *chr,
1081 IOCanRWHandler *fd_can_read,
1082 IOReadHandler *fd_read, void *opaque)
1086 CharDriverState *qemu_chr_open_null(void)
1088 CharDriverState *chr;
1090 chr = qemu_mallocz(sizeof(CharDriverState));
1093 chr->chr_write = null_chr_write;
1094 chr->chr_add_read_handler = null_chr_add_read_handler;
1100 static void socket_cleanup(void)
1105 static int socket_init(void)
1110 ret = WSAStartup(MAKEWORD(2,2), &Data);
1112 err = WSAGetLastError();
1113 fprintf(stderr, "WSAStartup: %d\n", err);
1116 atexit(socket_cleanup);
1120 static int send_all(int fd, const uint8_t *buf, int len1)
1126 ret = send(fd, buf, len, 0);
1129 errno = WSAGetLastError();
1130 if (errno != WSAEWOULDBLOCK) {
1133 } else if (ret == 0) {
1143 void socket_set_nonblock(int fd)
1145 unsigned long opt = 1;
1146 ioctlsocket(fd, FIONBIO, &opt);
1151 static int unix_write(int fd, const uint8_t *buf, int len1)
1157 ret = write(fd, buf, len);
1159 if (errno != EINTR && errno != EAGAIN)
1161 } else if (ret == 0) {
1171 static inline int send_all(int fd, const uint8_t *buf, int len1)
1173 return unix_write(fd, buf, len1);
1176 void socket_set_nonblock(int fd)
1178 fcntl(fd, F_SETFL, O_NONBLOCK);
1180 #endif /* !_WIN32 */
1186 IOCanRWHandler *fd_can_read;
1187 IOReadHandler *fd_read;
1192 #define STDIO_MAX_CLIENTS 2
1194 static int stdio_nb_clients;
1195 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1197 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1199 FDCharDriver *s = chr->opaque;
1200 return unix_write(s->fd_out, buf, len);
1203 static int fd_chr_read_poll(void *opaque)
1205 CharDriverState *chr = opaque;
1206 FDCharDriver *s = chr->opaque;
1208 s->max_size = s->fd_can_read(s->fd_opaque);
1212 static void fd_chr_read(void *opaque)
1214 CharDriverState *chr = opaque;
1215 FDCharDriver *s = chr->opaque;
1220 if (len > s->max_size)
1224 size = read(s->fd_in, buf, len);
1226 s->fd_read(s->fd_opaque, buf, size);
1230 static void fd_chr_add_read_handler(CharDriverState *chr,
1231 IOCanRWHandler *fd_can_read,
1232 IOReadHandler *fd_read, void *opaque)
1234 FDCharDriver *s = chr->opaque;
1236 if (s->fd_in >= 0) {
1237 s->fd_can_read = fd_can_read;
1238 s->fd_read = fd_read;
1239 s->fd_opaque = opaque;
1240 if (nographic && s->fd_in == 0) {
1242 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1243 fd_chr_read, NULL, chr);
1248 /* open a character device to a unix fd */
1249 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1251 CharDriverState *chr;
1254 chr = qemu_mallocz(sizeof(CharDriverState));
1257 s = qemu_mallocz(sizeof(FDCharDriver));
1265 chr->chr_write = fd_chr_write;
1266 chr->chr_add_read_handler = fd_chr_add_read_handler;
1270 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1274 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1277 return qemu_chr_open_fd(-1, fd_out);
1280 CharDriverState *qemu_chr_open_pipe(const char *filename)
1284 fd = open(filename, O_RDWR | O_BINARY);
1287 return qemu_chr_open_fd(fd, fd);
1291 /* for STDIO, we handle the case where several clients use it
1294 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1296 #define TERM_FIFO_MAX_SIZE 1
1298 static int term_got_escape, client_index;
1299 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1300 static int term_fifo_size;
1301 static int term_timestamps;
1302 static int64_t term_timestamps_start;
1304 void term_print_help(void)
1307 "C-a h print this help\n"
1308 "C-a x exit emulator\n"
1309 "C-a s save disk data back to file (if -snapshot)\n"
1310 "C-a b send break (magic sysrq)\n"
1311 "C-a t toggle console timestamps\n"
1312 "C-a c switch between console and monitor\n"
1313 "C-a C-a send C-a\n"
1317 /* called when a char is received */
1318 static void stdio_received_byte(int ch)
1320 if (term_got_escape) {
1321 term_got_escape = 0;
1332 for (i = 0; i < MAX_DISKS; i++) {
1334 bdrv_commit(bs_table[i]);
1339 if (client_index < stdio_nb_clients) {
1340 CharDriverState *chr;
1343 chr = stdio_clients[client_index];
1345 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1350 if (client_index >= stdio_nb_clients)
1352 if (client_index == 0) {
1353 /* send a new line in the monitor to get the prompt */
1359 term_timestamps = !term_timestamps;
1360 term_timestamps_start = -1;
1365 } else if (ch == TERM_ESCAPE) {
1366 term_got_escape = 1;
1369 if (client_index < stdio_nb_clients) {
1371 CharDriverState *chr;
1374 chr = stdio_clients[client_index];
1376 if (s->fd_can_read(s->fd_opaque) > 0) {
1378 s->fd_read(s->fd_opaque, buf, 1);
1379 } else if (term_fifo_size == 0) {
1380 term_fifo[term_fifo_size++] = ch;
1386 static int stdio_read_poll(void *opaque)
1388 CharDriverState *chr;
1391 if (client_index < stdio_nb_clients) {
1392 chr = stdio_clients[client_index];
1394 /* try to flush the queue if needed */
1395 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1396 s->fd_read(s->fd_opaque, term_fifo, 1);
1399 /* see if we can absorb more chars */
1400 if (term_fifo_size == 0)
1409 static void stdio_read(void *opaque)
1414 size = read(0, buf, 1);
1416 stdio_received_byte(buf[0]);
1419 static int stdio_write(CharDriverState *chr, const uint8_t *buf, int len)
1421 FDCharDriver *s = chr->opaque;
1422 if (!term_timestamps) {
1423 return unix_write(s->fd_out, buf, len);
1428 for(i = 0; i < len; i++) {
1429 unix_write(s->fd_out, buf + i, 1);
1430 if (buf[i] == '\n') {
1435 if (term_timestamps_start == -1)
1436 term_timestamps_start = ti;
1437 ti -= term_timestamps_start;
1438 secs = ti / 1000000000;
1439 snprintf(buf1, sizeof(buf1),
1440 "[%02d:%02d:%02d.%03d] ",
1444 (int)((ti / 1000000) % 1000));
1445 unix_write(s->fd_out, buf1, strlen(buf1));
1452 /* init terminal so that we can grab keys */
1453 static struct termios oldtty;
1454 static int old_fd0_flags;
1456 static void term_exit(void)
1458 tcsetattr (0, TCSANOW, &oldtty);
1459 fcntl(0, F_SETFL, old_fd0_flags);
1462 static void term_init(void)
1466 tcgetattr (0, &tty);
1468 old_fd0_flags = fcntl(0, F_GETFL);
1470 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1471 |INLCR|IGNCR|ICRNL|IXON);
1472 tty.c_oflag |= OPOST;
1473 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1474 /* if graphical mode, we allow Ctrl-C handling */
1476 tty.c_lflag &= ~ISIG;
1477 tty.c_cflag &= ~(CSIZE|PARENB);
1480 tty.c_cc[VTIME] = 0;
1482 tcsetattr (0, TCSANOW, &tty);
1486 fcntl(0, F_SETFL, O_NONBLOCK);
1489 CharDriverState *qemu_chr_open_stdio(void)
1491 CharDriverState *chr;
1494 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1496 chr = qemu_chr_open_fd(0, 1);
1497 chr->chr_write = stdio_write;
1498 if (stdio_nb_clients == 0)
1499 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1500 client_index = stdio_nb_clients;
1502 if (stdio_nb_clients != 0)
1504 chr = qemu_chr_open_fd(0, 1);
1506 stdio_clients[stdio_nb_clients++] = chr;
1507 if (stdio_nb_clients == 1) {
1508 /* set the terminal in raw mode */
1514 #if defined(__linux__)
1515 CharDriverState *qemu_chr_open_pty(void)
1518 char slave_name[1024];
1519 int master_fd, slave_fd;
1521 /* Not satisfying */
1522 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1526 /* Disabling local echo and line-buffered output */
1527 tcgetattr (master_fd, &tty);
1528 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1530 tty.c_cc[VTIME] = 0;
1531 tcsetattr (master_fd, TCSAFLUSH, &tty);
1533 fprintf(stderr, "char device redirected to %s\n", slave_name);
1534 return qemu_chr_open_fd(master_fd, master_fd);
1537 static void tty_serial_init(int fd, int speed,
1538 int parity, int data_bits, int stop_bits)
1544 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1545 speed, parity, data_bits, stop_bits);
1547 tcgetattr (fd, &tty);
1589 cfsetispeed(&tty, spd);
1590 cfsetospeed(&tty, spd);
1592 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1593 |INLCR|IGNCR|ICRNL|IXON);
1594 tty.c_oflag |= OPOST;
1595 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1596 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1617 tty.c_cflag |= PARENB;
1620 tty.c_cflag |= PARENB | PARODD;
1624 tcsetattr (fd, TCSANOW, &tty);
1627 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1629 FDCharDriver *s = chr->opaque;
1632 case CHR_IOCTL_SERIAL_SET_PARAMS:
1634 QEMUSerialSetParams *ssp = arg;
1635 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1636 ssp->data_bits, ssp->stop_bits);
1639 case CHR_IOCTL_SERIAL_SET_BREAK:
1641 int enable = *(int *)arg;
1643 tcsendbreak(s->fd_in, 1);
1652 CharDriverState *qemu_chr_open_tty(const char *filename)
1654 CharDriverState *chr;
1657 fd = open(filename, O_RDWR | O_NONBLOCK);
1660 fcntl(fd, F_SETFL, O_NONBLOCK);
1661 tty_serial_init(fd, 115200, 'N', 8, 1);
1662 chr = qemu_chr_open_fd(fd, fd);
1665 chr->chr_ioctl = tty_serial_ioctl;
1669 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1671 int fd = (int)chr->opaque;
1675 case CHR_IOCTL_PP_READ_DATA:
1676 if (ioctl(fd, PPRDATA, &b) < 0)
1678 *(uint8_t *)arg = b;
1680 case CHR_IOCTL_PP_WRITE_DATA:
1681 b = *(uint8_t *)arg;
1682 if (ioctl(fd, PPWDATA, &b) < 0)
1685 case CHR_IOCTL_PP_READ_CONTROL:
1686 if (ioctl(fd, PPRCONTROL, &b) < 0)
1688 *(uint8_t *)arg = b;
1690 case CHR_IOCTL_PP_WRITE_CONTROL:
1691 b = *(uint8_t *)arg;
1692 if (ioctl(fd, PPWCONTROL, &b) < 0)
1695 case CHR_IOCTL_PP_READ_STATUS:
1696 if (ioctl(fd, PPRSTATUS, &b) < 0)
1698 *(uint8_t *)arg = b;
1706 CharDriverState *qemu_chr_open_pp(const char *filename)
1708 CharDriverState *chr;
1711 fd = open(filename, O_RDWR);
1715 if (ioctl(fd, PPCLAIM) < 0) {
1720 chr = qemu_mallocz(sizeof(CharDriverState));
1725 chr->opaque = (void *)fd;
1726 chr->chr_write = null_chr_write;
1727 chr->chr_add_read_handler = null_chr_add_read_handler;
1728 chr->chr_ioctl = pp_ioctl;
1733 CharDriverState *qemu_chr_open_pty(void)
1739 #endif /* !defined(_WIN32) */
1743 IOCanRWHandler *fd_can_read;
1744 IOReadHandler *fd_read;
1747 HANDLE hcom, hrecv, hsend;
1748 OVERLAPPED orecv, osend;
1753 #define NSENDBUF 2048
1754 #define NRECVBUF 2048
1755 #define MAXCONNECT 1
1756 #define NTIMEOUT 5000
1758 static int win_chr_poll(void *opaque);
1759 static int win_chr_pipe_poll(void *opaque);
1761 static void win_chr_close2(WinCharState *s)
1764 CloseHandle(s->hsend);
1768 CloseHandle(s->hrecv);
1772 CloseHandle(s->hcom);
1776 qemu_del_polling_cb(win_chr_pipe_poll, s);
1778 qemu_del_polling_cb(win_chr_poll, s);
1781 static void win_chr_close(CharDriverState *chr)
1783 WinCharState *s = chr->opaque;
1787 static int win_chr_init(WinCharState *s, const char *filename)
1790 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1795 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1797 fprintf(stderr, "Failed CreateEvent\n");
1800 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1802 fprintf(stderr, "Failed CreateEvent\n");
1806 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1807 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1808 if (s->hcom == INVALID_HANDLE_VALUE) {
1809 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1814 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1815 fprintf(stderr, "Failed SetupComm\n");
1819 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1820 size = sizeof(COMMCONFIG);
1821 GetDefaultCommConfig(filename, &comcfg, &size);
1822 comcfg.dcb.DCBlength = sizeof(DCB);
1823 CommConfigDialog(filename, NULL, &comcfg);
1825 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1826 fprintf(stderr, "Failed SetCommState\n");
1830 if (!SetCommMask(s->hcom, EV_ERR)) {
1831 fprintf(stderr, "Failed SetCommMask\n");
1835 cto.ReadIntervalTimeout = MAXDWORD;
1836 if (!SetCommTimeouts(s->hcom, &cto)) {
1837 fprintf(stderr, "Failed SetCommTimeouts\n");
1841 if (!ClearCommError(s->hcom, &err, &comstat)) {
1842 fprintf(stderr, "Failed ClearCommError\n");
1845 qemu_add_polling_cb(win_chr_poll, s);
1853 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1855 WinCharState *s = chr->opaque;
1856 DWORD len, ret, size, err;
1859 ZeroMemory(&s->osend, sizeof(s->osend));
1860 s->osend.hEvent = s->hsend;
1863 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1865 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1867 err = GetLastError();
1868 if (err == ERROR_IO_PENDING) {
1869 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1887 static int win_chr_read_poll(WinCharState *s)
1889 s->max_size = s->fd_can_read(s->win_opaque);
1893 static void win_chr_readfile(WinCharState *s)
1899 ZeroMemory(&s->orecv, sizeof(s->orecv));
1900 s->orecv.hEvent = s->hrecv;
1901 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1903 err = GetLastError();
1904 if (err == ERROR_IO_PENDING) {
1905 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1910 s->fd_read(s->win_opaque, buf, size);
1914 static void win_chr_read(WinCharState *s)
1916 if (s->len > s->max_size)
1917 s->len = s->max_size;
1921 win_chr_readfile(s);
1924 static int win_chr_poll(void *opaque)
1926 WinCharState *s = opaque;
1930 ClearCommError(s->hcom, &comerr, &status);
1931 if (status.cbInQue > 0) {
1932 s->len = status.cbInQue;
1933 win_chr_read_poll(s);
1940 static void win_chr_add_read_handler(CharDriverState *chr,
1941 IOCanRWHandler *fd_can_read,
1942 IOReadHandler *fd_read, void *opaque)
1944 WinCharState *s = chr->opaque;
1946 s->fd_can_read = fd_can_read;
1947 s->fd_read = fd_read;
1948 s->win_opaque = opaque;
1951 CharDriverState *qemu_chr_open_win(const char *filename)
1953 CharDriverState *chr;
1956 chr = qemu_mallocz(sizeof(CharDriverState));
1959 s = qemu_mallocz(sizeof(WinCharState));
1965 chr->chr_write = win_chr_write;
1966 chr->chr_add_read_handler = win_chr_add_read_handler;
1967 chr->chr_close = win_chr_close;
1969 if (win_chr_init(s, filename) < 0) {
1977 static int win_chr_pipe_poll(void *opaque)
1979 WinCharState *s = opaque;
1982 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1985 win_chr_read_poll(s);
1992 static int win_chr_pipe_init(WinCharState *s, const char *filename)
2001 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2003 fprintf(stderr, "Failed CreateEvent\n");
2006 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2008 fprintf(stderr, "Failed CreateEvent\n");
2012 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2013 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2014 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2016 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2017 if (s->hcom == INVALID_HANDLE_VALUE) {
2018 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2023 ZeroMemory(&ov, sizeof(ov));
2024 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2025 ret = ConnectNamedPipe(s->hcom, &ov);
2027 fprintf(stderr, "Failed ConnectNamedPipe\n");
2031 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2033 fprintf(stderr, "Failed GetOverlappedResult\n");
2035 CloseHandle(ov.hEvent);
2042 CloseHandle(ov.hEvent);
2045 qemu_add_polling_cb(win_chr_pipe_poll, s);
2054 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2056 CharDriverState *chr;
2059 chr = qemu_mallocz(sizeof(CharDriverState));
2062 s = qemu_mallocz(sizeof(WinCharState));
2068 chr->chr_write = win_chr_write;
2069 chr->chr_add_read_handler = win_chr_add_read_handler;
2070 chr->chr_close = win_chr_close;
2072 if (win_chr_pipe_init(s, filename) < 0) {
2080 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2082 CharDriverState *chr;
2085 chr = qemu_mallocz(sizeof(CharDriverState));
2088 s = qemu_mallocz(sizeof(WinCharState));
2095 chr->chr_write = win_chr_write;
2096 chr->chr_add_read_handler = win_chr_add_read_handler;
2100 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2104 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2105 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2106 if (fd_out == INVALID_HANDLE_VALUE)
2109 return qemu_chr_open_win_file(fd_out);
2113 /***********************************************************/
2114 /* UDP Net console */
2117 IOCanRWHandler *fd_can_read;
2118 IOReadHandler *fd_read;
2121 struct sockaddr_in daddr;
2128 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2130 NetCharDriver *s = chr->opaque;
2132 return sendto(s->fd, buf, len, 0,
2133 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2136 static int udp_chr_read_poll(void *opaque)
2138 CharDriverState *chr = opaque;
2139 NetCharDriver *s = chr->opaque;
2141 s->max_size = s->fd_can_read(s->fd_opaque);
2143 /* If there were any stray characters in the queue process them
2146 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2147 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2149 s->max_size = s->fd_can_read(s->fd_opaque);
2154 static void udp_chr_read(void *opaque)
2156 CharDriverState *chr = opaque;
2157 NetCharDriver *s = chr->opaque;
2159 if (s->max_size == 0)
2161 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2162 s->bufptr = s->bufcnt;
2167 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2168 s->fd_read(s->fd_opaque, &s->buf[s->bufptr], 1);
2170 s->max_size = s->fd_can_read(s->fd_opaque);
2174 static void udp_chr_add_read_handler(CharDriverState *chr,
2175 IOCanRWHandler *fd_can_read,
2176 IOReadHandler *fd_read, void *opaque)
2178 NetCharDriver *s = chr->opaque;
2181 s->fd_can_read = fd_can_read;
2182 s->fd_read = fd_read;
2183 s->fd_opaque = opaque;
2184 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2185 udp_chr_read, NULL, chr);
2189 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2190 int parse_host_src_port(struct sockaddr_in *haddr,
2191 struct sockaddr_in *saddr,
2194 CharDriverState *qemu_chr_open_udp(const char *def)
2196 CharDriverState *chr = NULL;
2197 NetCharDriver *s = NULL;
2199 struct sockaddr_in saddr;
2201 chr = qemu_mallocz(sizeof(CharDriverState));
2204 s = qemu_mallocz(sizeof(NetCharDriver));
2208 fd = socket(PF_INET, SOCK_DGRAM, 0);
2210 perror("socket(PF_INET, SOCK_DGRAM)");
2214 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2215 printf("Could not parse: %s\n", def);
2219 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2229 chr->chr_write = udp_chr_write;
2230 chr->chr_add_read_handler = udp_chr_add_read_handler;
2243 /***********************************************************/
2244 /* TCP Net console */
2247 IOCanRWHandler *fd_can_read;
2248 IOReadHandler *fd_read;
2256 static void tcp_chr_accept(void *opaque);
2258 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2260 TCPCharDriver *s = chr->opaque;
2262 return send_all(s->fd, buf, len);
2264 /* XXX: indicate an error ? */
2269 static int tcp_chr_read_poll(void *opaque)
2271 CharDriverState *chr = opaque;
2272 TCPCharDriver *s = chr->opaque;
2275 s->max_size = s->fd_can_read(s->fd_opaque);
2280 #define IAC_BREAK 243
2281 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2283 char *buf, int *size)
2285 /* Handle any telnet client's basic IAC options to satisfy char by
2286 * char mode with no echo. All IAC options will be removed from
2287 * the buf and the do_telnetopt variable will be used to track the
2288 * state of the width of the IAC information.
2290 * IAC commands come in sets of 3 bytes with the exception of the
2291 * "IAC BREAK" command and the double IAC.
2297 for (i = 0; i < *size; i++) {
2298 if (s->do_telnetopt > 1) {
2299 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2300 /* Double IAC means send an IAC */
2304 s->do_telnetopt = 1;
2306 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2307 /* Handle IAC break commands by sending a serial break */
2308 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
2313 if (s->do_telnetopt >= 4) {
2314 s->do_telnetopt = 1;
2317 if ((unsigned char)buf[i] == IAC) {
2318 s->do_telnetopt = 2;
2329 static void tcp_chr_read(void *opaque)
2331 CharDriverState *chr = opaque;
2332 TCPCharDriver *s = chr->opaque;
2336 if (!s->connected || s->max_size <= 0)
2339 if (len > s->max_size)
2341 size = recv(s->fd, buf, len, 0);
2343 /* connection closed */
2345 if (s->listen_fd >= 0) {
2346 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2348 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2351 } else if (size > 0) {
2352 if (s->do_telnetopt)
2353 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2355 s->fd_read(s->fd_opaque, buf, size);
2359 static void tcp_chr_add_read_handler(CharDriverState *chr,
2360 IOCanRWHandler *fd_can_read,
2361 IOReadHandler *fd_read, void *opaque)
2363 TCPCharDriver *s = chr->opaque;
2365 s->fd_can_read = fd_can_read;
2366 s->fd_read = fd_read;
2367 s->fd_opaque = opaque;
2370 static void tcp_chr_connect(void *opaque)
2372 CharDriverState *chr = opaque;
2373 TCPCharDriver *s = chr->opaque;
2376 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2377 tcp_chr_read, NULL, chr);
2380 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2381 static void tcp_chr_telnet_init(int fd)
2384 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2385 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2386 send(fd, (char *)buf, 3, 0);
2387 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2388 send(fd, (char *)buf, 3, 0);
2389 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2390 send(fd, (char *)buf, 3, 0);
2391 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2392 send(fd, (char *)buf, 3, 0);
2395 static void tcp_chr_accept(void *opaque)
2397 CharDriverState *chr = opaque;
2398 TCPCharDriver *s = chr->opaque;
2399 struct sockaddr_in saddr;
2404 len = sizeof(saddr);
2405 fd = accept(s->listen_fd, (struct sockaddr *)&saddr, &len);
2406 if (fd < 0 && errno != EINTR) {
2408 } else if (fd >= 0) {
2409 if (s->do_telnetopt)
2410 tcp_chr_telnet_init(fd);
2414 socket_set_nonblock(fd);
2416 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2417 tcp_chr_connect(chr);
2420 static void tcp_chr_close(CharDriverState *chr)
2422 TCPCharDriver *s = chr->opaque;
2425 if (s->listen_fd >= 0)
2426 closesocket(s->listen_fd);
2430 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2433 CharDriverState *chr = NULL;
2434 TCPCharDriver *s = NULL;
2435 int fd = -1, ret, err, val;
2437 int is_waitconnect = 1;
2439 struct sockaddr_in saddr;
2441 if (parse_host_port(&saddr, host_str) < 0)
2445 while((ptr = strchr(ptr,','))) {
2447 if (!strncmp(ptr,"server",6)) {
2449 } else if (!strncmp(ptr,"nowait",6)) {
2452 printf("Unknown option: %s\n", ptr);
2459 chr = qemu_mallocz(sizeof(CharDriverState));
2462 s = qemu_mallocz(sizeof(TCPCharDriver));
2466 fd = socket(PF_INET, SOCK_STREAM, 0);
2470 if (!is_waitconnect)
2471 socket_set_nonblock(fd);
2477 /* allow fast reuse */
2479 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2481 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2484 ret = listen(fd, 0);
2488 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2490 s->do_telnetopt = 1;
2493 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2495 err = socket_error();
2496 if (err == EINTR || err == EWOULDBLOCK) {
2497 } else if (err == EINPROGRESS) {
2509 tcp_chr_connect(chr);
2511 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2515 chr->chr_write = tcp_chr_write;
2516 chr->chr_add_read_handler = tcp_chr_add_read_handler;
2517 chr->chr_close = tcp_chr_close;
2518 if (is_listen && is_waitconnect) {
2519 printf("QEMU waiting for connection on: %s\n", host_str);
2520 tcp_chr_accept(chr);
2521 socket_set_nonblock(s->listen_fd);
2533 CharDriverState *qemu_chr_open(const char *filename)
2537 if (!strcmp(filename, "vc")) {
2538 return text_console_init(&display_state);
2539 } else if (!strcmp(filename, "null")) {
2540 return qemu_chr_open_null();
2542 if (strstart(filename, "tcp:", &p)) {
2543 return qemu_chr_open_tcp(p, 0);
2545 if (strstart(filename, "telnet:", &p)) {
2546 return qemu_chr_open_tcp(p, 1);
2548 if (strstart(filename, "udp:", &p)) {
2549 return qemu_chr_open_udp(p);
2552 if (strstart(filename, "file:", &p)) {
2553 return qemu_chr_open_file_out(p);
2554 } else if (strstart(filename, "pipe:", &p)) {
2555 return qemu_chr_open_pipe(p);
2556 } else if (!strcmp(filename, "pty")) {
2557 return qemu_chr_open_pty();
2558 } else if (!strcmp(filename, "stdio")) {
2559 return qemu_chr_open_stdio();
2562 #if defined(__linux__)
2563 if (strstart(filename, "/dev/parport", NULL)) {
2564 return qemu_chr_open_pp(filename);
2566 if (strstart(filename, "/dev/", NULL)) {
2567 return qemu_chr_open_tty(filename);
2571 if (strstart(filename, "COM", NULL)) {
2572 return qemu_chr_open_win(filename);
2574 if (strstart(filename, "pipe:", &p)) {
2575 return qemu_chr_open_win_pipe(p);
2577 if (strstart(filename, "file:", &p)) {
2578 return qemu_chr_open_win_file_out(p);
2586 void qemu_chr_close(CharDriverState *chr)
2589 chr->chr_close(chr);
2592 /***********************************************************/
2593 /* network device redirectors */
2595 void hex_dump(FILE *f, const uint8_t *buf, int size)
2599 for(i=0;i<size;i+=16) {
2603 fprintf(f, "%08x ", i);
2606 fprintf(f, " %02x", buf[i+j]);
2611 for(j=0;j<len;j++) {
2613 if (c < ' ' || c > '~')
2615 fprintf(f, "%c", c);
2621 static int parse_macaddr(uint8_t *macaddr, const char *p)
2624 for(i = 0; i < 6; i++) {
2625 macaddr[i] = strtol(p, (char **)&p, 16);
2638 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2643 p1 = strchr(p, sep);
2649 if (len > buf_size - 1)
2651 memcpy(buf, p, len);
2658 int parse_host_src_port(struct sockaddr_in *haddr,
2659 struct sockaddr_in *saddr,
2660 const char *input_str)
2662 char *str = strdup(input_str);
2663 char *host_str = str;
2668 * Chop off any extra arguments at the end of the string which
2669 * would start with a comma, then fill in the src port information
2670 * if it was provided else use the "any address" and "any port".
2672 if ((ptr = strchr(str,',')))
2675 if ((src_str = strchr(input_str,'@'))) {
2680 if (parse_host_port(haddr, host_str) < 0)
2683 if (!src_str || *src_str == '\0')
2686 if (parse_host_port(saddr, src_str) < 0)
2697 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2705 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2707 saddr->sin_family = AF_INET;
2708 if (buf[0] == '\0') {
2709 saddr->sin_addr.s_addr = 0;
2711 if (isdigit(buf[0])) {
2712 if (!inet_aton(buf, &saddr->sin_addr))
2715 if ((he = gethostbyname(buf)) == NULL)
2717 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2720 port = strtol(p, (char **)&r, 0);
2723 saddr->sin_port = htons(port);
2727 /* find or alloc a new VLAN */
2728 VLANState *qemu_find_vlan(int id)
2730 VLANState **pvlan, *vlan;
2731 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2735 vlan = qemu_mallocz(sizeof(VLANState));
2740 pvlan = &first_vlan;
2741 while (*pvlan != NULL)
2742 pvlan = &(*pvlan)->next;
2747 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2748 IOReadHandler *fd_read,
2749 IOCanRWHandler *fd_can_read,
2752 VLANClientState *vc, **pvc;
2753 vc = qemu_mallocz(sizeof(VLANClientState));
2756 vc->fd_read = fd_read;
2757 vc->fd_can_read = fd_can_read;
2758 vc->opaque = opaque;
2762 pvc = &vlan->first_client;
2763 while (*pvc != NULL)
2764 pvc = &(*pvc)->next;
2769 int qemu_can_send_packet(VLANClientState *vc1)
2771 VLANState *vlan = vc1->vlan;
2772 VLANClientState *vc;
2774 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2776 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2783 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2785 VLANState *vlan = vc1->vlan;
2786 VLANClientState *vc;
2789 printf("vlan %d send:\n", vlan->id);
2790 hex_dump(stdout, buf, size);
2792 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2794 vc->fd_read(vc->opaque, buf, size);
2799 #if defined(CONFIG_SLIRP)
2801 /* slirp network adapter */
2803 static int slirp_inited;
2804 static VLANClientState *slirp_vc;
2806 int slirp_can_output(void)
2808 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2811 void slirp_output(const uint8_t *pkt, int pkt_len)
2814 printf("slirp output:\n");
2815 hex_dump(stdout, pkt, pkt_len);
2819 qemu_send_packet(slirp_vc, pkt, pkt_len);
2822 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2825 printf("slirp input:\n");
2826 hex_dump(stdout, buf, size);
2828 slirp_input(buf, size);
2831 static int net_slirp_init(VLANState *vlan)
2833 if (!slirp_inited) {
2837 slirp_vc = qemu_new_vlan_client(vlan,
2838 slirp_receive, NULL, NULL);
2839 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2843 static void net_slirp_redir(const char *redir_str)
2848 struct in_addr guest_addr;
2849 int host_port, guest_port;
2851 if (!slirp_inited) {
2857 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2859 if (!strcmp(buf, "tcp")) {
2861 } else if (!strcmp(buf, "udp")) {
2867 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2869 host_port = strtol(buf, &r, 0);
2873 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2875 if (buf[0] == '\0') {
2876 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2878 if (!inet_aton(buf, &guest_addr))
2881 guest_port = strtol(p, &r, 0);
2885 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2886 fprintf(stderr, "qemu: could not set up redirection\n");
2891 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2899 static void smb_exit(void)
2903 char filename[1024];
2905 /* erase all the files in the directory */
2906 d = opendir(smb_dir);
2911 if (strcmp(de->d_name, ".") != 0 &&
2912 strcmp(de->d_name, "..") != 0) {
2913 snprintf(filename, sizeof(filename), "%s/%s",
2914 smb_dir, de->d_name);
2922 /* automatic user mode samba server configuration */
2923 void net_slirp_smb(const char *exported_dir)
2925 char smb_conf[1024];
2926 char smb_cmdline[1024];
2929 if (!slirp_inited) {
2934 /* XXX: better tmp dir construction */
2935 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2936 if (mkdir(smb_dir, 0700) < 0) {
2937 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2940 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2942 f = fopen(smb_conf, "w");
2944 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2951 "socket address=127.0.0.1\n"
2952 "pid directory=%s\n"
2953 "lock directory=%s\n"
2954 "log file=%s/log.smbd\n"
2955 "smb passwd file=%s/smbpasswd\n"
2956 "security = share\n"
2971 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2974 slirp_add_exec(0, smb_cmdline, 4, 139);
2977 #endif /* !defined(_WIN32) */
2979 #endif /* CONFIG_SLIRP */
2981 #if !defined(_WIN32)
2983 typedef struct TAPState {
2984 VLANClientState *vc;
2988 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2990 TAPState *s = opaque;
2993 ret = write(s->fd, buf, size);
2994 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3001 static void tap_send(void *opaque)
3003 TAPState *s = opaque;
3007 size = read(s->fd, buf, sizeof(buf));
3009 qemu_send_packet(s->vc, buf, size);
3015 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3019 s = qemu_mallocz(sizeof(TAPState));
3023 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3024 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3025 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3030 static int tap_open(char *ifname, int ifname_size)
3036 fd = open("/dev/tap", O_RDWR);
3038 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3043 dev = devname(s.st_rdev, S_IFCHR);
3044 pstrcpy(ifname, ifname_size, dev);
3046 fcntl(fd, F_SETFL, O_NONBLOCK);
3049 #elif defined(__sun__)
3050 static int tap_open(char *ifname, int ifname_size)
3052 fprintf(stderr, "warning: tap_open not yet implemented\n");
3056 static int tap_open(char *ifname, int ifname_size)
3061 fd = open("/dev/net/tun", O_RDWR);
3063 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3066 memset(&ifr, 0, sizeof(ifr));
3067 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3068 if (ifname[0] != '\0')
3069 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3071 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3072 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3074 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3078 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3079 fcntl(fd, F_SETFL, O_NONBLOCK);
3084 static int net_tap_init(VLANState *vlan, const char *ifname1,
3085 const char *setup_script)
3088 int pid, status, fd;
3093 if (ifname1 != NULL)
3094 pstrcpy(ifname, sizeof(ifname), ifname1);
3097 fd = tap_open(ifname, sizeof(ifname));
3103 if (setup_script[0] != '\0') {
3104 /* try to launch network init script */
3109 *parg++ = (char *)setup_script;
3112 execv(setup_script, args);
3115 while (waitpid(pid, &status, 0) != pid);
3116 if (!WIFEXITED(status) ||
3117 WEXITSTATUS(status) != 0) {
3118 fprintf(stderr, "%s: could not launch network script\n",
3124 s = net_tap_fd_init(vlan, fd);
3127 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3128 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3132 #endif /* !_WIN32 */
3134 /* network connection */
3135 typedef struct NetSocketState {
3136 VLANClientState *vc;
3138 int state; /* 0 = getting length, 1 = getting data */
3142 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3145 typedef struct NetSocketListenState {
3148 } NetSocketListenState;
3150 /* XXX: we consider we can send the whole packet without blocking */
3151 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3153 NetSocketState *s = opaque;
3157 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3158 send_all(s->fd, buf, size);
3161 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3163 NetSocketState *s = opaque;
3164 sendto(s->fd, buf, size, 0,
3165 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3168 static void net_socket_send(void *opaque)
3170 NetSocketState *s = opaque;
3175 size = recv(s->fd, buf1, sizeof(buf1), 0);
3177 err = socket_error();
3178 if (err != EWOULDBLOCK)
3180 } else if (size == 0) {
3181 /* end of connection */
3183 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3189 /* reassemble a packet from the network */
3195 memcpy(s->buf + s->index, buf, l);
3199 if (s->index == 4) {
3201 s->packet_len = ntohl(*(uint32_t *)s->buf);
3207 l = s->packet_len - s->index;
3210 memcpy(s->buf + s->index, buf, l);
3214 if (s->index >= s->packet_len) {
3215 qemu_send_packet(s->vc, s->buf, s->packet_len);
3224 static void net_socket_send_dgram(void *opaque)
3226 NetSocketState *s = opaque;
3229 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3233 /* end of connection */
3234 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3237 qemu_send_packet(s->vc, s->buf, size);
3240 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3245 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3246 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3247 inet_ntoa(mcastaddr->sin_addr),
3248 (int)ntohl(mcastaddr->sin_addr.s_addr));
3252 fd = socket(PF_INET, SOCK_DGRAM, 0);
3254 perror("socket(PF_INET, SOCK_DGRAM)");
3259 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3260 (const char *)&val, sizeof(val));
3262 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3266 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3272 /* Add host to multicast group */
3273 imr.imr_multiaddr = mcastaddr->sin_addr;
3274 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3276 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3277 (const char *)&imr, sizeof(struct ip_mreq));
3279 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3283 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3285 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3286 (const char *)&val, sizeof(val));
3288 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3292 socket_set_nonblock(fd);
3300 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3303 struct sockaddr_in saddr;
3305 socklen_t saddr_len;
3308 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3309 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3310 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3314 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3316 if (saddr.sin_addr.s_addr==0) {
3317 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3321 /* clone dgram socket */
3322 newfd = net_socket_mcast_create(&saddr);
3324 /* error already reported by net_socket_mcast_create() */
3328 /* clone newfd to fd, close newfd */
3333 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3334 fd, strerror(errno));
3339 s = qemu_mallocz(sizeof(NetSocketState));
3344 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3345 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3347 /* mcast: save bound address as dst */
3348 if (is_connected) s->dgram_dst=saddr;
3350 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3351 "socket: fd=%d (%s mcast=%s:%d)",
3352 fd, is_connected? "cloned" : "",
3353 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3357 static void net_socket_connect(void *opaque)
3359 NetSocketState *s = opaque;
3360 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3363 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
3367 s = qemu_mallocz(sizeof(NetSocketState));
3371 s->vc = qemu_new_vlan_client(vlan,
3372 net_socket_receive, NULL, s);
3373 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3374 "socket: fd=%d", fd);
3376 net_socket_connect(s);
3378 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3383 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
3386 int so_type=-1, optlen=sizeof(so_type);
3388 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3389 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3394 return net_socket_fd_init_dgram(vlan, fd, is_connected);
3396 return net_socket_fd_init_stream(vlan, fd, is_connected);
3398 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3399 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3400 return net_socket_fd_init_stream(vlan, fd, is_connected);
3405 static void net_socket_accept(void *opaque)
3407 NetSocketListenState *s = opaque;
3409 struct sockaddr_in saddr;
3414 len = sizeof(saddr);
3415 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3416 if (fd < 0 && errno != EINTR) {
3418 } else if (fd >= 0) {
3422 s1 = net_socket_fd_init(s->vlan, fd, 1);
3426 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3427 "socket: connection from %s:%d",
3428 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3432 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3434 NetSocketListenState *s;
3436 struct sockaddr_in saddr;
3438 if (parse_host_port(&saddr, host_str) < 0)
3441 s = qemu_mallocz(sizeof(NetSocketListenState));
3445 fd = socket(PF_INET, SOCK_STREAM, 0);
3450 socket_set_nonblock(fd);
3452 /* allow fast reuse */
3454 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3456 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3461 ret = listen(fd, 0);
3468 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
3472 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
3475 int fd, connected, ret, err;
3476 struct sockaddr_in saddr;
3478 if (parse_host_port(&saddr, host_str) < 0)
3481 fd = socket(PF_INET, SOCK_STREAM, 0);
3486 socket_set_nonblock(fd);
3490 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3492 err = socket_error();
3493 if (err == EINTR || err == EWOULDBLOCK) {
3494 } else if (err == EINPROGRESS) {
3506 s = net_socket_fd_init(vlan, fd, connected);
3509 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3510 "socket: connect to %s:%d",
3511 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3515 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3519 struct sockaddr_in saddr;
3521 if (parse_host_port(&saddr, host_str) < 0)
3525 fd = net_socket_mcast_create(&saddr);
3529 s = net_socket_fd_init(vlan, fd, 0);
3533 s->dgram_dst = saddr;
3535 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3536 "socket: mcast=%s:%d",
3537 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3542 static int get_param_value(char *buf, int buf_size,
3543 const char *tag, const char *str)
3552 while (*p != '\0' && *p != '=') {
3553 if ((q - option) < sizeof(option) - 1)
3561 if (!strcmp(tag, option)) {
3563 while (*p != '\0' && *p != ',') {
3564 if ((q - buf) < buf_size - 1)
3571 while (*p != '\0' && *p != ',') {
3582 int net_client_init(const char *str)
3593 while (*p != '\0' && *p != ',') {
3594 if ((q - device) < sizeof(device) - 1)
3602 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3603 vlan_id = strtol(buf, NULL, 0);
3605 vlan = qemu_find_vlan(vlan_id);
3607 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3610 if (!strcmp(device, "nic")) {
3614 if (nb_nics >= MAX_NICS) {
3615 fprintf(stderr, "Too Many NICs\n");
3618 nd = &nd_table[nb_nics];
3619 macaddr = nd->macaddr;
3625 macaddr[5] = 0x56 + nb_nics;
3627 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3628 if (parse_macaddr(macaddr, buf) < 0) {
3629 fprintf(stderr, "invalid syntax for ethernet address\n");
3633 if (get_param_value(buf, sizeof(buf), "model", p)) {
3634 nd->model = strdup(buf);
3640 if (!strcmp(device, "none")) {
3641 /* does nothing. It is needed to signal that no network cards
3646 if (!strcmp(device, "user")) {
3647 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3648 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
3650 ret = net_slirp_init(vlan);
3654 if (!strcmp(device, "tap")) {
3656 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3657 fprintf(stderr, "tap: no interface name\n");
3660 ret = tap_win32_init(vlan, ifname);
3663 if (!strcmp(device, "tap")) {
3665 char setup_script[1024];
3667 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3668 fd = strtol(buf, NULL, 0);
3670 if (net_tap_fd_init(vlan, fd))
3673 get_param_value(ifname, sizeof(ifname), "ifname", p);
3674 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3675 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3677 ret = net_tap_init(vlan, ifname, setup_script);
3681 if (!strcmp(device, "socket")) {
3682 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3684 fd = strtol(buf, NULL, 0);
3686 if (net_socket_fd_init(vlan, fd, 1))
3688 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3689 ret = net_socket_listen_init(vlan, buf);
3690 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3691 ret = net_socket_connect_init(vlan, buf);
3692 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3693 ret = net_socket_mcast_init(vlan, buf);
3695 fprintf(stderr, "Unknown socket options: %s\n", p);
3700 fprintf(stderr, "Unknown network device: %s\n", device);
3704 fprintf(stderr, "Could not initialize device '%s'\n", device);
3710 void do_info_network(void)
3713 VLANClientState *vc;
3715 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3716 term_printf("VLAN %d devices:\n", vlan->id);
3717 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3718 term_printf(" %s\n", vc->info_str);
3722 /***********************************************************/
3725 static USBPort *used_usb_ports;
3726 static USBPort *free_usb_ports;
3728 /* ??? Maybe change this to register a hub to keep track of the topology. */
3729 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
3730 usb_attachfn attach)
3732 port->opaque = opaque;
3733 port->index = index;
3734 port->attach = attach;
3735 port->next = free_usb_ports;
3736 free_usb_ports = port;
3739 static int usb_device_add(const char *devname)
3745 if (!free_usb_ports)
3748 if (strstart(devname, "host:", &p)) {
3749 dev = usb_host_device_open(p);
3750 } else if (!strcmp(devname, "mouse")) {
3751 dev = usb_mouse_init();
3752 } else if (!strcmp(devname, "tablet")) {
3753 dev = usb_tablet_init();
3754 } else if (strstart(devname, "disk:", &p)) {
3755 dev = usb_msd_init(p);
3762 /* Find a USB port to add the device to. */
3763 port = free_usb_ports;
3767 /* Create a new hub and chain it on. */
3768 free_usb_ports = NULL;
3769 port->next = used_usb_ports;
3770 used_usb_ports = port;
3772 hub = usb_hub_init(VM_USB_HUB_SIZE);
3773 usb_attach(port, hub);
3774 port = free_usb_ports;
3777 free_usb_ports = port->next;
3778 port->next = used_usb_ports;
3779 used_usb_ports = port;
3780 usb_attach(port, dev);
3784 static int usb_device_del(const char *devname)
3792 if (!used_usb_ports)
3795 p = strchr(devname, '.');
3798 bus_num = strtoul(devname, NULL, 0);
3799 addr = strtoul(p + 1, NULL, 0);
3803 lastp = &used_usb_ports;
3804 port = used_usb_ports;
3805 while (port && port->dev->addr != addr) {
3806 lastp = &port->next;
3814 *lastp = port->next;
3815 usb_attach(port, NULL);
3816 dev->handle_destroy(dev);
3817 port->next = free_usb_ports;
3818 free_usb_ports = port;
3822 void do_usb_add(const char *devname)
3825 ret = usb_device_add(devname);
3827 term_printf("Could not add USB device '%s'\n", devname);
3830 void do_usb_del(const char *devname)
3833 ret = usb_device_del(devname);
3835 term_printf("Could not remove USB device '%s'\n", devname);
3842 const char *speed_str;
3845 term_printf("USB support not enabled\n");
3849 for (port = used_usb_ports; port; port = port->next) {
3853 switch(dev->speed) {
3857 case USB_SPEED_FULL:
3860 case USB_SPEED_HIGH:
3867 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
3868 0, dev->addr, speed_str, dev->devname);
3872 /***********************************************************/
3875 static char *pid_filename;
3877 /* Remove PID file. Called on normal exit */
3879 static void remove_pidfile(void)
3881 unlink (pid_filename);
3884 static void create_pidfile(const char *filename)
3886 struct stat pidstat;
3889 /* Try to write our PID to the named file */
3890 if (stat(filename, &pidstat) < 0) {
3891 if (errno == ENOENT) {
3892 if ((f = fopen (filename, "w")) == NULL) {
3893 perror("Opening pidfile");
3896 fprintf(f, "%d\n", getpid());
3898 pid_filename = qemu_strdup(filename);
3899 if (!pid_filename) {
3900 fprintf(stderr, "Could not save PID filename");
3903 atexit(remove_pidfile);
3906 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3912 /***********************************************************/
3915 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3919 static void dumb_resize(DisplayState *ds, int w, int h)
3923 static void dumb_refresh(DisplayState *ds)
3928 void dumb_display_init(DisplayState *ds)
3933 ds->dpy_update = dumb_update;
3934 ds->dpy_resize = dumb_resize;
3935 ds->dpy_refresh = dumb_refresh;
3938 /***********************************************************/
3941 #define MAX_IO_HANDLERS 64
3943 typedef struct IOHandlerRecord {
3945 IOCanRWHandler *fd_read_poll;
3947 IOHandler *fd_write;
3949 /* temporary data */
3951 struct IOHandlerRecord *next;
3954 static IOHandlerRecord *first_io_handler;
3956 /* XXX: fd_read_poll should be suppressed, but an API change is
3957 necessary in the character devices to suppress fd_can_read(). */
3958 int qemu_set_fd_handler2(int fd,
3959 IOCanRWHandler *fd_read_poll,
3961 IOHandler *fd_write,
3964 IOHandlerRecord **pioh, *ioh;
3966 if (!fd_read && !fd_write) {
3967 pioh = &first_io_handler;
3972 if (ioh->fd == fd) {
3980 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3984 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3987 ioh->next = first_io_handler;
3988 first_io_handler = ioh;
3991 ioh->fd_read_poll = fd_read_poll;
3992 ioh->fd_read = fd_read;
3993 ioh->fd_write = fd_write;
3994 ioh->opaque = opaque;
3999 int qemu_set_fd_handler(int fd,
4001 IOHandler *fd_write,
4004 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4007 /***********************************************************/
4008 /* Polling handling */
4010 typedef struct PollingEntry {
4013 struct PollingEntry *next;
4016 static PollingEntry *first_polling_entry;
4018 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4020 PollingEntry **ppe, *pe;
4021 pe = qemu_mallocz(sizeof(PollingEntry));
4025 pe->opaque = opaque;
4026 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4031 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4033 PollingEntry **ppe, *pe;
4034 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4036 if (pe->func == func && pe->opaque == opaque) {
4045 /***********************************************************/
4046 /* Wait objects support */
4047 typedef struct WaitObjects {
4049 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4050 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4051 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4054 static WaitObjects wait_objects = {0};
4056 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4058 WaitObjects *w = &wait_objects;
4060 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4062 w->events[w->num] = handle;
4063 w->func[w->num] = func;
4064 w->opaque[w->num] = opaque;
4069 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4072 WaitObjects *w = &wait_objects;
4075 for (i = 0; i < w->num; i++) {
4076 if (w->events[i] == handle)
4079 w->events[i] = w->events[i + 1];
4080 w->func[i] = w->func[i + 1];
4081 w->opaque[i] = w->opaque[i + 1];
4089 /***********************************************************/
4090 /* savevm/loadvm support */
4092 #define IO_BUF_SIZE 32768
4096 BlockDriverState *bs;
4099 int64_t base_offset;
4100 int64_t buf_offset; /* start of buffer when writing, end of buffer
4103 int buf_size; /* 0 when writing */
4104 uint8_t buf[IO_BUF_SIZE];
4107 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4111 f = qemu_mallocz(sizeof(QEMUFile));
4114 if (!strcmp(mode, "wb")) {
4116 } else if (!strcmp(mode, "rb")) {
4121 f->outfile = fopen(filename, mode);
4133 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4137 f = qemu_mallocz(sizeof(QEMUFile));
4142 f->is_writable = is_writable;
4143 f->base_offset = offset;
4147 void qemu_fflush(QEMUFile *f)
4149 if (!f->is_writable)
4151 if (f->buf_index > 0) {
4153 fseek(f->outfile, f->buf_offset, SEEK_SET);
4154 fwrite(f->buf, 1, f->buf_index, f->outfile);
4156 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4157 f->buf, f->buf_index);
4159 f->buf_offset += f->buf_index;
4164 static void qemu_fill_buffer(QEMUFile *f)
4171 fseek(f->outfile, f->buf_offset, SEEK_SET);
4172 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4176 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4177 f->buf, IO_BUF_SIZE);
4183 f->buf_offset += len;
4186 void qemu_fclose(QEMUFile *f)
4196 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4200 l = IO_BUF_SIZE - f->buf_index;
4203 memcpy(f->buf + f->buf_index, buf, l);
4207 if (f->buf_index >= IO_BUF_SIZE)
4212 void qemu_put_byte(QEMUFile *f, int v)
4214 f->buf[f->buf_index++] = v;
4215 if (f->buf_index >= IO_BUF_SIZE)
4219 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4225 l = f->buf_size - f->buf_index;
4227 qemu_fill_buffer(f);
4228 l = f->buf_size - f->buf_index;
4234 memcpy(buf, f->buf + f->buf_index, l);
4239 return size1 - size;
4242 int qemu_get_byte(QEMUFile *f)
4244 if (f->buf_index >= f->buf_size) {
4245 qemu_fill_buffer(f);
4246 if (f->buf_index >= f->buf_size)
4249 return f->buf[f->buf_index++];
4252 int64_t qemu_ftell(QEMUFile *f)
4254 return f->buf_offset - f->buf_size + f->buf_index;
4257 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4259 if (whence == SEEK_SET) {
4261 } else if (whence == SEEK_CUR) {
4262 pos += qemu_ftell(f);
4264 /* SEEK_END not supported */
4267 if (f->is_writable) {
4269 f->buf_offset = pos;
4271 f->buf_offset = pos;
4278 void qemu_put_be16(QEMUFile *f, unsigned int v)
4280 qemu_put_byte(f, v >> 8);
4281 qemu_put_byte(f, v);
4284 void qemu_put_be32(QEMUFile *f, unsigned int v)
4286 qemu_put_byte(f, v >> 24);
4287 qemu_put_byte(f, v >> 16);
4288 qemu_put_byte(f, v >> 8);
4289 qemu_put_byte(f, v);
4292 void qemu_put_be64(QEMUFile *f, uint64_t v)
4294 qemu_put_be32(f, v >> 32);
4295 qemu_put_be32(f, v);
4298 unsigned int qemu_get_be16(QEMUFile *f)
4301 v = qemu_get_byte(f) << 8;
4302 v |= qemu_get_byte(f);
4306 unsigned int qemu_get_be32(QEMUFile *f)
4309 v = qemu_get_byte(f) << 24;
4310 v |= qemu_get_byte(f) << 16;
4311 v |= qemu_get_byte(f) << 8;
4312 v |= qemu_get_byte(f);
4316 uint64_t qemu_get_be64(QEMUFile *f)
4319 v = (uint64_t)qemu_get_be32(f) << 32;
4320 v |= qemu_get_be32(f);
4324 typedef struct SaveStateEntry {
4328 SaveStateHandler *save_state;
4329 LoadStateHandler *load_state;
4331 struct SaveStateEntry *next;
4334 static SaveStateEntry *first_se;
4336 int register_savevm(const char *idstr,
4339 SaveStateHandler *save_state,
4340 LoadStateHandler *load_state,
4343 SaveStateEntry *se, **pse;
4345 se = qemu_malloc(sizeof(SaveStateEntry));
4348 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4349 se->instance_id = instance_id;
4350 se->version_id = version_id;
4351 se->save_state = save_state;
4352 se->load_state = load_state;
4353 se->opaque = opaque;
4356 /* add at the end of list */
4358 while (*pse != NULL)
4359 pse = &(*pse)->next;
4364 #define QEMU_VM_FILE_MAGIC 0x5145564d
4365 #define QEMU_VM_FILE_VERSION 0x00000002
4367 int qemu_savevm_state(QEMUFile *f)
4371 int64_t cur_pos, len_pos, total_len_pos;
4373 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4374 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4375 total_len_pos = qemu_ftell(f);
4376 qemu_put_be64(f, 0); /* total size */
4378 for(se = first_se; se != NULL; se = se->next) {
4380 len = strlen(se->idstr);
4381 qemu_put_byte(f, len);
4382 qemu_put_buffer(f, se->idstr, len);
4384 qemu_put_be32(f, se->instance_id);
4385 qemu_put_be32(f, se->version_id);
4387 /* record size: filled later */
4388 len_pos = qemu_ftell(f);
4389 qemu_put_be32(f, 0);
4391 se->save_state(f, se->opaque);
4393 /* fill record size */
4394 cur_pos = qemu_ftell(f);
4395 len = cur_pos - len_pos - 4;
4396 qemu_fseek(f, len_pos, SEEK_SET);
4397 qemu_put_be32(f, len);
4398 qemu_fseek(f, cur_pos, SEEK_SET);
4400 cur_pos = qemu_ftell(f);
4401 qemu_fseek(f, total_len_pos, SEEK_SET);
4402 qemu_put_be64(f, cur_pos - total_len_pos - 8);
4403 qemu_fseek(f, cur_pos, SEEK_SET);
4409 static SaveStateEntry *find_se(const char *idstr, int instance_id)
4413 for(se = first_se; se != NULL; se = se->next) {
4414 if (!strcmp(se->idstr, idstr) &&
4415 instance_id == se->instance_id)
4421 int qemu_loadvm_state(QEMUFile *f)
4424 int len, ret, instance_id, record_len, version_id;
4425 int64_t total_len, end_pos, cur_pos;
4429 v = qemu_get_be32(f);
4430 if (v != QEMU_VM_FILE_MAGIC)
4432 v = qemu_get_be32(f);
4433 if (v != QEMU_VM_FILE_VERSION) {
4438 total_len = qemu_get_be64(f);
4439 end_pos = total_len + qemu_ftell(f);
4441 if (qemu_ftell(f) >= end_pos)
4443 len = qemu_get_byte(f);
4444 qemu_get_buffer(f, idstr, len);
4446 instance_id = qemu_get_be32(f);
4447 version_id = qemu_get_be32(f);
4448 record_len = qemu_get_be32(f);
4450 printf("idstr=%s instance=0x%x version=%d len=%d\n",
4451 idstr, instance_id, version_id, record_len);
4453 cur_pos = qemu_ftell(f);
4454 se = find_se(idstr, instance_id);
4456 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
4457 instance_id, idstr);
4459 ret = se->load_state(f, se->opaque, version_id);
4461 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
4462 instance_id, idstr);
4465 /* always seek to exact end of record */
4466 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4473 /* device can contain snapshots */
4474 static int bdrv_can_snapshot(BlockDriverState *bs)
4477 !bdrv_is_removable(bs) &&
4478 !bdrv_is_read_only(bs));
4481 /* device must be snapshots in order to have a reliable snapshot */
4482 static int bdrv_has_snapshot(BlockDriverState *bs)
4485 !bdrv_is_removable(bs) &&
4486 !bdrv_is_read_only(bs));
4489 static BlockDriverState *get_bs_snapshots(void)
4491 BlockDriverState *bs;
4495 return bs_snapshots;
4496 for(i = 0; i <= MAX_DISKS; i++) {
4498 if (bdrv_can_snapshot(bs))
4507 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
4510 QEMUSnapshotInfo *sn_tab, *sn;
4514 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4517 for(i = 0; i < nb_sns; i++) {
4519 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
4529 void do_savevm(const char *name)
4531 BlockDriverState *bs, *bs1;
4532 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
4533 int must_delete, ret, i;
4534 BlockDriverInfo bdi1, *bdi = &bdi1;
4536 int saved_vm_running;
4539 bs = get_bs_snapshots();
4541 term_printf("No block device can accept snapshots\n");
4545 saved_vm_running = vm_running;
4550 ret = bdrv_snapshot_find(bs, old_sn, name);
4555 memset(sn, 0, sizeof(*sn));
4557 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
4558 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
4561 pstrcpy(sn->name, sizeof(sn->name), name);
4564 /* fill auxiliary fields */
4565 gettimeofday(&tv, NULL);
4566 sn->date_sec = tv.tv_sec;
4567 sn->date_nsec = tv.tv_usec * 1000;
4568 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
4570 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4571 term_printf("Device %s does not support VM state snapshots\n",
4572 bdrv_get_device_name(bs));
4576 /* save the VM state */
4577 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
4579 term_printf("Could not open VM state file\n");
4582 ret = qemu_savevm_state(f);
4583 sn->vm_state_size = qemu_ftell(f);
4586 term_printf("Error %d while writing VM\n", ret);
4590 /* create the snapshots */
4592 for(i = 0; i < MAX_DISKS; i++) {
4594 if (bdrv_has_snapshot(bs1)) {
4596 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
4598 term_printf("Error while deleting snapshot on '%s'\n",
4599 bdrv_get_device_name(bs1));
4602 ret = bdrv_snapshot_create(bs1, sn);
4604 term_printf("Error while creating snapshot on '%s'\n",
4605 bdrv_get_device_name(bs1));
4611 if (saved_vm_running)
4615 void do_loadvm(const char *name)
4617 BlockDriverState *bs, *bs1;
4618 BlockDriverInfo bdi1, *bdi = &bdi1;
4621 int saved_vm_running;
4623 bs = get_bs_snapshots();
4625 term_printf("No block device supports snapshots\n");
4629 saved_vm_running = vm_running;
4632 for(i = 0; i <= MAX_DISKS; i++) {
4634 if (bdrv_has_snapshot(bs1)) {
4635 ret = bdrv_snapshot_goto(bs1, name);
4638 term_printf("Warning: ");
4641 term_printf("Snapshots not supported on device '%s'\n",
4642 bdrv_get_device_name(bs1));
4645 term_printf("Could not find snapshot '%s' on device '%s'\n",
4646 name, bdrv_get_device_name(bs1));
4649 term_printf("Error %d while activating snapshot on '%s'\n",
4650 ret, bdrv_get_device_name(bs1));
4653 /* fatal on snapshot block device */
4660 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
4661 term_printf("Device %s does not support VM state snapshots\n",
4662 bdrv_get_device_name(bs));
4666 /* restore the VM state */
4667 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
4669 term_printf("Could not open VM state file\n");
4672 ret = qemu_loadvm_state(f);
4675 term_printf("Error %d while loading VM state\n", ret);
4678 if (saved_vm_running)
4682 void do_delvm(const char *name)
4684 BlockDriverState *bs, *bs1;
4687 bs = get_bs_snapshots();
4689 term_printf("No block device supports snapshots\n");
4693 for(i = 0; i <= MAX_DISKS; i++) {
4695 if (bdrv_has_snapshot(bs1)) {
4696 ret = bdrv_snapshot_delete(bs1, name);
4698 if (ret == -ENOTSUP)
4699 term_printf("Snapshots not supported on device '%s'\n",
4700 bdrv_get_device_name(bs1));
4702 term_printf("Error %d while deleting snapshot on '%s'\n",
4703 ret, bdrv_get_device_name(bs1));
4709 void do_info_snapshots(void)
4711 BlockDriverState *bs, *bs1;
4712 QEMUSnapshotInfo *sn_tab, *sn;
4716 bs = get_bs_snapshots();
4718 term_printf("No available block device supports snapshots\n");
4721 term_printf("Snapshot devices:");
4722 for(i = 0; i <= MAX_DISKS; i++) {
4724 if (bdrv_has_snapshot(bs1)) {
4726 term_printf(" %s", bdrv_get_device_name(bs1));
4731 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
4733 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
4736 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
4737 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
4738 for(i = 0; i < nb_sns; i++) {
4740 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
4745 /***********************************************************/
4746 /* cpu save/restore */
4748 #if defined(TARGET_I386)
4750 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
4752 qemu_put_be32(f, dt->selector);
4753 qemu_put_betl(f, dt->base);
4754 qemu_put_be32(f, dt->limit);
4755 qemu_put_be32(f, dt->flags);
4758 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
4760 dt->selector = qemu_get_be32(f);
4761 dt->base = qemu_get_betl(f);
4762 dt->limit = qemu_get_be32(f);
4763 dt->flags = qemu_get_be32(f);
4766 void cpu_save(QEMUFile *f, void *opaque)
4768 CPUState *env = opaque;
4769 uint16_t fptag, fpus, fpuc, fpregs_format;
4773 for(i = 0; i < CPU_NB_REGS; i++)
4774 qemu_put_betls(f, &env->regs[i]);
4775 qemu_put_betls(f, &env->eip);
4776 qemu_put_betls(f, &env->eflags);
4777 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
4778 qemu_put_be32s(f, &hflags);
4782 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
4784 for(i = 0; i < 8; i++) {
4785 fptag |= ((!env->fptags[i]) << i);
4788 qemu_put_be16s(f, &fpuc);
4789 qemu_put_be16s(f, &fpus);
4790 qemu_put_be16s(f, &fptag);
4792 #ifdef USE_X86LDOUBLE
4797 qemu_put_be16s(f, &fpregs_format);
4799 for(i = 0; i < 8; i++) {
4800 #ifdef USE_X86LDOUBLE
4804 /* we save the real CPU data (in case of MMX usage only 'mant'
4805 contains the MMX register */
4806 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
4807 qemu_put_be64(f, mant);
4808 qemu_put_be16(f, exp);
4811 /* if we use doubles for float emulation, we save the doubles to
4812 avoid losing information in case of MMX usage. It can give
4813 problems if the image is restored on a CPU where long
4814 doubles are used instead. */
4815 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
4819 for(i = 0; i < 6; i++)
4820 cpu_put_seg(f, &env->segs[i]);
4821 cpu_put_seg(f, &env->ldt);
4822 cpu_put_seg(f, &env->tr);
4823 cpu_put_seg(f, &env->gdt);
4824 cpu_put_seg(f, &env->idt);
4826 qemu_put_be32s(f, &env->sysenter_cs);
4827 qemu_put_be32s(f, &env->sysenter_esp);
4828 qemu_put_be32s(f, &env->sysenter_eip);
4830 qemu_put_betls(f, &env->cr[0]);
4831 qemu_put_betls(f, &env->cr[2]);
4832 qemu_put_betls(f, &env->cr[3]);
4833 qemu_put_betls(f, &env->cr[4]);
4835 for(i = 0; i < 8; i++)
4836 qemu_put_betls(f, &env->dr[i]);
4839 qemu_put_be32s(f, &env->a20_mask);
4842 qemu_put_be32s(f, &env->mxcsr);
4843 for(i = 0; i < CPU_NB_REGS; i++) {
4844 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4845 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4848 #ifdef TARGET_X86_64
4849 qemu_put_be64s(f, &env->efer);
4850 qemu_put_be64s(f, &env->star);
4851 qemu_put_be64s(f, &env->lstar);
4852 qemu_put_be64s(f, &env->cstar);
4853 qemu_put_be64s(f, &env->fmask);
4854 qemu_put_be64s(f, &env->kernelgsbase);
4858 #ifdef USE_X86LDOUBLE
4859 /* XXX: add that in a FPU generic layer */
4860 union x86_longdouble {
4865 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
4866 #define EXPBIAS1 1023
4867 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
4868 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
4870 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
4874 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
4875 /* exponent + sign */
4876 e = EXPD1(temp) - EXPBIAS1 + 16383;
4877 e |= SIGND1(temp) >> 16;
4882 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4884 CPUState *env = opaque;
4887 uint16_t fpus, fpuc, fptag, fpregs_format;
4889 if (version_id != 3)
4891 for(i = 0; i < CPU_NB_REGS; i++)
4892 qemu_get_betls(f, &env->regs[i]);
4893 qemu_get_betls(f, &env->eip);
4894 qemu_get_betls(f, &env->eflags);
4895 qemu_get_be32s(f, &hflags);
4897 qemu_get_be16s(f, &fpuc);
4898 qemu_get_be16s(f, &fpus);
4899 qemu_get_be16s(f, &fptag);
4900 qemu_get_be16s(f, &fpregs_format);
4902 /* NOTE: we cannot always restore the FPU state if the image come
4903 from a host with a different 'USE_X86LDOUBLE' define. We guess
4904 if we are in an MMX state to restore correctly in that case. */
4905 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
4906 for(i = 0; i < 8; i++) {
4910 switch(fpregs_format) {
4912 mant = qemu_get_be64(f);
4913 exp = qemu_get_be16(f);
4914 #ifdef USE_X86LDOUBLE
4915 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4917 /* difficult case */
4919 env->fpregs[i].mmx.MMX_Q(0) = mant;
4921 env->fpregs[i].d = cpu_set_fp80(mant, exp);
4925 mant = qemu_get_be64(f);
4926 #ifdef USE_X86LDOUBLE
4928 union x86_longdouble *p;
4929 /* difficult case */
4930 p = (void *)&env->fpregs[i];
4935 fp64_to_fp80(p, mant);
4939 env->fpregs[i].mmx.MMX_Q(0) = mant;
4948 /* XXX: restore FPU round state */
4949 env->fpstt = (fpus >> 11) & 7;
4950 env->fpus = fpus & ~0x3800;
4952 for(i = 0; i < 8; i++) {
4953 env->fptags[i] = (fptag >> i) & 1;
4956 for(i = 0; i < 6; i++)
4957 cpu_get_seg(f, &env->segs[i]);
4958 cpu_get_seg(f, &env->ldt);
4959 cpu_get_seg(f, &env->tr);
4960 cpu_get_seg(f, &env->gdt);
4961 cpu_get_seg(f, &env->idt);
4963 qemu_get_be32s(f, &env->sysenter_cs);
4964 qemu_get_be32s(f, &env->sysenter_esp);
4965 qemu_get_be32s(f, &env->sysenter_eip);
4967 qemu_get_betls(f, &env->cr[0]);
4968 qemu_get_betls(f, &env->cr[2]);
4969 qemu_get_betls(f, &env->cr[3]);
4970 qemu_get_betls(f, &env->cr[4]);
4972 for(i = 0; i < 8; i++)
4973 qemu_get_betls(f, &env->dr[i]);
4976 qemu_get_be32s(f, &env->a20_mask);
4978 qemu_get_be32s(f, &env->mxcsr);
4979 for(i = 0; i < CPU_NB_REGS; i++) {
4980 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4981 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4984 #ifdef TARGET_X86_64
4985 qemu_get_be64s(f, &env->efer);
4986 qemu_get_be64s(f, &env->star);
4987 qemu_get_be64s(f, &env->lstar);
4988 qemu_get_be64s(f, &env->cstar);
4989 qemu_get_be64s(f, &env->fmask);
4990 qemu_get_be64s(f, &env->kernelgsbase);
4993 /* XXX: compute hflags from scratch, except for CPL and IIF */
4994 env->hflags = hflags;
4999 #elif defined(TARGET_PPC)
5000 void cpu_save(QEMUFile *f, void *opaque)
5004 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5009 #elif defined(TARGET_MIPS)
5010 void cpu_save(QEMUFile *f, void *opaque)
5014 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5019 #elif defined(TARGET_SPARC)
5020 void cpu_save(QEMUFile *f, void *opaque)
5022 CPUState *env = opaque;
5026 for(i = 0; i < 8; i++)
5027 qemu_put_betls(f, &env->gregs[i]);
5028 for(i = 0; i < NWINDOWS * 16; i++)
5029 qemu_put_betls(f, &env->regbase[i]);
5032 for(i = 0; i < TARGET_FPREGS; i++) {
5038 qemu_put_be32(f, u.i);
5041 qemu_put_betls(f, &env->pc);
5042 qemu_put_betls(f, &env->npc);
5043 qemu_put_betls(f, &env->y);
5045 qemu_put_be32(f, tmp);
5046 qemu_put_betls(f, &env->fsr);
5047 qemu_put_betls(f, &env->tbr);
5048 #ifndef TARGET_SPARC64
5049 qemu_put_be32s(f, &env->wim);
5051 for(i = 0; i < 16; i++)
5052 qemu_put_be32s(f, &env->mmuregs[i]);
5056 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5058 CPUState *env = opaque;
5062 for(i = 0; i < 8; i++)
5063 qemu_get_betls(f, &env->gregs[i]);
5064 for(i = 0; i < NWINDOWS * 16; i++)
5065 qemu_get_betls(f, &env->regbase[i]);
5068 for(i = 0; i < TARGET_FPREGS; i++) {
5073 u.i = qemu_get_be32(f);
5077 qemu_get_betls(f, &env->pc);
5078 qemu_get_betls(f, &env->npc);
5079 qemu_get_betls(f, &env->y);
5080 tmp = qemu_get_be32(f);
5081 env->cwp = 0; /* needed to ensure that the wrapping registers are
5082 correctly updated */
5084 qemu_get_betls(f, &env->fsr);
5085 qemu_get_betls(f, &env->tbr);
5086 #ifndef TARGET_SPARC64
5087 qemu_get_be32s(f, &env->wim);
5089 for(i = 0; i < 16; i++)
5090 qemu_get_be32s(f, &env->mmuregs[i]);
5096 #elif defined(TARGET_ARM)
5098 /* ??? Need to implement these. */
5099 void cpu_save(QEMUFile *f, void *opaque)
5103 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5110 #warning No CPU save/restore functions
5114 /***********************************************************/
5115 /* ram save/restore */
5117 /* we just avoid storing empty pages */
5118 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
5123 for(i = 1; i < len; i++) {
5127 qemu_put_byte(f, 1);
5128 qemu_put_byte(f, v);
5131 qemu_put_byte(f, 0);
5132 qemu_put_buffer(f, buf, len);
5135 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5139 v = qemu_get_byte(f);
5142 if (qemu_get_buffer(f, buf, len) != len)
5146 v = qemu_get_byte(f);
5147 memset(buf, v, len);
5155 static void ram_save(QEMUFile *f, void *opaque)
5158 qemu_put_be32(f, phys_ram_size);
5159 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5160 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5164 static int ram_load(QEMUFile *f, void *opaque, int version_id)
5168 if (version_id != 1)
5170 if (qemu_get_be32(f) != phys_ram_size)
5172 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5173 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5180 /***********************************************************/
5181 /* bottom halves (can be seen as timers which expire ASAP) */
5190 static QEMUBH *first_bh = NULL;
5192 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5195 bh = qemu_mallocz(sizeof(QEMUBH));
5199 bh->opaque = opaque;
5203 int qemu_bh_poll(void)
5222 void qemu_bh_schedule(QEMUBH *bh)
5224 CPUState *env = cpu_single_env;
5228 bh->next = first_bh;
5231 /* stop the currently executing CPU to execute the BH ASAP */
5233 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5237 void qemu_bh_cancel(QEMUBH *bh)
5240 if (bh->scheduled) {
5243 pbh = &(*pbh)->next;
5249 void qemu_bh_delete(QEMUBH *bh)
5255 /***********************************************************/
5256 /* machine registration */
5258 QEMUMachine *first_machine = NULL;
5260 int qemu_register_machine(QEMUMachine *m)
5263 pm = &first_machine;
5271 QEMUMachine *find_machine(const char *name)
5275 for(m = first_machine; m != NULL; m = m->next) {
5276 if (!strcmp(m->name, name))
5282 /***********************************************************/
5283 /* main execution loop */
5285 void gui_update(void *opaque)
5287 display_state.dpy_refresh(&display_state);
5288 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
5291 struct vm_change_state_entry {
5292 VMChangeStateHandler *cb;
5294 LIST_ENTRY (vm_change_state_entry) entries;
5297 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
5299 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
5302 VMChangeStateEntry *e;
5304 e = qemu_mallocz(sizeof (*e));
5310 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
5314 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
5316 LIST_REMOVE (e, entries);
5320 static void vm_state_notify(int running)
5322 VMChangeStateEntry *e;
5324 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
5325 e->cb(e->opaque, running);
5329 /* XXX: support several handlers */
5330 static VMStopHandler *vm_stop_cb;
5331 static void *vm_stop_opaque;
5333 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
5336 vm_stop_opaque = opaque;
5340 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
5354 void vm_stop(int reason)
5357 cpu_disable_ticks();
5361 vm_stop_cb(vm_stop_opaque, reason);
5368 /* reset/shutdown handler */
5370 typedef struct QEMUResetEntry {
5371 QEMUResetHandler *func;
5373 struct QEMUResetEntry *next;
5376 static QEMUResetEntry *first_reset_entry;
5377 static int reset_requested;
5378 static int shutdown_requested;
5379 static int powerdown_requested;
5381 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
5383 QEMUResetEntry **pre, *re;
5385 pre = &first_reset_entry;
5386 while (*pre != NULL)
5387 pre = &(*pre)->next;
5388 re = qemu_mallocz(sizeof(QEMUResetEntry));
5390 re->opaque = opaque;
5395 void qemu_system_reset(void)
5399 /* reset all devices */
5400 for(re = first_reset_entry; re != NULL; re = re->next) {
5401 re->func(re->opaque);
5405 void qemu_system_reset_request(void)
5407 reset_requested = 1;
5409 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5412 void qemu_system_shutdown_request(void)
5414 shutdown_requested = 1;
5416 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5419 void qemu_system_powerdown_request(void)
5421 powerdown_requested = 1;
5423 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
5426 void main_loop_wait(int timeout)
5428 IOHandlerRecord *ioh, *ioh_next;
5429 fd_set rfds, wfds, xfds;
5435 /* XXX: need to suppress polling by better using win32 events */
5437 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
5438 ret |= pe->func(pe->opaque);
5441 if (ret == 0 && timeout > 0) {
5443 WaitObjects *w = &wait_objects;
5445 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
5446 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
5447 if (w->func[ret - WAIT_OBJECT_0])
5448 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
5449 } else if (ret == WAIT_TIMEOUT) {
5451 err = GetLastError();
5452 fprintf(stderr, "Wait error %d %d\n", ret, err);
5456 /* poll any events */
5457 /* XXX: separate device handlers from system ones */
5462 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5464 (!ioh->fd_read_poll ||
5465 ioh->fd_read_poll(ioh->opaque) != 0)) {
5466 FD_SET(ioh->fd, &rfds);
5470 if (ioh->fd_write) {
5471 FD_SET(ioh->fd, &wfds);
5481 tv.tv_usec = timeout * 1000;
5483 #if defined(CONFIG_SLIRP)
5485 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
5488 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
5490 /* XXX: better handling of removal */
5491 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
5492 ioh_next = ioh->next;
5493 if (FD_ISSET(ioh->fd, &rfds)) {
5494 ioh->fd_read(ioh->opaque);
5496 if (FD_ISSET(ioh->fd, &wfds)) {
5497 ioh->fd_write(ioh->opaque);
5501 #if defined(CONFIG_SLIRP)
5508 slirp_select_poll(&rfds, &wfds, &xfds);
5518 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
5519 qemu_get_clock(vm_clock));
5520 /* run dma transfers, if any */
5524 /* real time timers */
5525 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
5526 qemu_get_clock(rt_clock));
5529 static CPUState *cur_cpu;
5534 #ifdef CONFIG_PROFILER
5539 cur_cpu = first_cpu;
5546 env = env->next_cpu;
5549 #ifdef CONFIG_PROFILER
5550 ti = profile_getclock();
5552 ret = cpu_exec(env);
5553 #ifdef CONFIG_PROFILER
5554 qemu_time += profile_getclock() - ti;
5556 if (ret != EXCP_HALTED)
5558 /* all CPUs are halted ? */
5559 if (env == cur_cpu) {
5566 if (shutdown_requested) {
5567 ret = EXCP_INTERRUPT;
5570 if (reset_requested) {
5571 reset_requested = 0;
5572 qemu_system_reset();
5573 ret = EXCP_INTERRUPT;
5575 if (powerdown_requested) {
5576 powerdown_requested = 0;
5577 qemu_system_powerdown();
5578 ret = EXCP_INTERRUPT;
5580 if (ret == EXCP_DEBUG) {
5581 vm_stop(EXCP_DEBUG);
5583 /* if hlt instruction, we wait until the next IRQ */
5584 /* XXX: use timeout computed from timers */
5585 if (ret == EXCP_HLT)
5592 #ifdef CONFIG_PROFILER
5593 ti = profile_getclock();
5595 main_loop_wait(timeout);
5596 #ifdef CONFIG_PROFILER
5597 dev_time += profile_getclock() - ti;
5600 cpu_disable_ticks();
5606 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
5607 "usage: %s [options] [disk_image]\n"
5609 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
5611 "Standard options:\n"
5612 "-M machine select emulated machine (-M ? for list)\n"
5613 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
5614 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
5615 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
5616 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
5617 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
5618 "-snapshot write to temporary files instead of disk image files\n"
5620 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
5622 "-m megs set virtual RAM size to megs MB [default=%d]\n"
5623 "-smp n set the number of CPUs to 'n' [default=1]\n"
5624 "-nographic disable graphical output and redirect serial I/Os to console\n"
5626 "-k language use keyboard layout (for example \"fr\" for French)\n"
5629 "-audio-help print list of audio drivers and their options\n"
5630 "-soundhw c1,... enable audio support\n"
5631 " and only specified sound cards (comma separated list)\n"
5632 " use -soundhw ? to get the list of supported cards\n"
5633 " use -soundhw all to enable all of them\n"
5635 "-localtime set the real time clock to local time [default=utc]\n"
5636 "-full-screen start in full screen\n"
5638 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
5640 "-usb enable the USB driver (will be the default soon)\n"
5641 "-usbdevice name add the host or guest USB device 'name'\n"
5642 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5643 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
5646 "Network options:\n"
5647 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
5648 " create a new Network Interface Card and connect it to VLAN 'n'\n"
5650 "-net user[,vlan=n][,hostname=host]\n"
5651 " connect the user mode network stack to VLAN 'n' and send\n"
5652 " hostname 'host' to DHCP clients\n"
5655 "-net tap[,vlan=n],ifname=name\n"
5656 " connect the host TAP network interface to VLAN 'n'\n"
5658 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
5659 " connect the host TAP network interface to VLAN 'n' and use\n"
5660 " the network script 'file' (default=%s);\n"
5661 " use 'fd=h' to connect to an already opened TAP interface\n"
5663 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
5664 " connect the vlan 'n' to another VLAN using a socket connection\n"
5665 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
5666 " connect the vlan 'n' to multicast maddr and port\n"
5667 "-net none use it alone to have zero network devices; if no -net option\n"
5668 " is provided, the default is '-net nic -net user'\n"
5671 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
5673 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
5675 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
5676 " redirect TCP or UDP connections from host to guest [-net user]\n"
5679 "Linux boot specific:\n"
5680 "-kernel bzImage use 'bzImage' as kernel image\n"
5681 "-append cmdline use 'cmdline' as kernel command line\n"
5682 "-initrd file use 'file' as initial ram disk\n"
5684 "Debug/Expert options:\n"
5685 "-monitor dev redirect the monitor to char device 'dev'\n"
5686 "-serial dev redirect the serial port to char device 'dev'\n"
5687 "-parallel dev redirect the parallel port to char device 'dev'\n"
5688 "-pidfile file Write PID to 'file'\n"
5689 "-S freeze CPU at startup (use 'c' to start execution)\n"
5690 "-s wait gdb connection to port %d\n"
5691 "-p port change gdb connection port\n"
5692 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
5693 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
5694 " translation (t=none or lba) (usually qemu can guess them)\n"
5695 "-L path set the directory for the BIOS and VGA BIOS\n"
5697 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
5698 "-no-kqemu disable KQEMU kernel module usage\n"
5700 #ifdef USE_CODE_COPY
5701 "-no-code-copy disable code copy acceleration\n"
5704 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
5705 " (default is CL-GD5446 PCI VGA)\n"
5706 "-no-acpi disable ACPI\n"
5708 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
5709 "-vnc display start a VNC server on display\n"
5711 "During emulation, the following keys are useful:\n"
5712 "ctrl-alt-f toggle full screen\n"
5713 "ctrl-alt-n switch to virtual console 'n'\n"
5714 "ctrl-alt toggle mouse and keyboard grab\n"
5716 "When using -nographic, press 'ctrl-a h' to get some help.\n"
5721 DEFAULT_NETWORK_SCRIPT,
5723 DEFAULT_GDBSTUB_PORT,
5728 #define HAS_ARG 0x0001
5742 QEMU_OPTION_snapshot,
5744 QEMU_OPTION_no_fd_bootchk,
5747 QEMU_OPTION_nographic,
5749 QEMU_OPTION_audio_help,
5750 QEMU_OPTION_soundhw,
5768 QEMU_OPTION_no_code_copy,
5770 QEMU_OPTION_localtime,
5771 QEMU_OPTION_cirrusvga,
5773 QEMU_OPTION_std_vga,
5774 QEMU_OPTION_monitor,
5776 QEMU_OPTION_parallel,
5778 QEMU_OPTION_full_screen,
5779 QEMU_OPTION_pidfile,
5780 QEMU_OPTION_no_kqemu,
5781 QEMU_OPTION_kernel_kqemu,
5782 QEMU_OPTION_win2k_hack,
5784 QEMU_OPTION_usbdevice,
5787 QEMU_OPTION_no_acpi,
5790 typedef struct QEMUOption {
5796 const QEMUOption qemu_options[] = {
5797 { "h", 0, QEMU_OPTION_h },
5799 { "M", HAS_ARG, QEMU_OPTION_M },
5800 { "fda", HAS_ARG, QEMU_OPTION_fda },
5801 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
5802 { "hda", HAS_ARG, QEMU_OPTION_hda },
5803 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
5804 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
5805 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
5806 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
5807 { "boot", HAS_ARG, QEMU_OPTION_boot },
5808 { "snapshot", 0, QEMU_OPTION_snapshot },
5810 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
5812 { "m", HAS_ARG, QEMU_OPTION_m },
5813 { "nographic", 0, QEMU_OPTION_nographic },
5814 { "k", HAS_ARG, QEMU_OPTION_k },
5816 { "audio-help", 0, QEMU_OPTION_audio_help },
5817 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
5820 { "net", HAS_ARG, QEMU_OPTION_net},
5822 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
5824 { "smb", HAS_ARG, QEMU_OPTION_smb },
5826 { "redir", HAS_ARG, QEMU_OPTION_redir },
5829 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
5830 { "append", HAS_ARG, QEMU_OPTION_append },
5831 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
5833 { "S", 0, QEMU_OPTION_S },
5834 { "s", 0, QEMU_OPTION_s },
5835 { "p", HAS_ARG, QEMU_OPTION_p },
5836 { "d", HAS_ARG, QEMU_OPTION_d },
5837 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
5838 { "L", HAS_ARG, QEMU_OPTION_L },
5839 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
5841 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
5842 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
5844 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
5845 { "g", 1, QEMU_OPTION_g },
5847 { "localtime", 0, QEMU_OPTION_localtime },
5848 { "std-vga", 0, QEMU_OPTION_std_vga },
5849 { "monitor", 1, QEMU_OPTION_monitor },
5850 { "serial", 1, QEMU_OPTION_serial },
5851 { "parallel", 1, QEMU_OPTION_parallel },
5852 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
5853 { "full-screen", 0, QEMU_OPTION_full_screen },
5854 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
5855 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
5856 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
5857 { "smp", HAS_ARG, QEMU_OPTION_smp },
5858 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
5860 /* temporary options */
5861 { "usb", 0, QEMU_OPTION_usb },
5862 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
5863 { "no-acpi", 0, QEMU_OPTION_no_acpi },
5867 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5869 /* this stack is only used during signal handling */
5870 #define SIGNAL_STACK_SIZE 32768
5872 static uint8_t *signal_stack;
5876 /* password input */
5878 static BlockDriverState *get_bdrv(int index)
5880 BlockDriverState *bs;
5883 bs = bs_table[index];
5884 } else if (index < 6) {
5885 bs = fd_table[index - 4];
5892 static void read_passwords(void)
5894 BlockDriverState *bs;
5898 for(i = 0; i < 6; i++) {
5900 if (bs && bdrv_is_encrypted(bs)) {
5901 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
5902 for(j = 0; j < 3; j++) {
5903 monitor_readline("Password: ",
5904 1, password, sizeof(password));
5905 if (bdrv_set_key(bs, password) == 0)
5907 term_printf("invalid password\n");
5913 /* XXX: currently we cannot use simultaneously different CPUs */
5914 void register_machines(void)
5916 #if defined(TARGET_I386)
5917 qemu_register_machine(&pc_machine);
5918 qemu_register_machine(&isapc_machine);
5919 #elif defined(TARGET_PPC)
5920 qemu_register_machine(&heathrow_machine);
5921 qemu_register_machine(&core99_machine);
5922 qemu_register_machine(&prep_machine);
5923 #elif defined(TARGET_MIPS)
5924 qemu_register_machine(&mips_machine);
5925 #elif defined(TARGET_SPARC)
5926 #ifdef TARGET_SPARC64
5927 qemu_register_machine(&sun4u_machine);
5929 qemu_register_machine(&sun4m_machine);
5931 #elif defined(TARGET_ARM)
5932 qemu_register_machine(&integratorcp926_machine);
5933 qemu_register_machine(&integratorcp1026_machine);
5934 qemu_register_machine(&versatilepb_machine);
5935 qemu_register_machine(&versatileab_machine);
5936 #elif defined(TARGET_SH4)
5937 qemu_register_machine(&shix_machine);
5939 #error unsupported CPU
5944 struct soundhw soundhw[] = {
5951 { .init_isa = pcspk_audio_init }
5956 "Creative Sound Blaster 16",
5959 { .init_isa = SB16_init }
5966 "Yamaha YMF262 (OPL3)",
5968 "Yamaha YM3812 (OPL2)",
5972 { .init_isa = Adlib_init }
5979 "Gravis Ultrasound GF1",
5982 { .init_isa = GUS_init }
5988 "ENSONIQ AudioPCI ES1370",
5991 { .init_pci = es1370_init }
5994 { NULL, NULL, 0, 0, { NULL } }
5997 static void select_soundhw (const char *optarg)
6001 if (*optarg == '?') {
6004 printf ("Valid sound card names (comma separated):\n");
6005 for (c = soundhw; c->name; ++c) {
6006 printf ("%-11s %s\n", c->name, c->descr);
6008 printf ("\n-soundhw all will enable all of the above\n");
6009 exit (*optarg != '?');
6017 if (!strcmp (optarg, "all")) {
6018 for (c = soundhw; c->name; ++c) {
6026 e = strchr (p, ',');
6027 l = !e ? strlen (p) : (size_t) (e - p);
6029 for (c = soundhw; c->name; ++c) {
6030 if (!strncmp (c->name, p, l)) {
6039 "Unknown sound card name (too big to show)\n");
6042 fprintf (stderr, "Unknown sound card name `%.*s'\n",
6047 p += l + (e != NULL);
6051 goto show_valid_cards;
6057 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6059 exit(STATUS_CONTROL_C_EXIT);
6064 #define MAX_NET_CLIENTS 32
6066 int main(int argc, char **argv)
6068 #ifdef CONFIG_GDBSTUB
6069 int use_gdbstub, gdbstub_port;
6072 int snapshot, linux_boot;
6073 const char *initrd_filename;
6074 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6075 const char *kernel_filename, *kernel_cmdline;
6076 DisplayState *ds = &display_state;
6077 int cyls, heads, secs, translation;
6078 int start_emulation = 1;
6079 char net_clients[MAX_NET_CLIENTS][256];
6082 const char *r, *optarg;
6083 CharDriverState *monitor_hd;
6084 char monitor_device[128];
6085 char serial_devices[MAX_SERIAL_PORTS][128];
6086 int serial_device_index;
6087 char parallel_devices[MAX_PARALLEL_PORTS][128];
6088 int parallel_device_index;
6089 const char *loadvm = NULL;
6090 QEMUMachine *machine;
6091 char usb_devices[MAX_USB_CMDLINE][128];
6092 int usb_devices_index;
6094 LIST_INIT (&vm_change_state_head);
6097 struct sigaction act;
6098 sigfillset(&act.sa_mask);
6100 act.sa_handler = SIG_IGN;
6101 sigaction(SIGPIPE, &act, NULL);
6104 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6105 /* Note: cpu_interrupt() is currently not SMP safe, so we force
6106 QEMU to run on a single CPU */
6111 h = GetCurrentProcess();
6112 if (GetProcessAffinityMask(h, &mask, &smask)) {
6113 for(i = 0; i < 32; i++) {
6114 if (mask & (1 << i))
6119 SetProcessAffinityMask(h, mask);
6125 register_machines();
6126 machine = first_machine;
6127 initrd_filename = NULL;
6128 for(i = 0; i < MAX_FD; i++)
6129 fd_filename[i] = NULL;
6130 for(i = 0; i < MAX_DISKS; i++)
6131 hd_filename[i] = NULL;
6132 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6133 vga_ram_size = VGA_RAM_SIZE;
6134 bios_size = BIOS_SIZE;
6135 #ifdef CONFIG_GDBSTUB
6137 gdbstub_port = DEFAULT_GDBSTUB_PORT;
6141 kernel_filename = NULL;
6142 kernel_cmdline = "";
6148 cyls = heads = secs = 0;
6149 translation = BIOS_ATA_TRANSLATION_AUTO;
6150 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6152 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6153 for(i = 1; i < MAX_SERIAL_PORTS; i++)
6154 serial_devices[i][0] = '\0';
6155 serial_device_index = 0;
6157 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6158 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6159 parallel_devices[i][0] = '\0';
6160 parallel_device_index = 0;
6162 usb_devices_index = 0;
6167 /* default mac address of the first network interface */
6175 hd_filename[0] = argv[optind++];
6177 const QEMUOption *popt;
6180 popt = qemu_options;
6183 fprintf(stderr, "%s: invalid option -- '%s'\n",
6187 if (!strcmp(popt->name, r + 1))
6191 if (popt->flags & HAS_ARG) {
6192 if (optind >= argc) {
6193 fprintf(stderr, "%s: option '%s' requires an argument\n",
6197 optarg = argv[optind++];
6202 switch(popt->index) {
6204 machine = find_machine(optarg);
6207 printf("Supported machines are:\n");
6208 for(m = first_machine; m != NULL; m = m->next) {
6209 printf("%-10s %s%s\n",
6211 m == first_machine ? " (default)" : "");
6216 case QEMU_OPTION_initrd:
6217 initrd_filename = optarg;
6219 case QEMU_OPTION_hda:
6220 case QEMU_OPTION_hdb:
6221 case QEMU_OPTION_hdc:
6222 case QEMU_OPTION_hdd:
6225 hd_index = popt->index - QEMU_OPTION_hda;
6226 hd_filename[hd_index] = optarg;
6227 if (hd_index == cdrom_index)
6231 case QEMU_OPTION_snapshot:
6234 case QEMU_OPTION_hdachs:
6238 cyls = strtol(p, (char **)&p, 0);
6239 if (cyls < 1 || cyls > 16383)
6244 heads = strtol(p, (char **)&p, 0);
6245 if (heads < 1 || heads > 16)
6250 secs = strtol(p, (char **)&p, 0);
6251 if (secs < 1 || secs > 63)
6255 if (!strcmp(p, "none"))
6256 translation = BIOS_ATA_TRANSLATION_NONE;
6257 else if (!strcmp(p, "lba"))
6258 translation = BIOS_ATA_TRANSLATION_LBA;
6259 else if (!strcmp(p, "auto"))
6260 translation = BIOS_ATA_TRANSLATION_AUTO;
6263 } else if (*p != '\0') {
6265 fprintf(stderr, "qemu: invalid physical CHS format\n");
6270 case QEMU_OPTION_nographic:
6271 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
6272 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
6275 case QEMU_OPTION_kernel:
6276 kernel_filename = optarg;
6278 case QEMU_OPTION_append:
6279 kernel_cmdline = optarg;
6281 case QEMU_OPTION_cdrom:
6282 if (cdrom_index >= 0) {
6283 hd_filename[cdrom_index] = optarg;
6286 case QEMU_OPTION_boot:
6287 boot_device = optarg[0];
6288 if (boot_device != 'a' &&
6291 boot_device != 'n' &&
6293 boot_device != 'c' && boot_device != 'd') {
6294 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
6298 case QEMU_OPTION_fda:
6299 fd_filename[0] = optarg;
6301 case QEMU_OPTION_fdb:
6302 fd_filename[1] = optarg;
6305 case QEMU_OPTION_no_fd_bootchk:
6309 case QEMU_OPTION_no_code_copy:
6310 code_copy_enabled = 0;
6312 case QEMU_OPTION_net:
6313 if (nb_net_clients >= MAX_NET_CLIENTS) {
6314 fprintf(stderr, "qemu: too many network clients\n");
6317 pstrcpy(net_clients[nb_net_clients],
6318 sizeof(net_clients[0]),
6323 case QEMU_OPTION_tftp:
6324 tftp_prefix = optarg;
6327 case QEMU_OPTION_smb:
6328 net_slirp_smb(optarg);
6331 case QEMU_OPTION_redir:
6332 net_slirp_redir(optarg);
6336 case QEMU_OPTION_audio_help:
6340 case QEMU_OPTION_soundhw:
6341 select_soundhw (optarg);
6348 ram_size = atoi(optarg) * 1024 * 1024;
6351 if (ram_size > PHYS_RAM_MAX_SIZE) {
6352 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
6353 PHYS_RAM_MAX_SIZE / (1024 * 1024));
6362 mask = cpu_str_to_log_mask(optarg);
6364 printf("Log items (comma separated):\n");
6365 for(item = cpu_log_items; item->mask != 0; item++) {
6366 printf("%-10s %s\n", item->name, item->help);
6373 #ifdef CONFIG_GDBSTUB
6378 gdbstub_port = atoi(optarg);
6385 start_emulation = 0;
6388 keyboard_layout = optarg;
6390 case QEMU_OPTION_localtime:
6393 case QEMU_OPTION_cirrusvga:
6394 cirrus_vga_enabled = 1;
6396 case QEMU_OPTION_std_vga:
6397 cirrus_vga_enabled = 0;
6404 w = strtol(p, (char **)&p, 10);
6407 fprintf(stderr, "qemu: invalid resolution or depth\n");
6413 h = strtol(p, (char **)&p, 10);
6418 depth = strtol(p, (char **)&p, 10);
6419 if (depth != 8 && depth != 15 && depth != 16 &&
6420 depth != 24 && depth != 32)
6422 } else if (*p == '\0') {
6423 depth = graphic_depth;
6430 graphic_depth = depth;
6433 case QEMU_OPTION_monitor:
6434 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
6436 case QEMU_OPTION_serial:
6437 if (serial_device_index >= MAX_SERIAL_PORTS) {
6438 fprintf(stderr, "qemu: too many serial ports\n");
6441 pstrcpy(serial_devices[serial_device_index],
6442 sizeof(serial_devices[0]), optarg);
6443 serial_device_index++;
6445 case QEMU_OPTION_parallel:
6446 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
6447 fprintf(stderr, "qemu: too many parallel ports\n");
6450 pstrcpy(parallel_devices[parallel_device_index],
6451 sizeof(parallel_devices[0]), optarg);
6452 parallel_device_index++;
6454 case QEMU_OPTION_loadvm:
6457 case QEMU_OPTION_full_screen:
6460 case QEMU_OPTION_pidfile:
6461 create_pidfile(optarg);
6464 case QEMU_OPTION_win2k_hack:
6465 win2k_install_hack = 1;
6469 case QEMU_OPTION_no_kqemu:
6472 case QEMU_OPTION_kernel_kqemu:
6476 case QEMU_OPTION_usb:
6479 case QEMU_OPTION_usbdevice:
6481 if (usb_devices_index >= MAX_USB_CMDLINE) {
6482 fprintf(stderr, "Too many USB devices\n");
6485 pstrcpy(usb_devices[usb_devices_index],
6486 sizeof(usb_devices[usb_devices_index]),
6488 usb_devices_index++;
6490 case QEMU_OPTION_smp:
6491 smp_cpus = atoi(optarg);
6492 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
6493 fprintf(stderr, "Invalid number of CPUs\n");
6497 case QEMU_OPTION_vnc:
6498 vnc_display = atoi(optarg);
6499 if (vnc_display < 0) {
6500 fprintf(stderr, "Invalid VNC display\n");
6504 case QEMU_OPTION_no_acpi:
6515 linux_boot = (kernel_filename != NULL);
6518 hd_filename[0] == '\0' &&
6519 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
6520 fd_filename[0] == '\0')
6523 /* boot to cd by default if no hard disk */
6524 if (hd_filename[0] == '\0' && boot_device == 'c') {
6525 if (fd_filename[0] != '\0')
6531 setvbuf(stdout, NULL, _IOLBF, 0);
6541 /* init network clients */
6542 if (nb_net_clients == 0) {
6543 /* if no clients, we use a default config */
6544 pstrcpy(net_clients[0], sizeof(net_clients[0]),
6546 pstrcpy(net_clients[1], sizeof(net_clients[0]),
6551 for(i = 0;i < nb_net_clients; i++) {
6552 if (net_client_init(net_clients[i]) < 0)
6556 /* init the memory */
6557 phys_ram_size = ram_size + vga_ram_size + bios_size;
6559 phys_ram_base = qemu_vmalloc(phys_ram_size);
6560 if (!phys_ram_base) {
6561 fprintf(stderr, "Could not allocate physical memory\n");
6565 /* we always create the cdrom drive, even if no disk is there */
6567 if (cdrom_index >= 0) {
6568 bs_table[cdrom_index] = bdrv_new("cdrom");
6569 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
6572 /* open the virtual block devices */
6573 for(i = 0; i < MAX_DISKS; i++) {
6574 if (hd_filename[i]) {
6577 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
6578 bs_table[i] = bdrv_new(buf);
6580 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6581 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
6585 if (i == 0 && cyls != 0) {
6586 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
6587 bdrv_set_translation_hint(bs_table[i], translation);
6592 /* we always create at least one floppy disk */
6593 fd_table[0] = bdrv_new("fda");
6594 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
6596 for(i = 0; i < MAX_FD; i++) {
6597 if (fd_filename[i]) {
6600 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
6601 fd_table[i] = bdrv_new(buf);
6602 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
6604 if (fd_filename[i] != '\0') {
6605 if (bdrv_open(fd_table[i], fd_filename[i],
6606 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
6607 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
6615 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
6616 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
6622 dumb_display_init(ds);
6623 } else if (vnc_display != -1) {
6624 vnc_display_init(ds, vnc_display);
6626 #if defined(CONFIG_SDL)
6627 sdl_display_init(ds, full_screen);
6628 #elif defined(CONFIG_COCOA)
6629 cocoa_display_init(ds, full_screen);
6631 dumb_display_init(ds);
6635 monitor_hd = qemu_chr_open(monitor_device);
6637 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
6640 monitor_init(monitor_hd, !nographic);
6642 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
6643 if (serial_devices[i][0] != '\0') {
6644 serial_hds[i] = qemu_chr_open(serial_devices[i]);
6645 if (!serial_hds[i]) {
6646 fprintf(stderr, "qemu: could not open serial device '%s'\n",
6650 if (!strcmp(serial_devices[i], "vc"))
6651 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
6655 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
6656 if (parallel_devices[i][0] != '\0') {
6657 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
6658 if (!parallel_hds[i]) {
6659 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
6660 parallel_devices[i]);
6663 if (!strcmp(parallel_devices[i], "vc"))
6664 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
6668 machine->init(ram_size, vga_ram_size, boot_device,
6669 ds, fd_filename, snapshot,
6670 kernel_filename, kernel_cmdline, initrd_filename);
6672 /* init USB devices */
6674 for(i = 0; i < usb_devices_index; i++) {
6675 if (usb_device_add(usb_devices[i]) < 0) {
6676 fprintf(stderr, "Warning: could not add USB device %s\n",
6682 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
6683 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
6685 #ifdef CONFIG_GDBSTUB
6687 if (gdbserver_start(gdbstub_port) < 0) {
6688 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
6692 printf("Waiting gdb connection on port %d\n", gdbstub_port);
6700 /* XXX: simplify init */
6702 if (start_emulation) {