4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
50 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
55 #include <linux/if_tun.h>
58 #include <linux/rtc.h>
59 #include <linux/ppdev.h>
60 #include <linux/parport.h>
63 #include <sys/ethernet.h>
64 #include <sys/sockio.h>
65 #include <arpa/inet.h>
66 #include <netinet/arp.h>
67 #include <netinet/in.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/ip.h>
70 #include <netinet/ip_icmp.h> // must come after ip.h
71 #include <netinet/udp.h>
72 #include <netinet/tcp.h>
80 #if defined(CONFIG_SLIRP)
86 #include <sys/timeb.h>
88 #define getopt_long_only getopt_long
89 #define memalign(align, size) malloc(size)
92 #include "qemu_socket.h"
98 #endif /* CONFIG_SDL */
102 #define main qemu_main
103 #endif /* CONFIG_COCOA */
107 #include "exec-all.h"
109 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
111 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
113 #define SMBD_COMMAND "/usr/sbin/smbd"
116 //#define DEBUG_UNUSED_IOPORT
117 //#define DEBUG_IOPORT
119 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
122 #define DEFAULT_RAM_SIZE 144
124 #define DEFAULT_RAM_SIZE 128
127 #define GUI_REFRESH_INTERVAL 30
129 /* Max number of USB devices that can be specified on the commandline. */
130 #define MAX_USB_CMDLINE 8
132 /* XXX: use a two level table to limit memory usage */
133 #define MAX_IOPORTS 65536
135 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
136 char phys_ram_file[1024];
137 void *ioport_opaque[MAX_IOPORTS];
138 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
139 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
140 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
141 to store the VM snapshots */
142 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
143 BlockDriverState *pflash_table[MAX_PFLASH];
144 BlockDriverState *sd_bdrv;
145 BlockDriverState *mtd_bdrv;
146 /* point to the block driver where the snapshots are managed */
147 BlockDriverState *bs_snapshots;
149 static DisplayState display_state;
151 const char* keyboard_layout = NULL;
152 int64_t ticks_per_sec;
153 int boot_device = 'c';
155 int pit_min_timer_count = 0;
157 NICInfo nd_table[MAX_NICS];
160 int cirrus_vga_enabled = 1;
161 int vmsvga_enabled = 0;
163 int graphic_width = 1024;
164 int graphic_height = 768;
165 int graphic_depth = 8;
167 int graphic_width = 800;
168 int graphic_height = 600;
169 int graphic_depth = 15;
174 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
175 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
177 int win2k_install_hack = 0;
180 static VLANState *first_vlan;
182 const char *vnc_display;
183 #if defined(TARGET_SPARC)
185 #elif defined(TARGET_I386)
190 int acpi_enabled = 1;
194 int graphic_rotate = 0;
196 const char *option_rom[MAX_OPTION_ROMS];
198 int semihosting_enabled = 0;
203 const char *qemu_name;
206 unsigned int nb_prom_envs = 0;
207 const char *prom_envs[MAX_PROM_ENVS];
210 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
212 /***********************************************************/
213 /* x86 ISA bus support */
215 target_phys_addr_t isa_mem_base = 0;
218 uint32_t default_ioport_readb(void *opaque, uint32_t address)
220 #ifdef DEBUG_UNUSED_IOPORT
221 fprintf(stderr, "unused inb: port=0x%04x\n", address);
226 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
228 #ifdef DEBUG_UNUSED_IOPORT
229 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
233 /* default is to make two byte accesses */
234 uint32_t default_ioport_readw(void *opaque, uint32_t address)
237 data = ioport_read_table[0][address](ioport_opaque[address], address);
238 address = (address + 1) & (MAX_IOPORTS - 1);
239 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
243 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
245 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
246 address = (address + 1) & (MAX_IOPORTS - 1);
247 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
250 uint32_t default_ioport_readl(void *opaque, uint32_t address)
252 #ifdef DEBUG_UNUSED_IOPORT
253 fprintf(stderr, "unused inl: port=0x%04x\n", address);
258 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
260 #ifdef DEBUG_UNUSED_IOPORT
261 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
265 void init_ioports(void)
269 for(i = 0; i < MAX_IOPORTS; i++) {
270 ioport_read_table[0][i] = default_ioport_readb;
271 ioport_write_table[0][i] = default_ioport_writeb;
272 ioport_read_table[1][i] = default_ioport_readw;
273 ioport_write_table[1][i] = default_ioport_writew;
274 ioport_read_table[2][i] = default_ioport_readl;
275 ioport_write_table[2][i] = default_ioport_writel;
279 /* size is the word size in byte */
280 int register_ioport_read(int start, int length, int size,
281 IOPortReadFunc *func, void *opaque)
287 } else if (size == 2) {
289 } else if (size == 4) {
292 hw_error("register_ioport_read: invalid size");
295 for(i = start; i < start + length; i += size) {
296 ioport_read_table[bsize][i] = func;
297 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
298 hw_error("register_ioport_read: invalid opaque");
299 ioport_opaque[i] = opaque;
304 /* size is the word size in byte */
305 int register_ioport_write(int start, int length, int size,
306 IOPortWriteFunc *func, void *opaque)
312 } else if (size == 2) {
314 } else if (size == 4) {
317 hw_error("register_ioport_write: invalid size");
320 for(i = start; i < start + length; i += size) {
321 ioport_write_table[bsize][i] = func;
322 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
323 hw_error("register_ioport_write: invalid opaque");
324 ioport_opaque[i] = opaque;
329 void isa_unassign_ioport(int start, int length)
333 for(i = start; i < start + length; i++) {
334 ioport_read_table[0][i] = default_ioport_readb;
335 ioport_read_table[1][i] = default_ioport_readw;
336 ioport_read_table[2][i] = default_ioport_readl;
338 ioport_write_table[0][i] = default_ioport_writeb;
339 ioport_write_table[1][i] = default_ioport_writew;
340 ioport_write_table[2][i] = default_ioport_writel;
344 /***********************************************************/
346 void cpu_outb(CPUState *env, int addr, int val)
349 if (loglevel & CPU_LOG_IOPORT)
350 fprintf(logfile, "outb: %04x %02x\n", addr, val);
352 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
355 env->last_io_time = cpu_get_time_fast();
359 void cpu_outw(CPUState *env, int addr, int val)
362 if (loglevel & CPU_LOG_IOPORT)
363 fprintf(logfile, "outw: %04x %04x\n", addr, val);
365 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
368 env->last_io_time = cpu_get_time_fast();
372 void cpu_outl(CPUState *env, int addr, int val)
375 if (loglevel & CPU_LOG_IOPORT)
376 fprintf(logfile, "outl: %04x %08x\n", addr, val);
378 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
381 env->last_io_time = cpu_get_time_fast();
385 int cpu_inb(CPUState *env, int addr)
388 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
390 if (loglevel & CPU_LOG_IOPORT)
391 fprintf(logfile, "inb : %04x %02x\n", addr, val);
395 env->last_io_time = cpu_get_time_fast();
400 int cpu_inw(CPUState *env, int addr)
403 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "inw : %04x %04x\n", addr, val);
410 env->last_io_time = cpu_get_time_fast();
415 int cpu_inl(CPUState *env, int addr)
418 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
420 if (loglevel & CPU_LOG_IOPORT)
421 fprintf(logfile, "inl : %04x %08x\n", addr, val);
425 env->last_io_time = cpu_get_time_fast();
430 /***********************************************************/
431 void hw_error(const char *fmt, ...)
437 fprintf(stderr, "qemu: hardware error: ");
438 vfprintf(stderr, fmt, ap);
439 fprintf(stderr, "\n");
440 for(env = first_cpu; env != NULL; env = env->next_cpu) {
441 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
443 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
445 cpu_dump_state(env, stderr, fprintf, 0);
452 /***********************************************************/
455 static QEMUPutKBDEvent *qemu_put_kbd_event;
456 static void *qemu_put_kbd_event_opaque;
457 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
458 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
460 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
462 qemu_put_kbd_event_opaque = opaque;
463 qemu_put_kbd_event = func;
466 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
467 void *opaque, int absolute,
470 QEMUPutMouseEntry *s, *cursor;
472 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
476 s->qemu_put_mouse_event = func;
477 s->qemu_put_mouse_event_opaque = opaque;
478 s->qemu_put_mouse_event_absolute = absolute;
479 s->qemu_put_mouse_event_name = qemu_strdup(name);
482 if (!qemu_put_mouse_event_head) {
483 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
487 cursor = qemu_put_mouse_event_head;
488 while (cursor->next != NULL)
489 cursor = cursor->next;
492 qemu_put_mouse_event_current = s;
497 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
499 QEMUPutMouseEntry *prev = NULL, *cursor;
501 if (!qemu_put_mouse_event_head || entry == NULL)
504 cursor = qemu_put_mouse_event_head;
505 while (cursor != NULL && cursor != entry) {
507 cursor = cursor->next;
510 if (cursor == NULL) // does not exist or list empty
512 else if (prev == NULL) { // entry is head
513 qemu_put_mouse_event_head = cursor->next;
514 if (qemu_put_mouse_event_current == entry)
515 qemu_put_mouse_event_current = cursor->next;
516 qemu_free(entry->qemu_put_mouse_event_name);
521 prev->next = entry->next;
523 if (qemu_put_mouse_event_current == entry)
524 qemu_put_mouse_event_current = prev;
526 qemu_free(entry->qemu_put_mouse_event_name);
530 void kbd_put_keycode(int keycode)
532 if (qemu_put_kbd_event) {
533 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
537 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
539 QEMUPutMouseEvent *mouse_event;
540 void *mouse_event_opaque;
543 if (!qemu_put_mouse_event_current) {
548 qemu_put_mouse_event_current->qemu_put_mouse_event;
550 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
553 if (graphic_rotate) {
554 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
557 width = graphic_width;
558 mouse_event(mouse_event_opaque,
559 width - dy, dx, dz, buttons_state);
561 mouse_event(mouse_event_opaque,
562 dx, dy, dz, buttons_state);
566 int kbd_mouse_is_absolute(void)
568 if (!qemu_put_mouse_event_current)
571 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
574 void do_info_mice(void)
576 QEMUPutMouseEntry *cursor;
579 if (!qemu_put_mouse_event_head) {
580 term_printf("No mouse devices connected\n");
584 term_printf("Mouse devices available:\n");
585 cursor = qemu_put_mouse_event_head;
586 while (cursor != NULL) {
587 term_printf("%c Mouse #%d: %s\n",
588 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
589 index, cursor->qemu_put_mouse_event_name);
591 cursor = cursor->next;
595 void do_mouse_set(int index)
597 QEMUPutMouseEntry *cursor;
600 if (!qemu_put_mouse_event_head) {
601 term_printf("No mouse devices connected\n");
605 cursor = qemu_put_mouse_event_head;
606 while (cursor != NULL && index != i) {
608 cursor = cursor->next;
612 qemu_put_mouse_event_current = cursor;
614 term_printf("Mouse at given index not found\n");
617 /* compute with 96 bit intermediate result: (a*b)/c */
618 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
623 #ifdef WORDS_BIGENDIAN
633 rl = (uint64_t)u.l.low * (uint64_t)b;
634 rh = (uint64_t)u.l.high * (uint64_t)b;
637 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
641 /***********************************************************/
642 /* real time host monotonic timer */
644 #define QEMU_TIMER_BASE 1000000000LL
648 static int64_t clock_freq;
650 static void init_get_clock(void)
654 ret = QueryPerformanceFrequency(&freq);
656 fprintf(stderr, "Could not calibrate ticks\n");
659 clock_freq = freq.QuadPart;
662 static int64_t get_clock(void)
665 QueryPerformanceCounter(&ti);
666 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
671 static int use_rt_clock;
673 static void init_get_clock(void)
676 #if defined(__linux__)
679 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
686 static int64_t get_clock(void)
688 #if defined(__linux__)
691 clock_gettime(CLOCK_MONOTONIC, &ts);
692 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
696 /* XXX: using gettimeofday leads to problems if the date
697 changes, so it should be avoided. */
699 gettimeofday(&tv, NULL);
700 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
706 /***********************************************************/
707 /* guest cycle counter */
709 static int64_t cpu_ticks_prev;
710 static int64_t cpu_ticks_offset;
711 static int64_t cpu_clock_offset;
712 static int cpu_ticks_enabled;
714 /* return the host CPU cycle counter and handle stop/restart */
715 int64_t cpu_get_ticks(void)
717 if (!cpu_ticks_enabled) {
718 return cpu_ticks_offset;
721 ticks = cpu_get_real_ticks();
722 if (cpu_ticks_prev > ticks) {
723 /* Note: non increasing ticks may happen if the host uses
725 cpu_ticks_offset += cpu_ticks_prev - ticks;
727 cpu_ticks_prev = ticks;
728 return ticks + cpu_ticks_offset;
732 /* return the host CPU monotonic timer and handle stop/restart */
733 static int64_t cpu_get_clock(void)
736 if (!cpu_ticks_enabled) {
737 return cpu_clock_offset;
740 return ti + cpu_clock_offset;
744 /* enable cpu_get_ticks() */
745 void cpu_enable_ticks(void)
747 if (!cpu_ticks_enabled) {
748 cpu_ticks_offset -= cpu_get_real_ticks();
749 cpu_clock_offset -= get_clock();
750 cpu_ticks_enabled = 1;
754 /* disable cpu_get_ticks() : the clock is stopped. You must not call
755 cpu_get_ticks() after that. */
756 void cpu_disable_ticks(void)
758 if (cpu_ticks_enabled) {
759 cpu_ticks_offset = cpu_get_ticks();
760 cpu_clock_offset = cpu_get_clock();
761 cpu_ticks_enabled = 0;
765 /***********************************************************/
768 #define QEMU_TIMER_REALTIME 0
769 #define QEMU_TIMER_VIRTUAL 1
773 /* XXX: add frequency */
781 struct QEMUTimer *next;
784 struct qemu_alarm_timer {
787 int (*start)(struct qemu_alarm_timer *t);
788 void (*stop)(struct qemu_alarm_timer *t);
792 static struct qemu_alarm_timer *alarm_timer;
796 struct qemu_alarm_win32 {
800 } alarm_win32_data = {0, NULL, -1};
802 static int win32_start_timer(struct qemu_alarm_timer *t);
803 static void win32_stop_timer(struct qemu_alarm_timer *t);
807 static int unix_start_timer(struct qemu_alarm_timer *t);
808 static void unix_stop_timer(struct qemu_alarm_timer *t);
812 static int rtc_start_timer(struct qemu_alarm_timer *t);
813 static void rtc_stop_timer(struct qemu_alarm_timer *t);
819 static struct qemu_alarm_timer alarm_timers[] = {
821 /* RTC - if available - is preferred */
822 {"rtc", rtc_start_timer, rtc_stop_timer, NULL},
825 {"unix", unix_start_timer, unix_stop_timer, NULL},
827 {"win32", win32_start_timer, win32_stop_timer, &alarm_win32_data},
835 static QEMUTimer *active_timers[2];
837 QEMUClock *qemu_new_clock(int type)
840 clock = qemu_mallocz(sizeof(QEMUClock));
847 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
851 ts = qemu_mallocz(sizeof(QEMUTimer));
858 void qemu_free_timer(QEMUTimer *ts)
863 /* stop a timer, but do not dealloc it */
864 void qemu_del_timer(QEMUTimer *ts)
868 /* NOTE: this code must be signal safe because
869 qemu_timer_expired() can be called from a signal. */
870 pt = &active_timers[ts->clock->type];
883 /* modify the current timer so that it will be fired when current_time
884 >= expire_time. The corresponding callback will be called. */
885 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
891 /* add the timer in the sorted list */
892 /* NOTE: this code must be signal safe because
893 qemu_timer_expired() can be called from a signal. */
894 pt = &active_timers[ts->clock->type];
899 if (t->expire_time > expire_time)
903 ts->expire_time = expire_time;
908 int qemu_timer_pending(QEMUTimer *ts)
911 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
918 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
922 return (timer_head->expire_time <= current_time);
925 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
931 if (!ts || ts->expire_time > current_time)
933 /* remove timer from the list before calling the callback */
934 *ptimer_head = ts->next;
937 /* run the callback (the timer list can be modified) */
942 int64_t qemu_get_clock(QEMUClock *clock)
944 switch(clock->type) {
945 case QEMU_TIMER_REALTIME:
946 return get_clock() / 1000000;
948 case QEMU_TIMER_VIRTUAL:
949 return cpu_get_clock();
953 static void init_timers(void)
956 ticks_per_sec = QEMU_TIMER_BASE;
957 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
958 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
962 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
964 uint64_t expire_time;
966 if (qemu_timer_pending(ts)) {
967 expire_time = ts->expire_time;
971 qemu_put_be64(f, expire_time);
974 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
976 uint64_t expire_time;
978 expire_time = qemu_get_be64(f);
979 if (expire_time != -1) {
980 qemu_mod_timer(ts, expire_time);
986 static void timer_save(QEMUFile *f, void *opaque)
988 if (cpu_ticks_enabled) {
989 hw_error("cannot save state if virtual timers are running");
991 qemu_put_be64s(f, &cpu_ticks_offset);
992 qemu_put_be64s(f, &ticks_per_sec);
993 qemu_put_be64s(f, &cpu_clock_offset);
996 static int timer_load(QEMUFile *f, void *opaque, int version_id)
998 if (version_id != 1 && version_id != 2)
1000 if (cpu_ticks_enabled) {
1003 qemu_get_be64s(f, &cpu_ticks_offset);
1004 qemu_get_be64s(f, &ticks_per_sec);
1005 if (version_id == 2) {
1006 qemu_get_be64s(f, &cpu_clock_offset);
1012 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1013 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1015 static void host_alarm_handler(int host_signum)
1019 #define DISP_FREQ 1000
1021 static int64_t delta_min = INT64_MAX;
1022 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1024 ti = qemu_get_clock(vm_clock);
1025 if (last_clock != 0) {
1026 delta = ti - last_clock;
1027 if (delta < delta_min)
1029 if (delta > delta_max)
1032 if (++count == DISP_FREQ) {
1033 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1034 muldiv64(delta_min, 1000000, ticks_per_sec),
1035 muldiv64(delta_max, 1000000, ticks_per_sec),
1036 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1037 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1039 delta_min = INT64_MAX;
1047 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1048 qemu_get_clock(vm_clock)) ||
1049 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1050 qemu_get_clock(rt_clock))) {
1052 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1053 SetEvent(data->host_alarm);
1055 CPUState *env = cpu_single_env;
1057 /* stop the currently executing cpu because a timer occured */
1058 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1060 if (env->kqemu_enabled) {
1061 kqemu_cpu_interrupt(env);
1070 #if defined(__linux__)
1072 #define RTC_FREQ 1024
1074 static void enable_sigio_timer(int fd)
1076 struct sigaction act;
1079 sigfillset(&act.sa_mask);
1081 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1082 act.sa_flags |= SA_ONSTACK;
1084 act.sa_handler = host_alarm_handler;
1086 sigaction(SIGIO, &act, NULL);
1087 fcntl(fd, F_SETFL, O_ASYNC);
1088 fcntl(fd, F_SETOWN, getpid());
1091 static int rtc_start_timer(struct qemu_alarm_timer *t)
1095 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1098 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1099 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1100 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1101 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1104 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1110 enable_sigio_timer(rtc_fd);
1112 t->priv = (void *)rtc_fd;
1117 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1119 int rtc_fd = (int)t->priv;
1124 #endif /* !defined(__linux__) */
1126 static int unix_start_timer(struct qemu_alarm_timer *t)
1128 struct sigaction act;
1129 struct itimerval itv;
1133 sigfillset(&act.sa_mask);
1135 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1136 act.sa_flags |= SA_ONSTACK;
1138 act.sa_handler = host_alarm_handler;
1140 sigaction(SIGALRM, &act, NULL);
1142 itv.it_interval.tv_sec = 0;
1143 /* for i386 kernel 2.6 to get 1 ms */
1144 itv.it_interval.tv_usec = 999;
1145 itv.it_value.tv_sec = 0;
1146 itv.it_value.tv_usec = 10 * 1000;
1148 err = setitimer(ITIMER_REAL, &itv, NULL);
1155 static void unix_stop_timer(struct qemu_alarm_timer *t)
1157 struct itimerval itv;
1159 memset(&itv, 0, sizeof(itv));
1160 setitimer(ITIMER_REAL, &itv, NULL);
1163 #endif /* !defined(_WIN32) */
1167 static int win32_start_timer(struct qemu_alarm_timer *t)
1170 struct qemu_alarm_win32 *data = t->priv;
1172 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1173 if (!data->host_alarm) {
1174 perror("Failed CreateEvent");
1178 memset(&tc, 0, sizeof(tc));
1179 timeGetDevCaps(&tc, sizeof(tc));
1181 if (data->period < tc.wPeriodMin)
1182 data->period = tc.wPeriodMin;
1184 timeBeginPeriod(data->period);
1186 data->timerId = timeSetEvent(1, // interval (ms)
1187 data->period, // resolution
1188 host_alarm_handler, // function
1189 (DWORD)t, // parameter
1190 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1192 if (!data->timerId) {
1193 perror("Failed to initialize win32 alarm timer");
1195 timeEndPeriod(data->period);
1196 CloseHandle(data->host_alarm);
1200 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1205 static void win32_stop_timer(struct qemu_alarm_timer *t)
1207 struct qemu_alarm_win32 *data = t->priv;
1209 timeKillEvent(data->timerId);
1210 timeEndPeriod(data->period);
1212 CloseHandle(data->host_alarm);
1217 static void init_timer_alarm(void)
1219 struct qemu_alarm_timer *t;
1222 for (i = 0; alarm_timers[i].name; i++) {
1223 t = &alarm_timers[i];
1225 printf("trying %s...\n", t->name);
1233 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1234 fprintf(stderr, "Terminating\n");
1241 void quit_timers(void)
1243 alarm_timer->stop(alarm_timer);
1247 /***********************************************************/
1248 /* character device */
1250 static void qemu_chr_event(CharDriverState *s, int event)
1254 s->chr_event(s->handler_opaque, event);
1257 static void qemu_chr_reset_bh(void *opaque)
1259 CharDriverState *s = opaque;
1260 qemu_chr_event(s, CHR_EVENT_RESET);
1261 qemu_bh_delete(s->bh);
1265 void qemu_chr_reset(CharDriverState *s)
1267 if (s->bh == NULL) {
1268 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1269 qemu_bh_schedule(s->bh);
1273 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1275 return s->chr_write(s, buf, len);
1278 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1282 return s->chr_ioctl(s, cmd, arg);
1285 int qemu_chr_can_read(CharDriverState *s)
1287 if (!s->chr_can_read)
1289 return s->chr_can_read(s->handler_opaque);
1292 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1294 s->chr_read(s->handler_opaque, buf, len);
1298 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1303 vsnprintf(buf, sizeof(buf), fmt, ap);
1304 qemu_chr_write(s, buf, strlen(buf));
1308 void qemu_chr_send_event(CharDriverState *s, int event)
1310 if (s->chr_send_event)
1311 s->chr_send_event(s, event);
1314 void qemu_chr_add_handlers(CharDriverState *s,
1315 IOCanRWHandler *fd_can_read,
1316 IOReadHandler *fd_read,
1317 IOEventHandler *fd_event,
1320 s->chr_can_read = fd_can_read;
1321 s->chr_read = fd_read;
1322 s->chr_event = fd_event;
1323 s->handler_opaque = opaque;
1324 if (s->chr_update_read_handler)
1325 s->chr_update_read_handler(s);
1328 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1333 static CharDriverState *qemu_chr_open_null(void)
1335 CharDriverState *chr;
1337 chr = qemu_mallocz(sizeof(CharDriverState));
1340 chr->chr_write = null_chr_write;
1344 /* MUX driver for serial I/O splitting */
1345 static int term_timestamps;
1346 static int64_t term_timestamps_start;
1349 IOCanRWHandler *chr_can_read[MAX_MUX];
1350 IOReadHandler *chr_read[MAX_MUX];
1351 IOEventHandler *chr_event[MAX_MUX];
1352 void *ext_opaque[MAX_MUX];
1353 CharDriverState *drv;
1355 int term_got_escape;
1360 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1362 MuxDriver *d = chr->opaque;
1364 if (!term_timestamps) {
1365 ret = d->drv->chr_write(d->drv, buf, len);
1370 for(i = 0; i < len; i++) {
1371 ret += d->drv->chr_write(d->drv, buf+i, 1);
1372 if (buf[i] == '\n') {
1378 if (term_timestamps_start == -1)
1379 term_timestamps_start = ti;
1380 ti -= term_timestamps_start;
1381 secs = ti / 1000000000;
1382 snprintf(buf1, sizeof(buf1),
1383 "[%02d:%02d:%02d.%03d] ",
1387 (int)((ti / 1000000) % 1000));
1388 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1395 static char *mux_help[] = {
1396 "% h print this help\n\r",
1397 "% x exit emulator\n\r",
1398 "% s save disk data back to file (if -snapshot)\n\r",
1399 "% t toggle console timestamps\n\r"
1400 "% b send break (magic sysrq)\n\r",
1401 "% c switch between console and monitor\n\r",
1406 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1407 static void mux_print_help(CharDriverState *chr)
1410 char ebuf[15] = "Escape-Char";
1411 char cbuf[50] = "\n\r";
1413 if (term_escape_char > 0 && term_escape_char < 26) {
1414 sprintf(cbuf,"\n\r");
1415 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1417 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1419 chr->chr_write(chr, cbuf, strlen(cbuf));
1420 for (i = 0; mux_help[i] != NULL; i++) {
1421 for (j=0; mux_help[i][j] != '\0'; j++) {
1422 if (mux_help[i][j] == '%')
1423 chr->chr_write(chr, ebuf, strlen(ebuf));
1425 chr->chr_write(chr, &mux_help[i][j], 1);
1430 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1432 if (d->term_got_escape) {
1433 d->term_got_escape = 0;
1434 if (ch == term_escape_char)
1439 mux_print_help(chr);
1443 char *term = "QEMU: Terminated\n\r";
1444 chr->chr_write(chr,term,strlen(term));
1451 for (i = 0; i < MAX_DISKS; i++) {
1453 bdrv_commit(bs_table[i]);
1456 bdrv_commit(mtd_bdrv);
1460 qemu_chr_event(chr, CHR_EVENT_BREAK);
1463 /* Switch to the next registered device */
1465 if (chr->focus >= d->mux_cnt)
1469 term_timestamps = !term_timestamps;
1470 term_timestamps_start = -1;
1473 } else if (ch == term_escape_char) {
1474 d->term_got_escape = 1;
1482 static int mux_chr_can_read(void *opaque)
1484 CharDriverState *chr = opaque;
1485 MuxDriver *d = chr->opaque;
1486 if (d->chr_can_read[chr->focus])
1487 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1491 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1493 CharDriverState *chr = opaque;
1494 MuxDriver *d = chr->opaque;
1496 for(i = 0; i < size; i++)
1497 if (mux_proc_byte(chr, d, buf[i]))
1498 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1501 static void mux_chr_event(void *opaque, int event)
1503 CharDriverState *chr = opaque;
1504 MuxDriver *d = chr->opaque;
1507 /* Send the event to all registered listeners */
1508 for (i = 0; i < d->mux_cnt; i++)
1509 if (d->chr_event[i])
1510 d->chr_event[i](d->ext_opaque[i], event);
1513 static void mux_chr_update_read_handler(CharDriverState *chr)
1515 MuxDriver *d = chr->opaque;
1517 if (d->mux_cnt >= MAX_MUX) {
1518 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1521 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1522 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1523 d->chr_read[d->mux_cnt] = chr->chr_read;
1524 d->chr_event[d->mux_cnt] = chr->chr_event;
1525 /* Fix up the real driver with mux routines */
1526 if (d->mux_cnt == 0) {
1527 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1528 mux_chr_event, chr);
1530 chr->focus = d->mux_cnt;
1534 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1536 CharDriverState *chr;
1539 chr = qemu_mallocz(sizeof(CharDriverState));
1542 d = qemu_mallocz(sizeof(MuxDriver));
1551 chr->chr_write = mux_chr_write;
1552 chr->chr_update_read_handler = mux_chr_update_read_handler;
1559 static void socket_cleanup(void)
1564 static int socket_init(void)
1569 ret = WSAStartup(MAKEWORD(2,2), &Data);
1571 err = WSAGetLastError();
1572 fprintf(stderr, "WSAStartup: %d\n", err);
1575 atexit(socket_cleanup);
1579 static int send_all(int fd, const uint8_t *buf, int len1)
1585 ret = send(fd, buf, len, 0);
1588 errno = WSAGetLastError();
1589 if (errno != WSAEWOULDBLOCK) {
1592 } else if (ret == 0) {
1602 void socket_set_nonblock(int fd)
1604 unsigned long opt = 1;
1605 ioctlsocket(fd, FIONBIO, &opt);
1610 static int unix_write(int fd, const uint8_t *buf, int len1)
1616 ret = write(fd, buf, len);
1618 if (errno != EINTR && errno != EAGAIN)
1620 } else if (ret == 0) {
1630 static inline int send_all(int fd, const uint8_t *buf, int len1)
1632 return unix_write(fd, buf, len1);
1635 void socket_set_nonblock(int fd)
1637 fcntl(fd, F_SETFL, O_NONBLOCK);
1639 #endif /* !_WIN32 */
1648 #define STDIO_MAX_CLIENTS 1
1649 static int stdio_nb_clients = 0;
1651 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1653 FDCharDriver *s = chr->opaque;
1654 return unix_write(s->fd_out, buf, len);
1657 static int fd_chr_read_poll(void *opaque)
1659 CharDriverState *chr = opaque;
1660 FDCharDriver *s = chr->opaque;
1662 s->max_size = qemu_chr_can_read(chr);
1666 static void fd_chr_read(void *opaque)
1668 CharDriverState *chr = opaque;
1669 FDCharDriver *s = chr->opaque;
1674 if (len > s->max_size)
1678 size = read(s->fd_in, buf, len);
1680 /* FD has been closed. Remove it from the active list. */
1681 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1685 qemu_chr_read(chr, buf, size);
1689 static void fd_chr_update_read_handler(CharDriverState *chr)
1691 FDCharDriver *s = chr->opaque;
1693 if (s->fd_in >= 0) {
1694 if (nographic && s->fd_in == 0) {
1696 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1697 fd_chr_read, NULL, chr);
1702 /* open a character device to a unix fd */
1703 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1705 CharDriverState *chr;
1708 chr = qemu_mallocz(sizeof(CharDriverState));
1711 s = qemu_mallocz(sizeof(FDCharDriver));
1719 chr->chr_write = fd_chr_write;
1720 chr->chr_update_read_handler = fd_chr_update_read_handler;
1722 qemu_chr_reset(chr);
1727 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1731 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
1734 return qemu_chr_open_fd(-1, fd_out);
1737 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1740 char filename_in[256], filename_out[256];
1742 snprintf(filename_in, 256, "%s.in", filename);
1743 snprintf(filename_out, 256, "%s.out", filename);
1744 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
1745 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
1746 if (fd_in < 0 || fd_out < 0) {
1751 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
1755 return qemu_chr_open_fd(fd_in, fd_out);
1759 /* for STDIO, we handle the case where several clients use it
1762 #define TERM_FIFO_MAX_SIZE 1
1764 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1765 static int term_fifo_size;
1767 static int stdio_read_poll(void *opaque)
1769 CharDriverState *chr = opaque;
1771 /* try to flush the queue if needed */
1772 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1773 qemu_chr_read(chr, term_fifo, 1);
1776 /* see if we can absorb more chars */
1777 if (term_fifo_size == 0)
1783 static void stdio_read(void *opaque)
1787 CharDriverState *chr = opaque;
1789 size = read(0, buf, 1);
1791 /* stdin has been closed. Remove it from the active list. */
1792 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1796 if (qemu_chr_can_read(chr) > 0) {
1797 qemu_chr_read(chr, buf, 1);
1798 } else if (term_fifo_size == 0) {
1799 term_fifo[term_fifo_size++] = buf[0];
1804 /* init terminal so that we can grab keys */
1805 static struct termios oldtty;
1806 static int old_fd0_flags;
1808 static void term_exit(void)
1810 tcsetattr (0, TCSANOW, &oldtty);
1811 fcntl(0, F_SETFL, old_fd0_flags);
1814 static void term_init(void)
1818 tcgetattr (0, &tty);
1820 old_fd0_flags = fcntl(0, F_GETFL);
1822 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1823 |INLCR|IGNCR|ICRNL|IXON);
1824 tty.c_oflag |= OPOST;
1825 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1826 /* if graphical mode, we allow Ctrl-C handling */
1828 tty.c_lflag &= ~ISIG;
1829 tty.c_cflag &= ~(CSIZE|PARENB);
1832 tty.c_cc[VTIME] = 0;
1834 tcsetattr (0, TCSANOW, &tty);
1838 fcntl(0, F_SETFL, O_NONBLOCK);
1841 static CharDriverState *qemu_chr_open_stdio(void)
1843 CharDriverState *chr;
1845 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1847 chr = qemu_chr_open_fd(0, 1);
1848 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1855 #if defined(__linux__) || defined(__sun__)
1856 static CharDriverState *qemu_chr_open_pty(void)
1859 char slave_name[1024];
1860 int master_fd, slave_fd;
1862 #if defined(__linux__)
1863 /* Not satisfying */
1864 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1869 /* Disabling local echo and line-buffered output */
1870 tcgetattr (master_fd, &tty);
1871 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1873 tty.c_cc[VTIME] = 0;
1874 tcsetattr (master_fd, TCSAFLUSH, &tty);
1876 fprintf(stderr, "char device redirected to %s\n", slave_name);
1877 return qemu_chr_open_fd(master_fd, master_fd);
1880 static void tty_serial_init(int fd, int speed,
1881 int parity, int data_bits, int stop_bits)
1887 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1888 speed, parity, data_bits, stop_bits);
1890 tcgetattr (fd, &tty);
1932 cfsetispeed(&tty, spd);
1933 cfsetospeed(&tty, spd);
1935 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1936 |INLCR|IGNCR|ICRNL|IXON);
1937 tty.c_oflag |= OPOST;
1938 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1939 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1960 tty.c_cflag |= PARENB;
1963 tty.c_cflag |= PARENB | PARODD;
1967 tty.c_cflag |= CSTOPB;
1969 tcsetattr (fd, TCSANOW, &tty);
1972 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1974 FDCharDriver *s = chr->opaque;
1977 case CHR_IOCTL_SERIAL_SET_PARAMS:
1979 QEMUSerialSetParams *ssp = arg;
1980 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1981 ssp->data_bits, ssp->stop_bits);
1984 case CHR_IOCTL_SERIAL_SET_BREAK:
1986 int enable = *(int *)arg;
1988 tcsendbreak(s->fd_in, 1);
1997 static CharDriverState *qemu_chr_open_tty(const char *filename)
1999 CharDriverState *chr;
2002 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2003 fcntl(fd, F_SETFL, O_NONBLOCK);
2004 tty_serial_init(fd, 115200, 'N', 8, 1);
2005 chr = qemu_chr_open_fd(fd, fd);
2010 chr->chr_ioctl = tty_serial_ioctl;
2011 qemu_chr_reset(chr);
2014 #else /* ! __linux__ && ! __sun__ */
2015 static CharDriverState *qemu_chr_open_pty(void)
2019 #endif /* __linux__ || __sun__ */
2021 #if defined(__linux__)
2025 } ParallelCharDriver;
2027 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2029 if (s->mode != mode) {
2031 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2038 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2040 ParallelCharDriver *drv = chr->opaque;
2045 case CHR_IOCTL_PP_READ_DATA:
2046 if (ioctl(fd, PPRDATA, &b) < 0)
2048 *(uint8_t *)arg = b;
2050 case CHR_IOCTL_PP_WRITE_DATA:
2051 b = *(uint8_t *)arg;
2052 if (ioctl(fd, PPWDATA, &b) < 0)
2055 case CHR_IOCTL_PP_READ_CONTROL:
2056 if (ioctl(fd, PPRCONTROL, &b) < 0)
2058 /* Linux gives only the lowest bits, and no way to know data
2059 direction! For better compatibility set the fixed upper
2061 *(uint8_t *)arg = b | 0xc0;
2063 case CHR_IOCTL_PP_WRITE_CONTROL:
2064 b = *(uint8_t *)arg;
2065 if (ioctl(fd, PPWCONTROL, &b) < 0)
2068 case CHR_IOCTL_PP_READ_STATUS:
2069 if (ioctl(fd, PPRSTATUS, &b) < 0)
2071 *(uint8_t *)arg = b;
2073 case CHR_IOCTL_PP_EPP_READ_ADDR:
2074 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2075 struct ParallelIOArg *parg = arg;
2076 int n = read(fd, parg->buffer, parg->count);
2077 if (n != parg->count) {
2082 case CHR_IOCTL_PP_EPP_READ:
2083 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2084 struct ParallelIOArg *parg = arg;
2085 int n = read(fd, parg->buffer, parg->count);
2086 if (n != parg->count) {
2091 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2092 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2093 struct ParallelIOArg *parg = arg;
2094 int n = write(fd, parg->buffer, parg->count);
2095 if (n != parg->count) {
2100 case CHR_IOCTL_PP_EPP_WRITE:
2101 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2102 struct ParallelIOArg *parg = arg;
2103 int n = write(fd, parg->buffer, parg->count);
2104 if (n != parg->count) {
2115 static void pp_close(CharDriverState *chr)
2117 ParallelCharDriver *drv = chr->opaque;
2120 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2121 ioctl(fd, PPRELEASE);
2126 static CharDriverState *qemu_chr_open_pp(const char *filename)
2128 CharDriverState *chr;
2129 ParallelCharDriver *drv;
2132 TFR(fd = open(filename, O_RDWR));
2136 if (ioctl(fd, PPCLAIM) < 0) {
2141 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2147 drv->mode = IEEE1284_MODE_COMPAT;
2149 chr = qemu_mallocz(sizeof(CharDriverState));
2155 chr->chr_write = null_chr_write;
2156 chr->chr_ioctl = pp_ioctl;
2157 chr->chr_close = pp_close;
2160 qemu_chr_reset(chr);
2164 #endif /* __linux__ */
2170 HANDLE hcom, hrecv, hsend;
2171 OVERLAPPED orecv, osend;
2176 #define NSENDBUF 2048
2177 #define NRECVBUF 2048
2178 #define MAXCONNECT 1
2179 #define NTIMEOUT 5000
2181 static int win_chr_poll(void *opaque);
2182 static int win_chr_pipe_poll(void *opaque);
2184 static void win_chr_close(CharDriverState *chr)
2186 WinCharState *s = chr->opaque;
2189 CloseHandle(s->hsend);
2193 CloseHandle(s->hrecv);
2197 CloseHandle(s->hcom);
2201 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2203 qemu_del_polling_cb(win_chr_poll, chr);
2206 static int win_chr_init(CharDriverState *chr, const char *filename)
2208 WinCharState *s = chr->opaque;
2210 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2215 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2217 fprintf(stderr, "Failed CreateEvent\n");
2220 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2222 fprintf(stderr, "Failed CreateEvent\n");
2226 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2227 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2228 if (s->hcom == INVALID_HANDLE_VALUE) {
2229 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2234 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2235 fprintf(stderr, "Failed SetupComm\n");
2239 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2240 size = sizeof(COMMCONFIG);
2241 GetDefaultCommConfig(filename, &comcfg, &size);
2242 comcfg.dcb.DCBlength = sizeof(DCB);
2243 CommConfigDialog(filename, NULL, &comcfg);
2245 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2246 fprintf(stderr, "Failed SetCommState\n");
2250 if (!SetCommMask(s->hcom, EV_ERR)) {
2251 fprintf(stderr, "Failed SetCommMask\n");
2255 cto.ReadIntervalTimeout = MAXDWORD;
2256 if (!SetCommTimeouts(s->hcom, &cto)) {
2257 fprintf(stderr, "Failed SetCommTimeouts\n");
2261 if (!ClearCommError(s->hcom, &err, &comstat)) {
2262 fprintf(stderr, "Failed ClearCommError\n");
2265 qemu_add_polling_cb(win_chr_poll, chr);
2273 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2275 WinCharState *s = chr->opaque;
2276 DWORD len, ret, size, err;
2279 ZeroMemory(&s->osend, sizeof(s->osend));
2280 s->osend.hEvent = s->hsend;
2283 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2285 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2287 err = GetLastError();
2288 if (err == ERROR_IO_PENDING) {
2289 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2307 static int win_chr_read_poll(CharDriverState *chr)
2309 WinCharState *s = chr->opaque;
2311 s->max_size = qemu_chr_can_read(chr);
2315 static void win_chr_readfile(CharDriverState *chr)
2317 WinCharState *s = chr->opaque;
2322 ZeroMemory(&s->orecv, sizeof(s->orecv));
2323 s->orecv.hEvent = s->hrecv;
2324 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2326 err = GetLastError();
2327 if (err == ERROR_IO_PENDING) {
2328 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2333 qemu_chr_read(chr, buf, size);
2337 static void win_chr_read(CharDriverState *chr)
2339 WinCharState *s = chr->opaque;
2341 if (s->len > s->max_size)
2342 s->len = s->max_size;
2346 win_chr_readfile(chr);
2349 static int win_chr_poll(void *opaque)
2351 CharDriverState *chr = opaque;
2352 WinCharState *s = chr->opaque;
2356 ClearCommError(s->hcom, &comerr, &status);
2357 if (status.cbInQue > 0) {
2358 s->len = status.cbInQue;
2359 win_chr_read_poll(chr);
2366 static CharDriverState *qemu_chr_open_win(const char *filename)
2368 CharDriverState *chr;
2371 chr = qemu_mallocz(sizeof(CharDriverState));
2374 s = qemu_mallocz(sizeof(WinCharState));
2380 chr->chr_write = win_chr_write;
2381 chr->chr_close = win_chr_close;
2383 if (win_chr_init(chr, filename) < 0) {
2388 qemu_chr_reset(chr);
2392 static int win_chr_pipe_poll(void *opaque)
2394 CharDriverState *chr = opaque;
2395 WinCharState *s = chr->opaque;
2398 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2401 win_chr_read_poll(chr);
2408 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2410 WinCharState *s = chr->opaque;
2418 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2420 fprintf(stderr, "Failed CreateEvent\n");
2423 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2425 fprintf(stderr, "Failed CreateEvent\n");
2429 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2430 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2431 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2433 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2434 if (s->hcom == INVALID_HANDLE_VALUE) {
2435 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2440 ZeroMemory(&ov, sizeof(ov));
2441 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2442 ret = ConnectNamedPipe(s->hcom, &ov);
2444 fprintf(stderr, "Failed ConnectNamedPipe\n");
2448 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2450 fprintf(stderr, "Failed GetOverlappedResult\n");
2452 CloseHandle(ov.hEvent);
2459 CloseHandle(ov.hEvent);
2462 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2471 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2473 CharDriverState *chr;
2476 chr = qemu_mallocz(sizeof(CharDriverState));
2479 s = qemu_mallocz(sizeof(WinCharState));
2485 chr->chr_write = win_chr_write;
2486 chr->chr_close = win_chr_close;
2488 if (win_chr_pipe_init(chr, filename) < 0) {
2493 qemu_chr_reset(chr);
2497 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2499 CharDriverState *chr;
2502 chr = qemu_mallocz(sizeof(CharDriverState));
2505 s = qemu_mallocz(sizeof(WinCharState));
2512 chr->chr_write = win_chr_write;
2513 qemu_chr_reset(chr);
2517 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2519 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2522 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2526 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2527 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2528 if (fd_out == INVALID_HANDLE_VALUE)
2531 return qemu_chr_open_win_file(fd_out);
2533 #endif /* !_WIN32 */
2535 /***********************************************************/
2536 /* UDP Net console */
2540 struct sockaddr_in daddr;
2547 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2549 NetCharDriver *s = chr->opaque;
2551 return sendto(s->fd, buf, len, 0,
2552 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2555 static int udp_chr_read_poll(void *opaque)
2557 CharDriverState *chr = opaque;
2558 NetCharDriver *s = chr->opaque;
2560 s->max_size = qemu_chr_can_read(chr);
2562 /* If there were any stray characters in the queue process them
2565 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2566 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2568 s->max_size = qemu_chr_can_read(chr);
2573 static void udp_chr_read(void *opaque)
2575 CharDriverState *chr = opaque;
2576 NetCharDriver *s = chr->opaque;
2578 if (s->max_size == 0)
2580 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2581 s->bufptr = s->bufcnt;
2586 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2587 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2589 s->max_size = qemu_chr_can_read(chr);
2593 static void udp_chr_update_read_handler(CharDriverState *chr)
2595 NetCharDriver *s = chr->opaque;
2598 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2599 udp_chr_read, NULL, chr);
2603 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2605 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2607 int parse_host_src_port(struct sockaddr_in *haddr,
2608 struct sockaddr_in *saddr,
2611 static CharDriverState *qemu_chr_open_udp(const char *def)
2613 CharDriverState *chr = NULL;
2614 NetCharDriver *s = NULL;
2616 struct sockaddr_in saddr;
2618 chr = qemu_mallocz(sizeof(CharDriverState));
2621 s = qemu_mallocz(sizeof(NetCharDriver));
2625 fd = socket(PF_INET, SOCK_DGRAM, 0);
2627 perror("socket(PF_INET, SOCK_DGRAM)");
2631 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2632 printf("Could not parse: %s\n", def);
2636 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2646 chr->chr_write = udp_chr_write;
2647 chr->chr_update_read_handler = udp_chr_update_read_handler;
2660 /***********************************************************/
2661 /* TCP Net console */
2672 static void tcp_chr_accept(void *opaque);
2674 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2676 TCPCharDriver *s = chr->opaque;
2678 return send_all(s->fd, buf, len);
2680 /* XXX: indicate an error ? */
2685 static int tcp_chr_read_poll(void *opaque)
2687 CharDriverState *chr = opaque;
2688 TCPCharDriver *s = chr->opaque;
2691 s->max_size = qemu_chr_can_read(chr);
2696 #define IAC_BREAK 243
2697 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2699 char *buf, int *size)
2701 /* Handle any telnet client's basic IAC options to satisfy char by
2702 * char mode with no echo. All IAC options will be removed from
2703 * the buf and the do_telnetopt variable will be used to track the
2704 * state of the width of the IAC information.
2706 * IAC commands come in sets of 3 bytes with the exception of the
2707 * "IAC BREAK" command and the double IAC.
2713 for (i = 0; i < *size; i++) {
2714 if (s->do_telnetopt > 1) {
2715 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2716 /* Double IAC means send an IAC */
2720 s->do_telnetopt = 1;
2722 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2723 /* Handle IAC break commands by sending a serial break */
2724 qemu_chr_event(chr, CHR_EVENT_BREAK);
2729 if (s->do_telnetopt >= 4) {
2730 s->do_telnetopt = 1;
2733 if ((unsigned char)buf[i] == IAC) {
2734 s->do_telnetopt = 2;
2745 static void tcp_chr_read(void *opaque)
2747 CharDriverState *chr = opaque;
2748 TCPCharDriver *s = chr->opaque;
2752 if (!s->connected || s->max_size <= 0)
2755 if (len > s->max_size)
2757 size = recv(s->fd, buf, len, 0);
2759 /* connection closed */
2761 if (s->listen_fd >= 0) {
2762 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2764 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2767 } else if (size > 0) {
2768 if (s->do_telnetopt)
2769 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2771 qemu_chr_read(chr, buf, size);
2775 static void tcp_chr_connect(void *opaque)
2777 CharDriverState *chr = opaque;
2778 TCPCharDriver *s = chr->opaque;
2781 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2782 tcp_chr_read, NULL, chr);
2783 qemu_chr_reset(chr);
2786 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2787 static void tcp_chr_telnet_init(int fd)
2790 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2791 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2792 send(fd, (char *)buf, 3, 0);
2793 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2794 send(fd, (char *)buf, 3, 0);
2795 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2796 send(fd, (char *)buf, 3, 0);
2797 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2798 send(fd, (char *)buf, 3, 0);
2801 static void socket_set_nodelay(int fd)
2804 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2807 static void tcp_chr_accept(void *opaque)
2809 CharDriverState *chr = opaque;
2810 TCPCharDriver *s = chr->opaque;
2811 struct sockaddr_in saddr;
2813 struct sockaddr_un uaddr;
2815 struct sockaddr *addr;
2822 len = sizeof(uaddr);
2823 addr = (struct sockaddr *)&uaddr;
2827 len = sizeof(saddr);
2828 addr = (struct sockaddr *)&saddr;
2830 fd = accept(s->listen_fd, addr, &len);
2831 if (fd < 0 && errno != EINTR) {
2833 } else if (fd >= 0) {
2834 if (s->do_telnetopt)
2835 tcp_chr_telnet_init(fd);
2839 socket_set_nonblock(fd);
2841 socket_set_nodelay(fd);
2843 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2844 tcp_chr_connect(chr);
2847 static void tcp_chr_close(CharDriverState *chr)
2849 TCPCharDriver *s = chr->opaque;
2852 if (s->listen_fd >= 0)
2853 closesocket(s->listen_fd);
2857 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2861 CharDriverState *chr = NULL;
2862 TCPCharDriver *s = NULL;
2863 int fd = -1, ret, err, val;
2865 int is_waitconnect = 1;
2868 struct sockaddr_in saddr;
2870 struct sockaddr_un uaddr;
2872 struct sockaddr *addr;
2877 addr = (struct sockaddr *)&uaddr;
2878 addrlen = sizeof(uaddr);
2879 if (parse_unix_path(&uaddr, host_str) < 0)
2884 addr = (struct sockaddr *)&saddr;
2885 addrlen = sizeof(saddr);
2886 if (parse_host_port(&saddr, host_str) < 0)
2891 while((ptr = strchr(ptr,','))) {
2893 if (!strncmp(ptr,"server",6)) {
2895 } else if (!strncmp(ptr,"nowait",6)) {
2897 } else if (!strncmp(ptr,"nodelay",6)) {
2900 printf("Unknown option: %s\n", ptr);
2907 chr = qemu_mallocz(sizeof(CharDriverState));
2910 s = qemu_mallocz(sizeof(TCPCharDriver));
2916 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2919 fd = socket(PF_INET, SOCK_STREAM, 0);
2924 if (!is_waitconnect)
2925 socket_set_nonblock(fd);
2930 s->is_unix = is_unix;
2931 s->do_nodelay = do_nodelay && !is_unix;
2934 chr->chr_write = tcp_chr_write;
2935 chr->chr_close = tcp_chr_close;
2938 /* allow fast reuse */
2942 strncpy(path, uaddr.sun_path, 108);
2949 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2952 ret = bind(fd, addr, addrlen);
2956 ret = listen(fd, 0);
2961 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2963 s->do_telnetopt = 1;
2966 ret = connect(fd, addr, addrlen);
2968 err = socket_error();
2969 if (err == EINTR || err == EWOULDBLOCK) {
2970 } else if (err == EINPROGRESS) {
2973 } else if (err == WSAEALREADY) {
2985 socket_set_nodelay(fd);
2987 tcp_chr_connect(chr);
2989 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2992 if (is_listen && is_waitconnect) {
2993 printf("QEMU waiting for connection on: %s\n", host_str);
2994 tcp_chr_accept(chr);
2995 socket_set_nonblock(s->listen_fd);
3007 CharDriverState *qemu_chr_open(const char *filename)
3011 if (!strcmp(filename, "vc")) {
3012 return text_console_init(&display_state, 0);
3013 } else if (strstart(filename, "vc:", &p)) {
3014 return text_console_init(&display_state, p);
3015 } else if (!strcmp(filename, "null")) {
3016 return qemu_chr_open_null();
3018 if (strstart(filename, "tcp:", &p)) {
3019 return qemu_chr_open_tcp(p, 0, 0);
3021 if (strstart(filename, "telnet:", &p)) {
3022 return qemu_chr_open_tcp(p, 1, 0);
3024 if (strstart(filename, "udp:", &p)) {
3025 return qemu_chr_open_udp(p);
3027 if (strstart(filename, "mon:", &p)) {
3028 CharDriverState *drv = qemu_chr_open(p);
3030 drv = qemu_chr_open_mux(drv);
3031 monitor_init(drv, !nographic);
3034 printf("Unable to open driver: %s\n", p);
3038 if (strstart(filename, "unix:", &p)) {
3039 return qemu_chr_open_tcp(p, 0, 1);
3040 } else if (strstart(filename, "file:", &p)) {
3041 return qemu_chr_open_file_out(p);
3042 } else if (strstart(filename, "pipe:", &p)) {
3043 return qemu_chr_open_pipe(p);
3044 } else if (!strcmp(filename, "pty")) {
3045 return qemu_chr_open_pty();
3046 } else if (!strcmp(filename, "stdio")) {
3047 return qemu_chr_open_stdio();
3049 #if defined(__linux__)
3050 if (strstart(filename, "/dev/parport", NULL)) {
3051 return qemu_chr_open_pp(filename);
3054 #if defined(__linux__) || defined(__sun__)
3055 if (strstart(filename, "/dev/", NULL)) {
3056 return qemu_chr_open_tty(filename);
3060 if (strstart(filename, "COM", NULL)) {
3061 return qemu_chr_open_win(filename);
3063 if (strstart(filename, "pipe:", &p)) {
3064 return qemu_chr_open_win_pipe(p);
3066 if (strstart(filename, "con:", NULL)) {
3067 return qemu_chr_open_win_con(filename);
3069 if (strstart(filename, "file:", &p)) {
3070 return qemu_chr_open_win_file_out(p);
3078 void qemu_chr_close(CharDriverState *chr)
3081 chr->chr_close(chr);
3084 /***********************************************************/
3085 /* network device redirectors */
3087 void hex_dump(FILE *f, const uint8_t *buf, int size)
3091 for(i=0;i<size;i+=16) {
3095 fprintf(f, "%08x ", i);
3098 fprintf(f, " %02x", buf[i+j]);
3103 for(j=0;j<len;j++) {
3105 if (c < ' ' || c > '~')
3107 fprintf(f, "%c", c);
3113 static int parse_macaddr(uint8_t *macaddr, const char *p)
3116 for(i = 0; i < 6; i++) {
3117 macaddr[i] = strtol(p, (char **)&p, 16);
3130 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3135 p1 = strchr(p, sep);
3141 if (len > buf_size - 1)
3143 memcpy(buf, p, len);
3150 int parse_host_src_port(struct sockaddr_in *haddr,
3151 struct sockaddr_in *saddr,
3152 const char *input_str)
3154 char *str = strdup(input_str);
3155 char *host_str = str;
3160 * Chop off any extra arguments at the end of the string which
3161 * would start with a comma, then fill in the src port information
3162 * if it was provided else use the "any address" and "any port".
3164 if ((ptr = strchr(str,',')))
3167 if ((src_str = strchr(input_str,'@'))) {
3172 if (parse_host_port(haddr, host_str) < 0)
3175 if (!src_str || *src_str == '\0')
3178 if (parse_host_port(saddr, src_str) < 0)
3189 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3197 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3199 saddr->sin_family = AF_INET;
3200 if (buf[0] == '\0') {
3201 saddr->sin_addr.s_addr = 0;
3203 if (isdigit(buf[0])) {
3204 if (!inet_aton(buf, &saddr->sin_addr))
3207 if ((he = gethostbyname(buf)) == NULL)
3209 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3212 port = strtol(p, (char **)&r, 0);
3215 saddr->sin_port = htons(port);
3220 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3225 len = MIN(108, strlen(str));
3226 p = strchr(str, ',');
3228 len = MIN(len, p - str);
3230 memset(uaddr, 0, sizeof(*uaddr));
3232 uaddr->sun_family = AF_UNIX;
3233 memcpy(uaddr->sun_path, str, len);
3239 /* find or alloc a new VLAN */
3240 VLANState *qemu_find_vlan(int id)
3242 VLANState **pvlan, *vlan;
3243 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3247 vlan = qemu_mallocz(sizeof(VLANState));
3252 pvlan = &first_vlan;
3253 while (*pvlan != NULL)
3254 pvlan = &(*pvlan)->next;
3259 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3260 IOReadHandler *fd_read,
3261 IOCanRWHandler *fd_can_read,
3264 VLANClientState *vc, **pvc;
3265 vc = qemu_mallocz(sizeof(VLANClientState));
3268 vc->fd_read = fd_read;
3269 vc->fd_can_read = fd_can_read;
3270 vc->opaque = opaque;
3274 pvc = &vlan->first_client;
3275 while (*pvc != NULL)
3276 pvc = &(*pvc)->next;
3281 int qemu_can_send_packet(VLANClientState *vc1)
3283 VLANState *vlan = vc1->vlan;
3284 VLANClientState *vc;
3286 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3288 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3295 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3297 VLANState *vlan = vc1->vlan;
3298 VLANClientState *vc;
3301 printf("vlan %d send:\n", vlan->id);
3302 hex_dump(stdout, buf, size);
3304 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3306 vc->fd_read(vc->opaque, buf, size);
3311 #if defined(CONFIG_SLIRP)
3313 /* slirp network adapter */
3315 static int slirp_inited;
3316 static VLANClientState *slirp_vc;
3318 int slirp_can_output(void)
3320 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3323 void slirp_output(const uint8_t *pkt, int pkt_len)
3326 printf("slirp output:\n");
3327 hex_dump(stdout, pkt, pkt_len);
3331 qemu_send_packet(slirp_vc, pkt, pkt_len);
3334 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3337 printf("slirp input:\n");
3338 hex_dump(stdout, buf, size);
3340 slirp_input(buf, size);
3343 static int net_slirp_init(VLANState *vlan)
3345 if (!slirp_inited) {
3349 slirp_vc = qemu_new_vlan_client(vlan,
3350 slirp_receive, NULL, NULL);
3351 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3355 static void net_slirp_redir(const char *redir_str)
3360 struct in_addr guest_addr;
3361 int host_port, guest_port;
3363 if (!slirp_inited) {
3369 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3371 if (!strcmp(buf, "tcp")) {
3373 } else if (!strcmp(buf, "udp")) {
3379 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3381 host_port = strtol(buf, &r, 0);
3385 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3387 if (buf[0] == '\0') {
3388 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3390 if (!inet_aton(buf, &guest_addr))
3393 guest_port = strtol(p, &r, 0);
3397 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3398 fprintf(stderr, "qemu: could not set up redirection\n");
3403 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3411 static void smb_exit(void)
3415 char filename[1024];
3417 /* erase all the files in the directory */
3418 d = opendir(smb_dir);
3423 if (strcmp(de->d_name, ".") != 0 &&
3424 strcmp(de->d_name, "..") != 0) {
3425 snprintf(filename, sizeof(filename), "%s/%s",
3426 smb_dir, de->d_name);
3434 /* automatic user mode samba server configuration */
3435 void net_slirp_smb(const char *exported_dir)
3437 char smb_conf[1024];
3438 char smb_cmdline[1024];
3441 if (!slirp_inited) {
3446 /* XXX: better tmp dir construction */
3447 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3448 if (mkdir(smb_dir, 0700) < 0) {
3449 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3452 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3454 f = fopen(smb_conf, "w");
3456 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3463 "socket address=127.0.0.1\n"
3464 "pid directory=%s\n"
3465 "lock directory=%s\n"
3466 "log file=%s/log.smbd\n"
3467 "smb passwd file=%s/smbpasswd\n"
3468 "security = share\n"
3483 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3484 SMBD_COMMAND, smb_conf);
3486 slirp_add_exec(0, smb_cmdline, 4, 139);
3489 #endif /* !defined(_WIN32) */
3491 #endif /* CONFIG_SLIRP */
3493 #if !defined(_WIN32)
3495 typedef struct TAPState {
3496 VLANClientState *vc;
3500 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3502 TAPState *s = opaque;
3505 ret = write(s->fd, buf, size);
3506 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3513 static void tap_send(void *opaque)
3515 TAPState *s = opaque;
3522 sbuf.maxlen = sizeof(buf);
3524 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3526 size = read(s->fd, buf, sizeof(buf));
3529 qemu_send_packet(s->vc, buf, size);
3535 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3539 s = qemu_mallocz(sizeof(TAPState));
3543 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3544 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3545 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3549 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3550 static int tap_open(char *ifname, int ifname_size)
3556 TFR(fd = open("/dev/tap", O_RDWR));
3558 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3563 dev = devname(s.st_rdev, S_IFCHR);
3564 pstrcpy(ifname, ifname_size, dev);
3566 fcntl(fd, F_SETFL, O_NONBLOCK);
3569 #elif defined(__sun__)
3570 #define TUNNEWPPA (('T'<<16) | 0x0001)
3572 * Allocate TAP device, returns opened fd.
3573 * Stores dev name in the first arg(must be large enough).
3575 int tap_alloc(char *dev)
3577 int tap_fd, if_fd, ppa = -1;
3578 static int ip_fd = 0;
3581 static int arp_fd = 0;
3582 int ip_muxid, arp_muxid;
3583 struct strioctl strioc_if, strioc_ppa;
3584 int link_type = I_PLINK;;
3586 char actual_name[32] = "";
3588 memset(&ifr, 0x0, sizeof(ifr));
3592 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3596 /* Check if IP device was opened */
3600 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3602 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3606 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3608 syslog(LOG_ERR, "Can't open /dev/tap");
3612 /* Assign a new PPA and get its unit number. */
3613 strioc_ppa.ic_cmd = TUNNEWPPA;
3614 strioc_ppa.ic_timout = 0;
3615 strioc_ppa.ic_len = sizeof(ppa);
3616 strioc_ppa.ic_dp = (char *)&ppa;
3617 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3618 syslog (LOG_ERR, "Can't assign new interface");
3620 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3622 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3625 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3626 syslog(LOG_ERR, "Can't push IP module");
3630 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3631 syslog(LOG_ERR, "Can't get flags\n");
3633 snprintf (actual_name, 32, "tap%d", ppa);
3634 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3637 /* Assign ppa according to the unit number returned by tun device */
3639 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3640 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3641 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3642 syslog (LOG_ERR, "Can't get flags\n");
3643 /* Push arp module to if_fd */
3644 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3645 syslog (LOG_ERR, "Can't push ARP module (2)");
3647 /* Push arp module to ip_fd */
3648 if (ioctl (ip_fd, I_POP, NULL) < 0)
3649 syslog (LOG_ERR, "I_POP failed\n");
3650 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3651 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3653 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3655 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3657 /* Set ifname to arp */
3658 strioc_if.ic_cmd = SIOCSLIFNAME;
3659 strioc_if.ic_timout = 0;
3660 strioc_if.ic_len = sizeof(ifr);
3661 strioc_if.ic_dp = (char *)𝔦
3662 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3663 syslog (LOG_ERR, "Can't set ifname to arp\n");
3666 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3667 syslog(LOG_ERR, "Can't link TAP device to IP");
3671 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3672 syslog (LOG_ERR, "Can't link TAP device to ARP");
3676 memset(&ifr, 0x0, sizeof(ifr));
3677 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3678 ifr.lifr_ip_muxid = ip_muxid;
3679 ifr.lifr_arp_muxid = arp_muxid;
3681 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3683 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3684 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3685 syslog (LOG_ERR, "Can't set multiplexor id");
3688 sprintf(dev, "tap%d", ppa);
3692 static int tap_open(char *ifname, int ifname_size)
3696 if( (fd = tap_alloc(dev)) < 0 ){
3697 fprintf(stderr, "Cannot allocate TAP device\n");
3700 pstrcpy(ifname, ifname_size, dev);
3701 fcntl(fd, F_SETFL, O_NONBLOCK);
3705 static int tap_open(char *ifname, int ifname_size)
3710 TFR(fd = open("/dev/net/tun", O_RDWR));
3712 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3715 memset(&ifr, 0, sizeof(ifr));
3716 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3717 if (ifname[0] != '\0')
3718 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3720 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3721 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3723 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3727 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3728 fcntl(fd, F_SETFL, O_NONBLOCK);
3733 static int net_tap_init(VLANState *vlan, const char *ifname1,
3734 const char *setup_script)
3737 int pid, status, fd;
3742 if (ifname1 != NULL)
3743 pstrcpy(ifname, sizeof(ifname), ifname1);
3746 TFR(fd = tap_open(ifname, sizeof(ifname)));
3750 if (!setup_script || !strcmp(setup_script, "no"))
3752 if (setup_script[0] != '\0') {
3753 /* try to launch network init script */
3757 int open_max = sysconf (_SC_OPEN_MAX), i;
3758 for (i = 0; i < open_max; i++)
3759 if (i != STDIN_FILENO &&
3760 i != STDOUT_FILENO &&
3761 i != STDERR_FILENO &&
3766 *parg++ = (char *)setup_script;
3769 execv(setup_script, args);
3772 while (waitpid(pid, &status, 0) != pid);
3773 if (!WIFEXITED(status) ||
3774 WEXITSTATUS(status) != 0) {
3775 fprintf(stderr, "%s: could not launch network script\n",
3781 s = net_tap_fd_init(vlan, fd);
3784 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3785 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3789 #endif /* !_WIN32 */
3791 /* network connection */
3792 typedef struct NetSocketState {
3793 VLANClientState *vc;
3795 int state; /* 0 = getting length, 1 = getting data */
3799 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3802 typedef struct NetSocketListenState {
3805 } NetSocketListenState;
3807 /* XXX: we consider we can send the whole packet without blocking */
3808 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3810 NetSocketState *s = opaque;
3814 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3815 send_all(s->fd, buf, size);
3818 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3820 NetSocketState *s = opaque;
3821 sendto(s->fd, buf, size, 0,
3822 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3825 static void net_socket_send(void *opaque)
3827 NetSocketState *s = opaque;
3832 size = recv(s->fd, buf1, sizeof(buf1), 0);
3834 err = socket_error();
3835 if (err != EWOULDBLOCK)
3837 } else if (size == 0) {
3838 /* end of connection */
3840 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3846 /* reassemble a packet from the network */
3852 memcpy(s->buf + s->index, buf, l);
3856 if (s->index == 4) {
3858 s->packet_len = ntohl(*(uint32_t *)s->buf);
3864 l = s->packet_len - s->index;
3867 memcpy(s->buf + s->index, buf, l);
3871 if (s->index >= s->packet_len) {
3872 qemu_send_packet(s->vc, s->buf, s->packet_len);
3881 static void net_socket_send_dgram(void *opaque)
3883 NetSocketState *s = opaque;
3886 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3890 /* end of connection */
3891 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3894 qemu_send_packet(s->vc, s->buf, size);
3897 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3902 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3903 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3904 inet_ntoa(mcastaddr->sin_addr),
3905 (int)ntohl(mcastaddr->sin_addr.s_addr));
3909 fd = socket(PF_INET, SOCK_DGRAM, 0);
3911 perror("socket(PF_INET, SOCK_DGRAM)");
3916 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3917 (const char *)&val, sizeof(val));
3919 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3923 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3929 /* Add host to multicast group */
3930 imr.imr_multiaddr = mcastaddr->sin_addr;
3931 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3933 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3934 (const char *)&imr, sizeof(struct ip_mreq));
3936 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3940 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3942 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3943 (const char *)&val, sizeof(val));
3945 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3949 socket_set_nonblock(fd);
3957 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
3960 struct sockaddr_in saddr;
3962 socklen_t saddr_len;
3965 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3966 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
3967 * by ONLY ONE process: we must "clone" this dgram socket --jjo
3971 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3973 if (saddr.sin_addr.s_addr==0) {
3974 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3978 /* clone dgram socket */
3979 newfd = net_socket_mcast_create(&saddr);
3981 /* error already reported by net_socket_mcast_create() */
3985 /* clone newfd to fd, close newfd */
3990 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3991 fd, strerror(errno));
3996 s = qemu_mallocz(sizeof(NetSocketState));
4001 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4002 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4004 /* mcast: save bound address as dst */
4005 if (is_connected) s->dgram_dst=saddr;
4007 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4008 "socket: fd=%d (%s mcast=%s:%d)",
4009 fd, is_connected? "cloned" : "",
4010 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4014 static void net_socket_connect(void *opaque)
4016 NetSocketState *s = opaque;
4017 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4020 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4024 s = qemu_mallocz(sizeof(NetSocketState));
4028 s->vc = qemu_new_vlan_client(vlan,
4029 net_socket_receive, NULL, s);
4030 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4031 "socket: fd=%d", fd);
4033 net_socket_connect(s);
4035 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4040 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4043 int so_type=-1, optlen=sizeof(so_type);
4045 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4046 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4051 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4053 return net_socket_fd_init_stream(vlan, fd, is_connected);
4055 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4056 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4057 return net_socket_fd_init_stream(vlan, fd, is_connected);
4062 static void net_socket_accept(void *opaque)
4064 NetSocketListenState *s = opaque;
4066 struct sockaddr_in saddr;
4071 len = sizeof(saddr);
4072 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4073 if (fd < 0 && errno != EINTR) {
4075 } else if (fd >= 0) {
4079 s1 = net_socket_fd_init(s->vlan, fd, 1);
4083 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4084 "socket: connection from %s:%d",
4085 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4089 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4091 NetSocketListenState *s;
4093 struct sockaddr_in saddr;
4095 if (parse_host_port(&saddr, host_str) < 0)
4098 s = qemu_mallocz(sizeof(NetSocketListenState));
4102 fd = socket(PF_INET, SOCK_STREAM, 0);
4107 socket_set_nonblock(fd);
4109 /* allow fast reuse */
4111 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4113 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4118 ret = listen(fd, 0);
4125 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4129 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4132 int fd, connected, ret, err;
4133 struct sockaddr_in saddr;
4135 if (parse_host_port(&saddr, host_str) < 0)
4138 fd = socket(PF_INET, SOCK_STREAM, 0);
4143 socket_set_nonblock(fd);
4147 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4149 err = socket_error();
4150 if (err == EINTR || err == EWOULDBLOCK) {
4151 } else if (err == EINPROGRESS) {
4154 } else if (err == WSAEALREADY) {
4167 s = net_socket_fd_init(vlan, fd, connected);
4170 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4171 "socket: connect to %s:%d",
4172 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4176 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4180 struct sockaddr_in saddr;
4182 if (parse_host_port(&saddr, host_str) < 0)
4186 fd = net_socket_mcast_create(&saddr);
4190 s = net_socket_fd_init(vlan, fd, 0);
4194 s->dgram_dst = saddr;
4196 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4197 "socket: mcast=%s:%d",
4198 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4203 static int get_param_value(char *buf, int buf_size,
4204 const char *tag, const char *str)
4213 while (*p != '\0' && *p != '=') {
4214 if ((q - option) < sizeof(option) - 1)
4222 if (!strcmp(tag, option)) {
4224 while (*p != '\0' && *p != ',') {
4225 if ((q - buf) < buf_size - 1)
4232 while (*p != '\0' && *p != ',') {
4243 static int net_client_init(const char *str)
4254 while (*p != '\0' && *p != ',') {
4255 if ((q - device) < sizeof(device) - 1)
4263 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4264 vlan_id = strtol(buf, NULL, 0);
4266 vlan = qemu_find_vlan(vlan_id);
4268 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4271 if (!strcmp(device, "nic")) {
4275 if (nb_nics >= MAX_NICS) {
4276 fprintf(stderr, "Too Many NICs\n");
4279 nd = &nd_table[nb_nics];
4280 macaddr = nd->macaddr;
4286 macaddr[5] = 0x56 + nb_nics;
4288 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4289 if (parse_macaddr(macaddr, buf) < 0) {
4290 fprintf(stderr, "invalid syntax for ethernet address\n");
4294 if (get_param_value(buf, sizeof(buf), "model", p)) {
4295 nd->model = strdup(buf);
4299 vlan->nb_guest_devs++;
4302 if (!strcmp(device, "none")) {
4303 /* does nothing. It is needed to signal that no network cards
4308 if (!strcmp(device, "user")) {
4309 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4310 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4312 vlan->nb_host_devs++;
4313 ret = net_slirp_init(vlan);
4317 if (!strcmp(device, "tap")) {
4319 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4320 fprintf(stderr, "tap: no interface name\n");
4323 vlan->nb_host_devs++;
4324 ret = tap_win32_init(vlan, ifname);
4327 if (!strcmp(device, "tap")) {
4329 char setup_script[1024];
4331 vlan->nb_host_devs++;
4332 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4333 fd = strtol(buf, NULL, 0);
4335 if (net_tap_fd_init(vlan, fd))
4338 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4341 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4342 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4344 ret = net_tap_init(vlan, ifname, setup_script);
4348 if (!strcmp(device, "socket")) {
4349 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4351 fd = strtol(buf, NULL, 0);
4353 if (net_socket_fd_init(vlan, fd, 1))
4355 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4356 ret = net_socket_listen_init(vlan, buf);
4357 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4358 ret = net_socket_connect_init(vlan, buf);
4359 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4360 ret = net_socket_mcast_init(vlan, buf);
4362 fprintf(stderr, "Unknown socket options: %s\n", p);
4365 vlan->nb_host_devs++;
4368 fprintf(stderr, "Unknown network device: %s\n", device);
4372 fprintf(stderr, "Could not initialize device '%s'\n", device);
4378 void do_info_network(void)
4381 VLANClientState *vc;
4383 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4384 term_printf("VLAN %d devices:\n", vlan->id);
4385 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4386 term_printf(" %s\n", vc->info_str);
4390 /***********************************************************/
4393 static USBPort *used_usb_ports;
4394 static USBPort *free_usb_ports;
4396 /* ??? Maybe change this to register a hub to keep track of the topology. */
4397 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4398 usb_attachfn attach)
4400 port->opaque = opaque;
4401 port->index = index;
4402 port->attach = attach;
4403 port->next = free_usb_ports;
4404 free_usb_ports = port;
4407 static int usb_device_add(const char *devname)
4413 if (!free_usb_ports)
4416 if (strstart(devname, "host:", &p)) {
4417 dev = usb_host_device_open(p);
4418 } else if (!strcmp(devname, "mouse")) {
4419 dev = usb_mouse_init();
4420 } else if (!strcmp(devname, "tablet")) {
4421 dev = usb_tablet_init();
4422 } else if (!strcmp(devname, "keyboard")) {
4423 dev = usb_keyboard_init();
4424 } else if (strstart(devname, "disk:", &p)) {
4425 dev = usb_msd_init(p);
4426 } else if (!strcmp(devname, "wacom-tablet")) {
4427 dev = usb_wacom_init();
4434 /* Find a USB port to add the device to. */
4435 port = free_usb_ports;
4439 /* Create a new hub and chain it on. */
4440 free_usb_ports = NULL;
4441 port->next = used_usb_ports;
4442 used_usb_ports = port;
4444 hub = usb_hub_init(VM_USB_HUB_SIZE);
4445 usb_attach(port, hub);
4446 port = free_usb_ports;
4449 free_usb_ports = port->next;
4450 port->next = used_usb_ports;
4451 used_usb_ports = port;
4452 usb_attach(port, dev);
4456 static int usb_device_del(const char *devname)
4464 if (!used_usb_ports)
4467 p = strchr(devname, '.');
4470 bus_num = strtoul(devname, NULL, 0);
4471 addr = strtoul(p + 1, NULL, 0);
4475 lastp = &used_usb_ports;
4476 port = used_usb_ports;
4477 while (port && port->dev->addr != addr) {
4478 lastp = &port->next;
4486 *lastp = port->next;
4487 usb_attach(port, NULL);
4488 dev->handle_destroy(dev);
4489 port->next = free_usb_ports;
4490 free_usb_ports = port;
4494 void do_usb_add(const char *devname)
4497 ret = usb_device_add(devname);
4499 term_printf("Could not add USB device '%s'\n", devname);
4502 void do_usb_del(const char *devname)
4505 ret = usb_device_del(devname);
4507 term_printf("Could not remove USB device '%s'\n", devname);
4514 const char *speed_str;
4517 term_printf("USB support not enabled\n");
4521 for (port = used_usb_ports; port; port = port->next) {
4525 switch(dev->speed) {
4529 case USB_SPEED_FULL:
4532 case USB_SPEED_HIGH:
4539 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4540 0, dev->addr, speed_str, dev->devname);
4544 /***********************************************************/
4545 /* PCMCIA/Cardbus */
4547 static struct pcmcia_socket_entry_s {
4548 struct pcmcia_socket_s *socket;
4549 struct pcmcia_socket_entry_s *next;
4550 } *pcmcia_sockets = 0;
4552 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4554 struct pcmcia_socket_entry_s *entry;
4556 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4557 entry->socket = socket;
4558 entry->next = pcmcia_sockets;
4559 pcmcia_sockets = entry;
4562 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4564 struct pcmcia_socket_entry_s *entry, **ptr;
4566 ptr = &pcmcia_sockets;
4567 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4568 if (entry->socket == socket) {
4574 void pcmcia_info(void)
4576 struct pcmcia_socket_entry_s *iter;
4577 if (!pcmcia_sockets)
4578 term_printf("No PCMCIA sockets\n");
4580 for (iter = pcmcia_sockets; iter; iter = iter->next)
4581 term_printf("%s: %s\n", iter->socket->slot_string,
4582 iter->socket->attached ? iter->socket->card_string :
4586 /***********************************************************/
4589 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4593 static void dumb_resize(DisplayState *ds, int w, int h)
4597 static void dumb_refresh(DisplayState *ds)
4599 #if defined(CONFIG_SDL)
4604 static void dumb_display_init(DisplayState *ds)
4609 ds->dpy_update = dumb_update;
4610 ds->dpy_resize = dumb_resize;
4611 ds->dpy_refresh = dumb_refresh;
4614 /***********************************************************/
4617 #define MAX_IO_HANDLERS 64
4619 typedef struct IOHandlerRecord {
4621 IOCanRWHandler *fd_read_poll;
4623 IOHandler *fd_write;
4626 /* temporary data */
4628 struct IOHandlerRecord *next;
4631 static IOHandlerRecord *first_io_handler;
4633 /* XXX: fd_read_poll should be suppressed, but an API change is
4634 necessary in the character devices to suppress fd_can_read(). */
4635 int qemu_set_fd_handler2(int fd,
4636 IOCanRWHandler *fd_read_poll,
4638 IOHandler *fd_write,
4641 IOHandlerRecord **pioh, *ioh;
4643 if (!fd_read && !fd_write) {
4644 pioh = &first_io_handler;
4649 if (ioh->fd == fd) {
4656 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4660 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4663 ioh->next = first_io_handler;
4664 first_io_handler = ioh;
4667 ioh->fd_read_poll = fd_read_poll;
4668 ioh->fd_read = fd_read;
4669 ioh->fd_write = fd_write;
4670 ioh->opaque = opaque;
4676 int qemu_set_fd_handler(int fd,
4678 IOHandler *fd_write,
4681 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4684 /***********************************************************/
4685 /* Polling handling */
4687 typedef struct PollingEntry {
4690 struct PollingEntry *next;
4693 static PollingEntry *first_polling_entry;
4695 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4697 PollingEntry **ppe, *pe;
4698 pe = qemu_mallocz(sizeof(PollingEntry));
4702 pe->opaque = opaque;
4703 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4708 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4710 PollingEntry **ppe, *pe;
4711 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4713 if (pe->func == func && pe->opaque == opaque) {
4722 /***********************************************************/
4723 /* Wait objects support */
4724 typedef struct WaitObjects {
4726 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4727 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4728 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4731 static WaitObjects wait_objects = {0};
4733 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4735 WaitObjects *w = &wait_objects;
4737 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4739 w->events[w->num] = handle;
4740 w->func[w->num] = func;
4741 w->opaque[w->num] = opaque;
4746 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4749 WaitObjects *w = &wait_objects;
4752 for (i = 0; i < w->num; i++) {
4753 if (w->events[i] == handle)
4756 w->events[i] = w->events[i + 1];
4757 w->func[i] = w->func[i + 1];
4758 w->opaque[i] = w->opaque[i + 1];
4766 /***********************************************************/
4767 /* savevm/loadvm support */
4769 #define IO_BUF_SIZE 32768
4773 BlockDriverState *bs;
4776 int64_t base_offset;
4777 int64_t buf_offset; /* start of buffer when writing, end of buffer
4780 int buf_size; /* 0 when writing */
4781 uint8_t buf[IO_BUF_SIZE];
4784 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4788 f = qemu_mallocz(sizeof(QEMUFile));
4791 if (!strcmp(mode, "wb")) {
4793 } else if (!strcmp(mode, "rb")) {
4798 f->outfile = fopen(filename, mode);
4810 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4814 f = qemu_mallocz(sizeof(QEMUFile));
4819 f->is_writable = is_writable;
4820 f->base_offset = offset;
4824 void qemu_fflush(QEMUFile *f)
4826 if (!f->is_writable)
4828 if (f->buf_index > 0) {
4830 fseek(f->outfile, f->buf_offset, SEEK_SET);
4831 fwrite(f->buf, 1, f->buf_index, f->outfile);
4833 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4834 f->buf, f->buf_index);
4836 f->buf_offset += f->buf_index;
4841 static void qemu_fill_buffer(QEMUFile *f)
4848 fseek(f->outfile, f->buf_offset, SEEK_SET);
4849 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4853 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4854 f->buf, IO_BUF_SIZE);
4860 f->buf_offset += len;
4863 void qemu_fclose(QEMUFile *f)
4873 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4877 l = IO_BUF_SIZE - f->buf_index;
4880 memcpy(f->buf + f->buf_index, buf, l);
4884 if (f->buf_index >= IO_BUF_SIZE)
4889 void qemu_put_byte(QEMUFile *f, int v)
4891 f->buf[f->buf_index++] = v;
4892 if (f->buf_index >= IO_BUF_SIZE)
4896 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4902 l = f->buf_size - f->buf_index;
4904 qemu_fill_buffer(f);
4905 l = f->buf_size - f->buf_index;
4911 memcpy(buf, f->buf + f->buf_index, l);
4916 return size1 - size;
4919 int qemu_get_byte(QEMUFile *f)
4921 if (f->buf_index >= f->buf_size) {
4922 qemu_fill_buffer(f);
4923 if (f->buf_index >= f->buf_size)
4926 return f->buf[f->buf_index++];
4929 int64_t qemu_ftell(QEMUFile *f)
4931 return f->buf_offset - f->buf_size + f->buf_index;
4934 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4936 if (whence == SEEK_SET) {
4938 } else if (whence == SEEK_CUR) {
4939 pos += qemu_ftell(f);
4941 /* SEEK_END not supported */
4944 if (f->is_writable) {
4946 f->buf_offset = pos;
4948 f->buf_offset = pos;
4955 void qemu_put_be16(QEMUFile *f, unsigned int v)
4957 qemu_put_byte(f, v >> 8);
4958 qemu_put_byte(f, v);
4961 void qemu_put_be32(QEMUFile *f, unsigned int v)
4963 qemu_put_byte(f, v >> 24);
4964 qemu_put_byte(f, v >> 16);
4965 qemu_put_byte(f, v >> 8);
4966 qemu_put_byte(f, v);
4969 void qemu_put_be64(QEMUFile *f, uint64_t v)
4971 qemu_put_be32(f, v >> 32);
4972 qemu_put_be32(f, v);
4975 unsigned int qemu_get_be16(QEMUFile *f)
4978 v = qemu_get_byte(f) << 8;
4979 v |= qemu_get_byte(f);
4983 unsigned int qemu_get_be32(QEMUFile *f)
4986 v = qemu_get_byte(f) << 24;
4987 v |= qemu_get_byte(f) << 16;
4988 v |= qemu_get_byte(f) << 8;
4989 v |= qemu_get_byte(f);
4993 uint64_t qemu_get_be64(QEMUFile *f)
4996 v = (uint64_t)qemu_get_be32(f) << 32;
4997 v |= qemu_get_be32(f);
5001 typedef struct SaveStateEntry {
5005 SaveStateHandler *save_state;
5006 LoadStateHandler *load_state;
5008 struct SaveStateEntry *next;
5011 static SaveStateEntry *first_se;
5013 int register_savevm(const char *idstr,
5016 SaveStateHandler *save_state,
5017 LoadStateHandler *load_state,
5020 SaveStateEntry *se, **pse;
5022 se = qemu_malloc(sizeof(SaveStateEntry));
5025 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5026 se->instance_id = instance_id;
5027 se->version_id = version_id;
5028 se->save_state = save_state;
5029 se->load_state = load_state;
5030 se->opaque = opaque;
5033 /* add at the end of list */
5035 while (*pse != NULL)
5036 pse = &(*pse)->next;
5041 #define QEMU_VM_FILE_MAGIC 0x5145564d
5042 #define QEMU_VM_FILE_VERSION 0x00000002
5044 int qemu_savevm_state(QEMUFile *f)
5048 int64_t cur_pos, len_pos, total_len_pos;
5050 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5051 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5052 total_len_pos = qemu_ftell(f);
5053 qemu_put_be64(f, 0); /* total size */
5055 for(se = first_se; se != NULL; se = se->next) {
5057 len = strlen(se->idstr);
5058 qemu_put_byte(f, len);
5059 qemu_put_buffer(f, se->idstr, len);
5061 qemu_put_be32(f, se->instance_id);
5062 qemu_put_be32(f, se->version_id);
5064 /* record size: filled later */
5065 len_pos = qemu_ftell(f);
5066 qemu_put_be32(f, 0);
5068 se->save_state(f, se->opaque);
5070 /* fill record size */
5071 cur_pos = qemu_ftell(f);
5072 len = cur_pos - len_pos - 4;
5073 qemu_fseek(f, len_pos, SEEK_SET);
5074 qemu_put_be32(f, len);
5075 qemu_fseek(f, cur_pos, SEEK_SET);
5077 cur_pos = qemu_ftell(f);
5078 qemu_fseek(f, total_len_pos, SEEK_SET);
5079 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5080 qemu_fseek(f, cur_pos, SEEK_SET);
5086 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5090 for(se = first_se; se != NULL; se = se->next) {
5091 if (!strcmp(se->idstr, idstr) &&
5092 instance_id == se->instance_id)
5098 int qemu_loadvm_state(QEMUFile *f)
5101 int len, ret, instance_id, record_len, version_id;
5102 int64_t total_len, end_pos, cur_pos;
5106 v = qemu_get_be32(f);
5107 if (v != QEMU_VM_FILE_MAGIC)
5109 v = qemu_get_be32(f);
5110 if (v != QEMU_VM_FILE_VERSION) {
5115 total_len = qemu_get_be64(f);
5116 end_pos = total_len + qemu_ftell(f);
5118 if (qemu_ftell(f) >= end_pos)
5120 len = qemu_get_byte(f);
5121 qemu_get_buffer(f, idstr, len);
5123 instance_id = qemu_get_be32(f);
5124 version_id = qemu_get_be32(f);
5125 record_len = qemu_get_be32(f);
5127 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5128 idstr, instance_id, version_id, record_len);
5130 cur_pos = qemu_ftell(f);
5131 se = find_se(idstr, instance_id);
5133 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5134 instance_id, idstr);
5136 ret = se->load_state(f, se->opaque, version_id);
5138 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5139 instance_id, idstr);
5142 /* always seek to exact end of record */
5143 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5150 /* device can contain snapshots */
5151 static int bdrv_can_snapshot(BlockDriverState *bs)
5154 !bdrv_is_removable(bs) &&
5155 !bdrv_is_read_only(bs));
5158 /* device must be snapshots in order to have a reliable snapshot */
5159 static int bdrv_has_snapshot(BlockDriverState *bs)
5162 !bdrv_is_removable(bs) &&
5163 !bdrv_is_read_only(bs));
5166 static BlockDriverState *get_bs_snapshots(void)
5168 BlockDriverState *bs;
5172 return bs_snapshots;
5173 for(i = 0; i <= MAX_DISKS; i++) {
5175 if (bdrv_can_snapshot(bs))
5184 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5187 QEMUSnapshotInfo *sn_tab, *sn;
5191 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5194 for(i = 0; i < nb_sns; i++) {
5196 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5206 void do_savevm(const char *name)
5208 BlockDriverState *bs, *bs1;
5209 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5210 int must_delete, ret, i;
5211 BlockDriverInfo bdi1, *bdi = &bdi1;
5213 int saved_vm_running;
5220 bs = get_bs_snapshots();
5222 term_printf("No block device can accept snapshots\n");
5226 /* ??? Should this occur after vm_stop? */
5229 saved_vm_running = vm_running;
5234 ret = bdrv_snapshot_find(bs, old_sn, name);
5239 memset(sn, 0, sizeof(*sn));
5241 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5242 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5245 pstrcpy(sn->name, sizeof(sn->name), name);
5248 /* fill auxiliary fields */
5251 sn->date_sec = tb.time;
5252 sn->date_nsec = tb.millitm * 1000000;
5254 gettimeofday(&tv, NULL);
5255 sn->date_sec = tv.tv_sec;
5256 sn->date_nsec = tv.tv_usec * 1000;
5258 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5260 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5261 term_printf("Device %s does not support VM state snapshots\n",
5262 bdrv_get_device_name(bs));
5266 /* save the VM state */
5267 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5269 term_printf("Could not open VM state file\n");
5272 ret = qemu_savevm_state(f);
5273 sn->vm_state_size = qemu_ftell(f);
5276 term_printf("Error %d while writing VM\n", ret);
5280 /* create the snapshots */
5282 for(i = 0; i < MAX_DISKS; i++) {
5284 if (bdrv_has_snapshot(bs1)) {
5286 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5288 term_printf("Error while deleting snapshot on '%s'\n",
5289 bdrv_get_device_name(bs1));
5292 ret = bdrv_snapshot_create(bs1, sn);
5294 term_printf("Error while creating snapshot on '%s'\n",
5295 bdrv_get_device_name(bs1));
5301 if (saved_vm_running)
5305 void do_loadvm(const char *name)
5307 BlockDriverState *bs, *bs1;
5308 BlockDriverInfo bdi1, *bdi = &bdi1;
5311 int saved_vm_running;
5313 bs = get_bs_snapshots();
5315 term_printf("No block device supports snapshots\n");
5319 /* Flush all IO requests so they don't interfere with the new state. */
5322 saved_vm_running = vm_running;
5325 for(i = 0; i <= MAX_DISKS; i++) {
5327 if (bdrv_has_snapshot(bs1)) {
5328 ret = bdrv_snapshot_goto(bs1, name);
5331 term_printf("Warning: ");
5334 term_printf("Snapshots not supported on device '%s'\n",
5335 bdrv_get_device_name(bs1));
5338 term_printf("Could not find snapshot '%s' on device '%s'\n",
5339 name, bdrv_get_device_name(bs1));
5342 term_printf("Error %d while activating snapshot on '%s'\n",
5343 ret, bdrv_get_device_name(bs1));
5346 /* fatal on snapshot block device */
5353 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5354 term_printf("Device %s does not support VM state snapshots\n",
5355 bdrv_get_device_name(bs));
5359 /* restore the VM state */
5360 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5362 term_printf("Could not open VM state file\n");
5365 ret = qemu_loadvm_state(f);
5368 term_printf("Error %d while loading VM state\n", ret);
5371 if (saved_vm_running)
5375 void do_delvm(const char *name)
5377 BlockDriverState *bs, *bs1;
5380 bs = get_bs_snapshots();
5382 term_printf("No block device supports snapshots\n");
5386 for(i = 0; i <= MAX_DISKS; i++) {
5388 if (bdrv_has_snapshot(bs1)) {
5389 ret = bdrv_snapshot_delete(bs1, name);
5391 if (ret == -ENOTSUP)
5392 term_printf("Snapshots not supported on device '%s'\n",
5393 bdrv_get_device_name(bs1));
5395 term_printf("Error %d while deleting snapshot on '%s'\n",
5396 ret, bdrv_get_device_name(bs1));
5402 void do_info_snapshots(void)
5404 BlockDriverState *bs, *bs1;
5405 QEMUSnapshotInfo *sn_tab, *sn;
5409 bs = get_bs_snapshots();
5411 term_printf("No available block device supports snapshots\n");
5414 term_printf("Snapshot devices:");
5415 for(i = 0; i <= MAX_DISKS; i++) {
5417 if (bdrv_has_snapshot(bs1)) {
5419 term_printf(" %s", bdrv_get_device_name(bs1));
5424 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5426 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5429 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5430 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5431 for(i = 0; i < nb_sns; i++) {
5433 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5438 /***********************************************************/
5439 /* cpu save/restore */
5441 #if defined(TARGET_I386)
5443 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5445 qemu_put_be32(f, dt->selector);
5446 qemu_put_betl(f, dt->base);
5447 qemu_put_be32(f, dt->limit);
5448 qemu_put_be32(f, dt->flags);
5451 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5453 dt->selector = qemu_get_be32(f);
5454 dt->base = qemu_get_betl(f);
5455 dt->limit = qemu_get_be32(f);
5456 dt->flags = qemu_get_be32(f);
5459 void cpu_save(QEMUFile *f, void *opaque)
5461 CPUState *env = opaque;
5462 uint16_t fptag, fpus, fpuc, fpregs_format;
5466 for(i = 0; i < CPU_NB_REGS; i++)
5467 qemu_put_betls(f, &env->regs[i]);
5468 qemu_put_betls(f, &env->eip);
5469 qemu_put_betls(f, &env->eflags);
5470 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5471 qemu_put_be32s(f, &hflags);
5475 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5477 for(i = 0; i < 8; i++) {
5478 fptag |= ((!env->fptags[i]) << i);
5481 qemu_put_be16s(f, &fpuc);
5482 qemu_put_be16s(f, &fpus);
5483 qemu_put_be16s(f, &fptag);
5485 #ifdef USE_X86LDOUBLE
5490 qemu_put_be16s(f, &fpregs_format);
5492 for(i = 0; i < 8; i++) {
5493 #ifdef USE_X86LDOUBLE
5497 /* we save the real CPU data (in case of MMX usage only 'mant'
5498 contains the MMX register */
5499 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5500 qemu_put_be64(f, mant);
5501 qemu_put_be16(f, exp);
5504 /* if we use doubles for float emulation, we save the doubles to
5505 avoid losing information in case of MMX usage. It can give
5506 problems if the image is restored on a CPU where long
5507 doubles are used instead. */
5508 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5512 for(i = 0; i < 6; i++)
5513 cpu_put_seg(f, &env->segs[i]);
5514 cpu_put_seg(f, &env->ldt);
5515 cpu_put_seg(f, &env->tr);
5516 cpu_put_seg(f, &env->gdt);
5517 cpu_put_seg(f, &env->idt);
5519 qemu_put_be32s(f, &env->sysenter_cs);
5520 qemu_put_be32s(f, &env->sysenter_esp);
5521 qemu_put_be32s(f, &env->sysenter_eip);
5523 qemu_put_betls(f, &env->cr[0]);
5524 qemu_put_betls(f, &env->cr[2]);
5525 qemu_put_betls(f, &env->cr[3]);
5526 qemu_put_betls(f, &env->cr[4]);
5528 for(i = 0; i < 8; i++)
5529 qemu_put_betls(f, &env->dr[i]);
5532 qemu_put_be32s(f, &env->a20_mask);
5535 qemu_put_be32s(f, &env->mxcsr);
5536 for(i = 0; i < CPU_NB_REGS; i++) {
5537 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5538 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5541 #ifdef TARGET_X86_64
5542 qemu_put_be64s(f, &env->efer);
5543 qemu_put_be64s(f, &env->star);
5544 qemu_put_be64s(f, &env->lstar);
5545 qemu_put_be64s(f, &env->cstar);
5546 qemu_put_be64s(f, &env->fmask);
5547 qemu_put_be64s(f, &env->kernelgsbase);
5549 qemu_put_be32s(f, &env->smbase);
5552 #ifdef USE_X86LDOUBLE
5553 /* XXX: add that in a FPU generic layer */
5554 union x86_longdouble {
5559 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5560 #define EXPBIAS1 1023
5561 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5562 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5564 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5568 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5569 /* exponent + sign */
5570 e = EXPD1(temp) - EXPBIAS1 + 16383;
5571 e |= SIGND1(temp) >> 16;
5576 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5578 CPUState *env = opaque;
5581 uint16_t fpus, fpuc, fptag, fpregs_format;
5583 if (version_id != 3 && version_id != 4)
5585 for(i = 0; i < CPU_NB_REGS; i++)
5586 qemu_get_betls(f, &env->regs[i]);
5587 qemu_get_betls(f, &env->eip);
5588 qemu_get_betls(f, &env->eflags);
5589 qemu_get_be32s(f, &hflags);
5591 qemu_get_be16s(f, &fpuc);
5592 qemu_get_be16s(f, &fpus);
5593 qemu_get_be16s(f, &fptag);
5594 qemu_get_be16s(f, &fpregs_format);
5596 /* NOTE: we cannot always restore the FPU state if the image come
5597 from a host with a different 'USE_X86LDOUBLE' define. We guess
5598 if we are in an MMX state to restore correctly in that case. */
5599 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5600 for(i = 0; i < 8; i++) {
5604 switch(fpregs_format) {
5606 mant = qemu_get_be64(f);
5607 exp = qemu_get_be16(f);
5608 #ifdef USE_X86LDOUBLE
5609 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5611 /* difficult case */
5613 env->fpregs[i].mmx.MMX_Q(0) = mant;
5615 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5619 mant = qemu_get_be64(f);
5620 #ifdef USE_X86LDOUBLE
5622 union x86_longdouble *p;
5623 /* difficult case */
5624 p = (void *)&env->fpregs[i];
5629 fp64_to_fp80(p, mant);
5633 env->fpregs[i].mmx.MMX_Q(0) = mant;
5642 /* XXX: restore FPU round state */
5643 env->fpstt = (fpus >> 11) & 7;
5644 env->fpus = fpus & ~0x3800;
5646 for(i = 0; i < 8; i++) {
5647 env->fptags[i] = (fptag >> i) & 1;
5650 for(i = 0; i < 6; i++)
5651 cpu_get_seg(f, &env->segs[i]);
5652 cpu_get_seg(f, &env->ldt);
5653 cpu_get_seg(f, &env->tr);
5654 cpu_get_seg(f, &env->gdt);
5655 cpu_get_seg(f, &env->idt);
5657 qemu_get_be32s(f, &env->sysenter_cs);
5658 qemu_get_be32s(f, &env->sysenter_esp);
5659 qemu_get_be32s(f, &env->sysenter_eip);
5661 qemu_get_betls(f, &env->cr[0]);
5662 qemu_get_betls(f, &env->cr[2]);
5663 qemu_get_betls(f, &env->cr[3]);
5664 qemu_get_betls(f, &env->cr[4]);
5666 for(i = 0; i < 8; i++)
5667 qemu_get_betls(f, &env->dr[i]);
5670 qemu_get_be32s(f, &env->a20_mask);
5672 qemu_get_be32s(f, &env->mxcsr);
5673 for(i = 0; i < CPU_NB_REGS; i++) {
5674 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5675 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5678 #ifdef TARGET_X86_64
5679 qemu_get_be64s(f, &env->efer);
5680 qemu_get_be64s(f, &env->star);
5681 qemu_get_be64s(f, &env->lstar);
5682 qemu_get_be64s(f, &env->cstar);
5683 qemu_get_be64s(f, &env->fmask);
5684 qemu_get_be64s(f, &env->kernelgsbase);
5686 if (version_id >= 4)
5687 qemu_get_be32s(f, &env->smbase);
5689 /* XXX: compute hflags from scratch, except for CPL and IIF */
5690 env->hflags = hflags;
5695 #elif defined(TARGET_PPC)
5696 void cpu_save(QEMUFile *f, void *opaque)
5700 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5705 #elif defined(TARGET_MIPS)
5706 void cpu_save(QEMUFile *f, void *opaque)
5710 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5715 #elif defined(TARGET_SPARC)
5716 void cpu_save(QEMUFile *f, void *opaque)
5718 CPUState *env = opaque;
5722 for(i = 0; i < 8; i++)
5723 qemu_put_betls(f, &env->gregs[i]);
5724 for(i = 0; i < NWINDOWS * 16; i++)
5725 qemu_put_betls(f, &env->regbase[i]);
5728 for(i = 0; i < TARGET_FPREGS; i++) {
5734 qemu_put_be32(f, u.i);
5737 qemu_put_betls(f, &env->pc);
5738 qemu_put_betls(f, &env->npc);
5739 qemu_put_betls(f, &env->y);
5741 qemu_put_be32(f, tmp);
5742 qemu_put_betls(f, &env->fsr);
5743 qemu_put_betls(f, &env->tbr);
5744 #ifndef TARGET_SPARC64
5745 qemu_put_be32s(f, &env->wim);
5747 for(i = 0; i < 16; i++)
5748 qemu_put_be32s(f, &env->mmuregs[i]);
5752 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5754 CPUState *env = opaque;
5758 for(i = 0; i < 8; i++)
5759 qemu_get_betls(f, &env->gregs[i]);
5760 for(i = 0; i < NWINDOWS * 16; i++)
5761 qemu_get_betls(f, &env->regbase[i]);
5764 for(i = 0; i < TARGET_FPREGS; i++) {
5769 u.i = qemu_get_be32(f);
5773 qemu_get_betls(f, &env->pc);
5774 qemu_get_betls(f, &env->npc);
5775 qemu_get_betls(f, &env->y);
5776 tmp = qemu_get_be32(f);
5777 env->cwp = 0; /* needed to ensure that the wrapping registers are
5778 correctly updated */
5780 qemu_get_betls(f, &env->fsr);
5781 qemu_get_betls(f, &env->tbr);
5782 #ifndef TARGET_SPARC64
5783 qemu_get_be32s(f, &env->wim);
5785 for(i = 0; i < 16; i++)
5786 qemu_get_be32s(f, &env->mmuregs[i]);
5792 #elif defined(TARGET_ARM)
5794 void cpu_save(QEMUFile *f, void *opaque)
5797 CPUARMState *env = (CPUARMState *)opaque;
5799 for (i = 0; i < 16; i++) {
5800 qemu_put_be32(f, env->regs[i]);
5802 qemu_put_be32(f, cpsr_read(env));
5803 qemu_put_be32(f, env->spsr);
5804 for (i = 0; i < 6; i++) {
5805 qemu_put_be32(f, env->banked_spsr[i]);
5806 qemu_put_be32(f, env->banked_r13[i]);
5807 qemu_put_be32(f, env->banked_r14[i]);
5809 for (i = 0; i < 5; i++) {
5810 qemu_put_be32(f, env->usr_regs[i]);
5811 qemu_put_be32(f, env->fiq_regs[i]);
5813 qemu_put_be32(f, env->cp15.c0_cpuid);
5814 qemu_put_be32(f, env->cp15.c0_cachetype);
5815 qemu_put_be32(f, env->cp15.c1_sys);
5816 qemu_put_be32(f, env->cp15.c1_coproc);
5817 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5818 qemu_put_be32(f, env->cp15.c2_base);
5819 qemu_put_be32(f, env->cp15.c2_data);
5820 qemu_put_be32(f, env->cp15.c2_insn);
5821 qemu_put_be32(f, env->cp15.c3);
5822 qemu_put_be32(f, env->cp15.c5_insn);
5823 qemu_put_be32(f, env->cp15.c5_data);
5824 for (i = 0; i < 8; i++) {
5825 qemu_put_be32(f, env->cp15.c6_region[i]);
5827 qemu_put_be32(f, env->cp15.c6_insn);
5828 qemu_put_be32(f, env->cp15.c6_data);
5829 qemu_put_be32(f, env->cp15.c9_insn);
5830 qemu_put_be32(f, env->cp15.c9_data);
5831 qemu_put_be32(f, env->cp15.c13_fcse);
5832 qemu_put_be32(f, env->cp15.c13_context);
5833 qemu_put_be32(f, env->cp15.c15_cpar);
5835 qemu_put_be32(f, env->features);
5837 if (arm_feature(env, ARM_FEATURE_VFP)) {
5838 for (i = 0; i < 16; i++) {
5840 u.d = env->vfp.regs[i];
5841 qemu_put_be32(f, u.l.upper);
5842 qemu_put_be32(f, u.l.lower);
5844 for (i = 0; i < 16; i++) {
5845 qemu_put_be32(f, env->vfp.xregs[i]);
5848 /* TODO: Should use proper FPSCR access functions. */
5849 qemu_put_be32(f, env->vfp.vec_len);
5850 qemu_put_be32(f, env->vfp.vec_stride);
5853 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5854 for (i = 0; i < 16; i++) {
5855 qemu_put_be64(f, env->iwmmxt.regs[i]);
5857 for (i = 0; i < 16; i++) {
5858 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5863 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5865 CPUARMState *env = (CPUARMState *)opaque;
5868 if (version_id != 0)
5871 for (i = 0; i < 16; i++) {
5872 env->regs[i] = qemu_get_be32(f);
5874 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5875 env->spsr = qemu_get_be32(f);
5876 for (i = 0; i < 6; i++) {
5877 env->banked_spsr[i] = qemu_get_be32(f);
5878 env->banked_r13[i] = qemu_get_be32(f);
5879 env->banked_r14[i] = qemu_get_be32(f);
5881 for (i = 0; i < 5; i++) {
5882 env->usr_regs[i] = qemu_get_be32(f);
5883 env->fiq_regs[i] = qemu_get_be32(f);
5885 env->cp15.c0_cpuid = qemu_get_be32(f);
5886 env->cp15.c0_cachetype = qemu_get_be32(f);
5887 env->cp15.c1_sys = qemu_get_be32(f);
5888 env->cp15.c1_coproc = qemu_get_be32(f);
5889 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5890 env->cp15.c2_base = qemu_get_be32(f);
5891 env->cp15.c2_data = qemu_get_be32(f);
5892 env->cp15.c2_insn = qemu_get_be32(f);
5893 env->cp15.c3 = qemu_get_be32(f);
5894 env->cp15.c5_insn = qemu_get_be32(f);
5895 env->cp15.c5_data = qemu_get_be32(f);
5896 for (i = 0; i < 8; i++) {
5897 env->cp15.c6_region[i] = qemu_get_be32(f);
5899 env->cp15.c6_insn = qemu_get_be32(f);
5900 env->cp15.c6_data = qemu_get_be32(f);
5901 env->cp15.c9_insn = qemu_get_be32(f);
5902 env->cp15.c9_data = qemu_get_be32(f);
5903 env->cp15.c13_fcse = qemu_get_be32(f);
5904 env->cp15.c13_context = qemu_get_be32(f);
5905 env->cp15.c15_cpar = qemu_get_be32(f);
5907 env->features = qemu_get_be32(f);
5909 if (arm_feature(env, ARM_FEATURE_VFP)) {
5910 for (i = 0; i < 16; i++) {
5912 u.l.upper = qemu_get_be32(f);
5913 u.l.lower = qemu_get_be32(f);
5914 env->vfp.regs[i] = u.d;
5916 for (i = 0; i < 16; i++) {
5917 env->vfp.xregs[i] = qemu_get_be32(f);
5920 /* TODO: Should use proper FPSCR access functions. */
5921 env->vfp.vec_len = qemu_get_be32(f);
5922 env->vfp.vec_stride = qemu_get_be32(f);
5925 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5926 for (i = 0; i < 16; i++) {
5927 env->iwmmxt.regs[i] = qemu_get_be64(f);
5929 for (i = 0; i < 16; i++) {
5930 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5939 #warning No CPU save/restore functions
5943 /***********************************************************/
5944 /* ram save/restore */
5946 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5950 v = qemu_get_byte(f);
5953 if (qemu_get_buffer(f, buf, len) != len)
5957 v = qemu_get_byte(f);
5958 memset(buf, v, len);
5966 static int ram_load_v1(QEMUFile *f, void *opaque)
5970 if (qemu_get_be32(f) != phys_ram_size)
5972 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5973 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5980 #define BDRV_HASH_BLOCK_SIZE 1024
5981 #define IOBUF_SIZE 4096
5982 #define RAM_CBLOCK_MAGIC 0xfabe
5984 typedef struct RamCompressState {
5987 uint8_t buf[IOBUF_SIZE];
5990 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5993 memset(s, 0, sizeof(*s));
5995 ret = deflateInit2(&s->zstream, 1,
5997 9, Z_DEFAULT_STRATEGY);
6000 s->zstream.avail_out = IOBUF_SIZE;
6001 s->zstream.next_out = s->buf;
6005 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6007 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6008 qemu_put_be16(s->f, len);
6009 qemu_put_buffer(s->f, buf, len);
6012 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6016 s->zstream.avail_in = len;
6017 s->zstream.next_in = (uint8_t *)buf;
6018 while (s->zstream.avail_in > 0) {
6019 ret = deflate(&s->zstream, Z_NO_FLUSH);
6022 if (s->zstream.avail_out == 0) {
6023 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6024 s->zstream.avail_out = IOBUF_SIZE;
6025 s->zstream.next_out = s->buf;
6031 static void ram_compress_close(RamCompressState *s)
6035 /* compress last bytes */
6037 ret = deflate(&s->zstream, Z_FINISH);
6038 if (ret == Z_OK || ret == Z_STREAM_END) {
6039 len = IOBUF_SIZE - s->zstream.avail_out;
6041 ram_put_cblock(s, s->buf, len);
6043 s->zstream.avail_out = IOBUF_SIZE;
6044 s->zstream.next_out = s->buf;
6045 if (ret == Z_STREAM_END)
6052 deflateEnd(&s->zstream);
6055 typedef struct RamDecompressState {
6058 uint8_t buf[IOBUF_SIZE];
6059 } RamDecompressState;
6061 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6064 memset(s, 0, sizeof(*s));
6066 ret = inflateInit(&s->zstream);
6072 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6076 s->zstream.avail_out = len;
6077 s->zstream.next_out = buf;
6078 while (s->zstream.avail_out > 0) {
6079 if (s->zstream.avail_in == 0) {
6080 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6082 clen = qemu_get_be16(s->f);
6083 if (clen > IOBUF_SIZE)
6085 qemu_get_buffer(s->f, s->buf, clen);
6086 s->zstream.avail_in = clen;
6087 s->zstream.next_in = s->buf;
6089 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6090 if (ret != Z_OK && ret != Z_STREAM_END) {
6097 static void ram_decompress_close(RamDecompressState *s)
6099 inflateEnd(&s->zstream);
6102 static void ram_save(QEMUFile *f, void *opaque)
6105 RamCompressState s1, *s = &s1;
6108 qemu_put_be32(f, phys_ram_size);
6109 if (ram_compress_open(s, f) < 0)
6111 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6113 if (tight_savevm_enabled) {
6117 /* find if the memory block is available on a virtual
6120 for(j = 0; j < MAX_DISKS; j++) {
6122 sector_num = bdrv_hash_find(bs_table[j],
6123 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6124 if (sector_num >= 0)
6129 goto normal_compress;
6132 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6133 ram_compress_buf(s, buf, 10);
6139 ram_compress_buf(s, buf, 1);
6140 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6143 ram_compress_close(s);
6146 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6148 RamDecompressState s1, *s = &s1;
6152 if (version_id == 1)
6153 return ram_load_v1(f, opaque);
6154 if (version_id != 2)
6156 if (qemu_get_be32(f) != phys_ram_size)
6158 if (ram_decompress_open(s, f) < 0)
6160 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6161 if (ram_decompress_buf(s, buf, 1) < 0) {
6162 fprintf(stderr, "Error while reading ram block header\n");
6166 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6167 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6176 ram_decompress_buf(s, buf + 1, 9);
6178 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6179 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6180 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6183 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6184 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6185 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6186 bs_index, sector_num);
6193 printf("Error block header\n");
6197 ram_decompress_close(s);
6201 /***********************************************************/
6202 /* bottom halves (can be seen as timers which expire ASAP) */
6211 static QEMUBH *first_bh = NULL;
6213 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6216 bh = qemu_mallocz(sizeof(QEMUBH));
6220 bh->opaque = opaque;
6224 int qemu_bh_poll(void)
6243 void qemu_bh_schedule(QEMUBH *bh)
6245 CPUState *env = cpu_single_env;
6249 bh->next = first_bh;
6252 /* stop the currently executing CPU to execute the BH ASAP */
6254 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6258 void qemu_bh_cancel(QEMUBH *bh)
6261 if (bh->scheduled) {
6264 pbh = &(*pbh)->next;
6270 void qemu_bh_delete(QEMUBH *bh)
6276 /***********************************************************/
6277 /* machine registration */
6279 QEMUMachine *first_machine = NULL;
6281 int qemu_register_machine(QEMUMachine *m)
6284 pm = &first_machine;
6292 QEMUMachine *find_machine(const char *name)
6296 for(m = first_machine; m != NULL; m = m->next) {
6297 if (!strcmp(m->name, name))
6303 /***********************************************************/
6304 /* main execution loop */
6306 void gui_update(void *opaque)
6308 DisplayState *ds = opaque;
6309 ds->dpy_refresh(ds);
6310 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6313 struct vm_change_state_entry {
6314 VMChangeStateHandler *cb;
6316 LIST_ENTRY (vm_change_state_entry) entries;
6319 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6321 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6324 VMChangeStateEntry *e;
6326 e = qemu_mallocz(sizeof (*e));
6332 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6336 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6338 LIST_REMOVE (e, entries);
6342 static void vm_state_notify(int running)
6344 VMChangeStateEntry *e;
6346 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6347 e->cb(e->opaque, running);
6351 /* XXX: support several handlers */
6352 static VMStopHandler *vm_stop_cb;
6353 static void *vm_stop_opaque;
6355 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6358 vm_stop_opaque = opaque;
6362 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6376 void vm_stop(int reason)
6379 cpu_disable_ticks();
6383 vm_stop_cb(vm_stop_opaque, reason);
6390 /* reset/shutdown handler */
6392 typedef struct QEMUResetEntry {
6393 QEMUResetHandler *func;
6395 struct QEMUResetEntry *next;
6398 static QEMUResetEntry *first_reset_entry;
6399 static int reset_requested;
6400 static int shutdown_requested;
6401 static int powerdown_requested;
6403 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6405 QEMUResetEntry **pre, *re;
6407 pre = &first_reset_entry;
6408 while (*pre != NULL)
6409 pre = &(*pre)->next;
6410 re = qemu_mallocz(sizeof(QEMUResetEntry));
6412 re->opaque = opaque;
6417 static void qemu_system_reset(void)
6421 /* reset all devices */
6422 for(re = first_reset_entry; re != NULL; re = re->next) {
6423 re->func(re->opaque);
6427 void qemu_system_reset_request(void)
6430 shutdown_requested = 1;
6432 reset_requested = 1;
6435 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6438 void qemu_system_shutdown_request(void)
6440 shutdown_requested = 1;
6442 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6445 void qemu_system_powerdown_request(void)
6447 powerdown_requested = 1;
6449 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6452 void main_loop_wait(int timeout)
6454 IOHandlerRecord *ioh;
6455 fd_set rfds, wfds, xfds;
6464 /* XXX: need to suppress polling by better using win32 events */
6466 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6467 ret |= pe->func(pe->opaque);
6472 WaitObjects *w = &wait_objects;
6474 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6475 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6476 if (w->func[ret - WAIT_OBJECT_0])
6477 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6479 /* Check for additional signaled events */
6480 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6482 /* Check if event is signaled */
6483 ret2 = WaitForSingleObject(w->events[i], 0);
6484 if(ret2 == WAIT_OBJECT_0) {
6486 w->func[i](w->opaque[i]);
6487 } else if (ret2 == WAIT_TIMEOUT) {
6489 err = GetLastError();
6490 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6493 } else if (ret == WAIT_TIMEOUT) {
6495 err = GetLastError();
6496 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6500 /* poll any events */
6501 /* XXX: separate device handlers from system ones */
6506 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6510 (!ioh->fd_read_poll ||
6511 ioh->fd_read_poll(ioh->opaque) != 0)) {
6512 FD_SET(ioh->fd, &rfds);
6516 if (ioh->fd_write) {
6517 FD_SET(ioh->fd, &wfds);
6527 tv.tv_usec = timeout * 1000;
6529 #if defined(CONFIG_SLIRP)
6531 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6534 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6536 IOHandlerRecord **pioh;
6538 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6541 if (FD_ISSET(ioh->fd, &rfds)) {
6542 ioh->fd_read(ioh->opaque);
6544 if (FD_ISSET(ioh->fd, &wfds)) {
6545 ioh->fd_write(ioh->opaque);
6549 /* remove deleted IO handlers */
6550 pioh = &first_io_handler;
6560 #if defined(CONFIG_SLIRP)
6567 slirp_select_poll(&rfds, &wfds, &xfds);
6573 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6574 qemu_get_clock(vm_clock));
6575 /* run dma transfers, if any */
6579 /* real time timers */
6580 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6581 qemu_get_clock(rt_clock));
6583 /* Check bottom-halves last in case any of the earlier events triggered
6589 static CPUState *cur_cpu;
6594 #ifdef CONFIG_PROFILER
6599 cur_cpu = first_cpu;
6606 env = env->next_cpu;
6609 #ifdef CONFIG_PROFILER
6610 ti = profile_getclock();
6612 ret = cpu_exec(env);
6613 #ifdef CONFIG_PROFILER
6614 qemu_time += profile_getclock() - ti;
6616 if (ret == EXCP_HLT) {
6617 /* Give the next CPU a chance to run. */
6621 if (ret != EXCP_HALTED)
6623 /* all CPUs are halted ? */
6629 if (shutdown_requested) {
6630 ret = EXCP_INTERRUPT;
6633 if (reset_requested) {
6634 reset_requested = 0;
6635 qemu_system_reset();
6636 ret = EXCP_INTERRUPT;
6638 if (powerdown_requested) {
6639 powerdown_requested = 0;
6640 qemu_system_powerdown();
6641 ret = EXCP_INTERRUPT;
6643 if (ret == EXCP_DEBUG) {
6644 vm_stop(EXCP_DEBUG);
6646 /* If all cpus are halted then wait until the next IRQ */
6647 /* XXX: use timeout computed from timers */
6648 if (ret == EXCP_HALTED)
6655 #ifdef CONFIG_PROFILER
6656 ti = profile_getclock();
6658 main_loop_wait(timeout);
6659 #ifdef CONFIG_PROFILER
6660 dev_time += profile_getclock() - ti;
6663 cpu_disable_ticks();
6667 static void help(int exitcode)
6669 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6670 "usage: %s [options] [disk_image]\n"
6672 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6674 "Standard options:\n"
6675 "-M machine select emulated machine (-M ? for list)\n"
6676 "-cpu cpu select CPU (-cpu ? for list)\n"
6677 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6678 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6679 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6680 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6681 "-mtdblock file use 'file' as on-board Flash memory image\n"
6682 "-sd file use 'file' as SecureDigital card image\n"
6683 "-pflash file use 'file' as a parallel flash image\n"
6684 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6685 "-snapshot write to temporary files instead of disk image files\n"
6687 "-no-frame open SDL window without a frame and window decorations\n"
6688 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6689 "-no-quit disable SDL window close capability\n"
6692 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6694 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6695 "-smp n set the number of CPUs to 'n' [default=1]\n"
6696 "-nographic disable graphical output and redirect serial I/Os to console\n"
6697 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6699 "-k language use keyboard layout (for example \"fr\" for French)\n"
6702 "-audio-help print list of audio drivers and their options\n"
6703 "-soundhw c1,... enable audio support\n"
6704 " and only specified sound cards (comma separated list)\n"
6705 " use -soundhw ? to get the list of supported cards\n"
6706 " use -soundhw all to enable all of them\n"
6708 "-localtime set the real time clock to local time [default=utc]\n"
6709 "-full-screen start in full screen\n"
6711 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6713 "-usb enable the USB driver (will be the default soon)\n"
6714 "-usbdevice name add the host or guest USB device 'name'\n"
6715 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6716 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6718 "-name string set the name of the guest\n"
6720 "Network options:\n"
6721 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6722 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6724 "-net user[,vlan=n][,hostname=host]\n"
6725 " connect the user mode network stack to VLAN 'n' and send\n"
6726 " hostname 'host' to DHCP clients\n"
6729 "-net tap[,vlan=n],ifname=name\n"
6730 " connect the host TAP network interface to VLAN 'n'\n"
6732 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6733 " connect the host TAP network interface to VLAN 'n' and use\n"
6734 " the network script 'file' (default=%s);\n"
6735 " use 'script=no' to disable script execution;\n"
6736 " use 'fd=h' to connect to an already opened TAP interface\n"
6738 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6739 " connect the vlan 'n' to another VLAN using a socket connection\n"
6740 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6741 " connect the vlan 'n' to multicast maddr and port\n"
6742 "-net none use it alone to have zero network devices; if no -net option\n"
6743 " is provided, the default is '-net nic -net user'\n"
6746 "-tftp dir allow tftp access to files in dir [-net user]\n"
6747 "-bootp file advertise file in BOOTP replies\n"
6749 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6751 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6752 " redirect TCP or UDP connections from host to guest [-net user]\n"
6755 "Linux boot specific:\n"
6756 "-kernel bzImage use 'bzImage' as kernel image\n"
6757 "-append cmdline use 'cmdline' as kernel command line\n"
6758 "-initrd file use 'file' as initial ram disk\n"
6760 "Debug/Expert options:\n"
6761 "-monitor dev redirect the monitor to char device 'dev'\n"
6762 "-serial dev redirect the serial port to char device 'dev'\n"
6763 "-parallel dev redirect the parallel port to char device 'dev'\n"
6764 "-pidfile file Write PID to 'file'\n"
6765 "-S freeze CPU at startup (use 'c' to start execution)\n"
6766 "-s wait gdb connection to port\n"
6767 "-p port set gdb connection port [default=%s]\n"
6768 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6769 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6770 " translation (t=none or lba) (usually qemu can guess them)\n"
6771 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6773 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6774 "-no-kqemu disable KQEMU kernel module usage\n"
6776 #ifdef USE_CODE_COPY
6777 "-no-code-copy disable code copy acceleration\n"
6780 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6781 " (default is CL-GD5446 PCI VGA)\n"
6782 "-no-acpi disable ACPI\n"
6784 "-no-reboot exit instead of rebooting\n"
6785 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6786 "-vnc display start a VNC server on display\n"
6788 "-daemonize daemonize QEMU after initializing\n"
6790 "-option-rom rom load a file, rom, into the option ROM space\n"
6792 "-prom-env variable=value set OpenBIOS nvram variables\n"
6795 "During emulation, the following keys are useful:\n"
6796 "ctrl-alt-f toggle full screen\n"
6797 "ctrl-alt-n switch to virtual console 'n'\n"
6798 "ctrl-alt toggle mouse and keyboard grab\n"
6800 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6805 DEFAULT_NETWORK_SCRIPT,
6807 DEFAULT_GDBSTUB_PORT,
6812 #define HAS_ARG 0x0001
6826 QEMU_OPTION_mtdblock,
6830 QEMU_OPTION_snapshot,
6832 QEMU_OPTION_no_fd_bootchk,
6835 QEMU_OPTION_nographic,
6836 QEMU_OPTION_portrait,
6838 QEMU_OPTION_audio_help,
6839 QEMU_OPTION_soundhw,
6858 QEMU_OPTION_no_code_copy,
6860 QEMU_OPTION_localtime,
6861 QEMU_OPTION_cirrusvga,
6864 QEMU_OPTION_std_vga,
6866 QEMU_OPTION_monitor,
6868 QEMU_OPTION_parallel,
6870 QEMU_OPTION_full_screen,
6871 QEMU_OPTION_no_frame,
6872 QEMU_OPTION_alt_grab,
6873 QEMU_OPTION_no_quit,
6874 QEMU_OPTION_pidfile,
6875 QEMU_OPTION_no_kqemu,
6876 QEMU_OPTION_kernel_kqemu,
6877 QEMU_OPTION_win2k_hack,
6879 QEMU_OPTION_usbdevice,
6882 QEMU_OPTION_no_acpi,
6883 QEMU_OPTION_no_reboot,
6884 QEMU_OPTION_show_cursor,
6885 QEMU_OPTION_daemonize,
6886 QEMU_OPTION_option_rom,
6887 QEMU_OPTION_semihosting,
6889 QEMU_OPTION_prom_env,
6890 QEMU_OPTION_old_param,
6893 typedef struct QEMUOption {
6899 const QEMUOption qemu_options[] = {
6900 { "h", 0, QEMU_OPTION_h },
6901 { "help", 0, QEMU_OPTION_h },
6903 { "M", HAS_ARG, QEMU_OPTION_M },
6904 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6905 { "fda", HAS_ARG, QEMU_OPTION_fda },
6906 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6907 { "hda", HAS_ARG, QEMU_OPTION_hda },
6908 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6909 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6910 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6911 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6912 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6913 { "sd", HAS_ARG, QEMU_OPTION_sd },
6914 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6915 { "boot", HAS_ARG, QEMU_OPTION_boot },
6916 { "snapshot", 0, QEMU_OPTION_snapshot },
6918 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6920 { "m", HAS_ARG, QEMU_OPTION_m },
6921 { "nographic", 0, QEMU_OPTION_nographic },
6922 { "portrait", 0, QEMU_OPTION_portrait },
6923 { "k", HAS_ARG, QEMU_OPTION_k },
6925 { "audio-help", 0, QEMU_OPTION_audio_help },
6926 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6929 { "net", HAS_ARG, QEMU_OPTION_net},
6931 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6932 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6934 { "smb", HAS_ARG, QEMU_OPTION_smb },
6936 { "redir", HAS_ARG, QEMU_OPTION_redir },
6939 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6940 { "append", HAS_ARG, QEMU_OPTION_append },
6941 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6943 { "S", 0, QEMU_OPTION_S },
6944 { "s", 0, QEMU_OPTION_s },
6945 { "p", HAS_ARG, QEMU_OPTION_p },
6946 { "d", HAS_ARG, QEMU_OPTION_d },
6947 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6948 { "L", HAS_ARG, QEMU_OPTION_L },
6949 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6951 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6952 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6954 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6955 { "g", 1, QEMU_OPTION_g },
6957 { "localtime", 0, QEMU_OPTION_localtime },
6958 { "std-vga", 0, QEMU_OPTION_std_vga },
6959 { "echr", HAS_ARG, QEMU_OPTION_echr },
6960 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
6961 { "serial", HAS_ARG, QEMU_OPTION_serial },
6962 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
6963 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6964 { "full-screen", 0, QEMU_OPTION_full_screen },
6966 { "no-frame", 0, QEMU_OPTION_no_frame },
6967 { "alt-grab", 0, QEMU_OPTION_alt_grab },
6968 { "no-quit", 0, QEMU_OPTION_no_quit },
6970 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6971 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6972 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6973 { "smp", HAS_ARG, QEMU_OPTION_smp },
6974 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6976 /* temporary options */
6977 { "usb", 0, QEMU_OPTION_usb },
6978 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6979 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6980 { "no-acpi", 0, QEMU_OPTION_no_acpi },
6981 { "no-reboot", 0, QEMU_OPTION_no_reboot },
6982 { "show-cursor", 0, QEMU_OPTION_show_cursor },
6983 { "daemonize", 0, QEMU_OPTION_daemonize },
6984 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6985 #if defined(TARGET_ARM) || defined(TARGET_M68K)
6986 { "semihosting", 0, QEMU_OPTION_semihosting },
6988 { "name", HAS_ARG, QEMU_OPTION_name },
6989 #if defined(TARGET_SPARC)
6990 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
6992 #if defined(TARGET_ARM)
6993 { "old-param", 0, QEMU_OPTION_old_param },
6998 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7000 /* this stack is only used during signal handling */
7001 #define SIGNAL_STACK_SIZE 32768
7003 static uint8_t *signal_stack;
7007 /* password input */
7009 int qemu_key_check(BlockDriverState *bs, const char *name)
7014 if (!bdrv_is_encrypted(bs))
7017 term_printf("%s is encrypted.\n", name);
7018 for(i = 0; i < 3; i++) {
7019 monitor_readline("Password: ", 1, password, sizeof(password));
7020 if (bdrv_set_key(bs, password) == 0)
7022 term_printf("invalid password\n");
7027 static BlockDriverState *get_bdrv(int index)
7029 BlockDriverState *bs;
7032 bs = bs_table[index];
7033 } else if (index < 6) {
7034 bs = fd_table[index - 4];
7041 static void read_passwords(void)
7043 BlockDriverState *bs;
7046 for(i = 0; i < 6; i++) {
7049 qemu_key_check(bs, bdrv_get_device_name(bs));
7053 /* XXX: currently we cannot use simultaneously different CPUs */
7054 void register_machines(void)
7056 #if defined(TARGET_I386)
7057 qemu_register_machine(&pc_machine);
7058 qemu_register_machine(&isapc_machine);
7059 #elif defined(TARGET_PPC)
7060 qemu_register_machine(&heathrow_machine);
7061 qemu_register_machine(&core99_machine);
7062 qemu_register_machine(&prep_machine);
7063 qemu_register_machine(&ref405ep_machine);
7064 qemu_register_machine(&taihu_machine);
7065 #elif defined(TARGET_MIPS)
7066 qemu_register_machine(&mips_machine);
7067 qemu_register_machine(&mips_malta_machine);
7068 qemu_register_machine(&mips_pica61_machine);
7069 #elif defined(TARGET_SPARC)
7070 #ifdef TARGET_SPARC64
7071 qemu_register_machine(&sun4u_machine);
7073 qemu_register_machine(&ss5_machine);
7074 qemu_register_machine(&ss10_machine);
7076 #elif defined(TARGET_ARM)
7077 qemu_register_machine(&integratorcp_machine);
7078 qemu_register_machine(&versatilepb_machine);
7079 qemu_register_machine(&versatileab_machine);
7080 qemu_register_machine(&realview_machine);
7081 qemu_register_machine(&akitapda_machine);
7082 qemu_register_machine(&spitzpda_machine);
7083 qemu_register_machine(&borzoipda_machine);
7084 qemu_register_machine(&terrierpda_machine);
7085 qemu_register_machine(&palmte_machine);
7086 #elif defined(TARGET_SH4)
7087 qemu_register_machine(&shix_machine);
7088 #elif defined(TARGET_ALPHA)
7090 #elif defined(TARGET_M68K)
7091 qemu_register_machine(&mcf5208evb_machine);
7092 qemu_register_machine(&an5206_machine);
7094 #error unsupported CPU
7099 struct soundhw soundhw[] = {
7100 #ifdef HAS_AUDIO_CHOICE
7107 { .init_isa = pcspk_audio_init }
7112 "Creative Sound Blaster 16",
7115 { .init_isa = SB16_init }
7122 "Yamaha YMF262 (OPL3)",
7124 "Yamaha YM3812 (OPL2)",
7128 { .init_isa = Adlib_init }
7135 "Gravis Ultrasound GF1",
7138 { .init_isa = GUS_init }
7144 "ENSONIQ AudioPCI ES1370",
7147 { .init_pci = es1370_init }
7151 { NULL, NULL, 0, 0, { NULL } }
7154 static void select_soundhw (const char *optarg)
7158 if (*optarg == '?') {
7161 printf ("Valid sound card names (comma separated):\n");
7162 for (c = soundhw; c->name; ++c) {
7163 printf ("%-11s %s\n", c->name, c->descr);
7165 printf ("\n-soundhw all will enable all of the above\n");
7166 exit (*optarg != '?');
7174 if (!strcmp (optarg, "all")) {
7175 for (c = soundhw; c->name; ++c) {
7183 e = strchr (p, ',');
7184 l = !e ? strlen (p) : (size_t) (e - p);
7186 for (c = soundhw; c->name; ++c) {
7187 if (!strncmp (c->name, p, l)) {
7196 "Unknown sound card name (too big to show)\n");
7199 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7204 p += l + (e != NULL);
7208 goto show_valid_cards;
7214 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7216 exit(STATUS_CONTROL_C_EXIT);
7221 #define MAX_NET_CLIENTS 32
7223 int main(int argc, char **argv)
7225 #ifdef CONFIG_GDBSTUB
7227 const char *gdbstub_port;
7229 int i, cdrom_index, pflash_index;
7230 int snapshot, linux_boot;
7231 const char *initrd_filename;
7232 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7233 const char *pflash_filename[MAX_PFLASH];
7234 const char *sd_filename;
7235 const char *mtd_filename;
7236 const char *kernel_filename, *kernel_cmdline;
7237 DisplayState *ds = &display_state;
7238 int cyls, heads, secs, translation;
7239 char net_clients[MAX_NET_CLIENTS][256];
7242 const char *r, *optarg;
7243 CharDriverState *monitor_hd;
7244 char monitor_device[128];
7245 char serial_devices[MAX_SERIAL_PORTS][128];
7246 int serial_device_index;
7247 char parallel_devices[MAX_PARALLEL_PORTS][128];
7248 int parallel_device_index;
7249 const char *loadvm = NULL;
7250 QEMUMachine *machine;
7251 const char *cpu_model;
7252 char usb_devices[MAX_USB_CMDLINE][128];
7253 int usb_devices_index;
7255 const char *pid_file = NULL;
7258 LIST_INIT (&vm_change_state_head);
7261 struct sigaction act;
7262 sigfillset(&act.sa_mask);
7264 act.sa_handler = SIG_IGN;
7265 sigaction(SIGPIPE, &act, NULL);
7268 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7269 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7270 QEMU to run on a single CPU */
7275 h = GetCurrentProcess();
7276 if (GetProcessAffinityMask(h, &mask, &smask)) {
7277 for(i = 0; i < 32; i++) {
7278 if (mask & (1 << i))
7283 SetProcessAffinityMask(h, mask);
7289 register_machines();
7290 machine = first_machine;
7292 initrd_filename = NULL;
7293 for(i = 0; i < MAX_FD; i++)
7294 fd_filename[i] = NULL;
7295 for(i = 0; i < MAX_DISKS; i++)
7296 hd_filename[i] = NULL;
7297 for(i = 0; i < MAX_PFLASH; i++)
7298 pflash_filename[i] = NULL;
7301 mtd_filename = NULL;
7302 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7303 vga_ram_size = VGA_RAM_SIZE;
7304 #ifdef CONFIG_GDBSTUB
7306 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7310 kernel_filename = NULL;
7311 kernel_cmdline = "";
7317 cyls = heads = secs = 0;
7318 translation = BIOS_ATA_TRANSLATION_AUTO;
7319 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7321 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7322 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7323 serial_devices[i][0] = '\0';
7324 serial_device_index = 0;
7326 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7327 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7328 parallel_devices[i][0] = '\0';
7329 parallel_device_index = 0;
7331 usb_devices_index = 0;
7336 /* default mac address of the first network interface */
7344 hd_filename[0] = argv[optind++];
7346 const QEMUOption *popt;
7349 /* Treat --foo the same as -foo. */
7352 popt = qemu_options;
7355 fprintf(stderr, "%s: invalid option -- '%s'\n",
7359 if (!strcmp(popt->name, r + 1))
7363 if (popt->flags & HAS_ARG) {
7364 if (optind >= argc) {
7365 fprintf(stderr, "%s: option '%s' requires an argument\n",
7369 optarg = argv[optind++];
7374 switch(popt->index) {
7376 machine = find_machine(optarg);
7379 printf("Supported machines are:\n");
7380 for(m = first_machine; m != NULL; m = m->next) {
7381 printf("%-10s %s%s\n",
7383 m == first_machine ? " (default)" : "");
7385 exit(*optarg != '?');
7388 case QEMU_OPTION_cpu:
7389 /* hw initialization will check this */
7390 if (*optarg == '?') {
7391 #if defined(TARGET_PPC)
7392 ppc_cpu_list(stdout, &fprintf);
7393 #elif defined(TARGET_ARM)
7395 #elif defined(TARGET_MIPS)
7396 mips_cpu_list(stdout, &fprintf);
7397 #elif defined(TARGET_SPARC)
7398 sparc_cpu_list(stdout, &fprintf);
7405 case QEMU_OPTION_initrd:
7406 initrd_filename = optarg;
7408 case QEMU_OPTION_hda:
7409 case QEMU_OPTION_hdb:
7410 case QEMU_OPTION_hdc:
7411 case QEMU_OPTION_hdd:
7414 hd_index = popt->index - QEMU_OPTION_hda;
7415 hd_filename[hd_index] = optarg;
7416 if (hd_index == cdrom_index)
7420 case QEMU_OPTION_mtdblock:
7421 mtd_filename = optarg;
7423 case QEMU_OPTION_sd:
7424 sd_filename = optarg;
7426 case QEMU_OPTION_pflash:
7427 if (pflash_index >= MAX_PFLASH) {
7428 fprintf(stderr, "qemu: too many parallel flash images\n");
7431 pflash_filename[pflash_index++] = optarg;
7433 case QEMU_OPTION_snapshot:
7436 case QEMU_OPTION_hdachs:
7440 cyls = strtol(p, (char **)&p, 0);
7441 if (cyls < 1 || cyls > 16383)
7446 heads = strtol(p, (char **)&p, 0);
7447 if (heads < 1 || heads > 16)
7452 secs = strtol(p, (char **)&p, 0);
7453 if (secs < 1 || secs > 63)
7457 if (!strcmp(p, "none"))
7458 translation = BIOS_ATA_TRANSLATION_NONE;
7459 else if (!strcmp(p, "lba"))
7460 translation = BIOS_ATA_TRANSLATION_LBA;
7461 else if (!strcmp(p, "auto"))
7462 translation = BIOS_ATA_TRANSLATION_AUTO;
7465 } else if (*p != '\0') {
7467 fprintf(stderr, "qemu: invalid physical CHS format\n");
7472 case QEMU_OPTION_nographic:
7473 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7474 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7475 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7478 case QEMU_OPTION_portrait:
7481 case QEMU_OPTION_kernel:
7482 kernel_filename = optarg;
7484 case QEMU_OPTION_append:
7485 kernel_cmdline = optarg;
7487 case QEMU_OPTION_cdrom:
7488 if (cdrom_index >= 0) {
7489 hd_filename[cdrom_index] = optarg;
7492 case QEMU_OPTION_boot:
7493 boot_device = optarg[0];
7494 if (boot_device != 'a' &&
7495 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7497 boot_device != 'n' &&
7499 boot_device != 'c' && boot_device != 'd') {
7500 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7504 case QEMU_OPTION_fda:
7505 fd_filename[0] = optarg;
7507 case QEMU_OPTION_fdb:
7508 fd_filename[1] = optarg;
7511 case QEMU_OPTION_no_fd_bootchk:
7515 case QEMU_OPTION_no_code_copy:
7516 code_copy_enabled = 0;
7518 case QEMU_OPTION_net:
7519 if (nb_net_clients >= MAX_NET_CLIENTS) {
7520 fprintf(stderr, "qemu: too many network clients\n");
7523 pstrcpy(net_clients[nb_net_clients],
7524 sizeof(net_clients[0]),
7529 case QEMU_OPTION_tftp:
7530 tftp_prefix = optarg;
7532 case QEMU_OPTION_bootp:
7533 bootp_filename = optarg;
7536 case QEMU_OPTION_smb:
7537 net_slirp_smb(optarg);
7540 case QEMU_OPTION_redir:
7541 net_slirp_redir(optarg);
7545 case QEMU_OPTION_audio_help:
7549 case QEMU_OPTION_soundhw:
7550 select_soundhw (optarg);
7557 ram_size = atoi(optarg) * 1024 * 1024;
7560 if (ram_size > PHYS_RAM_MAX_SIZE) {
7561 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7562 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7571 mask = cpu_str_to_log_mask(optarg);
7573 printf("Log items (comma separated):\n");
7574 for(item = cpu_log_items; item->mask != 0; item++) {
7575 printf("%-10s %s\n", item->name, item->help);
7582 #ifdef CONFIG_GDBSTUB
7587 gdbstub_port = optarg;
7597 keyboard_layout = optarg;
7599 case QEMU_OPTION_localtime:
7602 case QEMU_OPTION_cirrusvga:
7603 cirrus_vga_enabled = 1;
7606 case QEMU_OPTION_vmsvga:
7607 cirrus_vga_enabled = 0;
7610 case QEMU_OPTION_std_vga:
7611 cirrus_vga_enabled = 0;
7619 w = strtol(p, (char **)&p, 10);
7622 fprintf(stderr, "qemu: invalid resolution or depth\n");
7628 h = strtol(p, (char **)&p, 10);
7633 depth = strtol(p, (char **)&p, 10);
7634 if (depth != 8 && depth != 15 && depth != 16 &&
7635 depth != 24 && depth != 32)
7637 } else if (*p == '\0') {
7638 depth = graphic_depth;
7645 graphic_depth = depth;
7648 case QEMU_OPTION_echr:
7651 term_escape_char = strtol(optarg, &r, 0);
7653 printf("Bad argument to echr\n");
7656 case QEMU_OPTION_monitor:
7657 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7659 case QEMU_OPTION_serial:
7660 if (serial_device_index >= MAX_SERIAL_PORTS) {
7661 fprintf(stderr, "qemu: too many serial ports\n");
7664 pstrcpy(serial_devices[serial_device_index],
7665 sizeof(serial_devices[0]), optarg);
7666 serial_device_index++;
7668 case QEMU_OPTION_parallel:
7669 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7670 fprintf(stderr, "qemu: too many parallel ports\n");
7673 pstrcpy(parallel_devices[parallel_device_index],
7674 sizeof(parallel_devices[0]), optarg);
7675 parallel_device_index++;
7677 case QEMU_OPTION_loadvm:
7680 case QEMU_OPTION_full_screen:
7684 case QEMU_OPTION_no_frame:
7687 case QEMU_OPTION_alt_grab:
7690 case QEMU_OPTION_no_quit:
7694 case QEMU_OPTION_pidfile:
7698 case QEMU_OPTION_win2k_hack:
7699 win2k_install_hack = 1;
7703 case QEMU_OPTION_no_kqemu:
7706 case QEMU_OPTION_kernel_kqemu:
7710 case QEMU_OPTION_usb:
7713 case QEMU_OPTION_usbdevice:
7715 if (usb_devices_index >= MAX_USB_CMDLINE) {
7716 fprintf(stderr, "Too many USB devices\n");
7719 pstrcpy(usb_devices[usb_devices_index],
7720 sizeof(usb_devices[usb_devices_index]),
7722 usb_devices_index++;
7724 case QEMU_OPTION_smp:
7725 smp_cpus = atoi(optarg);
7726 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7727 fprintf(stderr, "Invalid number of CPUs\n");
7731 case QEMU_OPTION_vnc:
7732 vnc_display = optarg;
7734 case QEMU_OPTION_no_acpi:
7737 case QEMU_OPTION_no_reboot:
7740 case QEMU_OPTION_show_cursor:
7743 case QEMU_OPTION_daemonize:
7746 case QEMU_OPTION_option_rom:
7747 if (nb_option_roms >= MAX_OPTION_ROMS) {
7748 fprintf(stderr, "Too many option ROMs\n");
7751 option_rom[nb_option_roms] = optarg;
7754 case QEMU_OPTION_semihosting:
7755 semihosting_enabled = 1;
7757 case QEMU_OPTION_name:
7761 case QEMU_OPTION_prom_env:
7762 if (nb_prom_envs >= MAX_PROM_ENVS) {
7763 fprintf(stderr, "Too many prom variables\n");
7766 prom_envs[nb_prom_envs] = optarg;
7771 case QEMU_OPTION_old_param:
7779 if (daemonize && !nographic && vnc_display == NULL) {
7780 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7787 if (pipe(fds) == -1)
7798 len = read(fds[0], &status, 1);
7799 if (len == -1 && (errno == EINTR))
7804 else if (status == 1) {
7805 fprintf(stderr, "Could not acquire pidfile\n");
7823 signal(SIGTSTP, SIG_IGN);
7824 signal(SIGTTOU, SIG_IGN);
7825 signal(SIGTTIN, SIG_IGN);
7829 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7832 write(fds[1], &status, 1);
7834 fprintf(stderr, "Could not acquire pid file\n");
7842 linux_boot = (kernel_filename != NULL);
7845 boot_device != 'n' &&
7846 hd_filename[0] == '\0' &&
7847 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7848 fd_filename[0] == '\0')
7851 /* boot to floppy or the default cd if no hard disk defined yet */
7852 if (hd_filename[0] == '\0' && boot_device == 'c') {
7853 if (fd_filename[0] != '\0')
7859 setvbuf(stdout, NULL, _IOLBF, 0);
7869 /* init network clients */
7870 if (nb_net_clients == 0) {
7871 /* if no clients, we use a default config */
7872 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7874 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7879 for(i = 0;i < nb_net_clients; i++) {
7880 if (net_client_init(net_clients[i]) < 0)
7883 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7884 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7886 if (vlan->nb_guest_devs == 0) {
7887 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7890 if (vlan->nb_host_devs == 0)
7892 "Warning: vlan %d is not connected to host network\n",
7897 if (boot_device == 'n') {
7898 for (i = 0; i < nb_nics; i++) {
7899 const char *model = nd_table[i].model;
7903 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7904 if (get_image_size(buf) > 0) {
7905 option_rom[nb_option_roms] = strdup(buf);
7911 fprintf(stderr, "No valid PXE rom found for network device\n");
7914 boot_device = 'c'; /* to prevent confusion by the BIOS */
7918 /* init the memory */
7919 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7921 phys_ram_base = qemu_vmalloc(phys_ram_size);
7922 if (!phys_ram_base) {
7923 fprintf(stderr, "Could not allocate physical memory\n");
7927 /* we always create the cdrom drive, even if no disk is there */
7929 if (cdrom_index >= 0) {
7930 bs_table[cdrom_index] = bdrv_new("cdrom");
7931 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7934 /* open the virtual block devices */
7935 for(i = 0; i < MAX_DISKS; i++) {
7936 if (hd_filename[i]) {
7939 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7940 bs_table[i] = bdrv_new(buf);
7942 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7943 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7947 if (i == 0 && cyls != 0) {
7948 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7949 bdrv_set_translation_hint(bs_table[i], translation);
7954 /* we always create at least one floppy disk */
7955 fd_table[0] = bdrv_new("fda");
7956 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7958 for(i = 0; i < MAX_FD; i++) {
7959 if (fd_filename[i]) {
7962 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7963 fd_table[i] = bdrv_new(buf);
7964 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7966 if (fd_filename[i][0] != '\0') {
7967 if (bdrv_open(fd_table[i], fd_filename[i],
7968 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7969 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7977 /* Open the virtual parallel flash block devices */
7978 for(i = 0; i < MAX_PFLASH; i++) {
7979 if (pflash_filename[i]) {
7980 if (!pflash_table[i]) {
7982 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7983 pflash_table[i] = bdrv_new(buf);
7985 if (bdrv_open(pflash_table[i], pflash_filename[i],
7986 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7987 fprintf(stderr, "qemu: could not open flash image '%s'\n",
7988 pflash_filename[i]);
7994 sd_bdrv = bdrv_new ("sd");
7995 /* FIXME: This isn't really a floppy, but it's a reasonable
7997 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7999 if (bdrv_open(sd_bdrv, sd_filename,
8000 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8001 fprintf(stderr, "qemu: could not open SD card image %s\n",
8004 qemu_key_check(sd_bdrv, sd_filename);
8008 mtd_bdrv = bdrv_new ("mtd");
8009 if (bdrv_open(mtd_bdrv, mtd_filename,
8010 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8011 qemu_key_check(mtd_bdrv, mtd_filename)) {
8012 fprintf(stderr, "qemu: could not open Flash image %s\n",
8014 bdrv_delete(mtd_bdrv);
8019 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8020 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8025 memset(&display_state, 0, sizeof(display_state));
8027 /* nearly nothing to do */
8028 dumb_display_init(ds);
8029 } else if (vnc_display != NULL) {
8030 vnc_display_init(ds, vnc_display);
8032 #if defined(CONFIG_SDL)
8033 sdl_display_init(ds, full_screen, no_frame);
8034 #elif defined(CONFIG_COCOA)
8035 cocoa_display_init(ds, full_screen);
8039 /* Maintain compatibility with multiple stdio monitors */
8040 if (!strcmp(monitor_device,"stdio")) {
8041 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8042 if (!strcmp(serial_devices[i],"mon:stdio")) {
8043 monitor_device[0] = '\0';
8045 } else if (!strcmp(serial_devices[i],"stdio")) {
8046 monitor_device[0] = '\0';
8047 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8052 if (monitor_device[0] != '\0') {
8053 monitor_hd = qemu_chr_open(monitor_device);
8055 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8058 monitor_init(monitor_hd, !nographic);
8061 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8062 const char *devname = serial_devices[i];
8063 if (devname[0] != '\0' && strcmp(devname, "none")) {
8064 serial_hds[i] = qemu_chr_open(devname);
8065 if (!serial_hds[i]) {
8066 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8070 if (strstart(devname, "vc", 0))
8071 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8075 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8076 const char *devname = parallel_devices[i];
8077 if (devname[0] != '\0' && strcmp(devname, "none")) {
8078 parallel_hds[i] = qemu_chr_open(devname);
8079 if (!parallel_hds[i]) {
8080 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8084 if (strstart(devname, "vc", 0))
8085 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8089 machine->init(ram_size, vga_ram_size, boot_device,
8090 ds, fd_filename, snapshot,
8091 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8093 /* init USB devices */
8095 for(i = 0; i < usb_devices_index; i++) {
8096 if (usb_device_add(usb_devices[i]) < 0) {
8097 fprintf(stderr, "Warning: could not add USB device %s\n",
8103 if (display_state.dpy_refresh) {
8104 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8105 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8108 #ifdef CONFIG_GDBSTUB
8110 /* XXX: use standard host:port notation and modify options
8112 if (gdbserver_start(gdbstub_port) < 0) {
8113 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8124 /* XXX: simplify init */
8137 len = write(fds[1], &status, 1);
8138 if (len == -1 && (errno == EINTR))
8144 TFR(fd = open("/dev/null", O_RDWR));