4 * Copyright (c) 2003-2008 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
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
29 #include "hw/audiodev.h"
36 #include "qemu-timer.h"
37 #include "qemu-char.h"
39 #include "audio/audio.h"
50 #include <sys/times.h>
55 #include <sys/ioctl.h>
56 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <sys/select.h>
61 #include <arpa/inet.h>
67 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
68 #include <freebsd/stdlib.h>
72 #include <linux/if_tun.h>
75 #include <linux/rtc.h>
77 /* For the benefit of older linux systems which don't supply it,
78 we use a local copy of hpet.h. */
79 /* #include <linux/hpet.h> */
82 #include <linux/ppdev.h>
83 #include <linux/parport.h>
86 #include <sys/ethernet.h>
87 #include <sys/sockio.h>
88 #include <netinet/arp.h>
89 #include <netinet/in.h>
90 #include <netinet/in_systm.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_icmp.h> // must come after ip.h
93 #include <netinet/udp.h>
94 #include <netinet/tcp.h>
101 #include <winsock2.h>
102 int inet_aton(const char *cp, struct in_addr *ia);
105 #if defined(CONFIG_SLIRP)
106 #include "libslirp.h"
111 #include <sys/timeb.h>
112 #include <mmsystem.h>
113 #define getopt_long_only getopt_long
114 #define memalign(align, size) malloc(size)
117 #include "qemu_socket.h"
123 #endif /* CONFIG_SDL */
127 #define main qemu_main
128 #endif /* CONFIG_COCOA */
132 #include "exec-all.h"
134 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135 #define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
137 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
139 #define SMBD_COMMAND "/usr/sbin/smbd"
142 //#define DEBUG_UNUSED_IOPORT
143 //#define DEBUG_IOPORT
145 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
148 #define DEFAULT_RAM_SIZE 144
150 #define DEFAULT_RAM_SIZE 128
153 #define GUI_REFRESH_INTERVAL 30
155 /* Max number of USB devices that can be specified on the commandline. */
156 #define MAX_USB_CMDLINE 8
158 /* XXX: use a two level table to limit memory usage */
159 #define MAX_IOPORTS 65536
161 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162 const char *bios_name = NULL;
163 void *ioport_opaque[MAX_IOPORTS];
164 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
167 to store the VM snapshots */
168 DriveInfo drives_table[MAX_DRIVES+1];
170 /* point to the block driver where the snapshots are managed */
171 BlockDriverState *bs_snapshots;
173 static DisplayState display_state;
176 const char* keyboard_layout = NULL;
177 int64_t ticks_per_sec;
179 int pit_min_timer_count = 0;
181 NICInfo nd_table[MAX_NICS];
183 static int rtc_utc = 1;
184 static int rtc_date_offset = -1; /* -1 means no change */
185 int cirrus_vga_enabled = 1;
186 int vmsvga_enabled = 0;
188 int graphic_width = 1024;
189 int graphic_height = 768;
190 int graphic_depth = 8;
192 int graphic_width = 800;
193 int graphic_height = 600;
194 int graphic_depth = 15;
199 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
200 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
202 int win2k_install_hack = 0;
205 static VLANState *first_vlan;
207 const char *vnc_display;
208 #if defined(TARGET_SPARC)
210 #elif defined(TARGET_I386)
215 int acpi_enabled = 1;
220 int graphic_rotate = 0;
222 const char *option_rom[MAX_OPTION_ROMS];
224 int semihosting_enabled = 0;
229 const char *qemu_name;
232 unsigned int nb_prom_envs = 0;
233 const char *prom_envs[MAX_PROM_ENVS];
239 } drives_opt[MAX_DRIVES];
241 static CPUState *cur_cpu;
242 static CPUState *next_cpu;
243 static int event_pending = 1;
245 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
247 /***********************************************************/
248 /* x86 ISA bus support */
250 target_phys_addr_t isa_mem_base = 0;
253 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
255 #ifdef DEBUG_UNUSED_IOPORT
256 fprintf(stderr, "unused inb: port=0x%04x\n", address);
261 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
263 #ifdef DEBUG_UNUSED_IOPORT
264 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
268 /* default is to make two byte accesses */
269 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
272 data = ioport_read_table[0][address](ioport_opaque[address], address);
273 address = (address + 1) & (MAX_IOPORTS - 1);
274 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
278 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
280 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
281 address = (address + 1) & (MAX_IOPORTS - 1);
282 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
285 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
287 #ifdef DEBUG_UNUSED_IOPORT
288 fprintf(stderr, "unused inl: port=0x%04x\n", address);
293 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
295 #ifdef DEBUG_UNUSED_IOPORT
296 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
300 static void init_ioports(void)
304 for(i = 0; i < MAX_IOPORTS; i++) {
305 ioport_read_table[0][i] = default_ioport_readb;
306 ioport_write_table[0][i] = default_ioport_writeb;
307 ioport_read_table[1][i] = default_ioport_readw;
308 ioport_write_table[1][i] = default_ioport_writew;
309 ioport_read_table[2][i] = default_ioport_readl;
310 ioport_write_table[2][i] = default_ioport_writel;
314 /* size is the word size in byte */
315 int register_ioport_read(int start, int length, int size,
316 IOPortReadFunc *func, void *opaque)
322 } else if (size == 2) {
324 } else if (size == 4) {
327 hw_error("register_ioport_read: invalid size");
330 for(i = start; i < start + length; i += size) {
331 ioport_read_table[bsize][i] = func;
332 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
333 hw_error("register_ioport_read: invalid opaque");
334 ioport_opaque[i] = opaque;
339 /* size is the word size in byte */
340 int register_ioport_write(int start, int length, int size,
341 IOPortWriteFunc *func, void *opaque)
347 } else if (size == 2) {
349 } else if (size == 4) {
352 hw_error("register_ioport_write: invalid size");
355 for(i = start; i < start + length; i += size) {
356 ioport_write_table[bsize][i] = func;
357 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
358 hw_error("register_ioport_write: invalid opaque");
359 ioport_opaque[i] = opaque;
364 void isa_unassign_ioport(int start, int length)
368 for(i = start; i < start + length; i++) {
369 ioport_read_table[0][i] = default_ioport_readb;
370 ioport_read_table[1][i] = default_ioport_readw;
371 ioport_read_table[2][i] = default_ioport_readl;
373 ioport_write_table[0][i] = default_ioport_writeb;
374 ioport_write_table[1][i] = default_ioport_writew;
375 ioport_write_table[2][i] = default_ioport_writel;
379 /***********************************************************/
381 void cpu_outb(CPUState *env, int addr, int val)
384 if (loglevel & CPU_LOG_IOPORT)
385 fprintf(logfile, "outb: %04x %02x\n", addr, val);
387 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
390 env->last_io_time = cpu_get_time_fast();
394 void cpu_outw(CPUState *env, int addr, int val)
397 if (loglevel & CPU_LOG_IOPORT)
398 fprintf(logfile, "outw: %04x %04x\n", addr, val);
400 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
403 env->last_io_time = cpu_get_time_fast();
407 void cpu_outl(CPUState *env, int addr, int val)
410 if (loglevel & CPU_LOG_IOPORT)
411 fprintf(logfile, "outl: %04x %08x\n", addr, val);
413 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
416 env->last_io_time = cpu_get_time_fast();
420 int cpu_inb(CPUState *env, int addr)
423 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
425 if (loglevel & CPU_LOG_IOPORT)
426 fprintf(logfile, "inb : %04x %02x\n", addr, val);
430 env->last_io_time = cpu_get_time_fast();
435 int cpu_inw(CPUState *env, int addr)
438 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
440 if (loglevel & CPU_LOG_IOPORT)
441 fprintf(logfile, "inw : %04x %04x\n", addr, val);
445 env->last_io_time = cpu_get_time_fast();
450 int cpu_inl(CPUState *env, int addr)
453 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
455 if (loglevel & CPU_LOG_IOPORT)
456 fprintf(logfile, "inl : %04x %08x\n", addr, val);
460 env->last_io_time = cpu_get_time_fast();
465 /***********************************************************/
466 void hw_error(const char *fmt, ...)
472 fprintf(stderr, "qemu: hardware error: ");
473 vfprintf(stderr, fmt, ap);
474 fprintf(stderr, "\n");
475 for(env = first_cpu; env != NULL; env = env->next_cpu) {
476 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
478 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
480 cpu_dump_state(env, stderr, fprintf, 0);
487 /***********************************************************/
490 static QEMUPutKBDEvent *qemu_put_kbd_event;
491 static void *qemu_put_kbd_event_opaque;
492 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
493 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
495 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
497 qemu_put_kbd_event_opaque = opaque;
498 qemu_put_kbd_event = func;
501 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
502 void *opaque, int absolute,
505 QEMUPutMouseEntry *s, *cursor;
507 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
511 s->qemu_put_mouse_event = func;
512 s->qemu_put_mouse_event_opaque = opaque;
513 s->qemu_put_mouse_event_absolute = absolute;
514 s->qemu_put_mouse_event_name = qemu_strdup(name);
517 if (!qemu_put_mouse_event_head) {
518 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
522 cursor = qemu_put_mouse_event_head;
523 while (cursor->next != NULL)
524 cursor = cursor->next;
527 qemu_put_mouse_event_current = s;
532 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
534 QEMUPutMouseEntry *prev = NULL, *cursor;
536 if (!qemu_put_mouse_event_head || entry == NULL)
539 cursor = qemu_put_mouse_event_head;
540 while (cursor != NULL && cursor != entry) {
542 cursor = cursor->next;
545 if (cursor == NULL) // does not exist or list empty
547 else if (prev == NULL) { // entry is head
548 qemu_put_mouse_event_head = cursor->next;
549 if (qemu_put_mouse_event_current == entry)
550 qemu_put_mouse_event_current = cursor->next;
551 qemu_free(entry->qemu_put_mouse_event_name);
556 prev->next = entry->next;
558 if (qemu_put_mouse_event_current == entry)
559 qemu_put_mouse_event_current = prev;
561 qemu_free(entry->qemu_put_mouse_event_name);
565 void kbd_put_keycode(int keycode)
567 if (qemu_put_kbd_event) {
568 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
572 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
574 QEMUPutMouseEvent *mouse_event;
575 void *mouse_event_opaque;
578 if (!qemu_put_mouse_event_current) {
583 qemu_put_mouse_event_current->qemu_put_mouse_event;
585 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
588 if (graphic_rotate) {
589 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
592 width = graphic_width - 1;
593 mouse_event(mouse_event_opaque,
594 width - dy, dx, dz, buttons_state);
596 mouse_event(mouse_event_opaque,
597 dx, dy, dz, buttons_state);
601 int kbd_mouse_is_absolute(void)
603 if (!qemu_put_mouse_event_current)
606 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
609 void do_info_mice(void)
611 QEMUPutMouseEntry *cursor;
614 if (!qemu_put_mouse_event_head) {
615 term_printf("No mouse devices connected\n");
619 term_printf("Mouse devices available:\n");
620 cursor = qemu_put_mouse_event_head;
621 while (cursor != NULL) {
622 term_printf("%c Mouse #%d: %s\n",
623 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
624 index, cursor->qemu_put_mouse_event_name);
626 cursor = cursor->next;
630 void do_mouse_set(int index)
632 QEMUPutMouseEntry *cursor;
635 if (!qemu_put_mouse_event_head) {
636 term_printf("No mouse devices connected\n");
640 cursor = qemu_put_mouse_event_head;
641 while (cursor != NULL && index != i) {
643 cursor = cursor->next;
647 qemu_put_mouse_event_current = cursor;
649 term_printf("Mouse at given index not found\n");
652 /* compute with 96 bit intermediate result: (a*b)/c */
653 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
658 #ifdef WORDS_BIGENDIAN
668 rl = (uint64_t)u.l.low * (uint64_t)b;
669 rh = (uint64_t)u.l.high * (uint64_t)b;
672 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
676 /***********************************************************/
677 /* real time host monotonic timer */
679 #define QEMU_TIMER_BASE 1000000000LL
683 static int64_t clock_freq;
685 static void init_get_clock(void)
689 ret = QueryPerformanceFrequency(&freq);
691 fprintf(stderr, "Could not calibrate ticks\n");
694 clock_freq = freq.QuadPart;
697 static int64_t get_clock(void)
700 QueryPerformanceCounter(&ti);
701 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
706 static int use_rt_clock;
708 static void init_get_clock(void)
711 #if defined(__linux__)
714 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
721 static int64_t get_clock(void)
723 #if defined(__linux__)
726 clock_gettime(CLOCK_MONOTONIC, &ts);
727 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
731 /* XXX: using gettimeofday leads to problems if the date
732 changes, so it should be avoided. */
734 gettimeofday(&tv, NULL);
735 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
741 /***********************************************************/
742 /* guest cycle counter */
744 static int64_t cpu_ticks_prev;
745 static int64_t cpu_ticks_offset;
746 static int64_t cpu_clock_offset;
747 static int cpu_ticks_enabled;
749 /* return the host CPU cycle counter and handle stop/restart */
750 int64_t cpu_get_ticks(void)
752 if (!cpu_ticks_enabled) {
753 return cpu_ticks_offset;
756 ticks = cpu_get_real_ticks();
757 if (cpu_ticks_prev > ticks) {
758 /* Note: non increasing ticks may happen if the host uses
760 cpu_ticks_offset += cpu_ticks_prev - ticks;
762 cpu_ticks_prev = ticks;
763 return ticks + cpu_ticks_offset;
767 /* return the host CPU monotonic timer and handle stop/restart */
768 static int64_t cpu_get_clock(void)
771 if (!cpu_ticks_enabled) {
772 return cpu_clock_offset;
775 return ti + cpu_clock_offset;
779 /* enable cpu_get_ticks() */
780 void cpu_enable_ticks(void)
782 if (!cpu_ticks_enabled) {
783 cpu_ticks_offset -= cpu_get_real_ticks();
784 cpu_clock_offset -= get_clock();
785 cpu_ticks_enabled = 1;
789 /* disable cpu_get_ticks() : the clock is stopped. You must not call
790 cpu_get_ticks() after that. */
791 void cpu_disable_ticks(void)
793 if (cpu_ticks_enabled) {
794 cpu_ticks_offset = cpu_get_ticks();
795 cpu_clock_offset = cpu_get_clock();
796 cpu_ticks_enabled = 0;
800 /***********************************************************/
803 #define QEMU_TIMER_REALTIME 0
804 #define QEMU_TIMER_VIRTUAL 1
808 /* XXX: add frequency */
816 struct QEMUTimer *next;
819 struct qemu_alarm_timer {
823 int (*start)(struct qemu_alarm_timer *t);
824 void (*stop)(struct qemu_alarm_timer *t);
825 void (*rearm)(struct qemu_alarm_timer *t);
829 #define ALARM_FLAG_DYNTICKS 0x1
830 #define ALARM_FLAG_EXPIRED 0x2
832 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
834 return t->flags & ALARM_FLAG_DYNTICKS;
837 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
839 if (!alarm_has_dynticks(t))
845 /* TODO: MIN_TIMER_REARM_US should be optimized */
846 #define MIN_TIMER_REARM_US 250
848 static struct qemu_alarm_timer *alarm_timer;
852 struct qemu_alarm_win32 {
856 } alarm_win32_data = {0, NULL, -1};
858 static int win32_start_timer(struct qemu_alarm_timer *t);
859 static void win32_stop_timer(struct qemu_alarm_timer *t);
860 static void win32_rearm_timer(struct qemu_alarm_timer *t);
864 static int unix_start_timer(struct qemu_alarm_timer *t);
865 static void unix_stop_timer(struct qemu_alarm_timer *t);
869 static int dynticks_start_timer(struct qemu_alarm_timer *t);
870 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
871 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
873 static int hpet_start_timer(struct qemu_alarm_timer *t);
874 static void hpet_stop_timer(struct qemu_alarm_timer *t);
876 static int rtc_start_timer(struct qemu_alarm_timer *t);
877 static void rtc_stop_timer(struct qemu_alarm_timer *t);
879 #endif /* __linux__ */
883 static struct qemu_alarm_timer alarm_timers[] = {
886 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
887 dynticks_stop_timer, dynticks_rearm_timer, NULL},
888 /* HPET - if available - is preferred */
889 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
890 /* ...otherwise try RTC */
891 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
893 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
895 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
896 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
897 {"win32", 0, win32_start_timer,
898 win32_stop_timer, NULL, &alarm_win32_data},
903 static void show_available_alarms(void)
907 printf("Available alarm timers, in order of precedence:\n");
908 for (i = 0; alarm_timers[i].name; i++)
909 printf("%s\n", alarm_timers[i].name);
912 static void configure_alarms(char const *opt)
916 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
920 if (!strcmp(opt, "?")) {
921 show_available_alarms();
927 /* Reorder the array */
928 name = strtok(arg, ",");
930 struct qemu_alarm_timer tmp;
932 for (i = 0; i < count && alarm_timers[i].name; i++) {
933 if (!strcmp(alarm_timers[i].name, name))
938 fprintf(stderr, "Unknown clock %s\n", name);
947 tmp = alarm_timers[i];
948 alarm_timers[i] = alarm_timers[cur];
949 alarm_timers[cur] = tmp;
953 name = strtok(NULL, ",");
959 /* Disable remaining timers */
960 for (i = cur; i < count; i++)
961 alarm_timers[i].name = NULL;
963 show_available_alarms();
971 static QEMUTimer *active_timers[2];
973 static QEMUClock *qemu_new_clock(int type)
976 clock = qemu_mallocz(sizeof(QEMUClock));
983 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
987 ts = qemu_mallocz(sizeof(QEMUTimer));
994 void qemu_free_timer(QEMUTimer *ts)
999 /* stop a timer, but do not dealloc it */
1000 void qemu_del_timer(QEMUTimer *ts)
1004 /* NOTE: this code must be signal safe because
1005 qemu_timer_expired() can be called from a signal. */
1006 pt = &active_timers[ts->clock->type];
1019 /* modify the current timer so that it will be fired when current_time
1020 >= expire_time. The corresponding callback will be called. */
1021 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1027 /* add the timer in the sorted list */
1028 /* NOTE: this code must be signal safe because
1029 qemu_timer_expired() can be called from a signal. */
1030 pt = &active_timers[ts->clock->type];
1035 if (t->expire_time > expire_time)
1039 ts->expire_time = expire_time;
1043 /* Rearm if necessary */
1044 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1045 pt == &active_timers[ts->clock->type])
1046 qemu_rearm_alarm_timer(alarm_timer);
1049 int qemu_timer_pending(QEMUTimer *ts)
1052 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1059 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1063 return (timer_head->expire_time <= current_time);
1066 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1072 if (!ts || ts->expire_time > current_time)
1074 /* remove timer from the list before calling the callback */
1075 *ptimer_head = ts->next;
1078 /* run the callback (the timer list can be modified) */
1083 int64_t qemu_get_clock(QEMUClock *clock)
1085 switch(clock->type) {
1086 case QEMU_TIMER_REALTIME:
1087 return get_clock() / 1000000;
1089 case QEMU_TIMER_VIRTUAL:
1090 return cpu_get_clock();
1094 static void init_timers(void)
1097 ticks_per_sec = QEMU_TIMER_BASE;
1098 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1099 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1103 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1105 uint64_t expire_time;
1107 if (qemu_timer_pending(ts)) {
1108 expire_time = ts->expire_time;
1112 qemu_put_be64(f, expire_time);
1115 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1117 uint64_t expire_time;
1119 expire_time = qemu_get_be64(f);
1120 if (expire_time != -1) {
1121 qemu_mod_timer(ts, expire_time);
1127 static void timer_save(QEMUFile *f, void *opaque)
1129 if (cpu_ticks_enabled) {
1130 hw_error("cannot save state if virtual timers are running");
1132 qemu_put_be64(f, cpu_ticks_offset);
1133 qemu_put_be64(f, ticks_per_sec);
1134 qemu_put_be64(f, cpu_clock_offset);
1137 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1139 if (version_id != 1 && version_id != 2)
1141 if (cpu_ticks_enabled) {
1144 cpu_ticks_offset=qemu_get_be64(f);
1145 ticks_per_sec=qemu_get_be64(f);
1146 if (version_id == 2) {
1147 cpu_clock_offset=qemu_get_be64(f);
1153 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1154 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1156 static void host_alarm_handler(int host_signum)
1160 #define DISP_FREQ 1000
1162 static int64_t delta_min = INT64_MAX;
1163 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1165 ti = qemu_get_clock(vm_clock);
1166 if (last_clock != 0) {
1167 delta = ti - last_clock;
1168 if (delta < delta_min)
1170 if (delta > delta_max)
1173 if (++count == DISP_FREQ) {
1174 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1175 muldiv64(delta_min, 1000000, ticks_per_sec),
1176 muldiv64(delta_max, 1000000, ticks_per_sec),
1177 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1178 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1180 delta_min = INT64_MAX;
1188 if (alarm_has_dynticks(alarm_timer) ||
1189 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1190 qemu_get_clock(vm_clock)) ||
1191 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1192 qemu_get_clock(rt_clock))) {
1194 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1195 SetEvent(data->host_alarm);
1197 CPUState *env = next_cpu;
1199 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1202 /* stop the currently executing cpu because a timer occured */
1203 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1205 if (env->kqemu_enabled) {
1206 kqemu_cpu_interrupt(env);
1214 static uint64_t qemu_next_deadline(void)
1216 int64_t nearest_delta_us = INT64_MAX;
1219 if (active_timers[QEMU_TIMER_REALTIME])
1220 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1221 qemu_get_clock(rt_clock))*1000;
1223 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1225 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1226 qemu_get_clock(vm_clock)+999)/1000;
1227 if (vmdelta_us < nearest_delta_us)
1228 nearest_delta_us = vmdelta_us;
1231 /* Avoid arming the timer to negative, zero, or too low values */
1232 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1233 nearest_delta_us = MIN_TIMER_REARM_US;
1235 return nearest_delta_us;
1240 #if defined(__linux__)
1242 #define RTC_FREQ 1024
1244 static void enable_sigio_timer(int fd)
1246 struct sigaction act;
1249 sigfillset(&act.sa_mask);
1251 act.sa_handler = host_alarm_handler;
1253 sigaction(SIGIO, &act, NULL);
1254 fcntl(fd, F_SETFL, O_ASYNC);
1255 fcntl(fd, F_SETOWN, getpid());
1258 static int hpet_start_timer(struct qemu_alarm_timer *t)
1260 struct hpet_info info;
1263 fd = open("/dev/hpet", O_RDONLY);
1268 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1270 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1271 "error, but for better emulation accuracy type:\n"
1272 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1276 /* Check capabilities */
1277 r = ioctl(fd, HPET_INFO, &info);
1281 /* Enable periodic mode */
1282 r = ioctl(fd, HPET_EPI, 0);
1283 if (info.hi_flags && (r < 0))
1286 /* Enable interrupt */
1287 r = ioctl(fd, HPET_IE_ON, 0);
1291 enable_sigio_timer(fd);
1292 t->priv = (void *)(long)fd;
1300 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1302 int fd = (long)t->priv;
1307 static int rtc_start_timer(struct qemu_alarm_timer *t)
1310 unsigned long current_rtc_freq = 0;
1312 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1315 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1316 if (current_rtc_freq != RTC_FREQ &&
1317 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1318 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1319 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1320 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1323 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1329 enable_sigio_timer(rtc_fd);
1331 t->priv = (void *)(long)rtc_fd;
1336 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1338 int rtc_fd = (long)t->priv;
1343 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1347 struct sigaction act;
1349 sigfillset(&act.sa_mask);
1351 act.sa_handler = host_alarm_handler;
1353 sigaction(SIGALRM, &act, NULL);
1355 ev.sigev_value.sival_int = 0;
1356 ev.sigev_notify = SIGEV_SIGNAL;
1357 ev.sigev_signo = SIGALRM;
1359 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1360 perror("timer_create");
1362 /* disable dynticks */
1363 fprintf(stderr, "Dynamic Ticks disabled\n");
1368 t->priv = (void *)host_timer;
1373 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1375 timer_t host_timer = (timer_t)t->priv;
1377 timer_delete(host_timer);
1380 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1382 timer_t host_timer = (timer_t)t->priv;
1383 struct itimerspec timeout;
1384 int64_t nearest_delta_us = INT64_MAX;
1387 if (!active_timers[QEMU_TIMER_REALTIME] &&
1388 !active_timers[QEMU_TIMER_VIRTUAL])
1391 nearest_delta_us = qemu_next_deadline();
1393 /* check whether a timer is already running */
1394 if (timer_gettime(host_timer, &timeout)) {
1396 fprintf(stderr, "Internal timer error: aborting\n");
1399 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1400 if (current_us && current_us <= nearest_delta_us)
1403 timeout.it_interval.tv_sec = 0;
1404 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1405 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1406 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1407 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1409 fprintf(stderr, "Internal timer error: aborting\n");
1414 #endif /* defined(__linux__) */
1416 static int unix_start_timer(struct qemu_alarm_timer *t)
1418 struct sigaction act;
1419 struct itimerval itv;
1423 sigfillset(&act.sa_mask);
1425 act.sa_handler = host_alarm_handler;
1427 sigaction(SIGALRM, &act, NULL);
1429 itv.it_interval.tv_sec = 0;
1430 /* for i386 kernel 2.6 to get 1 ms */
1431 itv.it_interval.tv_usec = 999;
1432 itv.it_value.tv_sec = 0;
1433 itv.it_value.tv_usec = 10 * 1000;
1435 err = setitimer(ITIMER_REAL, &itv, NULL);
1442 static void unix_stop_timer(struct qemu_alarm_timer *t)
1444 struct itimerval itv;
1446 memset(&itv, 0, sizeof(itv));
1447 setitimer(ITIMER_REAL, &itv, NULL);
1450 #endif /* !defined(_WIN32) */
1454 static int win32_start_timer(struct qemu_alarm_timer *t)
1457 struct qemu_alarm_win32 *data = t->priv;
1460 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1461 if (!data->host_alarm) {
1462 perror("Failed CreateEvent");
1466 memset(&tc, 0, sizeof(tc));
1467 timeGetDevCaps(&tc, sizeof(tc));
1469 if (data->period < tc.wPeriodMin)
1470 data->period = tc.wPeriodMin;
1472 timeBeginPeriod(data->period);
1474 flags = TIME_CALLBACK_FUNCTION;
1475 if (alarm_has_dynticks(t))
1476 flags |= TIME_ONESHOT;
1478 flags |= TIME_PERIODIC;
1480 data->timerId = timeSetEvent(1, // interval (ms)
1481 data->period, // resolution
1482 host_alarm_handler, // function
1483 (DWORD)t, // parameter
1486 if (!data->timerId) {
1487 perror("Failed to initialize win32 alarm timer");
1489 timeEndPeriod(data->period);
1490 CloseHandle(data->host_alarm);
1494 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1499 static void win32_stop_timer(struct qemu_alarm_timer *t)
1501 struct qemu_alarm_win32 *data = t->priv;
1503 timeKillEvent(data->timerId);
1504 timeEndPeriod(data->period);
1506 CloseHandle(data->host_alarm);
1509 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1511 struct qemu_alarm_win32 *data = t->priv;
1512 uint64_t nearest_delta_us;
1514 if (!active_timers[QEMU_TIMER_REALTIME] &&
1515 !active_timers[QEMU_TIMER_VIRTUAL])
1518 nearest_delta_us = qemu_next_deadline();
1519 nearest_delta_us /= 1000;
1521 timeKillEvent(data->timerId);
1523 data->timerId = timeSetEvent(1,
1527 TIME_ONESHOT | TIME_PERIODIC);
1529 if (!data->timerId) {
1530 perror("Failed to re-arm win32 alarm timer");
1532 timeEndPeriod(data->period);
1533 CloseHandle(data->host_alarm);
1540 static void init_timer_alarm(void)
1542 struct qemu_alarm_timer *t;
1545 for (i = 0; alarm_timers[i].name; i++) {
1546 t = &alarm_timers[i];
1554 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1555 fprintf(stderr, "Terminating\n");
1562 static void quit_timers(void)
1564 alarm_timer->stop(alarm_timer);
1568 /***********************************************************/
1569 /* host time/date access */
1570 void qemu_get_timedate(struct tm *tm, int offset)
1577 if (rtc_date_offset == -1) {
1581 ret = localtime(&ti);
1583 ti -= rtc_date_offset;
1587 memcpy(tm, ret, sizeof(struct tm));
1590 int qemu_timedate_diff(struct tm *tm)
1594 if (rtc_date_offset == -1)
1596 seconds = mktimegm(tm);
1598 seconds = mktime(tm);
1600 seconds = mktimegm(tm) + rtc_date_offset;
1602 return seconds - time(NULL);
1605 /***********************************************************/
1606 /* character device */
1608 static void qemu_chr_event(CharDriverState *s, int event)
1612 s->chr_event(s->handler_opaque, event);
1615 static void qemu_chr_reset_bh(void *opaque)
1617 CharDriverState *s = opaque;
1618 qemu_chr_event(s, CHR_EVENT_RESET);
1619 qemu_bh_delete(s->bh);
1623 void qemu_chr_reset(CharDriverState *s)
1625 if (s->bh == NULL) {
1626 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1627 qemu_bh_schedule(s->bh);
1631 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1633 return s->chr_write(s, buf, len);
1636 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1640 return s->chr_ioctl(s, cmd, arg);
1643 int qemu_chr_can_read(CharDriverState *s)
1645 if (!s->chr_can_read)
1647 return s->chr_can_read(s->handler_opaque);
1650 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1652 s->chr_read(s->handler_opaque, buf, len);
1655 void qemu_chr_accept_input(CharDriverState *s)
1657 if (s->chr_accept_input)
1658 s->chr_accept_input(s);
1661 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1666 vsnprintf(buf, sizeof(buf), fmt, ap);
1667 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1671 void qemu_chr_send_event(CharDriverState *s, int event)
1673 if (s->chr_send_event)
1674 s->chr_send_event(s, event);
1677 void qemu_chr_add_handlers(CharDriverState *s,
1678 IOCanRWHandler *fd_can_read,
1679 IOReadHandler *fd_read,
1680 IOEventHandler *fd_event,
1683 s->chr_can_read = fd_can_read;
1684 s->chr_read = fd_read;
1685 s->chr_event = fd_event;
1686 s->handler_opaque = opaque;
1687 if (s->chr_update_read_handler)
1688 s->chr_update_read_handler(s);
1691 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1696 static CharDriverState *qemu_chr_open_null(void)
1698 CharDriverState *chr;
1700 chr = qemu_mallocz(sizeof(CharDriverState));
1703 chr->chr_write = null_chr_write;
1707 /* MUX driver for serial I/O splitting */
1708 static int term_timestamps;
1709 static int64_t term_timestamps_start;
1711 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1712 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1714 IOCanRWHandler *chr_can_read[MAX_MUX];
1715 IOReadHandler *chr_read[MAX_MUX];
1716 IOEventHandler *chr_event[MAX_MUX];
1717 void *ext_opaque[MAX_MUX];
1718 CharDriverState *drv;
1719 unsigned char buffer[MUX_BUFFER_SIZE];
1723 int term_got_escape;
1728 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1730 MuxDriver *d = chr->opaque;
1732 if (!term_timestamps) {
1733 ret = d->drv->chr_write(d->drv, buf, len);
1738 for(i = 0; i < len; i++) {
1739 ret += d->drv->chr_write(d->drv, buf+i, 1);
1740 if (buf[i] == '\n') {
1746 if (term_timestamps_start == -1)
1747 term_timestamps_start = ti;
1748 ti -= term_timestamps_start;
1749 secs = ti / 1000000000;
1750 snprintf(buf1, sizeof(buf1),
1751 "[%02d:%02d:%02d.%03d] ",
1755 (int)((ti / 1000000) % 1000));
1756 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1763 static char *mux_help[] = {
1764 "% h print this help\n\r",
1765 "% x exit emulator\n\r",
1766 "% s save disk data back to file (if -snapshot)\n\r",
1767 "% t toggle console timestamps\n\r"
1768 "% b send break (magic sysrq)\n\r",
1769 "% c switch between console and monitor\n\r",
1774 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1775 static void mux_print_help(CharDriverState *chr)
1778 char ebuf[15] = "Escape-Char";
1779 char cbuf[50] = "\n\r";
1781 if (term_escape_char > 0 && term_escape_char < 26) {
1782 sprintf(cbuf,"\n\r");
1783 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1785 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1788 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1789 for (i = 0; mux_help[i] != NULL; i++) {
1790 for (j=0; mux_help[i][j] != '\0'; j++) {
1791 if (mux_help[i][j] == '%')
1792 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1794 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1799 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1801 if (d->term_got_escape) {
1802 d->term_got_escape = 0;
1803 if (ch == term_escape_char)
1808 mux_print_help(chr);
1812 char *term = "QEMU: Terminated\n\r";
1813 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1820 for (i = 0; i < nb_drives; i++) {
1821 bdrv_commit(drives_table[i].bdrv);
1826 qemu_chr_event(chr, CHR_EVENT_BREAK);
1829 /* Switch to the next registered device */
1831 if (chr->focus >= d->mux_cnt)
1835 term_timestamps = !term_timestamps;
1836 term_timestamps_start = -1;
1839 } else if (ch == term_escape_char) {
1840 d->term_got_escape = 1;
1848 static void mux_chr_accept_input(CharDriverState *chr)
1851 MuxDriver *d = chr->opaque;
1853 while (d->prod != d->cons &&
1854 d->chr_can_read[m] &&
1855 d->chr_can_read[m](d->ext_opaque[m])) {
1856 d->chr_read[m](d->ext_opaque[m],
1857 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1861 static int mux_chr_can_read(void *opaque)
1863 CharDriverState *chr = opaque;
1864 MuxDriver *d = chr->opaque;
1866 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1868 if (d->chr_can_read[chr->focus])
1869 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1873 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1875 CharDriverState *chr = opaque;
1876 MuxDriver *d = chr->opaque;
1880 mux_chr_accept_input (opaque);
1882 for(i = 0; i < size; i++)
1883 if (mux_proc_byte(chr, d, buf[i])) {
1884 if (d->prod == d->cons &&
1885 d->chr_can_read[m] &&
1886 d->chr_can_read[m](d->ext_opaque[m]))
1887 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1889 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1893 static void mux_chr_event(void *opaque, int event)
1895 CharDriverState *chr = opaque;
1896 MuxDriver *d = chr->opaque;
1899 /* Send the event to all registered listeners */
1900 for (i = 0; i < d->mux_cnt; i++)
1901 if (d->chr_event[i])
1902 d->chr_event[i](d->ext_opaque[i], event);
1905 static void mux_chr_update_read_handler(CharDriverState *chr)
1907 MuxDriver *d = chr->opaque;
1909 if (d->mux_cnt >= MAX_MUX) {
1910 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1913 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1914 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1915 d->chr_read[d->mux_cnt] = chr->chr_read;
1916 d->chr_event[d->mux_cnt] = chr->chr_event;
1917 /* Fix up the real driver with mux routines */
1918 if (d->mux_cnt == 0) {
1919 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1920 mux_chr_event, chr);
1922 chr->focus = d->mux_cnt;
1926 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1928 CharDriverState *chr;
1931 chr = qemu_mallocz(sizeof(CharDriverState));
1934 d = qemu_mallocz(sizeof(MuxDriver));
1943 chr->chr_write = mux_chr_write;
1944 chr->chr_update_read_handler = mux_chr_update_read_handler;
1945 chr->chr_accept_input = mux_chr_accept_input;
1952 static void socket_cleanup(void)
1957 static int socket_init(void)
1962 ret = WSAStartup(MAKEWORD(2,2), &Data);
1964 err = WSAGetLastError();
1965 fprintf(stderr, "WSAStartup: %d\n", err);
1968 atexit(socket_cleanup);
1972 static int send_all(int fd, const uint8_t *buf, int len1)
1978 ret = send(fd, buf, len, 0);
1981 errno = WSAGetLastError();
1982 if (errno != WSAEWOULDBLOCK) {
1985 } else if (ret == 0) {
1995 void socket_set_nonblock(int fd)
1997 unsigned long opt = 1;
1998 ioctlsocket(fd, FIONBIO, &opt);
2003 static int unix_write(int fd, const uint8_t *buf, int len1)
2009 ret = write(fd, buf, len);
2011 if (errno != EINTR && errno != EAGAIN)
2013 } else if (ret == 0) {
2023 static inline int send_all(int fd, const uint8_t *buf, int len1)
2025 return unix_write(fd, buf, len1);
2028 void socket_set_nonblock(int fd)
2030 fcntl(fd, F_SETFL, O_NONBLOCK);
2032 #endif /* !_WIN32 */
2041 #define STDIO_MAX_CLIENTS 1
2042 static int stdio_nb_clients = 0;
2044 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2046 FDCharDriver *s = chr->opaque;
2047 return unix_write(s->fd_out, buf, len);
2050 static int fd_chr_read_poll(void *opaque)
2052 CharDriverState *chr = opaque;
2053 FDCharDriver *s = chr->opaque;
2055 s->max_size = qemu_chr_can_read(chr);
2059 static void fd_chr_read(void *opaque)
2061 CharDriverState *chr = opaque;
2062 FDCharDriver *s = chr->opaque;
2067 if (len > s->max_size)
2071 size = read(s->fd_in, buf, len);
2073 /* FD has been closed. Remove it from the active list. */
2074 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2078 qemu_chr_read(chr, buf, size);
2082 static void fd_chr_update_read_handler(CharDriverState *chr)
2084 FDCharDriver *s = chr->opaque;
2086 if (s->fd_in >= 0) {
2087 if (nographic && s->fd_in == 0) {
2089 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2090 fd_chr_read, NULL, chr);
2095 static void fd_chr_close(struct CharDriverState *chr)
2097 FDCharDriver *s = chr->opaque;
2099 if (s->fd_in >= 0) {
2100 if (nographic && s->fd_in == 0) {
2102 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2109 /* open a character device to a unix fd */
2110 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2112 CharDriverState *chr;
2115 chr = qemu_mallocz(sizeof(CharDriverState));
2118 s = qemu_mallocz(sizeof(FDCharDriver));
2126 chr->chr_write = fd_chr_write;
2127 chr->chr_update_read_handler = fd_chr_update_read_handler;
2128 chr->chr_close = fd_chr_close;
2130 qemu_chr_reset(chr);
2135 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2139 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2142 return qemu_chr_open_fd(-1, fd_out);
2145 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2148 char filename_in[256], filename_out[256];
2150 snprintf(filename_in, 256, "%s.in", filename);
2151 snprintf(filename_out, 256, "%s.out", filename);
2152 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2153 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2154 if (fd_in < 0 || fd_out < 0) {
2159 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2163 return qemu_chr_open_fd(fd_in, fd_out);
2167 /* for STDIO, we handle the case where several clients use it
2170 #define TERM_FIFO_MAX_SIZE 1
2172 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2173 static int term_fifo_size;
2175 static int stdio_read_poll(void *opaque)
2177 CharDriverState *chr = opaque;
2179 /* try to flush the queue if needed */
2180 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2181 qemu_chr_read(chr, term_fifo, 1);
2184 /* see if we can absorb more chars */
2185 if (term_fifo_size == 0)
2191 static void stdio_read(void *opaque)
2195 CharDriverState *chr = opaque;
2197 size = read(0, buf, 1);
2199 /* stdin has been closed. Remove it from the active list. */
2200 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2204 if (qemu_chr_can_read(chr) > 0) {
2205 qemu_chr_read(chr, buf, 1);
2206 } else if (term_fifo_size == 0) {
2207 term_fifo[term_fifo_size++] = buf[0];
2212 /* init terminal so that we can grab keys */
2213 static struct termios oldtty;
2214 static int old_fd0_flags;
2215 static int term_atexit_done;
2217 static void term_exit(void)
2219 tcsetattr (0, TCSANOW, &oldtty);
2220 fcntl(0, F_SETFL, old_fd0_flags);
2223 static void term_init(void)
2227 tcgetattr (0, &tty);
2229 old_fd0_flags = fcntl(0, F_GETFL);
2231 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2232 |INLCR|IGNCR|ICRNL|IXON);
2233 tty.c_oflag |= OPOST;
2234 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2235 /* if graphical mode, we allow Ctrl-C handling */
2237 tty.c_lflag &= ~ISIG;
2238 tty.c_cflag &= ~(CSIZE|PARENB);
2241 tty.c_cc[VTIME] = 0;
2243 tcsetattr (0, TCSANOW, &tty);
2245 if (!term_atexit_done++)
2248 fcntl(0, F_SETFL, O_NONBLOCK);
2251 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2255 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2259 static CharDriverState *qemu_chr_open_stdio(void)
2261 CharDriverState *chr;
2263 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2265 chr = qemu_chr_open_fd(0, 1);
2266 chr->chr_close = qemu_chr_close_stdio;
2267 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2274 #if defined(__linux__) || defined(__sun__)
2275 static CharDriverState *qemu_chr_open_pty(void)
2278 char slave_name[1024];
2279 int master_fd, slave_fd;
2281 #if defined(__linux__)
2282 /* Not satisfying */
2283 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2288 /* Disabling local echo and line-buffered output */
2289 tcgetattr (master_fd, &tty);
2290 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2292 tty.c_cc[VTIME] = 0;
2293 tcsetattr (master_fd, TCSAFLUSH, &tty);
2295 fprintf(stderr, "char device redirected to %s\n", slave_name);
2296 return qemu_chr_open_fd(master_fd, master_fd);
2299 static void tty_serial_init(int fd, int speed,
2300 int parity, int data_bits, int stop_bits)
2306 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2307 speed, parity, data_bits, stop_bits);
2309 tcgetattr (fd, &tty);
2312 if (speed <= 50 * MARGIN)
2314 else if (speed <= 75 * MARGIN)
2316 else if (speed <= 300 * MARGIN)
2318 else if (speed <= 600 * MARGIN)
2320 else if (speed <= 1200 * MARGIN)
2322 else if (speed <= 2400 * MARGIN)
2324 else if (speed <= 4800 * MARGIN)
2326 else if (speed <= 9600 * MARGIN)
2328 else if (speed <= 19200 * MARGIN)
2330 else if (speed <= 38400 * MARGIN)
2332 else if (speed <= 57600 * MARGIN)
2334 else if (speed <= 115200 * MARGIN)
2339 cfsetispeed(&tty, spd);
2340 cfsetospeed(&tty, spd);
2342 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2343 |INLCR|IGNCR|ICRNL|IXON);
2344 tty.c_oflag |= OPOST;
2345 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2346 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2367 tty.c_cflag |= PARENB;
2370 tty.c_cflag |= PARENB | PARODD;
2374 tty.c_cflag |= CSTOPB;
2376 tcsetattr (fd, TCSANOW, &tty);
2379 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2381 FDCharDriver *s = chr->opaque;
2384 case CHR_IOCTL_SERIAL_SET_PARAMS:
2386 QEMUSerialSetParams *ssp = arg;
2387 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2388 ssp->data_bits, ssp->stop_bits);
2391 case CHR_IOCTL_SERIAL_SET_BREAK:
2393 int enable = *(int *)arg;
2395 tcsendbreak(s->fd_in, 1);
2404 static CharDriverState *qemu_chr_open_tty(const char *filename)
2406 CharDriverState *chr;
2409 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2410 fcntl(fd, F_SETFL, O_NONBLOCK);
2411 tty_serial_init(fd, 115200, 'N', 8, 1);
2412 chr = qemu_chr_open_fd(fd, fd);
2417 chr->chr_ioctl = tty_serial_ioctl;
2418 qemu_chr_reset(chr);
2421 #else /* ! __linux__ && ! __sun__ */
2422 static CharDriverState *qemu_chr_open_pty(void)
2426 #endif /* __linux__ || __sun__ */
2428 #if defined(__linux__)
2432 } ParallelCharDriver;
2434 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2436 if (s->mode != mode) {
2438 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2445 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2447 ParallelCharDriver *drv = chr->opaque;
2452 case CHR_IOCTL_PP_READ_DATA:
2453 if (ioctl(fd, PPRDATA, &b) < 0)
2455 *(uint8_t *)arg = b;
2457 case CHR_IOCTL_PP_WRITE_DATA:
2458 b = *(uint8_t *)arg;
2459 if (ioctl(fd, PPWDATA, &b) < 0)
2462 case CHR_IOCTL_PP_READ_CONTROL:
2463 if (ioctl(fd, PPRCONTROL, &b) < 0)
2465 /* Linux gives only the lowest bits, and no way to know data
2466 direction! For better compatibility set the fixed upper
2468 *(uint8_t *)arg = b | 0xc0;
2470 case CHR_IOCTL_PP_WRITE_CONTROL:
2471 b = *(uint8_t *)arg;
2472 if (ioctl(fd, PPWCONTROL, &b) < 0)
2475 case CHR_IOCTL_PP_READ_STATUS:
2476 if (ioctl(fd, PPRSTATUS, &b) < 0)
2478 *(uint8_t *)arg = b;
2480 case CHR_IOCTL_PP_EPP_READ_ADDR:
2481 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2482 struct ParallelIOArg *parg = arg;
2483 int n = read(fd, parg->buffer, parg->count);
2484 if (n != parg->count) {
2489 case CHR_IOCTL_PP_EPP_READ:
2490 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2491 struct ParallelIOArg *parg = arg;
2492 int n = read(fd, parg->buffer, parg->count);
2493 if (n != parg->count) {
2498 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2499 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2500 struct ParallelIOArg *parg = arg;
2501 int n = write(fd, parg->buffer, parg->count);
2502 if (n != parg->count) {
2507 case CHR_IOCTL_PP_EPP_WRITE:
2508 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2509 struct ParallelIOArg *parg = arg;
2510 int n = write(fd, parg->buffer, parg->count);
2511 if (n != parg->count) {
2522 static void pp_close(CharDriverState *chr)
2524 ParallelCharDriver *drv = chr->opaque;
2527 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2528 ioctl(fd, PPRELEASE);
2533 static CharDriverState *qemu_chr_open_pp(const char *filename)
2535 CharDriverState *chr;
2536 ParallelCharDriver *drv;
2539 TFR(fd = open(filename, O_RDWR));
2543 if (ioctl(fd, PPCLAIM) < 0) {
2548 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2554 drv->mode = IEEE1284_MODE_COMPAT;
2556 chr = qemu_mallocz(sizeof(CharDriverState));
2562 chr->chr_write = null_chr_write;
2563 chr->chr_ioctl = pp_ioctl;
2564 chr->chr_close = pp_close;
2567 qemu_chr_reset(chr);
2571 #endif /* __linux__ */
2577 HANDLE hcom, hrecv, hsend;
2578 OVERLAPPED orecv, osend;
2583 #define NSENDBUF 2048
2584 #define NRECVBUF 2048
2585 #define MAXCONNECT 1
2586 #define NTIMEOUT 5000
2588 static int win_chr_poll(void *opaque);
2589 static int win_chr_pipe_poll(void *opaque);
2591 static void win_chr_close(CharDriverState *chr)
2593 WinCharState *s = chr->opaque;
2596 CloseHandle(s->hsend);
2600 CloseHandle(s->hrecv);
2604 CloseHandle(s->hcom);
2608 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2610 qemu_del_polling_cb(win_chr_poll, chr);
2613 static int win_chr_init(CharDriverState *chr, const char *filename)
2615 WinCharState *s = chr->opaque;
2617 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2622 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2624 fprintf(stderr, "Failed CreateEvent\n");
2627 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2629 fprintf(stderr, "Failed CreateEvent\n");
2633 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2634 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2635 if (s->hcom == INVALID_HANDLE_VALUE) {
2636 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2641 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2642 fprintf(stderr, "Failed SetupComm\n");
2646 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2647 size = sizeof(COMMCONFIG);
2648 GetDefaultCommConfig(filename, &comcfg, &size);
2649 comcfg.dcb.DCBlength = sizeof(DCB);
2650 CommConfigDialog(filename, NULL, &comcfg);
2652 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2653 fprintf(stderr, "Failed SetCommState\n");
2657 if (!SetCommMask(s->hcom, EV_ERR)) {
2658 fprintf(stderr, "Failed SetCommMask\n");
2662 cto.ReadIntervalTimeout = MAXDWORD;
2663 if (!SetCommTimeouts(s->hcom, &cto)) {
2664 fprintf(stderr, "Failed SetCommTimeouts\n");
2668 if (!ClearCommError(s->hcom, &err, &comstat)) {
2669 fprintf(stderr, "Failed ClearCommError\n");
2672 qemu_add_polling_cb(win_chr_poll, chr);
2680 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2682 WinCharState *s = chr->opaque;
2683 DWORD len, ret, size, err;
2686 ZeroMemory(&s->osend, sizeof(s->osend));
2687 s->osend.hEvent = s->hsend;
2690 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2692 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2694 err = GetLastError();
2695 if (err == ERROR_IO_PENDING) {
2696 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2714 static int win_chr_read_poll(CharDriverState *chr)
2716 WinCharState *s = chr->opaque;
2718 s->max_size = qemu_chr_can_read(chr);
2722 static void win_chr_readfile(CharDriverState *chr)
2724 WinCharState *s = chr->opaque;
2729 ZeroMemory(&s->orecv, sizeof(s->orecv));
2730 s->orecv.hEvent = s->hrecv;
2731 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2733 err = GetLastError();
2734 if (err == ERROR_IO_PENDING) {
2735 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2740 qemu_chr_read(chr, buf, size);
2744 static void win_chr_read(CharDriverState *chr)
2746 WinCharState *s = chr->opaque;
2748 if (s->len > s->max_size)
2749 s->len = s->max_size;
2753 win_chr_readfile(chr);
2756 static int win_chr_poll(void *opaque)
2758 CharDriverState *chr = opaque;
2759 WinCharState *s = chr->opaque;
2763 ClearCommError(s->hcom, &comerr, &status);
2764 if (status.cbInQue > 0) {
2765 s->len = status.cbInQue;
2766 win_chr_read_poll(chr);
2773 static CharDriverState *qemu_chr_open_win(const char *filename)
2775 CharDriverState *chr;
2778 chr = qemu_mallocz(sizeof(CharDriverState));
2781 s = qemu_mallocz(sizeof(WinCharState));
2787 chr->chr_write = win_chr_write;
2788 chr->chr_close = win_chr_close;
2790 if (win_chr_init(chr, filename) < 0) {
2795 qemu_chr_reset(chr);
2799 static int win_chr_pipe_poll(void *opaque)
2801 CharDriverState *chr = opaque;
2802 WinCharState *s = chr->opaque;
2805 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2808 win_chr_read_poll(chr);
2815 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2817 WinCharState *s = chr->opaque;
2825 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2827 fprintf(stderr, "Failed CreateEvent\n");
2830 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2832 fprintf(stderr, "Failed CreateEvent\n");
2836 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2837 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2838 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2840 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2841 if (s->hcom == INVALID_HANDLE_VALUE) {
2842 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2847 ZeroMemory(&ov, sizeof(ov));
2848 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2849 ret = ConnectNamedPipe(s->hcom, &ov);
2851 fprintf(stderr, "Failed ConnectNamedPipe\n");
2855 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2857 fprintf(stderr, "Failed GetOverlappedResult\n");
2859 CloseHandle(ov.hEvent);
2866 CloseHandle(ov.hEvent);
2869 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2878 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2880 CharDriverState *chr;
2883 chr = qemu_mallocz(sizeof(CharDriverState));
2886 s = qemu_mallocz(sizeof(WinCharState));
2892 chr->chr_write = win_chr_write;
2893 chr->chr_close = win_chr_close;
2895 if (win_chr_pipe_init(chr, filename) < 0) {
2900 qemu_chr_reset(chr);
2904 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2906 CharDriverState *chr;
2909 chr = qemu_mallocz(sizeof(CharDriverState));
2912 s = qemu_mallocz(sizeof(WinCharState));
2919 chr->chr_write = win_chr_write;
2920 qemu_chr_reset(chr);
2924 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2926 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2929 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2933 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2934 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2935 if (fd_out == INVALID_HANDLE_VALUE)
2938 return qemu_chr_open_win_file(fd_out);
2940 #endif /* !_WIN32 */
2942 /***********************************************************/
2943 /* UDP Net console */
2947 struct sockaddr_in daddr;
2954 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2956 NetCharDriver *s = chr->opaque;
2958 return sendto(s->fd, buf, len, 0,
2959 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2962 static int udp_chr_read_poll(void *opaque)
2964 CharDriverState *chr = opaque;
2965 NetCharDriver *s = chr->opaque;
2967 s->max_size = qemu_chr_can_read(chr);
2969 /* If there were any stray characters in the queue process them
2972 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2973 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2975 s->max_size = qemu_chr_can_read(chr);
2980 static void udp_chr_read(void *opaque)
2982 CharDriverState *chr = opaque;
2983 NetCharDriver *s = chr->opaque;
2985 if (s->max_size == 0)
2987 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2988 s->bufptr = s->bufcnt;
2993 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2994 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2996 s->max_size = qemu_chr_can_read(chr);
3000 static void udp_chr_update_read_handler(CharDriverState *chr)
3002 NetCharDriver *s = chr->opaque;
3005 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3006 udp_chr_read, NULL, chr);
3010 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3012 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3014 int parse_host_src_port(struct sockaddr_in *haddr,
3015 struct sockaddr_in *saddr,
3018 static CharDriverState *qemu_chr_open_udp(const char *def)
3020 CharDriverState *chr = NULL;
3021 NetCharDriver *s = NULL;
3023 struct sockaddr_in saddr;
3025 chr = qemu_mallocz(sizeof(CharDriverState));
3028 s = qemu_mallocz(sizeof(NetCharDriver));
3032 fd = socket(PF_INET, SOCK_DGRAM, 0);
3034 perror("socket(PF_INET, SOCK_DGRAM)");
3038 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3039 printf("Could not parse: %s\n", def);
3043 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3053 chr->chr_write = udp_chr_write;
3054 chr->chr_update_read_handler = udp_chr_update_read_handler;
3067 /***********************************************************/
3068 /* TCP Net console */
3079 static void tcp_chr_accept(void *opaque);
3081 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3083 TCPCharDriver *s = chr->opaque;
3085 return send_all(s->fd, buf, len);
3087 /* XXX: indicate an error ? */
3092 static int tcp_chr_read_poll(void *opaque)
3094 CharDriverState *chr = opaque;
3095 TCPCharDriver *s = chr->opaque;
3098 s->max_size = qemu_chr_can_read(chr);
3103 #define IAC_BREAK 243
3104 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3106 uint8_t *buf, int *size)
3108 /* Handle any telnet client's basic IAC options to satisfy char by
3109 * char mode with no echo. All IAC options will be removed from
3110 * the buf and the do_telnetopt variable will be used to track the
3111 * state of the width of the IAC information.
3113 * IAC commands come in sets of 3 bytes with the exception of the
3114 * "IAC BREAK" command and the double IAC.
3120 for (i = 0; i < *size; i++) {
3121 if (s->do_telnetopt > 1) {
3122 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3123 /* Double IAC means send an IAC */
3127 s->do_telnetopt = 1;
3129 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3130 /* Handle IAC break commands by sending a serial break */
3131 qemu_chr_event(chr, CHR_EVENT_BREAK);
3136 if (s->do_telnetopt >= 4) {
3137 s->do_telnetopt = 1;
3140 if ((unsigned char)buf[i] == IAC) {
3141 s->do_telnetopt = 2;
3152 static void tcp_chr_read(void *opaque)
3154 CharDriverState *chr = opaque;
3155 TCPCharDriver *s = chr->opaque;
3159 if (!s->connected || s->max_size <= 0)
3162 if (len > s->max_size)
3164 size = recv(s->fd, buf, len, 0);
3166 /* connection closed */
3168 if (s->listen_fd >= 0) {
3169 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3171 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3174 } else if (size > 0) {
3175 if (s->do_telnetopt)
3176 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3178 qemu_chr_read(chr, buf, size);
3182 static void tcp_chr_connect(void *opaque)
3184 CharDriverState *chr = opaque;
3185 TCPCharDriver *s = chr->opaque;
3188 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3189 tcp_chr_read, NULL, chr);
3190 qemu_chr_reset(chr);
3193 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3194 static void tcp_chr_telnet_init(int fd)
3197 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3198 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3199 send(fd, (char *)buf, 3, 0);
3200 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3201 send(fd, (char *)buf, 3, 0);
3202 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3203 send(fd, (char *)buf, 3, 0);
3204 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3205 send(fd, (char *)buf, 3, 0);
3208 static void socket_set_nodelay(int fd)
3211 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3214 static void tcp_chr_accept(void *opaque)
3216 CharDriverState *chr = opaque;
3217 TCPCharDriver *s = chr->opaque;
3218 struct sockaddr_in saddr;
3220 struct sockaddr_un uaddr;
3222 struct sockaddr *addr;
3229 len = sizeof(uaddr);
3230 addr = (struct sockaddr *)&uaddr;
3234 len = sizeof(saddr);
3235 addr = (struct sockaddr *)&saddr;
3237 fd = accept(s->listen_fd, addr, &len);
3238 if (fd < 0 && errno != EINTR) {
3240 } else if (fd >= 0) {
3241 if (s->do_telnetopt)
3242 tcp_chr_telnet_init(fd);
3246 socket_set_nonblock(fd);
3248 socket_set_nodelay(fd);
3250 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3251 tcp_chr_connect(chr);
3254 static void tcp_chr_close(CharDriverState *chr)
3256 TCPCharDriver *s = chr->opaque;
3259 if (s->listen_fd >= 0)
3260 closesocket(s->listen_fd);
3264 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3268 CharDriverState *chr = NULL;
3269 TCPCharDriver *s = NULL;
3270 int fd = -1, ret, err, val;
3272 int is_waitconnect = 1;
3275 struct sockaddr_in saddr;
3277 struct sockaddr_un uaddr;
3279 struct sockaddr *addr;
3284 addr = (struct sockaddr *)&uaddr;
3285 addrlen = sizeof(uaddr);
3286 if (parse_unix_path(&uaddr, host_str) < 0)
3291 addr = (struct sockaddr *)&saddr;
3292 addrlen = sizeof(saddr);
3293 if (parse_host_port(&saddr, host_str) < 0)
3298 while((ptr = strchr(ptr,','))) {
3300 if (!strncmp(ptr,"server",6)) {
3302 } else if (!strncmp(ptr,"nowait",6)) {
3304 } else if (!strncmp(ptr,"nodelay",6)) {
3307 printf("Unknown option: %s\n", ptr);
3314 chr = qemu_mallocz(sizeof(CharDriverState));
3317 s = qemu_mallocz(sizeof(TCPCharDriver));
3323 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3326 fd = socket(PF_INET, SOCK_STREAM, 0);
3331 if (!is_waitconnect)
3332 socket_set_nonblock(fd);
3337 s->is_unix = is_unix;
3338 s->do_nodelay = do_nodelay && !is_unix;
3341 chr->chr_write = tcp_chr_write;
3342 chr->chr_close = tcp_chr_close;
3345 /* allow fast reuse */
3349 strncpy(path, uaddr.sun_path, 108);
3356 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3359 ret = bind(fd, addr, addrlen);
3363 ret = listen(fd, 0);
3368 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3370 s->do_telnetopt = 1;
3373 ret = connect(fd, addr, addrlen);
3375 err = socket_error();
3376 if (err == EINTR || err == EWOULDBLOCK) {
3377 } else if (err == EINPROGRESS) {
3380 } else if (err == WSAEALREADY) {
3392 socket_set_nodelay(fd);
3394 tcp_chr_connect(chr);
3396 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3399 if (is_listen && is_waitconnect) {
3400 printf("QEMU waiting for connection on: %s\n", host_str);
3401 tcp_chr_accept(chr);
3402 socket_set_nonblock(s->listen_fd);
3414 CharDriverState *qemu_chr_open(const char *filename)
3418 if (!strcmp(filename, "vc")) {
3419 return text_console_init(&display_state, 0);
3420 } else if (strstart(filename, "vc:", &p)) {
3421 return text_console_init(&display_state, p);
3422 } else if (!strcmp(filename, "null")) {
3423 return qemu_chr_open_null();
3425 if (strstart(filename, "tcp:", &p)) {
3426 return qemu_chr_open_tcp(p, 0, 0);
3428 if (strstart(filename, "telnet:", &p)) {
3429 return qemu_chr_open_tcp(p, 1, 0);
3431 if (strstart(filename, "udp:", &p)) {
3432 return qemu_chr_open_udp(p);
3434 if (strstart(filename, "mon:", &p)) {
3435 CharDriverState *drv = qemu_chr_open(p);
3437 drv = qemu_chr_open_mux(drv);
3438 monitor_init(drv, !nographic);
3441 printf("Unable to open driver: %s\n", p);
3445 if (strstart(filename, "unix:", &p)) {
3446 return qemu_chr_open_tcp(p, 0, 1);
3447 } else if (strstart(filename, "file:", &p)) {
3448 return qemu_chr_open_file_out(p);
3449 } else if (strstart(filename, "pipe:", &p)) {
3450 return qemu_chr_open_pipe(p);
3451 } else if (!strcmp(filename, "pty")) {
3452 return qemu_chr_open_pty();
3453 } else if (!strcmp(filename, "stdio")) {
3454 return qemu_chr_open_stdio();
3456 #if defined(__linux__)
3457 if (strstart(filename, "/dev/parport", NULL)) {
3458 return qemu_chr_open_pp(filename);
3461 #if defined(__linux__) || defined(__sun__)
3462 if (strstart(filename, "/dev/", NULL)) {
3463 return qemu_chr_open_tty(filename);
3467 if (strstart(filename, "COM", NULL)) {
3468 return qemu_chr_open_win(filename);
3470 if (strstart(filename, "pipe:", &p)) {
3471 return qemu_chr_open_win_pipe(p);
3473 if (strstart(filename, "con:", NULL)) {
3474 return qemu_chr_open_win_con(filename);
3476 if (strstart(filename, "file:", &p)) {
3477 return qemu_chr_open_win_file_out(p);
3480 #ifdef CONFIG_BRLAPI
3481 if (!strcmp(filename, "braille")) {
3482 return chr_baum_init();
3490 void qemu_chr_close(CharDriverState *chr)
3493 chr->chr_close(chr);
3497 /***********************************************************/
3498 /* network device redirectors */
3500 __attribute__ (( unused ))
3501 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3505 for(i=0;i<size;i+=16) {
3509 fprintf(f, "%08x ", i);
3512 fprintf(f, " %02x", buf[i+j]);
3517 for(j=0;j<len;j++) {
3519 if (c < ' ' || c > '~')
3521 fprintf(f, "%c", c);
3527 static int parse_macaddr(uint8_t *macaddr, const char *p)
3534 offset = strtol(p, &last_char, 0);
3535 if (0 == errno && '\0' == *last_char &&
3536 offset >= 0 && offset <= 0xFFFFFF) {
3537 macaddr[3] = (offset & 0xFF0000) >> 16;
3538 macaddr[4] = (offset & 0xFF00) >> 8;
3539 macaddr[5] = offset & 0xFF;
3542 for(i = 0; i < 6; i++) {
3543 macaddr[i] = strtol(p, (char **)&p, 16);
3548 if (*p != ':' && *p != '-')
3559 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3564 p1 = strchr(p, sep);
3570 if (len > buf_size - 1)
3572 memcpy(buf, p, len);
3579 int parse_host_src_port(struct sockaddr_in *haddr,
3580 struct sockaddr_in *saddr,
3581 const char *input_str)
3583 char *str = strdup(input_str);
3584 char *host_str = str;
3589 * Chop off any extra arguments at the end of the string which
3590 * would start with a comma, then fill in the src port information
3591 * if it was provided else use the "any address" and "any port".
3593 if ((ptr = strchr(str,',')))
3596 if ((src_str = strchr(input_str,'@'))) {
3601 if (parse_host_port(haddr, host_str) < 0)
3604 if (!src_str || *src_str == '\0')
3607 if (parse_host_port(saddr, src_str) < 0)
3618 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3626 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3628 saddr->sin_family = AF_INET;
3629 if (buf[0] == '\0') {
3630 saddr->sin_addr.s_addr = 0;
3632 if (isdigit(buf[0])) {
3633 if (!inet_aton(buf, &saddr->sin_addr))
3636 if ((he = gethostbyname(buf)) == NULL)
3638 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3641 port = strtol(p, (char **)&r, 0);
3644 saddr->sin_port = htons(port);
3649 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3654 len = MIN(108, strlen(str));
3655 p = strchr(str, ',');
3657 len = MIN(len, p - str);
3659 memset(uaddr, 0, sizeof(*uaddr));
3661 uaddr->sun_family = AF_UNIX;
3662 memcpy(uaddr->sun_path, str, len);
3668 /* find or alloc a new VLAN */
3669 VLANState *qemu_find_vlan(int id)
3671 VLANState **pvlan, *vlan;
3672 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3676 vlan = qemu_mallocz(sizeof(VLANState));
3681 pvlan = &first_vlan;
3682 while (*pvlan != NULL)
3683 pvlan = &(*pvlan)->next;
3688 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3689 IOReadHandler *fd_read,
3690 IOCanRWHandler *fd_can_read,
3693 VLANClientState *vc, **pvc;
3694 vc = qemu_mallocz(sizeof(VLANClientState));
3697 vc->fd_read = fd_read;
3698 vc->fd_can_read = fd_can_read;
3699 vc->opaque = opaque;
3703 pvc = &vlan->first_client;
3704 while (*pvc != NULL)
3705 pvc = &(*pvc)->next;
3710 int qemu_can_send_packet(VLANClientState *vc1)
3712 VLANState *vlan = vc1->vlan;
3713 VLANClientState *vc;
3715 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3717 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3724 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3726 VLANState *vlan = vc1->vlan;
3727 VLANClientState *vc;
3730 printf("vlan %d send:\n", vlan->id);
3731 hex_dump(stdout, buf, size);
3733 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3735 vc->fd_read(vc->opaque, buf, size);
3740 #if defined(CONFIG_SLIRP)
3742 /* slirp network adapter */
3744 static int slirp_inited;
3745 static VLANClientState *slirp_vc;
3747 int slirp_can_output(void)
3749 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3752 void slirp_output(const uint8_t *pkt, int pkt_len)
3755 printf("slirp output:\n");
3756 hex_dump(stdout, pkt, pkt_len);
3760 qemu_send_packet(slirp_vc, pkt, pkt_len);
3763 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3766 printf("slirp input:\n");
3767 hex_dump(stdout, buf, size);
3769 slirp_input(buf, size);
3772 static int net_slirp_init(VLANState *vlan)
3774 if (!slirp_inited) {
3778 slirp_vc = qemu_new_vlan_client(vlan,
3779 slirp_receive, NULL, NULL);
3780 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3784 static void net_slirp_redir(const char *redir_str)
3789 struct in_addr guest_addr;
3790 int host_port, guest_port;
3792 if (!slirp_inited) {
3798 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3800 if (!strcmp(buf, "tcp")) {
3802 } else if (!strcmp(buf, "udp")) {
3808 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3810 host_port = strtol(buf, &r, 0);
3814 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3816 if (buf[0] == '\0') {
3817 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3819 if (!inet_aton(buf, &guest_addr))
3822 guest_port = strtol(p, &r, 0);
3826 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3827 fprintf(stderr, "qemu: could not set up redirection\n");
3832 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3840 static void erase_dir(char *dir_name)
3844 char filename[1024];
3846 /* erase all the files in the directory */
3847 if ((d = opendir(dir_name)) != 0) {
3852 if (strcmp(de->d_name, ".") != 0 &&
3853 strcmp(de->d_name, "..") != 0) {
3854 snprintf(filename, sizeof(filename), "%s/%s",
3855 smb_dir, de->d_name);
3856 if (unlink(filename) != 0) /* is it a directory? */
3857 erase_dir(filename);
3865 /* automatic user mode samba server configuration */
3866 static void smb_exit(void)
3871 /* automatic user mode samba server configuration */
3872 static void net_slirp_smb(const char *exported_dir)
3874 char smb_conf[1024];
3875 char smb_cmdline[1024];
3878 if (!slirp_inited) {
3883 /* XXX: better tmp dir construction */
3884 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3885 if (mkdir(smb_dir, 0700) < 0) {
3886 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3889 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3891 f = fopen(smb_conf, "w");
3893 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3900 "socket address=127.0.0.1\n"
3901 "pid directory=%s\n"
3902 "lock directory=%s\n"
3903 "log file=%s/log.smbd\n"
3904 "smb passwd file=%s/smbpasswd\n"
3905 "security = share\n"
3920 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3921 SMBD_COMMAND, smb_conf);
3923 slirp_add_exec(0, smb_cmdline, 4, 139);
3926 #endif /* !defined(_WIN32) */
3927 void do_info_slirp(void)
3932 #endif /* CONFIG_SLIRP */
3934 #if !defined(_WIN32)
3936 typedef struct TAPState {
3937 VLANClientState *vc;
3939 char down_script[1024];
3942 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3944 TAPState *s = opaque;
3947 ret = write(s->fd, buf, size);
3948 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3955 static void tap_send(void *opaque)
3957 TAPState *s = opaque;
3964 sbuf.maxlen = sizeof(buf);
3966 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3968 size = read(s->fd, buf, sizeof(buf));
3971 qemu_send_packet(s->vc, buf, size);
3977 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3981 s = qemu_mallocz(sizeof(TAPState));
3985 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3986 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3987 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3991 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3992 static int tap_open(char *ifname, int ifname_size)
3998 TFR(fd = open("/dev/tap", O_RDWR));
4000 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4005 dev = devname(s.st_rdev, S_IFCHR);
4006 pstrcpy(ifname, ifname_size, dev);
4008 fcntl(fd, F_SETFL, O_NONBLOCK);
4011 #elif defined(__sun__)
4012 #define TUNNEWPPA (('T'<<16) | 0x0001)
4014 * Allocate TAP device, returns opened fd.
4015 * Stores dev name in the first arg(must be large enough).
4017 int tap_alloc(char *dev)
4019 int tap_fd, if_fd, ppa = -1;
4020 static int ip_fd = 0;
4023 static int arp_fd = 0;
4024 int ip_muxid, arp_muxid;
4025 struct strioctl strioc_if, strioc_ppa;
4026 int link_type = I_PLINK;;
4028 char actual_name[32] = "";
4030 memset(&ifr, 0x0, sizeof(ifr));
4034 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4038 /* Check if IP device was opened */
4042 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4044 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4048 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4050 syslog(LOG_ERR, "Can't open /dev/tap");
4054 /* Assign a new PPA and get its unit number. */
4055 strioc_ppa.ic_cmd = TUNNEWPPA;
4056 strioc_ppa.ic_timout = 0;
4057 strioc_ppa.ic_len = sizeof(ppa);
4058 strioc_ppa.ic_dp = (char *)&ppa;
4059 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4060 syslog (LOG_ERR, "Can't assign new interface");
4062 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4064 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4067 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4068 syslog(LOG_ERR, "Can't push IP module");
4072 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4073 syslog(LOG_ERR, "Can't get flags\n");
4075 snprintf (actual_name, 32, "tap%d", ppa);
4076 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4079 /* Assign ppa according to the unit number returned by tun device */
4081 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4082 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4083 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4084 syslog (LOG_ERR, "Can't get flags\n");
4085 /* Push arp module to if_fd */
4086 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4087 syslog (LOG_ERR, "Can't push ARP module (2)");
4089 /* Push arp module to ip_fd */
4090 if (ioctl (ip_fd, I_POP, NULL) < 0)
4091 syslog (LOG_ERR, "I_POP failed\n");
4092 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4093 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4095 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4097 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4099 /* Set ifname to arp */
4100 strioc_if.ic_cmd = SIOCSLIFNAME;
4101 strioc_if.ic_timout = 0;
4102 strioc_if.ic_len = sizeof(ifr);
4103 strioc_if.ic_dp = (char *)𝔦
4104 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4105 syslog (LOG_ERR, "Can't set ifname to arp\n");
4108 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4109 syslog(LOG_ERR, "Can't link TAP device to IP");
4113 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4114 syslog (LOG_ERR, "Can't link TAP device to ARP");
4118 memset(&ifr, 0x0, sizeof(ifr));
4119 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4120 ifr.lifr_ip_muxid = ip_muxid;
4121 ifr.lifr_arp_muxid = arp_muxid;
4123 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4125 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4126 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4127 syslog (LOG_ERR, "Can't set multiplexor id");
4130 sprintf(dev, "tap%d", ppa);
4134 static int tap_open(char *ifname, int ifname_size)
4138 if( (fd = tap_alloc(dev)) < 0 ){
4139 fprintf(stderr, "Cannot allocate TAP device\n");
4142 pstrcpy(ifname, ifname_size, dev);
4143 fcntl(fd, F_SETFL, O_NONBLOCK);
4147 static int tap_open(char *ifname, int ifname_size)
4152 TFR(fd = open("/dev/net/tun", O_RDWR));
4154 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4157 memset(&ifr, 0, sizeof(ifr));
4158 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4159 if (ifname[0] != '\0')
4160 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4162 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4163 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4165 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4169 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4170 fcntl(fd, F_SETFL, O_NONBLOCK);
4175 static int launch_script(const char *setup_script, const char *ifname, int fd)
4181 /* try to launch network script */
4185 int open_max = sysconf (_SC_OPEN_MAX), i;
4186 for (i = 0; i < open_max; i++)
4187 if (i != STDIN_FILENO &&
4188 i != STDOUT_FILENO &&
4189 i != STDERR_FILENO &&
4194 *parg++ = (char *)setup_script;
4195 *parg++ = (char *)ifname;
4197 execv(setup_script, args);
4200 while (waitpid(pid, &status, 0) != pid);
4201 if (!WIFEXITED(status) ||
4202 WEXITSTATUS(status) != 0) {
4203 fprintf(stderr, "%s: could not launch network script\n",
4211 static int net_tap_init(VLANState *vlan, const char *ifname1,
4212 const char *setup_script, const char *down_script)
4218 if (ifname1 != NULL)
4219 pstrcpy(ifname, sizeof(ifname), ifname1);
4222 TFR(fd = tap_open(ifname, sizeof(ifname)));
4226 if (!setup_script || !strcmp(setup_script, "no"))
4228 if (setup_script[0] != '\0') {
4229 if (launch_script(setup_script, ifname, fd))
4232 s = net_tap_fd_init(vlan, fd);
4235 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4236 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4237 if (down_script && strcmp(down_script, "no"))
4238 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4242 #endif /* !_WIN32 */
4244 /* network connection */
4245 typedef struct NetSocketState {
4246 VLANClientState *vc;
4248 int state; /* 0 = getting length, 1 = getting data */
4252 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4255 typedef struct NetSocketListenState {
4258 } NetSocketListenState;
4260 /* XXX: we consider we can send the whole packet without blocking */
4261 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4263 NetSocketState *s = opaque;
4267 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4268 send_all(s->fd, buf, size);
4271 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4273 NetSocketState *s = opaque;
4274 sendto(s->fd, buf, size, 0,
4275 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4278 static void net_socket_send(void *opaque)
4280 NetSocketState *s = opaque;
4285 size = recv(s->fd, buf1, sizeof(buf1), 0);
4287 err = socket_error();
4288 if (err != EWOULDBLOCK)
4290 } else if (size == 0) {
4291 /* end of connection */
4293 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4299 /* reassemble a packet from the network */
4305 memcpy(s->buf + s->index, buf, l);
4309 if (s->index == 4) {
4311 s->packet_len = ntohl(*(uint32_t *)s->buf);
4317 l = s->packet_len - s->index;
4320 memcpy(s->buf + s->index, buf, l);
4324 if (s->index >= s->packet_len) {
4325 qemu_send_packet(s->vc, s->buf, s->packet_len);
4334 static void net_socket_send_dgram(void *opaque)
4336 NetSocketState *s = opaque;
4339 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4343 /* end of connection */
4344 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4347 qemu_send_packet(s->vc, s->buf, size);
4350 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4355 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4356 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4357 inet_ntoa(mcastaddr->sin_addr),
4358 (int)ntohl(mcastaddr->sin_addr.s_addr));
4362 fd = socket(PF_INET, SOCK_DGRAM, 0);
4364 perror("socket(PF_INET, SOCK_DGRAM)");
4369 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4370 (const char *)&val, sizeof(val));
4372 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4376 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4382 /* Add host to multicast group */
4383 imr.imr_multiaddr = mcastaddr->sin_addr;
4384 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4386 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4387 (const char *)&imr, sizeof(struct ip_mreq));
4389 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4393 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4395 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4396 (const char *)&val, sizeof(val));
4398 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4402 socket_set_nonblock(fd);
4410 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4413 struct sockaddr_in saddr;
4415 socklen_t saddr_len;
4418 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4419 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4420 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4424 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4426 if (saddr.sin_addr.s_addr==0) {
4427 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4431 /* clone dgram socket */
4432 newfd = net_socket_mcast_create(&saddr);
4434 /* error already reported by net_socket_mcast_create() */
4438 /* clone newfd to fd, close newfd */
4443 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4444 fd, strerror(errno));
4449 s = qemu_mallocz(sizeof(NetSocketState));
4454 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4455 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4457 /* mcast: save bound address as dst */
4458 if (is_connected) s->dgram_dst=saddr;
4460 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4461 "socket: fd=%d (%s mcast=%s:%d)",
4462 fd, is_connected? "cloned" : "",
4463 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4467 static void net_socket_connect(void *opaque)
4469 NetSocketState *s = opaque;
4470 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4473 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4477 s = qemu_mallocz(sizeof(NetSocketState));
4481 s->vc = qemu_new_vlan_client(vlan,
4482 net_socket_receive, NULL, s);
4483 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4484 "socket: fd=%d", fd);
4486 net_socket_connect(s);
4488 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4493 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4496 int so_type=-1, optlen=sizeof(so_type);
4498 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4499 (socklen_t *)&optlen)< 0) {
4500 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4505 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4507 return net_socket_fd_init_stream(vlan, fd, is_connected);
4509 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4510 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4511 return net_socket_fd_init_stream(vlan, fd, is_connected);
4516 static void net_socket_accept(void *opaque)
4518 NetSocketListenState *s = opaque;
4520 struct sockaddr_in saddr;
4525 len = sizeof(saddr);
4526 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4527 if (fd < 0 && errno != EINTR) {
4529 } else if (fd >= 0) {
4533 s1 = net_socket_fd_init(s->vlan, fd, 1);
4537 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4538 "socket: connection from %s:%d",
4539 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4543 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4545 NetSocketListenState *s;
4547 struct sockaddr_in saddr;
4549 if (parse_host_port(&saddr, host_str) < 0)
4552 s = qemu_mallocz(sizeof(NetSocketListenState));
4556 fd = socket(PF_INET, SOCK_STREAM, 0);
4561 socket_set_nonblock(fd);
4563 /* allow fast reuse */
4565 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4567 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4572 ret = listen(fd, 0);
4579 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4583 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4586 int fd, connected, ret, err;
4587 struct sockaddr_in saddr;
4589 if (parse_host_port(&saddr, host_str) < 0)
4592 fd = socket(PF_INET, SOCK_STREAM, 0);
4597 socket_set_nonblock(fd);
4601 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4603 err = socket_error();
4604 if (err == EINTR || err == EWOULDBLOCK) {
4605 } else if (err == EINPROGRESS) {
4608 } else if (err == WSAEALREADY) {
4621 s = net_socket_fd_init(vlan, fd, connected);
4624 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4625 "socket: connect to %s:%d",
4626 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4630 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4634 struct sockaddr_in saddr;
4636 if (parse_host_port(&saddr, host_str) < 0)
4640 fd = net_socket_mcast_create(&saddr);
4644 s = net_socket_fd_init(vlan, fd, 0);
4648 s->dgram_dst = saddr;
4650 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4651 "socket: mcast=%s:%d",
4652 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4657 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4662 while (*p != '\0' && *p != '=') {
4663 if (q && (q - buf) < buf_size - 1)
4673 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4678 while (*p != '\0') {
4680 if (*(p + 1) != ',')
4684 if (q && (q - buf) < buf_size - 1)
4694 static int get_param_value(char *buf, int buf_size,
4695 const char *tag, const char *str)
4702 p = get_opt_name(option, sizeof(option), p);
4706 if (!strcmp(tag, option)) {
4707 (void)get_opt_value(buf, buf_size, p);
4710 p = get_opt_value(NULL, 0, p);
4719 static int check_params(char *buf, int buf_size,
4720 char **params, const char *str)
4727 p = get_opt_name(buf, buf_size, p);
4731 for(i = 0; params[i] != NULL; i++)
4732 if (!strcmp(params[i], buf))
4734 if (params[i] == NULL)
4736 p = get_opt_value(NULL, 0, p);
4745 static int net_client_init(const char *str)
4756 while (*p != '\0' && *p != ',') {
4757 if ((q - device) < sizeof(device) - 1)
4765 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4766 vlan_id = strtol(buf, NULL, 0);
4768 vlan = qemu_find_vlan(vlan_id);
4770 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4773 if (!strcmp(device, "nic")) {
4777 if (nb_nics >= MAX_NICS) {
4778 fprintf(stderr, "Too Many NICs\n");
4781 nd = &nd_table[nb_nics];
4782 macaddr = nd->macaddr;
4788 macaddr[5] = 0x56 + nb_nics;
4790 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4791 if (parse_macaddr(macaddr, buf) < 0) {
4792 fprintf(stderr, "invalid syntax for ethernet address\n");
4796 if (get_param_value(buf, sizeof(buf), "model", p)) {
4797 nd->model = strdup(buf);
4801 vlan->nb_guest_devs++;
4804 if (!strcmp(device, "none")) {
4805 /* does nothing. It is needed to signal that no network cards
4810 if (!strcmp(device, "user")) {
4811 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4812 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4814 vlan->nb_host_devs++;
4815 ret = net_slirp_init(vlan);
4819 if (!strcmp(device, "tap")) {
4821 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4822 fprintf(stderr, "tap: no interface name\n");
4825 vlan->nb_host_devs++;
4826 ret = tap_win32_init(vlan, ifname);
4829 if (!strcmp(device, "tap")) {
4831 char setup_script[1024], down_script[1024];
4833 vlan->nb_host_devs++;
4834 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4835 fd = strtol(buf, NULL, 0);
4836 fcntl(fd, F_SETFL, O_NONBLOCK);
4838 if (net_tap_fd_init(vlan, fd))
4841 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4844 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4845 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4847 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4848 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4850 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4854 if (!strcmp(device, "socket")) {
4855 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4857 fd = strtol(buf, NULL, 0);
4859 if (net_socket_fd_init(vlan, fd, 1))
4861 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4862 ret = net_socket_listen_init(vlan, buf);
4863 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4864 ret = net_socket_connect_init(vlan, buf);
4865 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4866 ret = net_socket_mcast_init(vlan, buf);
4868 fprintf(stderr, "Unknown socket options: %s\n", p);
4871 vlan->nb_host_devs++;
4874 fprintf(stderr, "Unknown network device: %s\n", device);
4878 fprintf(stderr, "Could not initialize device '%s'\n", device);
4884 void do_info_network(void)
4887 VLANClientState *vc;
4889 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4890 term_printf("VLAN %d devices:\n", vlan->id);
4891 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4892 term_printf(" %s\n", vc->info_str);
4896 #define HD_ALIAS "index=%d,media=disk"
4898 #define CDROM_ALIAS "index=1,media=cdrom"
4900 #define CDROM_ALIAS "index=2,media=cdrom"
4902 #define FD_ALIAS "index=%d,if=floppy"
4903 #define PFLASH_ALIAS "if=pflash"
4904 #define MTD_ALIAS "if=mtd"
4905 #define SD_ALIAS "index=0,if=sd"
4907 static int drive_add(const char *file, const char *fmt, ...)
4911 if (nb_drives_opt >= MAX_DRIVES) {
4912 fprintf(stderr, "qemu: too many drives\n");
4916 drives_opt[nb_drives_opt].file = file;
4918 vsnprintf(drives_opt[nb_drives_opt].opt,
4919 sizeof(drives_opt[0].opt), fmt, ap);
4922 return nb_drives_opt++;
4925 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4929 /* seek interface, bus and unit */
4931 for (index = 0; index < nb_drives; index++)
4932 if (drives_table[index].type == type &&
4933 drives_table[index].bus == bus &&
4934 drives_table[index].unit == unit)
4940 int drive_get_max_bus(BlockInterfaceType type)
4946 for (index = 0; index < nb_drives; index++) {
4947 if(drives_table[index].type == type &&
4948 drives_table[index].bus > max_bus)
4949 max_bus = drives_table[index].bus;
4954 static int drive_init(struct drive_opt *arg, int snapshot,
4955 QEMUMachine *machine)
4960 const char *mediastr = "";
4961 BlockInterfaceType type;
4962 enum { MEDIA_DISK, MEDIA_CDROM } media;
4963 int bus_id, unit_id;
4964 int cyls, heads, secs, translation;
4965 BlockDriverState *bdrv;
4970 char *str = arg->opt;
4971 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4972 "secs", "trans", "media", "snapshot", "file",
4975 if (check_params(buf, sizeof(buf), params, str) < 0) {
4976 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
4982 cyls = heads = secs = 0;
4985 translation = BIOS_ATA_TRANSLATION_AUTO;
4989 if (!strcmp(machine->name, "realview") ||
4990 !strcmp(machine->name, "SS-5") ||
4991 !strcmp(machine->name, "SS-10") ||
4992 !strcmp(machine->name, "SS-600MP") ||
4993 !strcmp(machine->name, "versatilepb") ||
4994 !strcmp(machine->name, "versatileab")) {
4996 max_devs = MAX_SCSI_DEVS;
4997 strcpy(devname, "scsi");
5000 max_devs = MAX_IDE_DEVS;
5001 strcpy(devname, "ide");
5005 /* extract parameters */
5007 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5008 bus_id = strtol(buf, NULL, 0);
5010 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5015 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5016 unit_id = strtol(buf, NULL, 0);
5018 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5023 if (get_param_value(buf, sizeof(buf), "if", str)) {
5024 strncpy(devname, buf, sizeof(devname));
5025 if (!strcmp(buf, "ide")) {
5027 max_devs = MAX_IDE_DEVS;
5028 } else if (!strcmp(buf, "scsi")) {
5030 max_devs = MAX_SCSI_DEVS;
5031 } else if (!strcmp(buf, "floppy")) {
5034 } else if (!strcmp(buf, "pflash")) {
5037 } else if (!strcmp(buf, "mtd")) {
5040 } else if (!strcmp(buf, "sd")) {
5044 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5049 if (get_param_value(buf, sizeof(buf), "index", str)) {
5050 index = strtol(buf, NULL, 0);
5052 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5057 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5058 cyls = strtol(buf, NULL, 0);
5061 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5062 heads = strtol(buf, NULL, 0);
5065 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5066 secs = strtol(buf, NULL, 0);
5069 if (cyls || heads || secs) {
5070 if (cyls < 1 || cyls > 16383) {
5071 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5074 if (heads < 1 || heads > 16) {
5075 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5078 if (secs < 1 || secs > 63) {
5079 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5084 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5087 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5091 if (!strcmp(buf, "none"))
5092 translation = BIOS_ATA_TRANSLATION_NONE;
5093 else if (!strcmp(buf, "lba"))
5094 translation = BIOS_ATA_TRANSLATION_LBA;
5095 else if (!strcmp(buf, "auto"))
5096 translation = BIOS_ATA_TRANSLATION_AUTO;
5098 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5103 if (get_param_value(buf, sizeof(buf), "media", str)) {
5104 if (!strcmp(buf, "disk")) {
5106 } else if (!strcmp(buf, "cdrom")) {
5107 if (cyls || secs || heads) {
5109 "qemu: '%s' invalid physical CHS format\n", str);
5112 media = MEDIA_CDROM;
5114 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5119 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5120 if (!strcmp(buf, "on"))
5122 else if (!strcmp(buf, "off"))
5125 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5130 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5131 if (!strcmp(buf, "off"))
5133 else if (!strcmp(buf, "on"))
5136 fprintf(stderr, "qemu: invalid cache option\n");
5141 if (arg->file == NULL)
5142 get_param_value(file, sizeof(file), "file", str);
5144 pstrcpy(file, sizeof(file), arg->file);
5146 /* compute bus and unit according index */
5149 if (bus_id != 0 || unit_id != -1) {
5151 "qemu: '%s' index cannot be used with bus and unit\n", str);
5159 unit_id = index % max_devs;
5160 bus_id = index / max_devs;
5164 /* if user doesn't specify a unit_id,
5165 * try to find the first free
5168 if (unit_id == -1) {
5170 while (drive_get_index(type, bus_id, unit_id) != -1) {
5172 if (max_devs && unit_id >= max_devs) {
5173 unit_id -= max_devs;
5181 if (max_devs && unit_id >= max_devs) {
5182 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5183 str, unit_id, max_devs - 1);
5188 * ignore multiple definitions
5191 if (drive_get_index(type, bus_id, unit_id) != -1)
5196 if (type == IF_IDE || type == IF_SCSI)
5197 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5199 snprintf(buf, sizeof(buf), "%s%i%s%i",
5200 devname, bus_id, mediastr, unit_id);
5202 snprintf(buf, sizeof(buf), "%s%s%i",
5203 devname, mediastr, unit_id);
5204 bdrv = bdrv_new(buf);
5205 drives_table[nb_drives].bdrv = bdrv;
5206 drives_table[nb_drives].type = type;
5207 drives_table[nb_drives].bus = bus_id;
5208 drives_table[nb_drives].unit = unit_id;
5217 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5218 bdrv_set_translation_hint(bdrv, translation);
5222 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5227 /* FIXME: This isn't really a floppy, but it's a reasonable
5230 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5240 bdrv_flags |= BDRV_O_SNAPSHOT;
5242 bdrv_flags |= BDRV_O_DIRECT;
5243 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5244 fprintf(stderr, "qemu: could not open disk image %s\n",
5251 /***********************************************************/
5254 static USBPort *used_usb_ports;
5255 static USBPort *free_usb_ports;
5257 /* ??? Maybe change this to register a hub to keep track of the topology. */
5258 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5259 usb_attachfn attach)
5261 port->opaque = opaque;
5262 port->index = index;
5263 port->attach = attach;
5264 port->next = free_usb_ports;
5265 free_usb_ports = port;
5268 static int usb_device_add(const char *devname)
5274 if (!free_usb_ports)
5277 if (strstart(devname, "host:", &p)) {
5278 dev = usb_host_device_open(p);
5279 } else if (!strcmp(devname, "mouse")) {
5280 dev = usb_mouse_init();
5281 } else if (!strcmp(devname, "tablet")) {
5282 dev = usb_tablet_init();
5283 } else if (!strcmp(devname, "keyboard")) {
5284 dev = usb_keyboard_init();
5285 } else if (strstart(devname, "disk:", &p)) {
5286 dev = usb_msd_init(p);
5287 } else if (!strcmp(devname, "wacom-tablet")) {
5288 dev = usb_wacom_init();
5289 } else if (strstart(devname, "serial:", &p)) {
5290 dev = usb_serial_init(p);
5291 #ifdef CONFIG_BRLAPI
5292 } else if (!strcmp(devname, "braille")) {
5293 dev = usb_baum_init();
5301 /* Find a USB port to add the device to. */
5302 port = free_usb_ports;
5306 /* Create a new hub and chain it on. */
5307 free_usb_ports = NULL;
5308 port->next = used_usb_ports;
5309 used_usb_ports = port;
5311 hub = usb_hub_init(VM_USB_HUB_SIZE);
5312 usb_attach(port, hub);
5313 port = free_usb_ports;
5316 free_usb_ports = port->next;
5317 port->next = used_usb_ports;
5318 used_usb_ports = port;
5319 usb_attach(port, dev);
5323 static int usb_device_del(const char *devname)
5331 if (!used_usb_ports)
5334 p = strchr(devname, '.');
5337 bus_num = strtoul(devname, NULL, 0);
5338 addr = strtoul(p + 1, NULL, 0);
5342 lastp = &used_usb_ports;
5343 port = used_usb_ports;
5344 while (port && port->dev->addr != addr) {
5345 lastp = &port->next;
5353 *lastp = port->next;
5354 usb_attach(port, NULL);
5355 dev->handle_destroy(dev);
5356 port->next = free_usb_ports;
5357 free_usb_ports = port;
5361 void do_usb_add(const char *devname)
5364 ret = usb_device_add(devname);
5366 term_printf("Could not add USB device '%s'\n", devname);
5369 void do_usb_del(const char *devname)
5372 ret = usb_device_del(devname);
5374 term_printf("Could not remove USB device '%s'\n", devname);
5381 const char *speed_str;
5384 term_printf("USB support not enabled\n");
5388 for (port = used_usb_ports; port; port = port->next) {
5392 switch(dev->speed) {
5396 case USB_SPEED_FULL:
5399 case USB_SPEED_HIGH:
5406 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5407 0, dev->addr, speed_str, dev->devname);
5411 /***********************************************************/
5412 /* PCMCIA/Cardbus */
5414 static struct pcmcia_socket_entry_s {
5415 struct pcmcia_socket_s *socket;
5416 struct pcmcia_socket_entry_s *next;
5417 } *pcmcia_sockets = 0;
5419 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5421 struct pcmcia_socket_entry_s *entry;
5423 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5424 entry->socket = socket;
5425 entry->next = pcmcia_sockets;
5426 pcmcia_sockets = entry;
5429 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5431 struct pcmcia_socket_entry_s *entry, **ptr;
5433 ptr = &pcmcia_sockets;
5434 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5435 if (entry->socket == socket) {
5441 void pcmcia_info(void)
5443 struct pcmcia_socket_entry_s *iter;
5444 if (!pcmcia_sockets)
5445 term_printf("No PCMCIA sockets\n");
5447 for (iter = pcmcia_sockets; iter; iter = iter->next)
5448 term_printf("%s: %s\n", iter->socket->slot_string,
5449 iter->socket->attached ? iter->socket->card_string :
5453 /***********************************************************/
5456 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5460 static void dumb_resize(DisplayState *ds, int w, int h)
5464 static void dumb_refresh(DisplayState *ds)
5466 #if defined(CONFIG_SDL)
5471 static void dumb_display_init(DisplayState *ds)
5476 ds->dpy_update = dumb_update;
5477 ds->dpy_resize = dumb_resize;
5478 ds->dpy_refresh = dumb_refresh;
5481 /***********************************************************/
5484 #define MAX_IO_HANDLERS 64
5486 typedef struct IOHandlerRecord {
5488 IOCanRWHandler *fd_read_poll;
5490 IOHandler *fd_write;
5493 /* temporary data */
5495 struct IOHandlerRecord *next;
5498 static IOHandlerRecord *first_io_handler;
5500 /* XXX: fd_read_poll should be suppressed, but an API change is
5501 necessary in the character devices to suppress fd_can_read(). */
5502 int qemu_set_fd_handler2(int fd,
5503 IOCanRWHandler *fd_read_poll,
5505 IOHandler *fd_write,
5508 IOHandlerRecord **pioh, *ioh;
5510 if (!fd_read && !fd_write) {
5511 pioh = &first_io_handler;
5516 if (ioh->fd == fd) {
5523 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5527 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5530 ioh->next = first_io_handler;
5531 first_io_handler = ioh;
5534 ioh->fd_read_poll = fd_read_poll;
5535 ioh->fd_read = fd_read;
5536 ioh->fd_write = fd_write;
5537 ioh->opaque = opaque;
5543 int qemu_set_fd_handler(int fd,
5545 IOHandler *fd_write,
5548 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5551 /***********************************************************/
5552 /* Polling handling */
5554 typedef struct PollingEntry {
5557 struct PollingEntry *next;
5560 static PollingEntry *first_polling_entry;
5562 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5564 PollingEntry **ppe, *pe;
5565 pe = qemu_mallocz(sizeof(PollingEntry));
5569 pe->opaque = opaque;
5570 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5575 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5577 PollingEntry **ppe, *pe;
5578 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5580 if (pe->func == func && pe->opaque == opaque) {
5589 /***********************************************************/
5590 /* Wait objects support */
5591 typedef struct WaitObjects {
5593 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5594 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5595 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5598 static WaitObjects wait_objects = {0};
5600 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5602 WaitObjects *w = &wait_objects;
5604 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5606 w->events[w->num] = handle;
5607 w->func[w->num] = func;
5608 w->opaque[w->num] = opaque;
5613 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5616 WaitObjects *w = &wait_objects;
5619 for (i = 0; i < w->num; i++) {
5620 if (w->events[i] == handle)
5623 w->events[i] = w->events[i + 1];
5624 w->func[i] = w->func[i + 1];
5625 w->opaque[i] = w->opaque[i + 1];
5633 /***********************************************************/
5634 /* savevm/loadvm support */
5636 #define IO_BUF_SIZE 32768
5640 BlockDriverState *bs;
5643 int64_t base_offset;
5644 int64_t buf_offset; /* start of buffer when writing, end of buffer
5647 int buf_size; /* 0 when writing */
5648 uint8_t buf[IO_BUF_SIZE];
5651 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5655 f = qemu_mallocz(sizeof(QEMUFile));
5658 if (!strcmp(mode, "wb")) {
5660 } else if (!strcmp(mode, "rb")) {
5665 f->outfile = fopen(filename, mode);
5677 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5681 f = qemu_mallocz(sizeof(QEMUFile));
5686 f->is_writable = is_writable;
5687 f->base_offset = offset;
5691 void qemu_fflush(QEMUFile *f)
5693 if (!f->is_writable)
5695 if (f->buf_index > 0) {
5697 fseek(f->outfile, f->buf_offset, SEEK_SET);
5698 fwrite(f->buf, 1, f->buf_index, f->outfile);
5700 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5701 f->buf, f->buf_index);
5703 f->buf_offset += f->buf_index;
5708 static void qemu_fill_buffer(QEMUFile *f)
5715 fseek(f->outfile, f->buf_offset, SEEK_SET);
5716 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5720 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5721 f->buf, IO_BUF_SIZE);
5727 f->buf_offset += len;
5730 void qemu_fclose(QEMUFile *f)
5740 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5744 l = IO_BUF_SIZE - f->buf_index;
5747 memcpy(f->buf + f->buf_index, buf, l);
5751 if (f->buf_index >= IO_BUF_SIZE)
5756 void qemu_put_byte(QEMUFile *f, int v)
5758 f->buf[f->buf_index++] = v;
5759 if (f->buf_index >= IO_BUF_SIZE)
5763 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5769 l = f->buf_size - f->buf_index;
5771 qemu_fill_buffer(f);
5772 l = f->buf_size - f->buf_index;
5778 memcpy(buf, f->buf + f->buf_index, l);
5783 return size1 - size;
5786 int qemu_get_byte(QEMUFile *f)
5788 if (f->buf_index >= f->buf_size) {
5789 qemu_fill_buffer(f);
5790 if (f->buf_index >= f->buf_size)
5793 return f->buf[f->buf_index++];
5796 int64_t qemu_ftell(QEMUFile *f)
5798 return f->buf_offset - f->buf_size + f->buf_index;
5801 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5803 if (whence == SEEK_SET) {
5805 } else if (whence == SEEK_CUR) {
5806 pos += qemu_ftell(f);
5808 /* SEEK_END not supported */
5811 if (f->is_writable) {
5813 f->buf_offset = pos;
5815 f->buf_offset = pos;
5822 void qemu_put_be16(QEMUFile *f, unsigned int v)
5824 qemu_put_byte(f, v >> 8);
5825 qemu_put_byte(f, v);
5828 void qemu_put_be32(QEMUFile *f, unsigned int v)
5830 qemu_put_byte(f, v >> 24);
5831 qemu_put_byte(f, v >> 16);
5832 qemu_put_byte(f, v >> 8);
5833 qemu_put_byte(f, v);
5836 void qemu_put_be64(QEMUFile *f, uint64_t v)
5838 qemu_put_be32(f, v >> 32);
5839 qemu_put_be32(f, v);
5842 unsigned int qemu_get_be16(QEMUFile *f)
5845 v = qemu_get_byte(f) << 8;
5846 v |= qemu_get_byte(f);
5850 unsigned int qemu_get_be32(QEMUFile *f)
5853 v = qemu_get_byte(f) << 24;
5854 v |= qemu_get_byte(f) << 16;
5855 v |= qemu_get_byte(f) << 8;
5856 v |= qemu_get_byte(f);
5860 uint64_t qemu_get_be64(QEMUFile *f)
5863 v = (uint64_t)qemu_get_be32(f) << 32;
5864 v |= qemu_get_be32(f);
5868 typedef struct SaveStateEntry {
5872 SaveStateHandler *save_state;
5873 LoadStateHandler *load_state;
5875 struct SaveStateEntry *next;
5878 static SaveStateEntry *first_se;
5880 int register_savevm(const char *idstr,
5883 SaveStateHandler *save_state,
5884 LoadStateHandler *load_state,
5887 SaveStateEntry *se, **pse;
5889 se = qemu_malloc(sizeof(SaveStateEntry));
5892 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5893 se->instance_id = instance_id;
5894 se->version_id = version_id;
5895 se->save_state = save_state;
5896 se->load_state = load_state;
5897 se->opaque = opaque;
5900 /* add at the end of list */
5902 while (*pse != NULL)
5903 pse = &(*pse)->next;
5908 #define QEMU_VM_FILE_MAGIC 0x5145564d
5909 #define QEMU_VM_FILE_VERSION 0x00000002
5911 static int qemu_savevm_state(QEMUFile *f)
5915 int64_t cur_pos, len_pos, total_len_pos;
5917 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5918 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5919 total_len_pos = qemu_ftell(f);
5920 qemu_put_be64(f, 0); /* total size */
5922 for(se = first_se; se != NULL; se = se->next) {
5924 len = strlen(se->idstr);
5925 qemu_put_byte(f, len);
5926 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5928 qemu_put_be32(f, se->instance_id);
5929 qemu_put_be32(f, se->version_id);
5931 /* record size: filled later */
5932 len_pos = qemu_ftell(f);
5933 qemu_put_be32(f, 0);
5934 se->save_state(f, se->opaque);
5936 /* fill record size */
5937 cur_pos = qemu_ftell(f);
5938 len = cur_pos - len_pos - 4;
5939 qemu_fseek(f, len_pos, SEEK_SET);
5940 qemu_put_be32(f, len);
5941 qemu_fseek(f, cur_pos, SEEK_SET);
5943 cur_pos = qemu_ftell(f);
5944 qemu_fseek(f, total_len_pos, SEEK_SET);
5945 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5946 qemu_fseek(f, cur_pos, SEEK_SET);
5952 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5956 for(se = first_se; se != NULL; se = se->next) {
5957 if (!strcmp(se->idstr, idstr) &&
5958 instance_id == se->instance_id)
5964 static int qemu_loadvm_state(QEMUFile *f)
5967 int len, ret, instance_id, record_len, version_id;
5968 int64_t total_len, end_pos, cur_pos;
5972 v = qemu_get_be32(f);
5973 if (v != QEMU_VM_FILE_MAGIC)
5975 v = qemu_get_be32(f);
5976 if (v != QEMU_VM_FILE_VERSION) {
5981 total_len = qemu_get_be64(f);
5982 end_pos = total_len + qemu_ftell(f);
5984 if (qemu_ftell(f) >= end_pos)
5986 len = qemu_get_byte(f);
5987 qemu_get_buffer(f, (uint8_t *)idstr, len);
5989 instance_id = qemu_get_be32(f);
5990 version_id = qemu_get_be32(f);
5991 record_len = qemu_get_be32(f);
5993 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5994 idstr, instance_id, version_id, record_len);
5996 cur_pos = qemu_ftell(f);
5997 se = find_se(idstr, instance_id);
5999 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6000 instance_id, idstr);
6002 ret = se->load_state(f, se->opaque, version_id);
6004 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6005 instance_id, idstr);
6008 /* always seek to exact end of record */
6009 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6016 /* device can contain snapshots */
6017 static int bdrv_can_snapshot(BlockDriverState *bs)
6020 !bdrv_is_removable(bs) &&
6021 !bdrv_is_read_only(bs));
6024 /* device must be snapshots in order to have a reliable snapshot */
6025 static int bdrv_has_snapshot(BlockDriverState *bs)
6028 !bdrv_is_removable(bs) &&
6029 !bdrv_is_read_only(bs));
6032 static BlockDriverState *get_bs_snapshots(void)
6034 BlockDriverState *bs;
6038 return bs_snapshots;
6039 for(i = 0; i <= nb_drives; i++) {
6040 bs = drives_table[i].bdrv;
6041 if (bdrv_can_snapshot(bs))
6050 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6053 QEMUSnapshotInfo *sn_tab, *sn;
6057 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6060 for(i = 0; i < nb_sns; i++) {
6062 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6072 void do_savevm(const char *name)
6074 BlockDriverState *bs, *bs1;
6075 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6076 int must_delete, ret, i;
6077 BlockDriverInfo bdi1, *bdi = &bdi1;
6079 int saved_vm_running;
6086 bs = get_bs_snapshots();
6088 term_printf("No block device can accept snapshots\n");
6092 /* ??? Should this occur after vm_stop? */
6095 saved_vm_running = vm_running;
6100 ret = bdrv_snapshot_find(bs, old_sn, name);
6105 memset(sn, 0, sizeof(*sn));
6107 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6108 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6111 pstrcpy(sn->name, sizeof(sn->name), name);
6114 /* fill auxiliary fields */
6117 sn->date_sec = tb.time;
6118 sn->date_nsec = tb.millitm * 1000000;
6120 gettimeofday(&tv, NULL);
6121 sn->date_sec = tv.tv_sec;
6122 sn->date_nsec = tv.tv_usec * 1000;
6124 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6126 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6127 term_printf("Device %s does not support VM state snapshots\n",
6128 bdrv_get_device_name(bs));
6132 /* save the VM state */
6133 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6135 term_printf("Could not open VM state file\n");
6138 ret = qemu_savevm_state(f);
6139 sn->vm_state_size = qemu_ftell(f);
6142 term_printf("Error %d while writing VM\n", ret);
6146 /* create the snapshots */
6148 for(i = 0; i < nb_drives; i++) {
6149 bs1 = drives_table[i].bdrv;
6150 if (bdrv_has_snapshot(bs1)) {
6152 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6154 term_printf("Error while deleting snapshot on '%s'\n",
6155 bdrv_get_device_name(bs1));
6158 ret = bdrv_snapshot_create(bs1, sn);
6160 term_printf("Error while creating snapshot on '%s'\n",
6161 bdrv_get_device_name(bs1));
6167 if (saved_vm_running)
6171 void do_loadvm(const char *name)
6173 BlockDriverState *bs, *bs1;
6174 BlockDriverInfo bdi1, *bdi = &bdi1;
6177 int saved_vm_running;
6179 bs = get_bs_snapshots();
6181 term_printf("No block device supports snapshots\n");
6185 /* Flush all IO requests so they don't interfere with the new state. */
6188 saved_vm_running = vm_running;
6191 for(i = 0; i <= nb_drives; i++) {
6192 bs1 = drives_table[i].bdrv;
6193 if (bdrv_has_snapshot(bs1)) {
6194 ret = bdrv_snapshot_goto(bs1, name);
6197 term_printf("Warning: ");
6200 term_printf("Snapshots not supported on device '%s'\n",
6201 bdrv_get_device_name(bs1));
6204 term_printf("Could not find snapshot '%s' on device '%s'\n",
6205 name, bdrv_get_device_name(bs1));
6208 term_printf("Error %d while activating snapshot on '%s'\n",
6209 ret, bdrv_get_device_name(bs1));
6212 /* fatal on snapshot block device */
6219 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6220 term_printf("Device %s does not support VM state snapshots\n",
6221 bdrv_get_device_name(bs));
6225 /* restore the VM state */
6226 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6228 term_printf("Could not open VM state file\n");
6231 ret = qemu_loadvm_state(f);
6234 term_printf("Error %d while loading VM state\n", ret);
6237 if (saved_vm_running)
6241 void do_delvm(const char *name)
6243 BlockDriverState *bs, *bs1;
6246 bs = get_bs_snapshots();
6248 term_printf("No block device supports snapshots\n");
6252 for(i = 0; i <= nb_drives; i++) {
6253 bs1 = drives_table[i].bdrv;
6254 if (bdrv_has_snapshot(bs1)) {
6255 ret = bdrv_snapshot_delete(bs1, name);
6257 if (ret == -ENOTSUP)
6258 term_printf("Snapshots not supported on device '%s'\n",
6259 bdrv_get_device_name(bs1));
6261 term_printf("Error %d while deleting snapshot on '%s'\n",
6262 ret, bdrv_get_device_name(bs1));
6268 void do_info_snapshots(void)
6270 BlockDriverState *bs, *bs1;
6271 QEMUSnapshotInfo *sn_tab, *sn;
6275 bs = get_bs_snapshots();
6277 term_printf("No available block device supports snapshots\n");
6280 term_printf("Snapshot devices:");
6281 for(i = 0; i <= nb_drives; i++) {
6282 bs1 = drives_table[i].bdrv;
6283 if (bdrv_has_snapshot(bs1)) {
6285 term_printf(" %s", bdrv_get_device_name(bs1));
6290 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6292 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6295 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6296 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6297 for(i = 0; i < nb_sns; i++) {
6299 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6304 /***********************************************************/
6305 /* cpu save/restore */
6307 #if defined(TARGET_I386)
6309 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6311 qemu_put_be32(f, dt->selector);
6312 qemu_put_betl(f, dt->base);
6313 qemu_put_be32(f, dt->limit);
6314 qemu_put_be32(f, dt->flags);
6317 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6319 dt->selector = qemu_get_be32(f);
6320 dt->base = qemu_get_betl(f);
6321 dt->limit = qemu_get_be32(f);
6322 dt->flags = qemu_get_be32(f);
6325 void cpu_save(QEMUFile *f, void *opaque)
6327 CPUState *env = opaque;
6328 uint16_t fptag, fpus, fpuc, fpregs_format;
6332 for(i = 0; i < CPU_NB_REGS; i++)
6333 qemu_put_betls(f, &env->regs[i]);
6334 qemu_put_betls(f, &env->eip);
6335 qemu_put_betls(f, &env->eflags);
6336 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6337 qemu_put_be32s(f, &hflags);
6341 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6343 for(i = 0; i < 8; i++) {
6344 fptag |= ((!env->fptags[i]) << i);
6347 qemu_put_be16s(f, &fpuc);
6348 qemu_put_be16s(f, &fpus);
6349 qemu_put_be16s(f, &fptag);
6351 #ifdef USE_X86LDOUBLE
6356 qemu_put_be16s(f, &fpregs_format);
6358 for(i = 0; i < 8; i++) {
6359 #ifdef USE_X86LDOUBLE
6363 /* we save the real CPU data (in case of MMX usage only 'mant'
6364 contains the MMX register */
6365 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6366 qemu_put_be64(f, mant);
6367 qemu_put_be16(f, exp);
6370 /* if we use doubles for float emulation, we save the doubles to
6371 avoid losing information in case of MMX usage. It can give
6372 problems if the image is restored on a CPU where long
6373 doubles are used instead. */
6374 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6378 for(i = 0; i < 6; i++)
6379 cpu_put_seg(f, &env->segs[i]);
6380 cpu_put_seg(f, &env->ldt);
6381 cpu_put_seg(f, &env->tr);
6382 cpu_put_seg(f, &env->gdt);
6383 cpu_put_seg(f, &env->idt);
6385 qemu_put_be32s(f, &env->sysenter_cs);
6386 qemu_put_be32s(f, &env->sysenter_esp);
6387 qemu_put_be32s(f, &env->sysenter_eip);
6389 qemu_put_betls(f, &env->cr[0]);
6390 qemu_put_betls(f, &env->cr[2]);
6391 qemu_put_betls(f, &env->cr[3]);
6392 qemu_put_betls(f, &env->cr[4]);
6394 for(i = 0; i < 8; i++)
6395 qemu_put_betls(f, &env->dr[i]);
6398 qemu_put_be32s(f, &env->a20_mask);
6401 qemu_put_be32s(f, &env->mxcsr);
6402 for(i = 0; i < CPU_NB_REGS; i++) {
6403 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6404 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6407 #ifdef TARGET_X86_64
6408 qemu_put_be64s(f, &env->efer);
6409 qemu_put_be64s(f, &env->star);
6410 qemu_put_be64s(f, &env->lstar);
6411 qemu_put_be64s(f, &env->cstar);
6412 qemu_put_be64s(f, &env->fmask);
6413 qemu_put_be64s(f, &env->kernelgsbase);
6415 qemu_put_be32s(f, &env->smbase);
6418 #ifdef USE_X86LDOUBLE
6419 /* XXX: add that in a FPU generic layer */
6420 union x86_longdouble {
6425 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6426 #define EXPBIAS1 1023
6427 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6428 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6430 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6434 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6435 /* exponent + sign */
6436 e = EXPD1(temp) - EXPBIAS1 + 16383;
6437 e |= SIGND1(temp) >> 16;
6442 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6444 CPUState *env = opaque;
6447 uint16_t fpus, fpuc, fptag, fpregs_format;
6449 if (version_id != 3 && version_id != 4)
6451 for(i = 0; i < CPU_NB_REGS; i++)
6452 qemu_get_betls(f, &env->regs[i]);
6453 qemu_get_betls(f, &env->eip);
6454 qemu_get_betls(f, &env->eflags);
6455 qemu_get_be32s(f, &hflags);
6457 qemu_get_be16s(f, &fpuc);
6458 qemu_get_be16s(f, &fpus);
6459 qemu_get_be16s(f, &fptag);
6460 qemu_get_be16s(f, &fpregs_format);
6462 /* NOTE: we cannot always restore the FPU state if the image come
6463 from a host with a different 'USE_X86LDOUBLE' define. We guess
6464 if we are in an MMX state to restore correctly in that case. */
6465 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6466 for(i = 0; i < 8; i++) {
6470 switch(fpregs_format) {
6472 mant = qemu_get_be64(f);
6473 exp = qemu_get_be16(f);
6474 #ifdef USE_X86LDOUBLE
6475 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6477 /* difficult case */
6479 env->fpregs[i].mmx.MMX_Q(0) = mant;
6481 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6485 mant = qemu_get_be64(f);
6486 #ifdef USE_X86LDOUBLE
6488 union x86_longdouble *p;
6489 /* difficult case */
6490 p = (void *)&env->fpregs[i];
6495 fp64_to_fp80(p, mant);
6499 env->fpregs[i].mmx.MMX_Q(0) = mant;
6508 /* XXX: restore FPU round state */
6509 env->fpstt = (fpus >> 11) & 7;
6510 env->fpus = fpus & ~0x3800;
6512 for(i = 0; i < 8; i++) {
6513 env->fptags[i] = (fptag >> i) & 1;
6516 for(i = 0; i < 6; i++)
6517 cpu_get_seg(f, &env->segs[i]);
6518 cpu_get_seg(f, &env->ldt);
6519 cpu_get_seg(f, &env->tr);
6520 cpu_get_seg(f, &env->gdt);
6521 cpu_get_seg(f, &env->idt);
6523 qemu_get_be32s(f, &env->sysenter_cs);
6524 qemu_get_be32s(f, &env->sysenter_esp);
6525 qemu_get_be32s(f, &env->sysenter_eip);
6527 qemu_get_betls(f, &env->cr[0]);
6528 qemu_get_betls(f, &env->cr[2]);
6529 qemu_get_betls(f, &env->cr[3]);
6530 qemu_get_betls(f, &env->cr[4]);
6532 for(i = 0; i < 8; i++)
6533 qemu_get_betls(f, &env->dr[i]);
6536 qemu_get_be32s(f, &env->a20_mask);
6538 qemu_get_be32s(f, &env->mxcsr);
6539 for(i = 0; i < CPU_NB_REGS; i++) {
6540 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6541 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6544 #ifdef TARGET_X86_64
6545 qemu_get_be64s(f, &env->efer);
6546 qemu_get_be64s(f, &env->star);
6547 qemu_get_be64s(f, &env->lstar);
6548 qemu_get_be64s(f, &env->cstar);
6549 qemu_get_be64s(f, &env->fmask);
6550 qemu_get_be64s(f, &env->kernelgsbase);
6552 if (version_id >= 4)
6553 qemu_get_be32s(f, &env->smbase);
6555 /* XXX: compute hflags from scratch, except for CPL and IIF */
6556 env->hflags = hflags;
6561 #elif defined(TARGET_PPC)
6562 void cpu_save(QEMUFile *f, void *opaque)
6566 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6571 #elif defined(TARGET_MIPS)
6572 void cpu_save(QEMUFile *f, void *opaque)
6576 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6581 #elif defined(TARGET_SPARC)
6582 void cpu_save(QEMUFile *f, void *opaque)
6584 CPUState *env = opaque;
6588 for(i = 0; i < 8; i++)
6589 qemu_put_betls(f, &env->gregs[i]);
6590 for(i = 0; i < NWINDOWS * 16; i++)
6591 qemu_put_betls(f, &env->regbase[i]);
6594 for(i = 0; i < TARGET_FPREGS; i++) {
6600 qemu_put_be32(f, u.i);
6603 qemu_put_betls(f, &env->pc);
6604 qemu_put_betls(f, &env->npc);
6605 qemu_put_betls(f, &env->y);
6607 qemu_put_be32(f, tmp);
6608 qemu_put_betls(f, &env->fsr);
6609 qemu_put_betls(f, &env->tbr);
6610 #ifndef TARGET_SPARC64
6611 qemu_put_be32s(f, &env->wim);
6613 for(i = 0; i < 16; i++)
6614 qemu_put_be32s(f, &env->mmuregs[i]);
6618 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6620 CPUState *env = opaque;
6624 for(i = 0; i < 8; i++)
6625 qemu_get_betls(f, &env->gregs[i]);
6626 for(i = 0; i < NWINDOWS * 16; i++)
6627 qemu_get_betls(f, &env->regbase[i]);
6630 for(i = 0; i < TARGET_FPREGS; i++) {
6635 u.i = qemu_get_be32(f);
6639 qemu_get_betls(f, &env->pc);
6640 qemu_get_betls(f, &env->npc);
6641 qemu_get_betls(f, &env->y);
6642 tmp = qemu_get_be32(f);
6643 env->cwp = 0; /* needed to ensure that the wrapping registers are
6644 correctly updated */
6646 qemu_get_betls(f, &env->fsr);
6647 qemu_get_betls(f, &env->tbr);
6648 #ifndef TARGET_SPARC64
6649 qemu_get_be32s(f, &env->wim);
6651 for(i = 0; i < 16; i++)
6652 qemu_get_be32s(f, &env->mmuregs[i]);
6658 #elif defined(TARGET_ARM)
6660 void cpu_save(QEMUFile *f, void *opaque)
6663 CPUARMState *env = (CPUARMState *)opaque;
6665 for (i = 0; i < 16; i++) {
6666 qemu_put_be32(f, env->regs[i]);
6668 qemu_put_be32(f, cpsr_read(env));
6669 qemu_put_be32(f, env->spsr);
6670 for (i = 0; i < 6; i++) {
6671 qemu_put_be32(f, env->banked_spsr[i]);
6672 qemu_put_be32(f, env->banked_r13[i]);
6673 qemu_put_be32(f, env->banked_r14[i]);
6675 for (i = 0; i < 5; i++) {
6676 qemu_put_be32(f, env->usr_regs[i]);
6677 qemu_put_be32(f, env->fiq_regs[i]);
6679 qemu_put_be32(f, env->cp15.c0_cpuid);
6680 qemu_put_be32(f, env->cp15.c0_cachetype);
6681 qemu_put_be32(f, env->cp15.c1_sys);
6682 qemu_put_be32(f, env->cp15.c1_coproc);
6683 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6684 qemu_put_be32(f, env->cp15.c2_base0);
6685 qemu_put_be32(f, env->cp15.c2_base1);
6686 qemu_put_be32(f, env->cp15.c2_mask);
6687 qemu_put_be32(f, env->cp15.c2_data);
6688 qemu_put_be32(f, env->cp15.c2_insn);
6689 qemu_put_be32(f, env->cp15.c3);
6690 qemu_put_be32(f, env->cp15.c5_insn);
6691 qemu_put_be32(f, env->cp15.c5_data);
6692 for (i = 0; i < 8; i++) {
6693 qemu_put_be32(f, env->cp15.c6_region[i]);
6695 qemu_put_be32(f, env->cp15.c6_insn);
6696 qemu_put_be32(f, env->cp15.c6_data);
6697 qemu_put_be32(f, env->cp15.c9_insn);
6698 qemu_put_be32(f, env->cp15.c9_data);
6699 qemu_put_be32(f, env->cp15.c13_fcse);
6700 qemu_put_be32(f, env->cp15.c13_context);
6701 qemu_put_be32(f, env->cp15.c13_tls1);
6702 qemu_put_be32(f, env->cp15.c13_tls2);
6703 qemu_put_be32(f, env->cp15.c13_tls3);
6704 qemu_put_be32(f, env->cp15.c15_cpar);
6706 qemu_put_be32(f, env->features);
6708 if (arm_feature(env, ARM_FEATURE_VFP)) {
6709 for (i = 0; i < 16; i++) {
6711 u.d = env->vfp.regs[i];
6712 qemu_put_be32(f, u.l.upper);
6713 qemu_put_be32(f, u.l.lower);
6715 for (i = 0; i < 16; i++) {
6716 qemu_put_be32(f, env->vfp.xregs[i]);
6719 /* TODO: Should use proper FPSCR access functions. */
6720 qemu_put_be32(f, env->vfp.vec_len);
6721 qemu_put_be32(f, env->vfp.vec_stride);
6723 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6724 for (i = 16; i < 32; i++) {
6726 u.d = env->vfp.regs[i];
6727 qemu_put_be32(f, u.l.upper);
6728 qemu_put_be32(f, u.l.lower);
6733 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6734 for (i = 0; i < 16; i++) {
6735 qemu_put_be64(f, env->iwmmxt.regs[i]);
6737 for (i = 0; i < 16; i++) {
6738 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6742 if (arm_feature(env, ARM_FEATURE_M)) {
6743 qemu_put_be32(f, env->v7m.other_sp);
6744 qemu_put_be32(f, env->v7m.vecbase);
6745 qemu_put_be32(f, env->v7m.basepri);
6746 qemu_put_be32(f, env->v7m.control);
6747 qemu_put_be32(f, env->v7m.current_sp);
6748 qemu_put_be32(f, env->v7m.exception);
6752 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6754 CPUARMState *env = (CPUARMState *)opaque;
6757 if (version_id != ARM_CPU_SAVE_VERSION)
6760 for (i = 0; i < 16; i++) {
6761 env->regs[i] = qemu_get_be32(f);
6763 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6764 env->spsr = qemu_get_be32(f);
6765 for (i = 0; i < 6; i++) {
6766 env->banked_spsr[i] = qemu_get_be32(f);
6767 env->banked_r13[i] = qemu_get_be32(f);
6768 env->banked_r14[i] = qemu_get_be32(f);
6770 for (i = 0; i < 5; i++) {
6771 env->usr_regs[i] = qemu_get_be32(f);
6772 env->fiq_regs[i] = qemu_get_be32(f);
6774 env->cp15.c0_cpuid = qemu_get_be32(f);
6775 env->cp15.c0_cachetype = qemu_get_be32(f);
6776 env->cp15.c1_sys = qemu_get_be32(f);
6777 env->cp15.c1_coproc = qemu_get_be32(f);
6778 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6779 env->cp15.c2_base0 = qemu_get_be32(f);
6780 env->cp15.c2_base1 = qemu_get_be32(f);
6781 env->cp15.c2_mask = qemu_get_be32(f);
6782 env->cp15.c2_data = qemu_get_be32(f);
6783 env->cp15.c2_insn = qemu_get_be32(f);
6784 env->cp15.c3 = qemu_get_be32(f);
6785 env->cp15.c5_insn = qemu_get_be32(f);
6786 env->cp15.c5_data = qemu_get_be32(f);
6787 for (i = 0; i < 8; i++) {
6788 env->cp15.c6_region[i] = qemu_get_be32(f);
6790 env->cp15.c6_insn = qemu_get_be32(f);
6791 env->cp15.c6_data = qemu_get_be32(f);
6792 env->cp15.c9_insn = qemu_get_be32(f);
6793 env->cp15.c9_data = qemu_get_be32(f);
6794 env->cp15.c13_fcse = qemu_get_be32(f);
6795 env->cp15.c13_context = qemu_get_be32(f);
6796 env->cp15.c13_tls1 = qemu_get_be32(f);
6797 env->cp15.c13_tls2 = qemu_get_be32(f);
6798 env->cp15.c13_tls3 = qemu_get_be32(f);
6799 env->cp15.c15_cpar = qemu_get_be32(f);
6801 env->features = qemu_get_be32(f);
6803 if (arm_feature(env, ARM_FEATURE_VFP)) {
6804 for (i = 0; i < 16; i++) {
6806 u.l.upper = qemu_get_be32(f);
6807 u.l.lower = qemu_get_be32(f);
6808 env->vfp.regs[i] = u.d;
6810 for (i = 0; i < 16; i++) {
6811 env->vfp.xregs[i] = qemu_get_be32(f);
6814 /* TODO: Should use proper FPSCR access functions. */
6815 env->vfp.vec_len = qemu_get_be32(f);
6816 env->vfp.vec_stride = qemu_get_be32(f);
6818 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6819 for (i = 0; i < 16; i++) {
6821 u.l.upper = qemu_get_be32(f);
6822 u.l.lower = qemu_get_be32(f);
6823 env->vfp.regs[i] = u.d;
6828 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6829 for (i = 0; i < 16; i++) {
6830 env->iwmmxt.regs[i] = qemu_get_be64(f);
6832 for (i = 0; i < 16; i++) {
6833 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6837 if (arm_feature(env, ARM_FEATURE_M)) {
6838 env->v7m.other_sp = qemu_get_be32(f);
6839 env->v7m.vecbase = qemu_get_be32(f);
6840 env->v7m.basepri = qemu_get_be32(f);
6841 env->v7m.control = qemu_get_be32(f);
6842 env->v7m.current_sp = qemu_get_be32(f);
6843 env->v7m.exception = qemu_get_be32(f);
6851 //#warning No CPU save/restore functions
6855 /***********************************************************/
6856 /* ram save/restore */
6858 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6862 v = qemu_get_byte(f);
6865 if (qemu_get_buffer(f, buf, len) != len)
6869 v = qemu_get_byte(f);
6870 memset(buf, v, len);
6878 static int ram_load_v1(QEMUFile *f, void *opaque)
6882 if (qemu_get_be32(f) != phys_ram_size)
6884 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6885 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6892 #define BDRV_HASH_BLOCK_SIZE 1024
6893 #define IOBUF_SIZE 4096
6894 #define RAM_CBLOCK_MAGIC 0xfabe
6896 typedef struct RamCompressState {
6899 uint8_t buf[IOBUF_SIZE];
6902 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6905 memset(s, 0, sizeof(*s));
6907 ret = deflateInit2(&s->zstream, 1,
6909 9, Z_DEFAULT_STRATEGY);
6912 s->zstream.avail_out = IOBUF_SIZE;
6913 s->zstream.next_out = s->buf;
6917 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6919 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6920 qemu_put_be16(s->f, len);
6921 qemu_put_buffer(s->f, buf, len);
6924 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6928 s->zstream.avail_in = len;
6929 s->zstream.next_in = (uint8_t *)buf;
6930 while (s->zstream.avail_in > 0) {
6931 ret = deflate(&s->zstream, Z_NO_FLUSH);
6934 if (s->zstream.avail_out == 0) {
6935 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6936 s->zstream.avail_out = IOBUF_SIZE;
6937 s->zstream.next_out = s->buf;
6943 static void ram_compress_close(RamCompressState *s)
6947 /* compress last bytes */
6949 ret = deflate(&s->zstream, Z_FINISH);
6950 if (ret == Z_OK || ret == Z_STREAM_END) {
6951 len = IOBUF_SIZE - s->zstream.avail_out;
6953 ram_put_cblock(s, s->buf, len);
6955 s->zstream.avail_out = IOBUF_SIZE;
6956 s->zstream.next_out = s->buf;
6957 if (ret == Z_STREAM_END)
6964 deflateEnd(&s->zstream);
6967 typedef struct RamDecompressState {
6970 uint8_t buf[IOBUF_SIZE];
6971 } RamDecompressState;
6973 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6976 memset(s, 0, sizeof(*s));
6978 ret = inflateInit(&s->zstream);
6984 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6988 s->zstream.avail_out = len;
6989 s->zstream.next_out = buf;
6990 while (s->zstream.avail_out > 0) {
6991 if (s->zstream.avail_in == 0) {
6992 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6994 clen = qemu_get_be16(s->f);
6995 if (clen > IOBUF_SIZE)
6997 qemu_get_buffer(s->f, s->buf, clen);
6998 s->zstream.avail_in = clen;
6999 s->zstream.next_in = s->buf;
7001 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7002 if (ret != Z_OK && ret != Z_STREAM_END) {
7009 static void ram_decompress_close(RamDecompressState *s)
7011 inflateEnd(&s->zstream);
7014 static void ram_save(QEMUFile *f, void *opaque)
7017 RamCompressState s1, *s = &s1;
7020 qemu_put_be32(f, phys_ram_size);
7021 if (ram_compress_open(s, f) < 0)
7023 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7025 if (tight_savevm_enabled) {
7029 /* find if the memory block is available on a virtual
7032 for(j = 0; j < nb_drives; j++) {
7033 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7035 BDRV_HASH_BLOCK_SIZE);
7036 if (sector_num >= 0)
7040 goto normal_compress;
7043 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7044 ram_compress_buf(s, buf, 10);
7050 ram_compress_buf(s, buf, 1);
7051 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7054 ram_compress_close(s);
7057 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7059 RamDecompressState s1, *s = &s1;
7063 if (version_id == 1)
7064 return ram_load_v1(f, opaque);
7065 if (version_id != 2)
7067 if (qemu_get_be32(f) != phys_ram_size)
7069 if (ram_decompress_open(s, f) < 0)
7071 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7072 if (ram_decompress_buf(s, buf, 1) < 0) {
7073 fprintf(stderr, "Error while reading ram block header\n");
7077 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7078 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7087 ram_decompress_buf(s, buf + 1, 9);
7089 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7090 if (bs_index >= nb_drives) {
7091 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7094 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7096 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7097 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7098 bs_index, sector_num);
7105 printf("Error block header\n");
7109 ram_decompress_close(s);
7113 /***********************************************************/
7114 /* bottom halves (can be seen as timers which expire ASAP) */
7123 static QEMUBH *first_bh = NULL;
7125 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7128 bh = qemu_mallocz(sizeof(QEMUBH));
7132 bh->opaque = opaque;
7136 int qemu_bh_poll(void)
7155 void qemu_bh_schedule(QEMUBH *bh)
7157 CPUState *env = cpu_single_env;
7161 bh->next = first_bh;
7164 /* stop the currently executing CPU to execute the BH ASAP */
7166 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7170 void qemu_bh_cancel(QEMUBH *bh)
7173 if (bh->scheduled) {
7176 pbh = &(*pbh)->next;
7182 void qemu_bh_delete(QEMUBH *bh)
7188 /***********************************************************/
7189 /* machine registration */
7191 QEMUMachine *first_machine = NULL;
7193 int qemu_register_machine(QEMUMachine *m)
7196 pm = &first_machine;
7204 static QEMUMachine *find_machine(const char *name)
7208 for(m = first_machine; m != NULL; m = m->next) {
7209 if (!strcmp(m->name, name))
7215 /***********************************************************/
7216 /* main execution loop */
7218 static void gui_update(void *opaque)
7220 DisplayState *ds = opaque;
7221 ds->dpy_refresh(ds);
7222 qemu_mod_timer(ds->gui_timer,
7223 (ds->gui_timer_interval ?
7224 ds->gui_timer_interval :
7225 GUI_REFRESH_INTERVAL)
7226 + qemu_get_clock(rt_clock));
7229 struct vm_change_state_entry {
7230 VMChangeStateHandler *cb;
7232 LIST_ENTRY (vm_change_state_entry) entries;
7235 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7237 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7240 VMChangeStateEntry *e;
7242 e = qemu_mallocz(sizeof (*e));
7248 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7252 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7254 LIST_REMOVE (e, entries);
7258 static void vm_state_notify(int running)
7260 VMChangeStateEntry *e;
7262 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7263 e->cb(e->opaque, running);
7267 /* XXX: support several handlers */
7268 static VMStopHandler *vm_stop_cb;
7269 static void *vm_stop_opaque;
7271 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7274 vm_stop_opaque = opaque;
7278 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7289 qemu_rearm_alarm_timer(alarm_timer);
7293 void vm_stop(int reason)
7296 cpu_disable_ticks();
7300 vm_stop_cb(vm_stop_opaque, reason);
7307 /* reset/shutdown handler */
7309 typedef struct QEMUResetEntry {
7310 QEMUResetHandler *func;
7312 struct QEMUResetEntry *next;
7315 static QEMUResetEntry *first_reset_entry;
7316 static int reset_requested;
7317 static int shutdown_requested;
7318 static int powerdown_requested;
7320 int qemu_shutdown_requested(void)
7322 int r = shutdown_requested;
7323 shutdown_requested = 0;
7327 int qemu_reset_requested(void)
7329 int r = reset_requested;
7330 reset_requested = 0;
7334 int qemu_powerdown_requested(void)
7336 int r = powerdown_requested;
7337 powerdown_requested = 0;
7341 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7343 QEMUResetEntry **pre, *re;
7345 pre = &first_reset_entry;
7346 while (*pre != NULL)
7347 pre = &(*pre)->next;
7348 re = qemu_mallocz(sizeof(QEMUResetEntry));
7350 re->opaque = opaque;
7355 void qemu_system_reset(void)
7359 /* reset all devices */
7360 for(re = first_reset_entry; re != NULL; re = re->next) {
7361 re->func(re->opaque);
7365 void qemu_system_reset_request(void)
7368 shutdown_requested = 1;
7370 reset_requested = 1;
7373 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7376 void qemu_system_shutdown_request(void)
7378 shutdown_requested = 1;
7380 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7383 void qemu_system_powerdown_request(void)
7385 powerdown_requested = 1;
7387 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7390 void main_loop_wait(int timeout)
7392 IOHandlerRecord *ioh;
7393 fd_set rfds, wfds, xfds;
7402 /* XXX: need to suppress polling by better using win32 events */
7404 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7405 ret |= pe->func(pe->opaque);
7410 WaitObjects *w = &wait_objects;
7412 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7413 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7414 if (w->func[ret - WAIT_OBJECT_0])
7415 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7417 /* Check for additional signaled events */
7418 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7420 /* Check if event is signaled */
7421 ret2 = WaitForSingleObject(w->events[i], 0);
7422 if(ret2 == WAIT_OBJECT_0) {
7424 w->func[i](w->opaque[i]);
7425 } else if (ret2 == WAIT_TIMEOUT) {
7427 err = GetLastError();
7428 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7431 } else if (ret == WAIT_TIMEOUT) {
7433 err = GetLastError();
7434 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7438 /* poll any events */
7439 /* XXX: separate device handlers from system ones */
7444 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7448 (!ioh->fd_read_poll ||
7449 ioh->fd_read_poll(ioh->opaque) != 0)) {
7450 FD_SET(ioh->fd, &rfds);
7454 if (ioh->fd_write) {
7455 FD_SET(ioh->fd, &wfds);
7465 tv.tv_usec = timeout * 1000;
7467 #if defined(CONFIG_SLIRP)
7469 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7472 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7474 IOHandlerRecord **pioh;
7476 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7477 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7478 ioh->fd_read(ioh->opaque);
7480 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7481 ioh->fd_write(ioh->opaque);
7485 /* remove deleted IO handlers */
7486 pioh = &first_io_handler;
7496 #if defined(CONFIG_SLIRP)
7503 slirp_select_poll(&rfds, &wfds, &xfds);
7509 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7510 qemu_get_clock(vm_clock));
7511 /* run dma transfers, if any */
7515 /* real time timers */
7516 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7517 qemu_get_clock(rt_clock));
7519 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7520 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7521 qemu_rearm_alarm_timer(alarm_timer);
7524 /* Check bottom-halves last in case any of the earlier events triggered
7530 static int main_loop(void)
7533 #ifdef CONFIG_PROFILER
7538 cur_cpu = first_cpu;
7539 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7546 #ifdef CONFIG_PROFILER
7547 ti = profile_getclock();
7549 ret = cpu_exec(env);
7550 #ifdef CONFIG_PROFILER
7551 qemu_time += profile_getclock() - ti;
7553 next_cpu = env->next_cpu ?: first_cpu;
7554 if (event_pending && likely(ret != EXCP_DEBUG)) {
7555 ret = EXCP_INTERRUPT;
7559 if (ret == EXCP_HLT) {
7560 /* Give the next CPU a chance to run. */
7564 if (ret != EXCP_HALTED)
7566 /* all CPUs are halted ? */
7572 if (shutdown_requested) {
7573 ret = EXCP_INTERRUPT;
7581 if (reset_requested) {
7582 reset_requested = 0;
7583 qemu_system_reset();
7584 ret = EXCP_INTERRUPT;
7586 if (powerdown_requested) {
7587 powerdown_requested = 0;
7588 qemu_system_powerdown();
7589 ret = EXCP_INTERRUPT;
7591 if (unlikely(ret == EXCP_DEBUG)) {
7592 vm_stop(EXCP_DEBUG);
7594 /* If all cpus are halted then wait until the next IRQ */
7595 /* XXX: use timeout computed from timers */
7596 if (ret == EXCP_HALTED)
7603 #ifdef CONFIG_PROFILER
7604 ti = profile_getclock();
7606 main_loop_wait(timeout);
7607 #ifdef CONFIG_PROFILER
7608 dev_time += profile_getclock() - ti;
7611 cpu_disable_ticks();
7615 static void help(int exitcode)
7617 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7618 "usage: %s [options] [disk_image]\n"
7620 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7622 "Standard options:\n"
7623 "-M machine select emulated machine (-M ? for list)\n"
7624 "-cpu cpu select CPU (-cpu ? for list)\n"
7625 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7626 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7627 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7628 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7629 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7630 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7631 " [,cache=on|off]\n"
7632 " use 'file' as a drive image\n"
7633 "-mtdblock file use 'file' as on-board Flash memory image\n"
7634 "-sd file use 'file' as SecureDigital card image\n"
7635 "-pflash file use 'file' as a parallel flash image\n"
7636 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7637 "-snapshot write to temporary files instead of disk image files\n"
7639 "-no-frame open SDL window without a frame and window decorations\n"
7640 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7641 "-no-quit disable SDL window close capability\n"
7644 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7646 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7647 "-smp n set the number of CPUs to 'n' [default=1]\n"
7648 "-nographic disable graphical output and redirect serial I/Os to console\n"
7649 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7651 "-k language use keyboard layout (for example \"fr\" for French)\n"
7654 "-audio-help print list of audio drivers and their options\n"
7655 "-soundhw c1,... enable audio support\n"
7656 " and only specified sound cards (comma separated list)\n"
7657 " use -soundhw ? to get the list of supported cards\n"
7658 " use -soundhw all to enable all of them\n"
7660 "-localtime set the real time clock to local time [default=utc]\n"
7661 "-full-screen start in full screen\n"
7663 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7665 "-usb enable the USB driver (will be the default soon)\n"
7666 "-usbdevice name add the host or guest USB device 'name'\n"
7667 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7668 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7670 "-name string set the name of the guest\n"
7672 "Network options:\n"
7673 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7674 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7676 "-net user[,vlan=n][,hostname=host]\n"
7677 " connect the user mode network stack to VLAN 'n' and send\n"
7678 " hostname 'host' to DHCP clients\n"
7681 "-net tap[,vlan=n],ifname=name\n"
7682 " connect the host TAP network interface to VLAN 'n'\n"
7684 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7685 " connect the host TAP network interface to VLAN 'n' and use the\n"
7686 " network scripts 'file' (default=%s)\n"
7687 " and 'dfile' (default=%s);\n"
7688 " use '[down]script=no' to disable script execution;\n"
7689 " use 'fd=h' to connect to an already opened TAP interface\n"
7691 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7692 " connect the vlan 'n' to another VLAN using a socket connection\n"
7693 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7694 " connect the vlan 'n' to multicast maddr and port\n"
7695 "-net none use it alone to have zero network devices; if no -net option\n"
7696 " is provided, the default is '-net nic -net user'\n"
7699 "-tftp dir allow tftp access to files in dir [-net user]\n"
7700 "-bootp file advertise file in BOOTP replies\n"
7702 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7704 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7705 " redirect TCP or UDP connections from host to guest [-net user]\n"
7708 "Linux boot specific:\n"
7709 "-kernel bzImage use 'bzImage' as kernel image\n"
7710 "-append cmdline use 'cmdline' as kernel command line\n"
7711 "-initrd file use 'file' as initial ram disk\n"
7713 "Debug/Expert options:\n"
7714 "-monitor dev redirect the monitor to char device 'dev'\n"
7715 "-serial dev redirect the serial port to char device 'dev'\n"
7716 "-parallel dev redirect the parallel port to char device 'dev'\n"
7717 "-pidfile file Write PID to 'file'\n"
7718 "-S freeze CPU at startup (use 'c' to start execution)\n"
7719 "-s wait gdb connection to port\n"
7720 "-p port set gdb connection port [default=%s]\n"
7721 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7722 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7723 " translation (t=none or lba) (usually qemu can guess them)\n"
7724 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7726 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7727 "-no-kqemu disable KQEMU kernel module usage\n"
7730 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7731 " (default is CL-GD5446 PCI VGA)\n"
7732 "-no-acpi disable ACPI\n"
7734 #ifdef CONFIG_CURSES
7735 "-curses use a curses/ncurses interface instead of SDL\n"
7737 "-no-reboot exit instead of rebooting\n"
7738 "-no-shutdown stop before shutdown\n"
7739 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7740 "-vnc display start a VNC server on display\n"
7742 "-daemonize daemonize QEMU after initializing\n"
7744 "-option-rom rom load a file, rom, into the option ROM space\n"
7746 "-prom-env variable=value set OpenBIOS nvram variables\n"
7748 "-clock force the use of the given methods for timer alarm.\n"
7749 " To see what timers are available use -clock ?\n"
7750 "-startdate select initial date of the clock\n"
7752 "During emulation, the following keys are useful:\n"
7753 "ctrl-alt-f toggle full screen\n"
7754 "ctrl-alt-n switch to virtual console 'n'\n"
7755 "ctrl-alt toggle mouse and keyboard grab\n"
7757 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7762 DEFAULT_NETWORK_SCRIPT,
7763 DEFAULT_NETWORK_DOWN_SCRIPT,
7765 DEFAULT_GDBSTUB_PORT,
7770 #define HAS_ARG 0x0001
7785 QEMU_OPTION_mtdblock,
7789 QEMU_OPTION_snapshot,
7791 QEMU_OPTION_no_fd_bootchk,
7794 QEMU_OPTION_nographic,
7795 QEMU_OPTION_portrait,
7797 QEMU_OPTION_audio_help,
7798 QEMU_OPTION_soundhw,
7818 QEMU_OPTION_no_code_copy,
7820 QEMU_OPTION_localtime,
7821 QEMU_OPTION_cirrusvga,
7824 QEMU_OPTION_std_vga,
7826 QEMU_OPTION_monitor,
7828 QEMU_OPTION_parallel,
7830 QEMU_OPTION_full_screen,
7831 QEMU_OPTION_no_frame,
7832 QEMU_OPTION_alt_grab,
7833 QEMU_OPTION_no_quit,
7834 QEMU_OPTION_pidfile,
7835 QEMU_OPTION_no_kqemu,
7836 QEMU_OPTION_kernel_kqemu,
7837 QEMU_OPTION_win2k_hack,
7839 QEMU_OPTION_usbdevice,
7842 QEMU_OPTION_no_acpi,
7844 QEMU_OPTION_no_reboot,
7845 QEMU_OPTION_no_shutdown,
7846 QEMU_OPTION_show_cursor,
7847 QEMU_OPTION_daemonize,
7848 QEMU_OPTION_option_rom,
7849 QEMU_OPTION_semihosting,
7851 QEMU_OPTION_prom_env,
7852 QEMU_OPTION_old_param,
7854 QEMU_OPTION_startdate,
7857 typedef struct QEMUOption {
7863 const QEMUOption qemu_options[] = {
7864 { "h", 0, QEMU_OPTION_h },
7865 { "help", 0, QEMU_OPTION_h },
7867 { "M", HAS_ARG, QEMU_OPTION_M },
7868 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7869 { "fda", HAS_ARG, QEMU_OPTION_fda },
7870 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7871 { "hda", HAS_ARG, QEMU_OPTION_hda },
7872 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7873 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7874 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7875 { "drive", HAS_ARG, QEMU_OPTION_drive },
7876 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7877 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7878 { "sd", HAS_ARG, QEMU_OPTION_sd },
7879 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7880 { "boot", HAS_ARG, QEMU_OPTION_boot },
7881 { "snapshot", 0, QEMU_OPTION_snapshot },
7883 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7885 { "m", HAS_ARG, QEMU_OPTION_m },
7886 { "nographic", 0, QEMU_OPTION_nographic },
7887 { "portrait", 0, QEMU_OPTION_portrait },
7888 { "k", HAS_ARG, QEMU_OPTION_k },
7890 { "audio-help", 0, QEMU_OPTION_audio_help },
7891 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7894 { "net", HAS_ARG, QEMU_OPTION_net},
7896 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7897 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7899 { "smb", HAS_ARG, QEMU_OPTION_smb },
7901 { "redir", HAS_ARG, QEMU_OPTION_redir },
7904 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7905 { "append", HAS_ARG, QEMU_OPTION_append },
7906 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7908 { "S", 0, QEMU_OPTION_S },
7909 { "s", 0, QEMU_OPTION_s },
7910 { "p", HAS_ARG, QEMU_OPTION_p },
7911 { "d", HAS_ARG, QEMU_OPTION_d },
7912 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7913 { "L", HAS_ARG, QEMU_OPTION_L },
7914 { "bios", HAS_ARG, QEMU_OPTION_bios },
7915 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7917 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7918 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7920 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7921 { "g", 1, QEMU_OPTION_g },
7923 { "localtime", 0, QEMU_OPTION_localtime },
7924 { "std-vga", 0, QEMU_OPTION_std_vga },
7925 { "echr", HAS_ARG, QEMU_OPTION_echr },
7926 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7927 { "serial", HAS_ARG, QEMU_OPTION_serial },
7928 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7929 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7930 { "full-screen", 0, QEMU_OPTION_full_screen },
7932 { "no-frame", 0, QEMU_OPTION_no_frame },
7933 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7934 { "no-quit", 0, QEMU_OPTION_no_quit },
7936 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7937 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7938 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7939 { "smp", HAS_ARG, QEMU_OPTION_smp },
7940 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7941 #ifdef CONFIG_CURSES
7942 { "curses", 0, QEMU_OPTION_curses },
7945 /* temporary options */
7946 { "usb", 0, QEMU_OPTION_usb },
7947 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7948 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7949 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7950 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7951 { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7952 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7953 { "daemonize", 0, QEMU_OPTION_daemonize },
7954 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7955 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7956 { "semihosting", 0, QEMU_OPTION_semihosting },
7958 { "name", HAS_ARG, QEMU_OPTION_name },
7959 #if defined(TARGET_SPARC)
7960 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7962 #if defined(TARGET_ARM)
7963 { "old-param", 0, QEMU_OPTION_old_param },
7965 { "clock", HAS_ARG, QEMU_OPTION_clock },
7966 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7970 /* password input */
7972 int qemu_key_check(BlockDriverState *bs, const char *name)
7977 if (!bdrv_is_encrypted(bs))
7980 term_printf("%s is encrypted.\n", name);
7981 for(i = 0; i < 3; i++) {
7982 monitor_readline("Password: ", 1, password, sizeof(password));
7983 if (bdrv_set_key(bs, password) == 0)
7985 term_printf("invalid password\n");
7990 static BlockDriverState *get_bdrv(int index)
7992 if (index > nb_drives)
7994 return drives_table[index].bdrv;
7997 static void read_passwords(void)
7999 BlockDriverState *bs;
8002 for(i = 0; i < 6; i++) {
8005 qemu_key_check(bs, bdrv_get_device_name(bs));
8009 /* XXX: currently we cannot use simultaneously different CPUs */
8010 static void register_machines(void)
8012 #if defined(TARGET_I386)
8013 qemu_register_machine(&pc_machine);
8014 qemu_register_machine(&isapc_machine);
8015 #elif defined(TARGET_PPC)
8016 qemu_register_machine(&heathrow_machine);
8017 qemu_register_machine(&core99_machine);
8018 qemu_register_machine(&prep_machine);
8019 qemu_register_machine(&ref405ep_machine);
8020 qemu_register_machine(&taihu_machine);
8021 #elif defined(TARGET_MIPS)
8022 qemu_register_machine(&mips_machine);
8023 qemu_register_machine(&mips_magnum_machine);
8024 qemu_register_machine(&mips_malta_machine);
8025 qemu_register_machine(&mips_pica61_machine);
8026 qemu_register_machine(&mips_mipssim_machine);
8027 #elif defined(TARGET_SPARC)
8028 #ifdef TARGET_SPARC64
8029 qemu_register_machine(&sun4u_machine);
8031 qemu_register_machine(&ss5_machine);
8032 qemu_register_machine(&ss10_machine);
8033 qemu_register_machine(&ss600mp_machine);
8034 qemu_register_machine(&ss20_machine);
8035 qemu_register_machine(&ss2_machine);
8036 qemu_register_machine(&voyager_machine);
8037 qemu_register_machine(&ss_lx_machine);
8038 qemu_register_machine(&ss4_machine);
8039 qemu_register_machine(&scls_machine);
8040 qemu_register_machine(&sbook_machine);
8041 qemu_register_machine(&ss1000_machine);
8042 qemu_register_machine(&ss2000_machine);
8044 #elif defined(TARGET_ARM)
8045 qemu_register_machine(&integratorcp_machine);
8046 qemu_register_machine(&versatilepb_machine);
8047 qemu_register_machine(&versatileab_machine);
8048 qemu_register_machine(&realview_machine);
8049 qemu_register_machine(&akitapda_machine);
8050 qemu_register_machine(&spitzpda_machine);
8051 qemu_register_machine(&borzoipda_machine);
8052 qemu_register_machine(&terrierpda_machine);
8053 qemu_register_machine(&palmte_machine);
8054 qemu_register_machine(&lm3s811evb_machine);
8055 qemu_register_machine(&lm3s6965evb_machine);
8056 qemu_register_machine(&connex_machine);
8057 qemu_register_machine(&verdex_machine);
8058 qemu_register_machine(&mainstone2_machine);
8059 #elif defined(TARGET_SH4)
8060 qemu_register_machine(&shix_machine);
8061 qemu_register_machine(&r2d_machine);
8062 #elif defined(TARGET_ALPHA)
8064 #elif defined(TARGET_M68K)
8065 qemu_register_machine(&mcf5208evb_machine);
8066 qemu_register_machine(&an5206_machine);
8067 qemu_register_machine(&dummy_m68k_machine);
8068 #elif defined(TARGET_CRIS)
8069 qemu_register_machine(&bareetraxfs_machine);
8071 #error unsupported CPU
8076 struct soundhw soundhw[] = {
8077 #ifdef HAS_AUDIO_CHOICE
8078 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8084 { .init_isa = pcspk_audio_init }
8089 "Creative Sound Blaster 16",
8092 { .init_isa = SB16_init }
8099 "Yamaha YMF262 (OPL3)",
8101 "Yamaha YM3812 (OPL2)",
8105 { .init_isa = Adlib_init }
8112 "Gravis Ultrasound GF1",
8115 { .init_isa = GUS_init }
8122 "Intel 82801AA AC97 Audio",
8125 { .init_pci = ac97_init }
8131 "ENSONIQ AudioPCI ES1370",
8134 { .init_pci = es1370_init }
8138 { NULL, NULL, 0, 0, { NULL } }
8141 static void select_soundhw (const char *optarg)
8145 if (*optarg == '?') {
8148 printf ("Valid sound card names (comma separated):\n");
8149 for (c = soundhw; c->name; ++c) {
8150 printf ("%-11s %s\n", c->name, c->descr);
8152 printf ("\n-soundhw all will enable all of the above\n");
8153 exit (*optarg != '?');
8161 if (!strcmp (optarg, "all")) {
8162 for (c = soundhw; c->name; ++c) {
8170 e = strchr (p, ',');
8171 l = !e ? strlen (p) : (size_t) (e - p);
8173 for (c = soundhw; c->name; ++c) {
8174 if (!strncmp (c->name, p, l)) {
8183 "Unknown sound card name (too big to show)\n");
8186 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8191 p += l + (e != NULL);
8195 goto show_valid_cards;
8201 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8203 exit(STATUS_CONTROL_C_EXIT);
8208 #define MAX_NET_CLIENTS 32
8210 int main(int argc, char **argv)
8212 #ifdef CONFIG_GDBSTUB
8214 const char *gdbstub_port;
8216 uint32_t boot_devices_bitmap = 0;
8218 int snapshot, linux_boot, net_boot;
8219 const char *initrd_filename;
8220 const char *kernel_filename, *kernel_cmdline;
8221 const char *boot_devices = "";
8222 DisplayState *ds = &display_state;
8223 int cyls, heads, secs, translation;
8224 const char *net_clients[MAX_NET_CLIENTS];
8228 const char *r, *optarg;
8229 CharDriverState *monitor_hd;
8230 const char *monitor_device;
8231 const char *serial_devices[MAX_SERIAL_PORTS];
8232 int serial_device_index;
8233 const char *parallel_devices[MAX_PARALLEL_PORTS];
8234 int parallel_device_index;
8235 const char *loadvm = NULL;
8236 QEMUMachine *machine;
8237 const char *cpu_model;
8238 const char *usb_devices[MAX_USB_CMDLINE];
8239 int usb_devices_index;
8241 const char *pid_file = NULL;
8244 LIST_INIT (&vm_change_state_head);
8247 struct sigaction act;
8248 sigfillset(&act.sa_mask);
8250 act.sa_handler = SIG_IGN;
8251 sigaction(SIGPIPE, &act, NULL);
8254 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8255 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8256 QEMU to run on a single CPU */
8261 h = GetCurrentProcess();
8262 if (GetProcessAffinityMask(h, &mask, &smask)) {
8263 for(i = 0; i < 32; i++) {
8264 if (mask & (1 << i))
8269 SetProcessAffinityMask(h, mask);
8275 register_machines();
8276 machine = first_machine;
8278 initrd_filename = NULL;
8279 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8280 vga_ram_size = VGA_RAM_SIZE;
8281 #ifdef CONFIG_GDBSTUB
8283 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8288 kernel_filename = NULL;
8289 kernel_cmdline = "";
8290 cyls = heads = secs = 0;
8291 translation = BIOS_ATA_TRANSLATION_AUTO;
8292 monitor_device = "vc";
8294 serial_devices[0] = "vc";
8295 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8296 serial_devices[i] = NULL;
8297 serial_device_index = 0;
8299 parallel_devices[0] = "vc";
8300 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8301 parallel_devices[i] = NULL;
8302 parallel_device_index = 0;
8304 usb_devices_index = 0;
8312 /* default mac address of the first network interface */
8320 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8322 const QEMUOption *popt;
8325 /* Treat --foo the same as -foo. */
8328 popt = qemu_options;
8331 fprintf(stderr, "%s: invalid option -- '%s'\n",
8335 if (!strcmp(popt->name, r + 1))
8339 if (popt->flags & HAS_ARG) {
8340 if (optind >= argc) {
8341 fprintf(stderr, "%s: option '%s' requires an argument\n",
8345 optarg = argv[optind++];
8350 switch(popt->index) {
8352 machine = find_machine(optarg);
8355 printf("Supported machines are:\n");
8356 for(m = first_machine; m != NULL; m = m->next) {
8357 printf("%-10s %s%s\n",
8359 m == first_machine ? " (default)" : "");
8361 exit(*optarg != '?');
8364 case QEMU_OPTION_cpu:
8365 /* hw initialization will check this */
8366 if (*optarg == '?') {
8367 /* XXX: implement xxx_cpu_list for targets that still miss it */
8368 #if defined(cpu_list)
8369 cpu_list(stdout, &fprintf);
8376 case QEMU_OPTION_initrd:
8377 initrd_filename = optarg;
8379 case QEMU_OPTION_hda:
8381 hda_index = drive_add(optarg, HD_ALIAS, 0);
8383 hda_index = drive_add(optarg, HD_ALIAS
8384 ",cyls=%d,heads=%d,secs=%d%s",
8385 0, cyls, heads, secs,
8386 translation == BIOS_ATA_TRANSLATION_LBA ?
8388 translation == BIOS_ATA_TRANSLATION_NONE ?
8389 ",trans=none" : "");
8391 case QEMU_OPTION_hdb:
8392 case QEMU_OPTION_hdc:
8393 case QEMU_OPTION_hdd:
8394 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8396 case QEMU_OPTION_drive:
8397 drive_add(NULL, "%s", optarg);
8399 case QEMU_OPTION_mtdblock:
8400 drive_add(optarg, MTD_ALIAS);
8402 case QEMU_OPTION_sd:
8403 drive_add(optarg, SD_ALIAS);
8405 case QEMU_OPTION_pflash:
8406 drive_add(optarg, PFLASH_ALIAS);
8408 case QEMU_OPTION_snapshot:
8411 case QEMU_OPTION_hdachs:
8415 cyls = strtol(p, (char **)&p, 0);
8416 if (cyls < 1 || cyls > 16383)
8421 heads = strtol(p, (char **)&p, 0);
8422 if (heads < 1 || heads > 16)
8427 secs = strtol(p, (char **)&p, 0);
8428 if (secs < 1 || secs > 63)
8432 if (!strcmp(p, "none"))
8433 translation = BIOS_ATA_TRANSLATION_NONE;
8434 else if (!strcmp(p, "lba"))
8435 translation = BIOS_ATA_TRANSLATION_LBA;
8436 else if (!strcmp(p, "auto"))
8437 translation = BIOS_ATA_TRANSLATION_AUTO;
8440 } else if (*p != '\0') {
8442 fprintf(stderr, "qemu: invalid physical CHS format\n");
8445 if (hda_index != -1)
8446 snprintf(drives_opt[hda_index].opt,
8447 sizeof(drives_opt[hda_index].opt),
8448 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8449 0, cyls, heads, secs,
8450 translation == BIOS_ATA_TRANSLATION_LBA ?
8452 translation == BIOS_ATA_TRANSLATION_NONE ?
8453 ",trans=none" : "");
8456 case QEMU_OPTION_nographic:
8457 serial_devices[0] = "stdio";
8458 parallel_devices[0] = "null";
8459 monitor_device = "stdio";
8462 #ifdef CONFIG_CURSES
8463 case QEMU_OPTION_curses:
8467 case QEMU_OPTION_portrait:
8470 case QEMU_OPTION_kernel:
8471 kernel_filename = optarg;
8473 case QEMU_OPTION_append:
8474 kernel_cmdline = optarg;
8476 case QEMU_OPTION_cdrom:
8477 drive_add(optarg, CDROM_ALIAS);
8479 case QEMU_OPTION_boot:
8480 boot_devices = optarg;
8481 /* We just do some generic consistency checks */
8483 /* Could easily be extended to 64 devices if needed */
8486 boot_devices_bitmap = 0;
8487 for (p = boot_devices; *p != '\0'; p++) {
8488 /* Allowed boot devices are:
8489 * a b : floppy disk drives
8490 * c ... f : IDE disk drives
8491 * g ... m : machine implementation dependant drives
8492 * n ... p : network devices
8493 * It's up to each machine implementation to check
8494 * if the given boot devices match the actual hardware
8495 * implementation and firmware features.
8497 if (*p < 'a' || *p > 'q') {
8498 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8501 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8503 "Boot device '%c' was given twice\n",*p);
8506 boot_devices_bitmap |= 1 << (*p - 'a');
8510 case QEMU_OPTION_fda:
8511 case QEMU_OPTION_fdb:
8512 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8515 case QEMU_OPTION_no_fd_bootchk:
8519 case QEMU_OPTION_no_code_copy:
8520 code_copy_enabled = 0;
8522 case QEMU_OPTION_net:
8523 if (nb_net_clients >= MAX_NET_CLIENTS) {
8524 fprintf(stderr, "qemu: too many network clients\n");
8527 net_clients[nb_net_clients] = optarg;
8531 case QEMU_OPTION_tftp:
8532 tftp_prefix = optarg;
8534 case QEMU_OPTION_bootp:
8535 bootp_filename = optarg;
8538 case QEMU_OPTION_smb:
8539 net_slirp_smb(optarg);
8542 case QEMU_OPTION_redir:
8543 net_slirp_redir(optarg);
8547 case QEMU_OPTION_audio_help:
8551 case QEMU_OPTION_soundhw:
8552 select_soundhw (optarg);
8559 ram_size = atoi(optarg) * 1024 * 1024;
8562 if (ram_size > PHYS_RAM_MAX_SIZE) {
8563 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8564 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8573 mask = cpu_str_to_log_mask(optarg);
8575 printf("Log items (comma separated):\n");
8576 for(item = cpu_log_items; item->mask != 0; item++) {
8577 printf("%-10s %s\n", item->name, item->help);
8584 #ifdef CONFIG_GDBSTUB
8589 gdbstub_port = optarg;
8595 case QEMU_OPTION_bios:
8602 keyboard_layout = optarg;
8604 case QEMU_OPTION_localtime:
8607 case QEMU_OPTION_cirrusvga:
8608 cirrus_vga_enabled = 1;
8611 case QEMU_OPTION_vmsvga:
8612 cirrus_vga_enabled = 0;
8615 case QEMU_OPTION_std_vga:
8616 cirrus_vga_enabled = 0;
8624 w = strtol(p, (char **)&p, 10);
8627 fprintf(stderr, "qemu: invalid resolution or depth\n");
8633 h = strtol(p, (char **)&p, 10);
8638 depth = strtol(p, (char **)&p, 10);
8639 if (depth != 8 && depth != 15 && depth != 16 &&
8640 depth != 24 && depth != 32)
8642 } else if (*p == '\0') {
8643 depth = graphic_depth;
8650 graphic_depth = depth;
8653 case QEMU_OPTION_echr:
8656 term_escape_char = strtol(optarg, &r, 0);
8658 printf("Bad argument to echr\n");
8661 case QEMU_OPTION_monitor:
8662 monitor_device = optarg;
8664 case QEMU_OPTION_serial:
8665 if (serial_device_index >= MAX_SERIAL_PORTS) {
8666 fprintf(stderr, "qemu: too many serial ports\n");
8669 serial_devices[serial_device_index] = optarg;
8670 serial_device_index++;
8672 case QEMU_OPTION_parallel:
8673 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8674 fprintf(stderr, "qemu: too many parallel ports\n");
8677 parallel_devices[parallel_device_index] = optarg;
8678 parallel_device_index++;
8680 case QEMU_OPTION_loadvm:
8683 case QEMU_OPTION_full_screen:
8687 case QEMU_OPTION_no_frame:
8690 case QEMU_OPTION_alt_grab:
8693 case QEMU_OPTION_no_quit:
8697 case QEMU_OPTION_pidfile:
8701 case QEMU_OPTION_win2k_hack:
8702 win2k_install_hack = 1;
8706 case QEMU_OPTION_no_kqemu:
8709 case QEMU_OPTION_kernel_kqemu:
8713 case QEMU_OPTION_usb:
8716 case QEMU_OPTION_usbdevice:
8718 if (usb_devices_index >= MAX_USB_CMDLINE) {
8719 fprintf(stderr, "Too many USB devices\n");
8722 usb_devices[usb_devices_index] = optarg;
8723 usb_devices_index++;
8725 case QEMU_OPTION_smp:
8726 smp_cpus = atoi(optarg);
8727 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8728 fprintf(stderr, "Invalid number of CPUs\n");
8732 case QEMU_OPTION_vnc:
8733 vnc_display = optarg;
8735 case QEMU_OPTION_no_acpi:
8738 case QEMU_OPTION_no_reboot:
8741 case QEMU_OPTION_no_shutdown:
8744 case QEMU_OPTION_show_cursor:
8747 case QEMU_OPTION_daemonize:
8750 case QEMU_OPTION_option_rom:
8751 if (nb_option_roms >= MAX_OPTION_ROMS) {
8752 fprintf(stderr, "Too many option ROMs\n");
8755 option_rom[nb_option_roms] = optarg;
8758 case QEMU_OPTION_semihosting:
8759 semihosting_enabled = 1;
8761 case QEMU_OPTION_name:
8765 case QEMU_OPTION_prom_env:
8766 if (nb_prom_envs >= MAX_PROM_ENVS) {
8767 fprintf(stderr, "Too many prom variables\n");
8770 prom_envs[nb_prom_envs] = optarg;
8775 case QEMU_OPTION_old_param:
8779 case QEMU_OPTION_clock:
8780 configure_alarms(optarg);
8782 case QEMU_OPTION_startdate:
8785 time_t rtc_start_date;
8786 if (!strcmp(optarg, "now")) {
8787 rtc_date_offset = -1;
8789 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8797 } else if (sscanf(optarg, "%d-%d-%d",
8800 &tm.tm_mday) == 3) {
8809 rtc_start_date = mktimegm(&tm);
8810 if (rtc_start_date == -1) {
8812 fprintf(stderr, "Invalid date format. Valid format are:\n"
8813 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8816 rtc_date_offset = time(NULL) - rtc_start_date;
8825 if (daemonize && !nographic && vnc_display == NULL) {
8826 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8833 if (pipe(fds) == -1)
8844 len = read(fds[0], &status, 1);
8845 if (len == -1 && (errno == EINTR))
8850 else if (status == 1) {
8851 fprintf(stderr, "Could not acquire pidfile\n");
8869 signal(SIGTSTP, SIG_IGN);
8870 signal(SIGTTOU, SIG_IGN);
8871 signal(SIGTTIN, SIG_IGN);
8875 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8878 write(fds[1], &status, 1);
8880 fprintf(stderr, "Could not acquire pid file\n");
8888 linux_boot = (kernel_filename != NULL);
8889 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8891 /* XXX: this should not be: some embedded targets just have flash */
8892 if (!linux_boot && net_boot == 0 &&
8896 /* boot to floppy or the default cd if no hard disk defined yet */
8897 if (!boot_devices[0]) {
8898 boot_devices = "cad";
8900 setvbuf(stdout, NULL, _IOLBF, 0);
8910 /* init network clients */
8911 if (nb_net_clients == 0) {
8912 /* if no clients, we use a default config */
8913 net_clients[0] = "nic";
8914 net_clients[1] = "user";
8918 for(i = 0;i < nb_net_clients; i++) {
8919 if (net_client_init(net_clients[i]) < 0)
8922 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8923 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8925 if (vlan->nb_guest_devs == 0) {
8926 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8929 if (vlan->nb_host_devs == 0)
8931 "Warning: vlan %d is not connected to host network\n",
8936 /* XXX: this should be moved in the PC machine instantiation code */
8937 if (net_boot != 0) {
8939 for (i = 0; i < nb_nics && i < 4; i++) {
8940 const char *model = nd_table[i].model;
8942 if (net_boot & (1 << i)) {
8945 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8946 if (get_image_size(buf) > 0) {
8947 if (nb_option_roms >= MAX_OPTION_ROMS) {
8948 fprintf(stderr, "Too many option ROMs\n");
8951 option_rom[nb_option_roms] = strdup(buf);
8958 fprintf(stderr, "No valid PXE rom found for network device\n");
8964 /* init the memory */
8965 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8967 phys_ram_base = qemu_vmalloc(phys_ram_size);
8968 if (!phys_ram_base) {
8969 fprintf(stderr, "Could not allocate physical memory\n");
8975 /* we always create the cdrom drive, even if no disk is there */
8977 if (nb_drives_opt < MAX_DRIVES)
8978 drive_add(NULL, CDROM_ALIAS);
8980 /* we always create at least one floppy */
8982 if (nb_drives_opt < MAX_DRIVES)
8983 drive_add(NULL, FD_ALIAS, 0);
8985 /* we always create one sd slot, even if no card is in it */
8987 if (nb_drives_opt < MAX_DRIVES)
8988 drive_add(NULL, SD_ALIAS);
8990 /* open the virtual block devices */
8992 for(i = 0; i < nb_drives_opt; i++)
8993 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8996 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8997 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9002 memset(&display_state, 0, sizeof(display_state));
9005 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9008 /* nearly nothing to do */
9009 dumb_display_init(ds);
9010 } else if (vnc_display != NULL) {
9011 vnc_display_init(ds);
9012 if (vnc_display_open(ds, vnc_display) < 0)
9015 #if defined(CONFIG_CURSES)
9017 curses_display_init(ds, full_screen);
9021 #if defined(CONFIG_SDL)
9022 sdl_display_init(ds, full_screen, no_frame);
9023 #elif defined(CONFIG_COCOA)
9024 cocoa_display_init(ds, full_screen);
9026 dumb_display_init(ds);
9030 /* Maintain compatibility with multiple stdio monitors */
9031 if (!strcmp(monitor_device,"stdio")) {
9032 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9033 const char *devname = serial_devices[i];
9034 if (devname && !strcmp(devname,"mon:stdio")) {
9035 monitor_device = NULL;
9037 } else if (devname && !strcmp(devname,"stdio")) {
9038 monitor_device = NULL;
9039 serial_devices[i] = "mon:stdio";
9044 if (monitor_device) {
9045 monitor_hd = qemu_chr_open(monitor_device);
9047 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9050 monitor_init(monitor_hd, !nographic);
9053 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9054 const char *devname = serial_devices[i];
9055 if (devname && strcmp(devname, "none")) {
9056 serial_hds[i] = qemu_chr_open(devname);
9057 if (!serial_hds[i]) {
9058 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9062 if (strstart(devname, "vc", 0))
9063 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9067 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9068 const char *devname = parallel_devices[i];
9069 if (devname && strcmp(devname, "none")) {
9070 parallel_hds[i] = qemu_chr_open(devname);
9071 if (!parallel_hds[i]) {
9072 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9076 if (strstart(devname, "vc", 0))
9077 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9081 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9082 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9084 /* init USB devices */
9086 for(i = 0; i < usb_devices_index; i++) {
9087 if (usb_device_add(usb_devices[i]) < 0) {
9088 fprintf(stderr, "Warning: could not add USB device %s\n",
9094 if (display_state.dpy_refresh) {
9095 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9096 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9099 #ifdef CONFIG_GDBSTUB
9101 /* XXX: use standard host:port notation and modify options
9103 if (gdbserver_start(gdbstub_port) < 0) {
9104 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9115 /* XXX: simplify init */
9128 len = write(fds[1], &status, 1);
9129 if (len == -1 && (errno == EINTR))
9135 TFR(fd = open("/dev/null", O_RDWR));
9149 #if !defined(_WIN32)
9150 /* close network clients */
9151 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9152 VLANClientState *vc;
9154 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9155 if (vc->fd_read == tap_receive) {
9157 TAPState *s = vc->opaque;
9159 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9161 launch_script(s->down_script, ifname, s->fd);