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;
219 int graphic_rotate = 0;
221 const char *option_rom[MAX_OPTION_ROMS];
223 int semihosting_enabled = 0;
228 const char *qemu_name;
231 unsigned int nb_prom_envs = 0;
232 const char *prom_envs[MAX_PROM_ENVS];
238 } drives_opt[MAX_DRIVES];
240 static CPUState *cur_cpu;
241 static CPUState *next_cpu;
242 static int event_pending = 1;
244 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
246 /***********************************************************/
247 /* x86 ISA bus support */
249 target_phys_addr_t isa_mem_base = 0;
252 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
254 #ifdef DEBUG_UNUSED_IOPORT
255 fprintf(stderr, "unused inb: port=0x%04x\n", address);
260 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
262 #ifdef DEBUG_UNUSED_IOPORT
263 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
267 /* default is to make two byte accesses */
268 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
271 data = ioport_read_table[0][address](ioport_opaque[address], address);
272 address = (address + 1) & (MAX_IOPORTS - 1);
273 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
277 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
279 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
280 address = (address + 1) & (MAX_IOPORTS - 1);
281 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
284 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
286 #ifdef DEBUG_UNUSED_IOPORT
287 fprintf(stderr, "unused inl: port=0x%04x\n", address);
292 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
294 #ifdef DEBUG_UNUSED_IOPORT
295 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
299 static void init_ioports(void)
303 for(i = 0; i < MAX_IOPORTS; i++) {
304 ioport_read_table[0][i] = default_ioport_readb;
305 ioport_write_table[0][i] = default_ioport_writeb;
306 ioport_read_table[1][i] = default_ioport_readw;
307 ioport_write_table[1][i] = default_ioport_writew;
308 ioport_read_table[2][i] = default_ioport_readl;
309 ioport_write_table[2][i] = default_ioport_writel;
313 /* size is the word size in byte */
314 int register_ioport_read(int start, int length, int size,
315 IOPortReadFunc *func, void *opaque)
321 } else if (size == 2) {
323 } else if (size == 4) {
326 hw_error("register_ioport_read: invalid size");
329 for(i = start; i < start + length; i += size) {
330 ioport_read_table[bsize][i] = func;
331 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
332 hw_error("register_ioport_read: invalid opaque");
333 ioport_opaque[i] = opaque;
338 /* size is the word size in byte */
339 int register_ioport_write(int start, int length, int size,
340 IOPortWriteFunc *func, void *opaque)
346 } else if (size == 2) {
348 } else if (size == 4) {
351 hw_error("register_ioport_write: invalid size");
354 for(i = start; i < start + length; i += size) {
355 ioport_write_table[bsize][i] = func;
356 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
357 hw_error("register_ioport_write: invalid opaque");
358 ioport_opaque[i] = opaque;
363 void isa_unassign_ioport(int start, int length)
367 for(i = start; i < start + length; i++) {
368 ioport_read_table[0][i] = default_ioport_readb;
369 ioport_read_table[1][i] = default_ioport_readw;
370 ioport_read_table[2][i] = default_ioport_readl;
372 ioport_write_table[0][i] = default_ioport_writeb;
373 ioport_write_table[1][i] = default_ioport_writew;
374 ioport_write_table[2][i] = default_ioport_writel;
378 /***********************************************************/
380 void cpu_outb(CPUState *env, int addr, int val)
383 if (loglevel & CPU_LOG_IOPORT)
384 fprintf(logfile, "outb: %04x %02x\n", addr, val);
386 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
389 env->last_io_time = cpu_get_time_fast();
393 void cpu_outw(CPUState *env, int addr, int val)
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "outw: %04x %04x\n", addr, val);
399 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
402 env->last_io_time = cpu_get_time_fast();
406 void cpu_outl(CPUState *env, int addr, int val)
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "outl: %04x %08x\n", addr, val);
412 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
415 env->last_io_time = cpu_get_time_fast();
419 int cpu_inb(CPUState *env, int addr)
422 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
424 if (loglevel & CPU_LOG_IOPORT)
425 fprintf(logfile, "inb : %04x %02x\n", addr, val);
429 env->last_io_time = cpu_get_time_fast();
434 int cpu_inw(CPUState *env, int addr)
437 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
439 if (loglevel & CPU_LOG_IOPORT)
440 fprintf(logfile, "inw : %04x %04x\n", addr, val);
444 env->last_io_time = cpu_get_time_fast();
449 int cpu_inl(CPUState *env, int addr)
452 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
454 if (loglevel & CPU_LOG_IOPORT)
455 fprintf(logfile, "inl : %04x %08x\n", addr, val);
459 env->last_io_time = cpu_get_time_fast();
464 /***********************************************************/
465 void hw_error(const char *fmt, ...)
471 fprintf(stderr, "qemu: hardware error: ");
472 vfprintf(stderr, fmt, ap);
473 fprintf(stderr, "\n");
474 for(env = first_cpu; env != NULL; env = env->next_cpu) {
475 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
477 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
479 cpu_dump_state(env, stderr, fprintf, 0);
486 /***********************************************************/
489 static QEMUPutKBDEvent *qemu_put_kbd_event;
490 static void *qemu_put_kbd_event_opaque;
491 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
492 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
494 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
496 qemu_put_kbd_event_opaque = opaque;
497 qemu_put_kbd_event = func;
500 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
501 void *opaque, int absolute,
504 QEMUPutMouseEntry *s, *cursor;
506 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
510 s->qemu_put_mouse_event = func;
511 s->qemu_put_mouse_event_opaque = opaque;
512 s->qemu_put_mouse_event_absolute = absolute;
513 s->qemu_put_mouse_event_name = qemu_strdup(name);
516 if (!qemu_put_mouse_event_head) {
517 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
521 cursor = qemu_put_mouse_event_head;
522 while (cursor->next != NULL)
523 cursor = cursor->next;
526 qemu_put_mouse_event_current = s;
531 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
533 QEMUPutMouseEntry *prev = NULL, *cursor;
535 if (!qemu_put_mouse_event_head || entry == NULL)
538 cursor = qemu_put_mouse_event_head;
539 while (cursor != NULL && cursor != entry) {
541 cursor = cursor->next;
544 if (cursor == NULL) // does not exist or list empty
546 else if (prev == NULL) { // entry is head
547 qemu_put_mouse_event_head = cursor->next;
548 if (qemu_put_mouse_event_current == entry)
549 qemu_put_mouse_event_current = cursor->next;
550 qemu_free(entry->qemu_put_mouse_event_name);
555 prev->next = entry->next;
557 if (qemu_put_mouse_event_current == entry)
558 qemu_put_mouse_event_current = prev;
560 qemu_free(entry->qemu_put_mouse_event_name);
564 void kbd_put_keycode(int keycode)
566 if (qemu_put_kbd_event) {
567 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
571 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
573 QEMUPutMouseEvent *mouse_event;
574 void *mouse_event_opaque;
577 if (!qemu_put_mouse_event_current) {
582 qemu_put_mouse_event_current->qemu_put_mouse_event;
584 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
587 if (graphic_rotate) {
588 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
591 width = graphic_width - 1;
592 mouse_event(mouse_event_opaque,
593 width - dy, dx, dz, buttons_state);
595 mouse_event(mouse_event_opaque,
596 dx, dy, dz, buttons_state);
600 int kbd_mouse_is_absolute(void)
602 if (!qemu_put_mouse_event_current)
605 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
608 void do_info_mice(void)
610 QEMUPutMouseEntry *cursor;
613 if (!qemu_put_mouse_event_head) {
614 term_printf("No mouse devices connected\n");
618 term_printf("Mouse devices available:\n");
619 cursor = qemu_put_mouse_event_head;
620 while (cursor != NULL) {
621 term_printf("%c Mouse #%d: %s\n",
622 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
623 index, cursor->qemu_put_mouse_event_name);
625 cursor = cursor->next;
629 void do_mouse_set(int index)
631 QEMUPutMouseEntry *cursor;
634 if (!qemu_put_mouse_event_head) {
635 term_printf("No mouse devices connected\n");
639 cursor = qemu_put_mouse_event_head;
640 while (cursor != NULL && index != i) {
642 cursor = cursor->next;
646 qemu_put_mouse_event_current = cursor;
648 term_printf("Mouse at given index not found\n");
651 /* compute with 96 bit intermediate result: (a*b)/c */
652 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
657 #ifdef WORDS_BIGENDIAN
667 rl = (uint64_t)u.l.low * (uint64_t)b;
668 rh = (uint64_t)u.l.high * (uint64_t)b;
671 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
675 /***********************************************************/
676 /* real time host monotonic timer */
678 #define QEMU_TIMER_BASE 1000000000LL
682 static int64_t clock_freq;
684 static void init_get_clock(void)
688 ret = QueryPerformanceFrequency(&freq);
690 fprintf(stderr, "Could not calibrate ticks\n");
693 clock_freq = freq.QuadPart;
696 static int64_t get_clock(void)
699 QueryPerformanceCounter(&ti);
700 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
705 static int use_rt_clock;
707 static void init_get_clock(void)
710 #if defined(__linux__)
713 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
720 static int64_t get_clock(void)
722 #if defined(__linux__)
725 clock_gettime(CLOCK_MONOTONIC, &ts);
726 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
730 /* XXX: using gettimeofday leads to problems if the date
731 changes, so it should be avoided. */
733 gettimeofday(&tv, NULL);
734 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
740 /***********************************************************/
741 /* guest cycle counter */
743 static int64_t cpu_ticks_prev;
744 static int64_t cpu_ticks_offset;
745 static int64_t cpu_clock_offset;
746 static int cpu_ticks_enabled;
748 /* return the host CPU cycle counter and handle stop/restart */
749 int64_t cpu_get_ticks(void)
751 if (!cpu_ticks_enabled) {
752 return cpu_ticks_offset;
755 ticks = cpu_get_real_ticks();
756 if (cpu_ticks_prev > ticks) {
757 /* Note: non increasing ticks may happen if the host uses
759 cpu_ticks_offset += cpu_ticks_prev - ticks;
761 cpu_ticks_prev = ticks;
762 return ticks + cpu_ticks_offset;
766 /* return the host CPU monotonic timer and handle stop/restart */
767 static int64_t cpu_get_clock(void)
770 if (!cpu_ticks_enabled) {
771 return cpu_clock_offset;
774 return ti + cpu_clock_offset;
778 /* enable cpu_get_ticks() */
779 void cpu_enable_ticks(void)
781 if (!cpu_ticks_enabled) {
782 cpu_ticks_offset -= cpu_get_real_ticks();
783 cpu_clock_offset -= get_clock();
784 cpu_ticks_enabled = 1;
788 /* disable cpu_get_ticks() : the clock is stopped. You must not call
789 cpu_get_ticks() after that. */
790 void cpu_disable_ticks(void)
792 if (cpu_ticks_enabled) {
793 cpu_ticks_offset = cpu_get_ticks();
794 cpu_clock_offset = cpu_get_clock();
795 cpu_ticks_enabled = 0;
799 /***********************************************************/
802 #define QEMU_TIMER_REALTIME 0
803 #define QEMU_TIMER_VIRTUAL 1
807 /* XXX: add frequency */
815 struct QEMUTimer *next;
818 struct qemu_alarm_timer {
822 int (*start)(struct qemu_alarm_timer *t);
823 void (*stop)(struct qemu_alarm_timer *t);
824 void (*rearm)(struct qemu_alarm_timer *t);
828 #define ALARM_FLAG_DYNTICKS 0x1
829 #define ALARM_FLAG_EXPIRED 0x2
831 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
833 return t->flags & ALARM_FLAG_DYNTICKS;
836 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
838 if (!alarm_has_dynticks(t))
844 /* TODO: MIN_TIMER_REARM_US should be optimized */
845 #define MIN_TIMER_REARM_US 250
847 static struct qemu_alarm_timer *alarm_timer;
851 struct qemu_alarm_win32 {
855 } alarm_win32_data = {0, NULL, -1};
857 static int win32_start_timer(struct qemu_alarm_timer *t);
858 static void win32_stop_timer(struct qemu_alarm_timer *t);
859 static void win32_rearm_timer(struct qemu_alarm_timer *t);
863 static int unix_start_timer(struct qemu_alarm_timer *t);
864 static void unix_stop_timer(struct qemu_alarm_timer *t);
868 static int dynticks_start_timer(struct qemu_alarm_timer *t);
869 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
870 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
872 static int hpet_start_timer(struct qemu_alarm_timer *t);
873 static void hpet_stop_timer(struct qemu_alarm_timer *t);
875 static int rtc_start_timer(struct qemu_alarm_timer *t);
876 static void rtc_stop_timer(struct qemu_alarm_timer *t);
878 #endif /* __linux__ */
882 static struct qemu_alarm_timer alarm_timers[] = {
885 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
886 dynticks_stop_timer, dynticks_rearm_timer, NULL},
887 /* HPET - if available - is preferred */
888 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
889 /* ...otherwise try RTC */
890 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
892 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
894 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
895 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
896 {"win32", 0, win32_start_timer,
897 win32_stop_timer, NULL, &alarm_win32_data},
902 static void show_available_alarms(void)
906 printf("Available alarm timers, in order of precedence:\n");
907 for (i = 0; alarm_timers[i].name; i++)
908 printf("%s\n", alarm_timers[i].name);
911 static void configure_alarms(char const *opt)
915 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
919 if (!strcmp(opt, "?")) {
920 show_available_alarms();
926 /* Reorder the array */
927 name = strtok(arg, ",");
929 struct qemu_alarm_timer tmp;
931 for (i = 0; i < count && alarm_timers[i].name; i++) {
932 if (!strcmp(alarm_timers[i].name, name))
937 fprintf(stderr, "Unknown clock %s\n", name);
946 tmp = alarm_timers[i];
947 alarm_timers[i] = alarm_timers[cur];
948 alarm_timers[cur] = tmp;
952 name = strtok(NULL, ",");
958 /* Disable remaining timers */
959 for (i = cur; i < count; i++)
960 alarm_timers[i].name = NULL;
962 show_available_alarms();
970 static QEMUTimer *active_timers[2];
972 static QEMUClock *qemu_new_clock(int type)
975 clock = qemu_mallocz(sizeof(QEMUClock));
982 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
986 ts = qemu_mallocz(sizeof(QEMUTimer));
993 void qemu_free_timer(QEMUTimer *ts)
998 /* stop a timer, but do not dealloc it */
999 void qemu_del_timer(QEMUTimer *ts)
1003 /* NOTE: this code must be signal safe because
1004 qemu_timer_expired() can be called from a signal. */
1005 pt = &active_timers[ts->clock->type];
1018 /* modify the current timer so that it will be fired when current_time
1019 >= expire_time. The corresponding callback will be called. */
1020 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1026 /* add the timer in the sorted list */
1027 /* NOTE: this code must be signal safe because
1028 qemu_timer_expired() can be called from a signal. */
1029 pt = &active_timers[ts->clock->type];
1034 if (t->expire_time > expire_time)
1038 ts->expire_time = expire_time;
1042 /* Rearm if necessary */
1043 if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0 &&
1044 pt == &active_timers[ts->clock->type])
1045 qemu_rearm_alarm_timer(alarm_timer);
1048 int qemu_timer_pending(QEMUTimer *ts)
1051 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1058 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1062 return (timer_head->expire_time <= current_time);
1065 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1071 if (!ts || ts->expire_time > current_time)
1073 /* remove timer from the list before calling the callback */
1074 *ptimer_head = ts->next;
1077 /* run the callback (the timer list can be modified) */
1082 int64_t qemu_get_clock(QEMUClock *clock)
1084 switch(clock->type) {
1085 case QEMU_TIMER_REALTIME:
1086 return get_clock() / 1000000;
1088 case QEMU_TIMER_VIRTUAL:
1089 return cpu_get_clock();
1093 static void init_timers(void)
1096 ticks_per_sec = QEMU_TIMER_BASE;
1097 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1098 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1102 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1104 uint64_t expire_time;
1106 if (qemu_timer_pending(ts)) {
1107 expire_time = ts->expire_time;
1111 qemu_put_be64(f, expire_time);
1114 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1116 uint64_t expire_time;
1118 expire_time = qemu_get_be64(f);
1119 if (expire_time != -1) {
1120 qemu_mod_timer(ts, expire_time);
1126 static void timer_save(QEMUFile *f, void *opaque)
1128 if (cpu_ticks_enabled) {
1129 hw_error("cannot save state if virtual timers are running");
1131 qemu_put_be64(f, cpu_ticks_offset);
1132 qemu_put_be64(f, ticks_per_sec);
1133 qemu_put_be64(f, cpu_clock_offset);
1136 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1138 if (version_id != 1 && version_id != 2)
1140 if (cpu_ticks_enabled) {
1143 cpu_ticks_offset=qemu_get_be64(f);
1144 ticks_per_sec=qemu_get_be64(f);
1145 if (version_id == 2) {
1146 cpu_clock_offset=qemu_get_be64(f);
1152 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1153 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1155 static void host_alarm_handler(int host_signum)
1159 #define DISP_FREQ 1000
1161 static int64_t delta_min = INT64_MAX;
1162 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1164 ti = qemu_get_clock(vm_clock);
1165 if (last_clock != 0) {
1166 delta = ti - last_clock;
1167 if (delta < delta_min)
1169 if (delta > delta_max)
1172 if (++count == DISP_FREQ) {
1173 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1174 muldiv64(delta_min, 1000000, ticks_per_sec),
1175 muldiv64(delta_max, 1000000, ticks_per_sec),
1176 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1177 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1179 delta_min = INT64_MAX;
1187 if (alarm_has_dynticks(alarm_timer) ||
1188 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1189 qemu_get_clock(vm_clock)) ||
1190 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1191 qemu_get_clock(rt_clock))) {
1193 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1194 SetEvent(data->host_alarm);
1196 CPUState *env = next_cpu;
1198 alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1201 /* stop the currently executing cpu because a timer occured */
1202 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1204 if (env->kqemu_enabled) {
1205 kqemu_cpu_interrupt(env);
1213 static uint64_t qemu_next_deadline(void)
1215 int64_t nearest_delta_us = INT64_MAX;
1218 if (active_timers[QEMU_TIMER_REALTIME])
1219 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1220 qemu_get_clock(rt_clock))*1000;
1222 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1224 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1225 qemu_get_clock(vm_clock)+999)/1000;
1226 if (vmdelta_us < nearest_delta_us)
1227 nearest_delta_us = vmdelta_us;
1230 /* Avoid arming the timer to negative, zero, or too low values */
1231 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1232 nearest_delta_us = MIN_TIMER_REARM_US;
1234 return nearest_delta_us;
1239 #if defined(__linux__)
1241 #define RTC_FREQ 1024
1243 static void enable_sigio_timer(int fd)
1245 struct sigaction act;
1248 sigfillset(&act.sa_mask);
1250 act.sa_handler = host_alarm_handler;
1252 sigaction(SIGIO, &act, NULL);
1253 fcntl(fd, F_SETFL, O_ASYNC);
1254 fcntl(fd, F_SETOWN, getpid());
1257 static int hpet_start_timer(struct qemu_alarm_timer *t)
1259 struct hpet_info info;
1262 fd = open("/dev/hpet", O_RDONLY);
1267 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1269 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1270 "error, but for better emulation accuracy type:\n"
1271 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1275 /* Check capabilities */
1276 r = ioctl(fd, HPET_INFO, &info);
1280 /* Enable periodic mode */
1281 r = ioctl(fd, HPET_EPI, 0);
1282 if (info.hi_flags && (r < 0))
1285 /* Enable interrupt */
1286 r = ioctl(fd, HPET_IE_ON, 0);
1290 enable_sigio_timer(fd);
1291 t->priv = (void *)(long)fd;
1299 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1301 int fd = (long)t->priv;
1306 static int rtc_start_timer(struct qemu_alarm_timer *t)
1309 unsigned long current_rtc_freq = 0;
1311 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1314 ioctl(rtc_fd, RTC_IRQP_READ, ¤t_rtc_freq);
1315 if (current_rtc_freq != RTC_FREQ &&
1316 ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1317 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1318 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1319 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1322 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1328 enable_sigio_timer(rtc_fd);
1330 t->priv = (void *)(long)rtc_fd;
1335 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1337 int rtc_fd = (long)t->priv;
1342 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1346 struct sigaction act;
1348 sigfillset(&act.sa_mask);
1350 act.sa_handler = host_alarm_handler;
1352 sigaction(SIGALRM, &act, NULL);
1354 ev.sigev_value.sival_int = 0;
1355 ev.sigev_notify = SIGEV_SIGNAL;
1356 ev.sigev_signo = SIGALRM;
1358 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1359 perror("timer_create");
1361 /* disable dynticks */
1362 fprintf(stderr, "Dynamic Ticks disabled\n");
1367 t->priv = (void *)host_timer;
1372 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1374 timer_t host_timer = (timer_t)t->priv;
1376 timer_delete(host_timer);
1379 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1381 timer_t host_timer = (timer_t)t->priv;
1382 struct itimerspec timeout;
1383 int64_t nearest_delta_us = INT64_MAX;
1386 if (!active_timers[QEMU_TIMER_REALTIME] &&
1387 !active_timers[QEMU_TIMER_VIRTUAL])
1390 nearest_delta_us = qemu_next_deadline();
1392 /* check whether a timer is already running */
1393 if (timer_gettime(host_timer, &timeout)) {
1395 fprintf(stderr, "Internal timer error: aborting\n");
1398 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1399 if (current_us && current_us <= nearest_delta_us)
1402 timeout.it_interval.tv_sec = 0;
1403 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1404 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1405 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1406 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1408 fprintf(stderr, "Internal timer error: aborting\n");
1413 #endif /* defined(__linux__) */
1415 static int unix_start_timer(struct qemu_alarm_timer *t)
1417 struct sigaction act;
1418 struct itimerval itv;
1422 sigfillset(&act.sa_mask);
1424 act.sa_handler = host_alarm_handler;
1426 sigaction(SIGALRM, &act, NULL);
1428 itv.it_interval.tv_sec = 0;
1429 /* for i386 kernel 2.6 to get 1 ms */
1430 itv.it_interval.tv_usec = 999;
1431 itv.it_value.tv_sec = 0;
1432 itv.it_value.tv_usec = 10 * 1000;
1434 err = setitimer(ITIMER_REAL, &itv, NULL);
1441 static void unix_stop_timer(struct qemu_alarm_timer *t)
1443 struct itimerval itv;
1445 memset(&itv, 0, sizeof(itv));
1446 setitimer(ITIMER_REAL, &itv, NULL);
1449 #endif /* !defined(_WIN32) */
1453 static int win32_start_timer(struct qemu_alarm_timer *t)
1456 struct qemu_alarm_win32 *data = t->priv;
1459 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1460 if (!data->host_alarm) {
1461 perror("Failed CreateEvent");
1465 memset(&tc, 0, sizeof(tc));
1466 timeGetDevCaps(&tc, sizeof(tc));
1468 if (data->period < tc.wPeriodMin)
1469 data->period = tc.wPeriodMin;
1471 timeBeginPeriod(data->period);
1473 flags = TIME_CALLBACK_FUNCTION;
1474 if (alarm_has_dynticks(t))
1475 flags |= TIME_ONESHOT;
1477 flags |= TIME_PERIODIC;
1479 data->timerId = timeSetEvent(1, // interval (ms)
1480 data->period, // resolution
1481 host_alarm_handler, // function
1482 (DWORD)t, // parameter
1485 if (!data->timerId) {
1486 perror("Failed to initialize win32 alarm timer");
1488 timeEndPeriod(data->period);
1489 CloseHandle(data->host_alarm);
1493 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1498 static void win32_stop_timer(struct qemu_alarm_timer *t)
1500 struct qemu_alarm_win32 *data = t->priv;
1502 timeKillEvent(data->timerId);
1503 timeEndPeriod(data->period);
1505 CloseHandle(data->host_alarm);
1508 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1510 struct qemu_alarm_win32 *data = t->priv;
1511 uint64_t nearest_delta_us;
1513 if (!active_timers[QEMU_TIMER_REALTIME] &&
1514 !active_timers[QEMU_TIMER_VIRTUAL])
1517 nearest_delta_us = qemu_next_deadline();
1518 nearest_delta_us /= 1000;
1520 timeKillEvent(data->timerId);
1522 data->timerId = timeSetEvent(1,
1526 TIME_ONESHOT | TIME_PERIODIC);
1528 if (!data->timerId) {
1529 perror("Failed to re-arm win32 alarm timer");
1531 timeEndPeriod(data->period);
1532 CloseHandle(data->host_alarm);
1539 static void init_timer_alarm(void)
1541 struct qemu_alarm_timer *t;
1544 for (i = 0; alarm_timers[i].name; i++) {
1545 t = &alarm_timers[i];
1553 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1554 fprintf(stderr, "Terminating\n");
1561 static void quit_timers(void)
1563 alarm_timer->stop(alarm_timer);
1567 /***********************************************************/
1568 /* host time/date access */
1569 void qemu_get_timedate(struct tm *tm, int offset)
1576 if (rtc_date_offset == -1) {
1580 ret = localtime(&ti);
1582 ti -= rtc_date_offset;
1586 memcpy(tm, ret, sizeof(struct tm));
1589 int qemu_timedate_diff(struct tm *tm)
1593 if (rtc_date_offset == -1)
1595 seconds = mktimegm(tm);
1597 seconds = mktime(tm);
1599 seconds = mktimegm(tm) + rtc_date_offset;
1601 return seconds - time(NULL);
1604 /***********************************************************/
1605 /* character device */
1607 static void qemu_chr_event(CharDriverState *s, int event)
1611 s->chr_event(s->handler_opaque, event);
1614 static void qemu_chr_reset_bh(void *opaque)
1616 CharDriverState *s = opaque;
1617 qemu_chr_event(s, CHR_EVENT_RESET);
1618 qemu_bh_delete(s->bh);
1622 void qemu_chr_reset(CharDriverState *s)
1624 if (s->bh == NULL) {
1625 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1626 qemu_bh_schedule(s->bh);
1630 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1632 return s->chr_write(s, buf, len);
1635 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1639 return s->chr_ioctl(s, cmd, arg);
1642 int qemu_chr_can_read(CharDriverState *s)
1644 if (!s->chr_can_read)
1646 return s->chr_can_read(s->handler_opaque);
1649 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1651 s->chr_read(s->handler_opaque, buf, len);
1654 void qemu_chr_accept_input(CharDriverState *s)
1656 if (s->chr_accept_input)
1657 s->chr_accept_input(s);
1660 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1665 vsnprintf(buf, sizeof(buf), fmt, ap);
1666 qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1670 void qemu_chr_send_event(CharDriverState *s, int event)
1672 if (s->chr_send_event)
1673 s->chr_send_event(s, event);
1676 void qemu_chr_add_handlers(CharDriverState *s,
1677 IOCanRWHandler *fd_can_read,
1678 IOReadHandler *fd_read,
1679 IOEventHandler *fd_event,
1682 s->chr_can_read = fd_can_read;
1683 s->chr_read = fd_read;
1684 s->chr_event = fd_event;
1685 s->handler_opaque = opaque;
1686 if (s->chr_update_read_handler)
1687 s->chr_update_read_handler(s);
1690 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1695 static CharDriverState *qemu_chr_open_null(void)
1697 CharDriverState *chr;
1699 chr = qemu_mallocz(sizeof(CharDriverState));
1702 chr->chr_write = null_chr_write;
1706 /* MUX driver for serial I/O splitting */
1707 static int term_timestamps;
1708 static int64_t term_timestamps_start;
1710 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1711 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1713 IOCanRWHandler *chr_can_read[MAX_MUX];
1714 IOReadHandler *chr_read[MAX_MUX];
1715 IOEventHandler *chr_event[MAX_MUX];
1716 void *ext_opaque[MAX_MUX];
1717 CharDriverState *drv;
1718 unsigned char buffer[MUX_BUFFER_SIZE];
1722 int term_got_escape;
1727 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1729 MuxDriver *d = chr->opaque;
1731 if (!term_timestamps) {
1732 ret = d->drv->chr_write(d->drv, buf, len);
1737 for(i = 0; i < len; i++) {
1738 ret += d->drv->chr_write(d->drv, buf+i, 1);
1739 if (buf[i] == '\n') {
1745 if (term_timestamps_start == -1)
1746 term_timestamps_start = ti;
1747 ti -= term_timestamps_start;
1748 secs = ti / 1000000000;
1749 snprintf(buf1, sizeof(buf1),
1750 "[%02d:%02d:%02d.%03d] ",
1754 (int)((ti / 1000000) % 1000));
1755 d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1762 static char *mux_help[] = {
1763 "% h print this help\n\r",
1764 "% x exit emulator\n\r",
1765 "% s save disk data back to file (if -snapshot)\n\r",
1766 "% t toggle console timestamps\n\r"
1767 "% b send break (magic sysrq)\n\r",
1768 "% c switch between console and monitor\n\r",
1773 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1774 static void mux_print_help(CharDriverState *chr)
1777 char ebuf[15] = "Escape-Char";
1778 char cbuf[50] = "\n\r";
1780 if (term_escape_char > 0 && term_escape_char < 26) {
1781 sprintf(cbuf,"\n\r");
1782 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1784 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1787 chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1788 for (i = 0; mux_help[i] != NULL; i++) {
1789 for (j=0; mux_help[i][j] != '\0'; j++) {
1790 if (mux_help[i][j] == '%')
1791 chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1793 chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1798 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1800 if (d->term_got_escape) {
1801 d->term_got_escape = 0;
1802 if (ch == term_escape_char)
1807 mux_print_help(chr);
1811 char *term = "QEMU: Terminated\n\r";
1812 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1819 for (i = 0; i < nb_drives; i++) {
1820 bdrv_commit(drives_table[i].bdrv);
1825 qemu_chr_event(chr, CHR_EVENT_BREAK);
1828 /* Switch to the next registered device */
1830 if (chr->focus >= d->mux_cnt)
1834 term_timestamps = !term_timestamps;
1835 term_timestamps_start = -1;
1838 } else if (ch == term_escape_char) {
1839 d->term_got_escape = 1;
1847 static void mux_chr_accept_input(CharDriverState *chr)
1850 MuxDriver *d = chr->opaque;
1852 while (d->prod != d->cons &&
1853 d->chr_can_read[m] &&
1854 d->chr_can_read[m](d->ext_opaque[m])) {
1855 d->chr_read[m](d->ext_opaque[m],
1856 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1860 static int mux_chr_can_read(void *opaque)
1862 CharDriverState *chr = opaque;
1863 MuxDriver *d = chr->opaque;
1865 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1867 if (d->chr_can_read[chr->focus])
1868 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1872 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1874 CharDriverState *chr = opaque;
1875 MuxDriver *d = chr->opaque;
1879 mux_chr_accept_input (opaque);
1881 for(i = 0; i < size; i++)
1882 if (mux_proc_byte(chr, d, buf[i])) {
1883 if (d->prod == d->cons &&
1884 d->chr_can_read[m] &&
1885 d->chr_can_read[m](d->ext_opaque[m]))
1886 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1888 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1892 static void mux_chr_event(void *opaque, int event)
1894 CharDriverState *chr = opaque;
1895 MuxDriver *d = chr->opaque;
1898 /* Send the event to all registered listeners */
1899 for (i = 0; i < d->mux_cnt; i++)
1900 if (d->chr_event[i])
1901 d->chr_event[i](d->ext_opaque[i], event);
1904 static void mux_chr_update_read_handler(CharDriverState *chr)
1906 MuxDriver *d = chr->opaque;
1908 if (d->mux_cnt >= MAX_MUX) {
1909 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1912 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1913 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1914 d->chr_read[d->mux_cnt] = chr->chr_read;
1915 d->chr_event[d->mux_cnt] = chr->chr_event;
1916 /* Fix up the real driver with mux routines */
1917 if (d->mux_cnt == 0) {
1918 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1919 mux_chr_event, chr);
1921 chr->focus = d->mux_cnt;
1925 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1927 CharDriverState *chr;
1930 chr = qemu_mallocz(sizeof(CharDriverState));
1933 d = qemu_mallocz(sizeof(MuxDriver));
1942 chr->chr_write = mux_chr_write;
1943 chr->chr_update_read_handler = mux_chr_update_read_handler;
1944 chr->chr_accept_input = mux_chr_accept_input;
1951 static void socket_cleanup(void)
1956 static int socket_init(void)
1961 ret = WSAStartup(MAKEWORD(2,2), &Data);
1963 err = WSAGetLastError();
1964 fprintf(stderr, "WSAStartup: %d\n", err);
1967 atexit(socket_cleanup);
1971 static int send_all(int fd, const uint8_t *buf, int len1)
1977 ret = send(fd, buf, len, 0);
1980 errno = WSAGetLastError();
1981 if (errno != WSAEWOULDBLOCK) {
1984 } else if (ret == 0) {
1994 void socket_set_nonblock(int fd)
1996 unsigned long opt = 1;
1997 ioctlsocket(fd, FIONBIO, &opt);
2002 static int unix_write(int fd, const uint8_t *buf, int len1)
2008 ret = write(fd, buf, len);
2010 if (errno != EINTR && errno != EAGAIN)
2012 } else if (ret == 0) {
2022 static inline int send_all(int fd, const uint8_t *buf, int len1)
2024 return unix_write(fd, buf, len1);
2027 void socket_set_nonblock(int fd)
2029 fcntl(fd, F_SETFL, O_NONBLOCK);
2031 #endif /* !_WIN32 */
2040 #define STDIO_MAX_CLIENTS 1
2041 static int stdio_nb_clients = 0;
2043 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2045 FDCharDriver *s = chr->opaque;
2046 return unix_write(s->fd_out, buf, len);
2049 static int fd_chr_read_poll(void *opaque)
2051 CharDriverState *chr = opaque;
2052 FDCharDriver *s = chr->opaque;
2054 s->max_size = qemu_chr_can_read(chr);
2058 static void fd_chr_read(void *opaque)
2060 CharDriverState *chr = opaque;
2061 FDCharDriver *s = chr->opaque;
2066 if (len > s->max_size)
2070 size = read(s->fd_in, buf, len);
2072 /* FD has been closed. Remove it from the active list. */
2073 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2077 qemu_chr_read(chr, buf, size);
2081 static void fd_chr_update_read_handler(CharDriverState *chr)
2083 FDCharDriver *s = chr->opaque;
2085 if (s->fd_in >= 0) {
2086 if (nographic && s->fd_in == 0) {
2088 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2089 fd_chr_read, NULL, chr);
2094 static void fd_chr_close(struct CharDriverState *chr)
2096 FDCharDriver *s = chr->opaque;
2098 if (s->fd_in >= 0) {
2099 if (nographic && s->fd_in == 0) {
2101 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2108 /* open a character device to a unix fd */
2109 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2111 CharDriverState *chr;
2114 chr = qemu_mallocz(sizeof(CharDriverState));
2117 s = qemu_mallocz(sizeof(FDCharDriver));
2125 chr->chr_write = fd_chr_write;
2126 chr->chr_update_read_handler = fd_chr_update_read_handler;
2127 chr->chr_close = fd_chr_close;
2129 qemu_chr_reset(chr);
2134 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2138 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2141 return qemu_chr_open_fd(-1, fd_out);
2144 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2147 char filename_in[256], filename_out[256];
2149 snprintf(filename_in, 256, "%s.in", filename);
2150 snprintf(filename_out, 256, "%s.out", filename);
2151 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2152 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2153 if (fd_in < 0 || fd_out < 0) {
2158 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2162 return qemu_chr_open_fd(fd_in, fd_out);
2166 /* for STDIO, we handle the case where several clients use it
2169 #define TERM_FIFO_MAX_SIZE 1
2171 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2172 static int term_fifo_size;
2174 static int stdio_read_poll(void *opaque)
2176 CharDriverState *chr = opaque;
2178 /* try to flush the queue if needed */
2179 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2180 qemu_chr_read(chr, term_fifo, 1);
2183 /* see if we can absorb more chars */
2184 if (term_fifo_size == 0)
2190 static void stdio_read(void *opaque)
2194 CharDriverState *chr = opaque;
2196 size = read(0, buf, 1);
2198 /* stdin has been closed. Remove it from the active list. */
2199 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2203 if (qemu_chr_can_read(chr) > 0) {
2204 qemu_chr_read(chr, buf, 1);
2205 } else if (term_fifo_size == 0) {
2206 term_fifo[term_fifo_size++] = buf[0];
2211 /* init terminal so that we can grab keys */
2212 static struct termios oldtty;
2213 static int old_fd0_flags;
2214 static int term_atexit_done;
2216 static void term_exit(void)
2218 tcsetattr (0, TCSANOW, &oldtty);
2219 fcntl(0, F_SETFL, old_fd0_flags);
2222 static void term_init(void)
2226 tcgetattr (0, &tty);
2228 old_fd0_flags = fcntl(0, F_GETFL);
2230 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2231 |INLCR|IGNCR|ICRNL|IXON);
2232 tty.c_oflag |= OPOST;
2233 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2234 /* if graphical mode, we allow Ctrl-C handling */
2236 tty.c_lflag &= ~ISIG;
2237 tty.c_cflag &= ~(CSIZE|PARENB);
2240 tty.c_cc[VTIME] = 0;
2242 tcsetattr (0, TCSANOW, &tty);
2244 if (!term_atexit_done++)
2247 fcntl(0, F_SETFL, O_NONBLOCK);
2250 static void qemu_chr_close_stdio(struct CharDriverState *chr)
2254 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2258 static CharDriverState *qemu_chr_open_stdio(void)
2260 CharDriverState *chr;
2262 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2264 chr = qemu_chr_open_fd(0, 1);
2265 chr->chr_close = qemu_chr_close_stdio;
2266 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2273 #if defined(__linux__) || defined(__sun__)
2274 static CharDriverState *qemu_chr_open_pty(void)
2277 char slave_name[1024];
2278 int master_fd, slave_fd;
2280 #if defined(__linux__)
2281 /* Not satisfying */
2282 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2287 /* Disabling local echo and line-buffered output */
2288 tcgetattr (master_fd, &tty);
2289 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2291 tty.c_cc[VTIME] = 0;
2292 tcsetattr (master_fd, TCSAFLUSH, &tty);
2294 fprintf(stderr, "char device redirected to %s\n", slave_name);
2295 return qemu_chr_open_fd(master_fd, master_fd);
2298 static void tty_serial_init(int fd, int speed,
2299 int parity, int data_bits, int stop_bits)
2305 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2306 speed, parity, data_bits, stop_bits);
2308 tcgetattr (fd, &tty);
2311 if (speed <= 50 * MARGIN)
2313 else if (speed <= 75 * MARGIN)
2315 else if (speed <= 300 * MARGIN)
2317 else if (speed <= 600 * MARGIN)
2319 else if (speed <= 1200 * MARGIN)
2321 else if (speed <= 2400 * MARGIN)
2323 else if (speed <= 4800 * MARGIN)
2325 else if (speed <= 9600 * MARGIN)
2327 else if (speed <= 19200 * MARGIN)
2329 else if (speed <= 38400 * MARGIN)
2331 else if (speed <= 57600 * MARGIN)
2333 else if (speed <= 115200 * MARGIN)
2338 cfsetispeed(&tty, spd);
2339 cfsetospeed(&tty, spd);
2341 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2342 |INLCR|IGNCR|ICRNL|IXON);
2343 tty.c_oflag |= OPOST;
2344 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2345 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2366 tty.c_cflag |= PARENB;
2369 tty.c_cflag |= PARENB | PARODD;
2373 tty.c_cflag |= CSTOPB;
2375 tcsetattr (fd, TCSANOW, &tty);
2378 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2380 FDCharDriver *s = chr->opaque;
2383 case CHR_IOCTL_SERIAL_SET_PARAMS:
2385 QEMUSerialSetParams *ssp = arg;
2386 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2387 ssp->data_bits, ssp->stop_bits);
2390 case CHR_IOCTL_SERIAL_SET_BREAK:
2392 int enable = *(int *)arg;
2394 tcsendbreak(s->fd_in, 1);
2403 static CharDriverState *qemu_chr_open_tty(const char *filename)
2405 CharDriverState *chr;
2408 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2409 fcntl(fd, F_SETFL, O_NONBLOCK);
2410 tty_serial_init(fd, 115200, 'N', 8, 1);
2411 chr = qemu_chr_open_fd(fd, fd);
2416 chr->chr_ioctl = tty_serial_ioctl;
2417 qemu_chr_reset(chr);
2420 #else /* ! __linux__ && ! __sun__ */
2421 static CharDriverState *qemu_chr_open_pty(void)
2425 #endif /* __linux__ || __sun__ */
2427 #if defined(__linux__)
2431 } ParallelCharDriver;
2433 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2435 if (s->mode != mode) {
2437 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2444 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2446 ParallelCharDriver *drv = chr->opaque;
2451 case CHR_IOCTL_PP_READ_DATA:
2452 if (ioctl(fd, PPRDATA, &b) < 0)
2454 *(uint8_t *)arg = b;
2456 case CHR_IOCTL_PP_WRITE_DATA:
2457 b = *(uint8_t *)arg;
2458 if (ioctl(fd, PPWDATA, &b) < 0)
2461 case CHR_IOCTL_PP_READ_CONTROL:
2462 if (ioctl(fd, PPRCONTROL, &b) < 0)
2464 /* Linux gives only the lowest bits, and no way to know data
2465 direction! For better compatibility set the fixed upper
2467 *(uint8_t *)arg = b | 0xc0;
2469 case CHR_IOCTL_PP_WRITE_CONTROL:
2470 b = *(uint8_t *)arg;
2471 if (ioctl(fd, PPWCONTROL, &b) < 0)
2474 case CHR_IOCTL_PP_READ_STATUS:
2475 if (ioctl(fd, PPRSTATUS, &b) < 0)
2477 *(uint8_t *)arg = b;
2479 case CHR_IOCTL_PP_EPP_READ_ADDR:
2480 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2481 struct ParallelIOArg *parg = arg;
2482 int n = read(fd, parg->buffer, parg->count);
2483 if (n != parg->count) {
2488 case CHR_IOCTL_PP_EPP_READ:
2489 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2490 struct ParallelIOArg *parg = arg;
2491 int n = read(fd, parg->buffer, parg->count);
2492 if (n != parg->count) {
2497 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2498 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2499 struct ParallelIOArg *parg = arg;
2500 int n = write(fd, parg->buffer, parg->count);
2501 if (n != parg->count) {
2506 case CHR_IOCTL_PP_EPP_WRITE:
2507 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2508 struct ParallelIOArg *parg = arg;
2509 int n = write(fd, parg->buffer, parg->count);
2510 if (n != parg->count) {
2521 static void pp_close(CharDriverState *chr)
2523 ParallelCharDriver *drv = chr->opaque;
2526 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2527 ioctl(fd, PPRELEASE);
2532 static CharDriverState *qemu_chr_open_pp(const char *filename)
2534 CharDriverState *chr;
2535 ParallelCharDriver *drv;
2538 TFR(fd = open(filename, O_RDWR));
2542 if (ioctl(fd, PPCLAIM) < 0) {
2547 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2553 drv->mode = IEEE1284_MODE_COMPAT;
2555 chr = qemu_mallocz(sizeof(CharDriverState));
2561 chr->chr_write = null_chr_write;
2562 chr->chr_ioctl = pp_ioctl;
2563 chr->chr_close = pp_close;
2566 qemu_chr_reset(chr);
2570 #endif /* __linux__ */
2576 HANDLE hcom, hrecv, hsend;
2577 OVERLAPPED orecv, osend;
2582 #define NSENDBUF 2048
2583 #define NRECVBUF 2048
2584 #define MAXCONNECT 1
2585 #define NTIMEOUT 5000
2587 static int win_chr_poll(void *opaque);
2588 static int win_chr_pipe_poll(void *opaque);
2590 static void win_chr_close(CharDriverState *chr)
2592 WinCharState *s = chr->opaque;
2595 CloseHandle(s->hsend);
2599 CloseHandle(s->hrecv);
2603 CloseHandle(s->hcom);
2607 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2609 qemu_del_polling_cb(win_chr_poll, chr);
2612 static int win_chr_init(CharDriverState *chr, const char *filename)
2614 WinCharState *s = chr->opaque;
2616 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2621 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2623 fprintf(stderr, "Failed CreateEvent\n");
2626 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2628 fprintf(stderr, "Failed CreateEvent\n");
2632 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2633 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2634 if (s->hcom == INVALID_HANDLE_VALUE) {
2635 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2640 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2641 fprintf(stderr, "Failed SetupComm\n");
2645 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2646 size = sizeof(COMMCONFIG);
2647 GetDefaultCommConfig(filename, &comcfg, &size);
2648 comcfg.dcb.DCBlength = sizeof(DCB);
2649 CommConfigDialog(filename, NULL, &comcfg);
2651 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2652 fprintf(stderr, "Failed SetCommState\n");
2656 if (!SetCommMask(s->hcom, EV_ERR)) {
2657 fprintf(stderr, "Failed SetCommMask\n");
2661 cto.ReadIntervalTimeout = MAXDWORD;
2662 if (!SetCommTimeouts(s->hcom, &cto)) {
2663 fprintf(stderr, "Failed SetCommTimeouts\n");
2667 if (!ClearCommError(s->hcom, &err, &comstat)) {
2668 fprintf(stderr, "Failed ClearCommError\n");
2671 qemu_add_polling_cb(win_chr_poll, chr);
2679 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2681 WinCharState *s = chr->opaque;
2682 DWORD len, ret, size, err;
2685 ZeroMemory(&s->osend, sizeof(s->osend));
2686 s->osend.hEvent = s->hsend;
2689 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2691 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2693 err = GetLastError();
2694 if (err == ERROR_IO_PENDING) {
2695 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2713 static int win_chr_read_poll(CharDriverState *chr)
2715 WinCharState *s = chr->opaque;
2717 s->max_size = qemu_chr_can_read(chr);
2721 static void win_chr_readfile(CharDriverState *chr)
2723 WinCharState *s = chr->opaque;
2728 ZeroMemory(&s->orecv, sizeof(s->orecv));
2729 s->orecv.hEvent = s->hrecv;
2730 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2732 err = GetLastError();
2733 if (err == ERROR_IO_PENDING) {
2734 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2739 qemu_chr_read(chr, buf, size);
2743 static void win_chr_read(CharDriverState *chr)
2745 WinCharState *s = chr->opaque;
2747 if (s->len > s->max_size)
2748 s->len = s->max_size;
2752 win_chr_readfile(chr);
2755 static int win_chr_poll(void *opaque)
2757 CharDriverState *chr = opaque;
2758 WinCharState *s = chr->opaque;
2762 ClearCommError(s->hcom, &comerr, &status);
2763 if (status.cbInQue > 0) {
2764 s->len = status.cbInQue;
2765 win_chr_read_poll(chr);
2772 static CharDriverState *qemu_chr_open_win(const char *filename)
2774 CharDriverState *chr;
2777 chr = qemu_mallocz(sizeof(CharDriverState));
2780 s = qemu_mallocz(sizeof(WinCharState));
2786 chr->chr_write = win_chr_write;
2787 chr->chr_close = win_chr_close;
2789 if (win_chr_init(chr, filename) < 0) {
2794 qemu_chr_reset(chr);
2798 static int win_chr_pipe_poll(void *opaque)
2800 CharDriverState *chr = opaque;
2801 WinCharState *s = chr->opaque;
2804 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2807 win_chr_read_poll(chr);
2814 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2816 WinCharState *s = chr->opaque;
2824 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2826 fprintf(stderr, "Failed CreateEvent\n");
2829 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2831 fprintf(stderr, "Failed CreateEvent\n");
2835 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2836 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2837 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2839 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2840 if (s->hcom == INVALID_HANDLE_VALUE) {
2841 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2846 ZeroMemory(&ov, sizeof(ov));
2847 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2848 ret = ConnectNamedPipe(s->hcom, &ov);
2850 fprintf(stderr, "Failed ConnectNamedPipe\n");
2854 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2856 fprintf(stderr, "Failed GetOverlappedResult\n");
2858 CloseHandle(ov.hEvent);
2865 CloseHandle(ov.hEvent);
2868 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2877 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2879 CharDriverState *chr;
2882 chr = qemu_mallocz(sizeof(CharDriverState));
2885 s = qemu_mallocz(sizeof(WinCharState));
2891 chr->chr_write = win_chr_write;
2892 chr->chr_close = win_chr_close;
2894 if (win_chr_pipe_init(chr, filename) < 0) {
2899 qemu_chr_reset(chr);
2903 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2905 CharDriverState *chr;
2908 chr = qemu_mallocz(sizeof(CharDriverState));
2911 s = qemu_mallocz(sizeof(WinCharState));
2918 chr->chr_write = win_chr_write;
2919 qemu_chr_reset(chr);
2923 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2925 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2928 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2932 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2933 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2934 if (fd_out == INVALID_HANDLE_VALUE)
2937 return qemu_chr_open_win_file(fd_out);
2939 #endif /* !_WIN32 */
2941 /***********************************************************/
2942 /* UDP Net console */
2946 struct sockaddr_in daddr;
2953 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2955 NetCharDriver *s = chr->opaque;
2957 return sendto(s->fd, buf, len, 0,
2958 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2961 static int udp_chr_read_poll(void *opaque)
2963 CharDriverState *chr = opaque;
2964 NetCharDriver *s = chr->opaque;
2966 s->max_size = qemu_chr_can_read(chr);
2968 /* If there were any stray characters in the queue process them
2971 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2972 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2974 s->max_size = qemu_chr_can_read(chr);
2979 static void udp_chr_read(void *opaque)
2981 CharDriverState *chr = opaque;
2982 NetCharDriver *s = chr->opaque;
2984 if (s->max_size == 0)
2986 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2987 s->bufptr = s->bufcnt;
2992 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2993 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2995 s->max_size = qemu_chr_can_read(chr);
2999 static void udp_chr_update_read_handler(CharDriverState *chr)
3001 NetCharDriver *s = chr->opaque;
3004 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3005 udp_chr_read, NULL, chr);
3009 int parse_host_port(struct sockaddr_in *saddr, const char *str);
3011 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3013 int parse_host_src_port(struct sockaddr_in *haddr,
3014 struct sockaddr_in *saddr,
3017 static CharDriverState *qemu_chr_open_udp(const char *def)
3019 CharDriverState *chr = NULL;
3020 NetCharDriver *s = NULL;
3022 struct sockaddr_in saddr;
3024 chr = qemu_mallocz(sizeof(CharDriverState));
3027 s = qemu_mallocz(sizeof(NetCharDriver));
3031 fd = socket(PF_INET, SOCK_DGRAM, 0);
3033 perror("socket(PF_INET, SOCK_DGRAM)");
3037 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3038 printf("Could not parse: %s\n", def);
3042 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3052 chr->chr_write = udp_chr_write;
3053 chr->chr_update_read_handler = udp_chr_update_read_handler;
3066 /***********************************************************/
3067 /* TCP Net console */
3078 static void tcp_chr_accept(void *opaque);
3080 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3082 TCPCharDriver *s = chr->opaque;
3084 return send_all(s->fd, buf, len);
3086 /* XXX: indicate an error ? */
3091 static int tcp_chr_read_poll(void *opaque)
3093 CharDriverState *chr = opaque;
3094 TCPCharDriver *s = chr->opaque;
3097 s->max_size = qemu_chr_can_read(chr);
3102 #define IAC_BREAK 243
3103 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3105 uint8_t *buf, int *size)
3107 /* Handle any telnet client's basic IAC options to satisfy char by
3108 * char mode with no echo. All IAC options will be removed from
3109 * the buf and the do_telnetopt variable will be used to track the
3110 * state of the width of the IAC information.
3112 * IAC commands come in sets of 3 bytes with the exception of the
3113 * "IAC BREAK" command and the double IAC.
3119 for (i = 0; i < *size; i++) {
3120 if (s->do_telnetopt > 1) {
3121 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3122 /* Double IAC means send an IAC */
3126 s->do_telnetopt = 1;
3128 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3129 /* Handle IAC break commands by sending a serial break */
3130 qemu_chr_event(chr, CHR_EVENT_BREAK);
3135 if (s->do_telnetopt >= 4) {
3136 s->do_telnetopt = 1;
3139 if ((unsigned char)buf[i] == IAC) {
3140 s->do_telnetopt = 2;
3151 static void tcp_chr_read(void *opaque)
3153 CharDriverState *chr = opaque;
3154 TCPCharDriver *s = chr->opaque;
3158 if (!s->connected || s->max_size <= 0)
3161 if (len > s->max_size)
3163 size = recv(s->fd, buf, len, 0);
3165 /* connection closed */
3167 if (s->listen_fd >= 0) {
3168 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3170 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3173 } else if (size > 0) {
3174 if (s->do_telnetopt)
3175 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3177 qemu_chr_read(chr, buf, size);
3181 static void tcp_chr_connect(void *opaque)
3183 CharDriverState *chr = opaque;
3184 TCPCharDriver *s = chr->opaque;
3187 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3188 tcp_chr_read, NULL, chr);
3189 qemu_chr_reset(chr);
3192 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3193 static void tcp_chr_telnet_init(int fd)
3196 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3197 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3198 send(fd, (char *)buf, 3, 0);
3199 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3200 send(fd, (char *)buf, 3, 0);
3201 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3202 send(fd, (char *)buf, 3, 0);
3203 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3204 send(fd, (char *)buf, 3, 0);
3207 static void socket_set_nodelay(int fd)
3210 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3213 static void tcp_chr_accept(void *opaque)
3215 CharDriverState *chr = opaque;
3216 TCPCharDriver *s = chr->opaque;
3217 struct sockaddr_in saddr;
3219 struct sockaddr_un uaddr;
3221 struct sockaddr *addr;
3228 len = sizeof(uaddr);
3229 addr = (struct sockaddr *)&uaddr;
3233 len = sizeof(saddr);
3234 addr = (struct sockaddr *)&saddr;
3236 fd = accept(s->listen_fd, addr, &len);
3237 if (fd < 0 && errno != EINTR) {
3239 } else if (fd >= 0) {
3240 if (s->do_telnetopt)
3241 tcp_chr_telnet_init(fd);
3245 socket_set_nonblock(fd);
3247 socket_set_nodelay(fd);
3249 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3250 tcp_chr_connect(chr);
3253 static void tcp_chr_close(CharDriverState *chr)
3255 TCPCharDriver *s = chr->opaque;
3258 if (s->listen_fd >= 0)
3259 closesocket(s->listen_fd);
3263 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3267 CharDriverState *chr = NULL;
3268 TCPCharDriver *s = NULL;
3269 int fd = -1, ret, err, val;
3271 int is_waitconnect = 1;
3274 struct sockaddr_in saddr;
3276 struct sockaddr_un uaddr;
3278 struct sockaddr *addr;
3283 addr = (struct sockaddr *)&uaddr;
3284 addrlen = sizeof(uaddr);
3285 if (parse_unix_path(&uaddr, host_str) < 0)
3290 addr = (struct sockaddr *)&saddr;
3291 addrlen = sizeof(saddr);
3292 if (parse_host_port(&saddr, host_str) < 0)
3297 while((ptr = strchr(ptr,','))) {
3299 if (!strncmp(ptr,"server",6)) {
3301 } else if (!strncmp(ptr,"nowait",6)) {
3303 } else if (!strncmp(ptr,"nodelay",6)) {
3306 printf("Unknown option: %s\n", ptr);
3313 chr = qemu_mallocz(sizeof(CharDriverState));
3316 s = qemu_mallocz(sizeof(TCPCharDriver));
3322 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3325 fd = socket(PF_INET, SOCK_STREAM, 0);
3330 if (!is_waitconnect)
3331 socket_set_nonblock(fd);
3336 s->is_unix = is_unix;
3337 s->do_nodelay = do_nodelay && !is_unix;
3340 chr->chr_write = tcp_chr_write;
3341 chr->chr_close = tcp_chr_close;
3344 /* allow fast reuse */
3348 strncpy(path, uaddr.sun_path, 108);
3355 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3358 ret = bind(fd, addr, addrlen);
3362 ret = listen(fd, 0);
3367 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3369 s->do_telnetopt = 1;
3372 ret = connect(fd, addr, addrlen);
3374 err = socket_error();
3375 if (err == EINTR || err == EWOULDBLOCK) {
3376 } else if (err == EINPROGRESS) {
3379 } else if (err == WSAEALREADY) {
3391 socket_set_nodelay(fd);
3393 tcp_chr_connect(chr);
3395 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3398 if (is_listen && is_waitconnect) {
3399 printf("QEMU waiting for connection on: %s\n", host_str);
3400 tcp_chr_accept(chr);
3401 socket_set_nonblock(s->listen_fd);
3413 CharDriverState *qemu_chr_open(const char *filename)
3417 if (!strcmp(filename, "vc")) {
3418 return text_console_init(&display_state, 0);
3419 } else if (strstart(filename, "vc:", &p)) {
3420 return text_console_init(&display_state, p);
3421 } else if (!strcmp(filename, "null")) {
3422 return qemu_chr_open_null();
3424 if (strstart(filename, "tcp:", &p)) {
3425 return qemu_chr_open_tcp(p, 0, 0);
3427 if (strstart(filename, "telnet:", &p)) {
3428 return qemu_chr_open_tcp(p, 1, 0);
3430 if (strstart(filename, "udp:", &p)) {
3431 return qemu_chr_open_udp(p);
3433 if (strstart(filename, "mon:", &p)) {
3434 CharDriverState *drv = qemu_chr_open(p);
3436 drv = qemu_chr_open_mux(drv);
3437 monitor_init(drv, !nographic);
3440 printf("Unable to open driver: %s\n", p);
3444 if (strstart(filename, "unix:", &p)) {
3445 return qemu_chr_open_tcp(p, 0, 1);
3446 } else if (strstart(filename, "file:", &p)) {
3447 return qemu_chr_open_file_out(p);
3448 } else if (strstart(filename, "pipe:", &p)) {
3449 return qemu_chr_open_pipe(p);
3450 } else if (!strcmp(filename, "pty")) {
3451 return qemu_chr_open_pty();
3452 } else if (!strcmp(filename, "stdio")) {
3453 return qemu_chr_open_stdio();
3455 #if defined(__linux__)
3456 if (strstart(filename, "/dev/parport", NULL)) {
3457 return qemu_chr_open_pp(filename);
3460 #if defined(__linux__) || defined(__sun__)
3461 if (strstart(filename, "/dev/", NULL)) {
3462 return qemu_chr_open_tty(filename);
3466 if (strstart(filename, "COM", NULL)) {
3467 return qemu_chr_open_win(filename);
3469 if (strstart(filename, "pipe:", &p)) {
3470 return qemu_chr_open_win_pipe(p);
3472 if (strstart(filename, "con:", NULL)) {
3473 return qemu_chr_open_win_con(filename);
3475 if (strstart(filename, "file:", &p)) {
3476 return qemu_chr_open_win_file_out(p);
3479 #ifdef CONFIG_BRLAPI
3480 if (!strcmp(filename, "braille")) {
3481 return chr_baum_init();
3489 void qemu_chr_close(CharDriverState *chr)
3492 chr->chr_close(chr);
3496 /***********************************************************/
3497 /* network device redirectors */
3499 __attribute__ (( unused ))
3500 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3504 for(i=0;i<size;i+=16) {
3508 fprintf(f, "%08x ", i);
3511 fprintf(f, " %02x", buf[i+j]);
3516 for(j=0;j<len;j++) {
3518 if (c < ' ' || c > '~')
3520 fprintf(f, "%c", c);
3526 static int parse_macaddr(uint8_t *macaddr, const char *p)
3533 offset = strtol(p, &last_char, 0);
3534 if (0 == errno && '\0' == *last_char &&
3535 offset >= 0 && offset <= 0xFFFFFF) {
3536 macaddr[3] = (offset & 0xFF0000) >> 16;
3537 macaddr[4] = (offset & 0xFF00) >> 8;
3538 macaddr[5] = offset & 0xFF;
3541 for(i = 0; i < 6; i++) {
3542 macaddr[i] = strtol(p, (char **)&p, 16);
3547 if (*p != ':' && *p != '-')
3558 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3563 p1 = strchr(p, sep);
3569 if (len > buf_size - 1)
3571 memcpy(buf, p, len);
3578 int parse_host_src_port(struct sockaddr_in *haddr,
3579 struct sockaddr_in *saddr,
3580 const char *input_str)
3582 char *str = strdup(input_str);
3583 char *host_str = str;
3588 * Chop off any extra arguments at the end of the string which
3589 * would start with a comma, then fill in the src port information
3590 * if it was provided else use the "any address" and "any port".
3592 if ((ptr = strchr(str,',')))
3595 if ((src_str = strchr(input_str,'@'))) {
3600 if (parse_host_port(haddr, host_str) < 0)
3603 if (!src_str || *src_str == '\0')
3606 if (parse_host_port(saddr, src_str) < 0)
3617 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3625 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3627 saddr->sin_family = AF_INET;
3628 if (buf[0] == '\0') {
3629 saddr->sin_addr.s_addr = 0;
3631 if (isdigit(buf[0])) {
3632 if (!inet_aton(buf, &saddr->sin_addr))
3635 if ((he = gethostbyname(buf)) == NULL)
3637 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3640 port = strtol(p, (char **)&r, 0);
3643 saddr->sin_port = htons(port);
3648 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3653 len = MIN(108, strlen(str));
3654 p = strchr(str, ',');
3656 len = MIN(len, p - str);
3658 memset(uaddr, 0, sizeof(*uaddr));
3660 uaddr->sun_family = AF_UNIX;
3661 memcpy(uaddr->sun_path, str, len);
3667 /* find or alloc a new VLAN */
3668 VLANState *qemu_find_vlan(int id)
3670 VLANState **pvlan, *vlan;
3671 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3675 vlan = qemu_mallocz(sizeof(VLANState));
3680 pvlan = &first_vlan;
3681 while (*pvlan != NULL)
3682 pvlan = &(*pvlan)->next;
3687 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3688 IOReadHandler *fd_read,
3689 IOCanRWHandler *fd_can_read,
3692 VLANClientState *vc, **pvc;
3693 vc = qemu_mallocz(sizeof(VLANClientState));
3696 vc->fd_read = fd_read;
3697 vc->fd_can_read = fd_can_read;
3698 vc->opaque = opaque;
3702 pvc = &vlan->first_client;
3703 while (*pvc != NULL)
3704 pvc = &(*pvc)->next;
3709 int qemu_can_send_packet(VLANClientState *vc1)
3711 VLANState *vlan = vc1->vlan;
3712 VLANClientState *vc;
3714 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3716 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3723 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3725 VLANState *vlan = vc1->vlan;
3726 VLANClientState *vc;
3729 printf("vlan %d send:\n", vlan->id);
3730 hex_dump(stdout, buf, size);
3732 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3734 vc->fd_read(vc->opaque, buf, size);
3739 #if defined(CONFIG_SLIRP)
3741 /* slirp network adapter */
3743 static int slirp_inited;
3744 static VLANClientState *slirp_vc;
3746 int slirp_can_output(void)
3748 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3751 void slirp_output(const uint8_t *pkt, int pkt_len)
3754 printf("slirp output:\n");
3755 hex_dump(stdout, pkt, pkt_len);
3759 qemu_send_packet(slirp_vc, pkt, pkt_len);
3762 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3765 printf("slirp input:\n");
3766 hex_dump(stdout, buf, size);
3768 slirp_input(buf, size);
3771 static int net_slirp_init(VLANState *vlan)
3773 if (!slirp_inited) {
3777 slirp_vc = qemu_new_vlan_client(vlan,
3778 slirp_receive, NULL, NULL);
3779 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3783 static void net_slirp_redir(const char *redir_str)
3788 struct in_addr guest_addr;
3789 int host_port, guest_port;
3791 if (!slirp_inited) {
3797 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3799 if (!strcmp(buf, "tcp")) {
3801 } else if (!strcmp(buf, "udp")) {
3807 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3809 host_port = strtol(buf, &r, 0);
3813 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3815 if (buf[0] == '\0') {
3816 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3818 if (!inet_aton(buf, &guest_addr))
3821 guest_port = strtol(p, &r, 0);
3825 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3826 fprintf(stderr, "qemu: could not set up redirection\n");
3831 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3839 static void erase_dir(char *dir_name)
3843 char filename[1024];
3845 /* erase all the files in the directory */
3846 if ((d = opendir(dir_name)) != 0) {
3851 if (strcmp(de->d_name, ".") != 0 &&
3852 strcmp(de->d_name, "..") != 0) {
3853 snprintf(filename, sizeof(filename), "%s/%s",
3854 smb_dir, de->d_name);
3855 if (unlink(filename) != 0) /* is it a directory? */
3856 erase_dir(filename);
3864 /* automatic user mode samba server configuration */
3865 static void smb_exit(void)
3870 /* automatic user mode samba server configuration */
3871 static void net_slirp_smb(const char *exported_dir)
3873 char smb_conf[1024];
3874 char smb_cmdline[1024];
3877 if (!slirp_inited) {
3882 /* XXX: better tmp dir construction */
3883 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3884 if (mkdir(smb_dir, 0700) < 0) {
3885 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3888 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3890 f = fopen(smb_conf, "w");
3892 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3899 "socket address=127.0.0.1\n"
3900 "pid directory=%s\n"
3901 "lock directory=%s\n"
3902 "log file=%s/log.smbd\n"
3903 "smb passwd file=%s/smbpasswd\n"
3904 "security = share\n"
3919 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3920 SMBD_COMMAND, smb_conf);
3922 slirp_add_exec(0, smb_cmdline, 4, 139);
3925 #endif /* !defined(_WIN32) */
3926 void do_info_slirp(void)
3931 #endif /* CONFIG_SLIRP */
3933 #if !defined(_WIN32)
3935 typedef struct TAPState {
3936 VLANClientState *vc;
3938 char down_script[1024];
3941 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3943 TAPState *s = opaque;
3946 ret = write(s->fd, buf, size);
3947 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3954 static void tap_send(void *opaque)
3956 TAPState *s = opaque;
3963 sbuf.maxlen = sizeof(buf);
3965 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3967 size = read(s->fd, buf, sizeof(buf));
3970 qemu_send_packet(s->vc, buf, size);
3976 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3980 s = qemu_mallocz(sizeof(TAPState));
3984 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3985 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3986 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3990 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3991 static int tap_open(char *ifname, int ifname_size)
3997 TFR(fd = open("/dev/tap", O_RDWR));
3999 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4004 dev = devname(s.st_rdev, S_IFCHR);
4005 pstrcpy(ifname, ifname_size, dev);
4007 fcntl(fd, F_SETFL, O_NONBLOCK);
4010 #elif defined(__sun__)
4011 #define TUNNEWPPA (('T'<<16) | 0x0001)
4013 * Allocate TAP device, returns opened fd.
4014 * Stores dev name in the first arg(must be large enough).
4016 int tap_alloc(char *dev)
4018 int tap_fd, if_fd, ppa = -1;
4019 static int ip_fd = 0;
4022 static int arp_fd = 0;
4023 int ip_muxid, arp_muxid;
4024 struct strioctl strioc_if, strioc_ppa;
4025 int link_type = I_PLINK;;
4027 char actual_name[32] = "";
4029 memset(&ifr, 0x0, sizeof(ifr));
4033 while( *ptr && !isdigit((int)*ptr) ) ptr++;
4037 /* Check if IP device was opened */
4041 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4043 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4047 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4049 syslog(LOG_ERR, "Can't open /dev/tap");
4053 /* Assign a new PPA and get its unit number. */
4054 strioc_ppa.ic_cmd = TUNNEWPPA;
4055 strioc_ppa.ic_timout = 0;
4056 strioc_ppa.ic_len = sizeof(ppa);
4057 strioc_ppa.ic_dp = (char *)&ppa;
4058 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4059 syslog (LOG_ERR, "Can't assign new interface");
4061 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4063 syslog(LOG_ERR, "Can't open /dev/tap (2)");
4066 if(ioctl(if_fd, I_PUSH, "ip") < 0){
4067 syslog(LOG_ERR, "Can't push IP module");
4071 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4072 syslog(LOG_ERR, "Can't get flags\n");
4074 snprintf (actual_name, 32, "tap%d", ppa);
4075 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4078 /* Assign ppa according to the unit number returned by tun device */
4080 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4081 syslog (LOG_ERR, "Can't set PPA %d", ppa);
4082 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4083 syslog (LOG_ERR, "Can't get flags\n");
4084 /* Push arp module to if_fd */
4085 if (ioctl (if_fd, I_PUSH, "arp") < 0)
4086 syslog (LOG_ERR, "Can't push ARP module (2)");
4088 /* Push arp module to ip_fd */
4089 if (ioctl (ip_fd, I_POP, NULL) < 0)
4090 syslog (LOG_ERR, "I_POP failed\n");
4091 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4092 syslog (LOG_ERR, "Can't push ARP module (3)\n");
4094 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4096 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4098 /* Set ifname to arp */
4099 strioc_if.ic_cmd = SIOCSLIFNAME;
4100 strioc_if.ic_timout = 0;
4101 strioc_if.ic_len = sizeof(ifr);
4102 strioc_if.ic_dp = (char *)𝔦
4103 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4104 syslog (LOG_ERR, "Can't set ifname to arp\n");
4107 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4108 syslog(LOG_ERR, "Can't link TAP device to IP");
4112 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4113 syslog (LOG_ERR, "Can't link TAP device to ARP");
4117 memset(&ifr, 0x0, sizeof(ifr));
4118 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4119 ifr.lifr_ip_muxid = ip_muxid;
4120 ifr.lifr_arp_muxid = arp_muxid;
4122 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4124 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4125 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4126 syslog (LOG_ERR, "Can't set multiplexor id");
4129 sprintf(dev, "tap%d", ppa);
4133 static int tap_open(char *ifname, int ifname_size)
4137 if( (fd = tap_alloc(dev)) < 0 ){
4138 fprintf(stderr, "Cannot allocate TAP device\n");
4141 pstrcpy(ifname, ifname_size, dev);
4142 fcntl(fd, F_SETFL, O_NONBLOCK);
4146 static int tap_open(char *ifname, int ifname_size)
4151 TFR(fd = open("/dev/net/tun", O_RDWR));
4153 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4156 memset(&ifr, 0, sizeof(ifr));
4157 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4158 if (ifname[0] != '\0')
4159 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4161 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4162 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4164 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4168 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4169 fcntl(fd, F_SETFL, O_NONBLOCK);
4174 static int launch_script(const char *setup_script, const char *ifname, int fd)
4180 /* try to launch network script */
4184 int open_max = sysconf (_SC_OPEN_MAX), i;
4185 for (i = 0; i < open_max; i++)
4186 if (i != STDIN_FILENO &&
4187 i != STDOUT_FILENO &&
4188 i != STDERR_FILENO &&
4193 *parg++ = (char *)setup_script;
4194 *parg++ = (char *)ifname;
4196 execv(setup_script, args);
4199 while (waitpid(pid, &status, 0) != pid);
4200 if (!WIFEXITED(status) ||
4201 WEXITSTATUS(status) != 0) {
4202 fprintf(stderr, "%s: could not launch network script\n",
4210 static int net_tap_init(VLANState *vlan, const char *ifname1,
4211 const char *setup_script, const char *down_script)
4217 if (ifname1 != NULL)
4218 pstrcpy(ifname, sizeof(ifname), ifname1);
4221 TFR(fd = tap_open(ifname, sizeof(ifname)));
4225 if (!setup_script || !strcmp(setup_script, "no"))
4227 if (setup_script[0] != '\0') {
4228 if (launch_script(setup_script, ifname, fd))
4231 s = net_tap_fd_init(vlan, fd);
4234 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4235 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4236 if (down_script && strcmp(down_script, "no"))
4237 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4241 #endif /* !_WIN32 */
4243 /* network connection */
4244 typedef struct NetSocketState {
4245 VLANClientState *vc;
4247 int state; /* 0 = getting length, 1 = getting data */
4251 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4254 typedef struct NetSocketListenState {
4257 } NetSocketListenState;
4259 /* XXX: we consider we can send the whole packet without blocking */
4260 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4262 NetSocketState *s = opaque;
4266 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4267 send_all(s->fd, buf, size);
4270 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4272 NetSocketState *s = opaque;
4273 sendto(s->fd, buf, size, 0,
4274 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4277 static void net_socket_send(void *opaque)
4279 NetSocketState *s = opaque;
4284 size = recv(s->fd, buf1, sizeof(buf1), 0);
4286 err = socket_error();
4287 if (err != EWOULDBLOCK)
4289 } else if (size == 0) {
4290 /* end of connection */
4292 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4298 /* reassemble a packet from the network */
4304 memcpy(s->buf + s->index, buf, l);
4308 if (s->index == 4) {
4310 s->packet_len = ntohl(*(uint32_t *)s->buf);
4316 l = s->packet_len - s->index;
4319 memcpy(s->buf + s->index, buf, l);
4323 if (s->index >= s->packet_len) {
4324 qemu_send_packet(s->vc, s->buf, s->packet_len);
4333 static void net_socket_send_dgram(void *opaque)
4335 NetSocketState *s = opaque;
4338 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4342 /* end of connection */
4343 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4346 qemu_send_packet(s->vc, s->buf, size);
4349 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4354 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4355 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4356 inet_ntoa(mcastaddr->sin_addr),
4357 (int)ntohl(mcastaddr->sin_addr.s_addr));
4361 fd = socket(PF_INET, SOCK_DGRAM, 0);
4363 perror("socket(PF_INET, SOCK_DGRAM)");
4368 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4369 (const char *)&val, sizeof(val));
4371 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4375 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4381 /* Add host to multicast group */
4382 imr.imr_multiaddr = mcastaddr->sin_addr;
4383 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4385 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4386 (const char *)&imr, sizeof(struct ip_mreq));
4388 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4392 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4394 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4395 (const char *)&val, sizeof(val));
4397 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4401 socket_set_nonblock(fd);
4409 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4412 struct sockaddr_in saddr;
4414 socklen_t saddr_len;
4417 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4418 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4419 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4423 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4425 if (saddr.sin_addr.s_addr==0) {
4426 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4430 /* clone dgram socket */
4431 newfd = net_socket_mcast_create(&saddr);
4433 /* error already reported by net_socket_mcast_create() */
4437 /* clone newfd to fd, close newfd */
4442 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4443 fd, strerror(errno));
4448 s = qemu_mallocz(sizeof(NetSocketState));
4453 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4454 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4456 /* mcast: save bound address as dst */
4457 if (is_connected) s->dgram_dst=saddr;
4459 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4460 "socket: fd=%d (%s mcast=%s:%d)",
4461 fd, is_connected? "cloned" : "",
4462 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4466 static void net_socket_connect(void *opaque)
4468 NetSocketState *s = opaque;
4469 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4472 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4476 s = qemu_mallocz(sizeof(NetSocketState));
4480 s->vc = qemu_new_vlan_client(vlan,
4481 net_socket_receive, NULL, s);
4482 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4483 "socket: fd=%d", fd);
4485 net_socket_connect(s);
4487 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4492 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4495 int so_type=-1, optlen=sizeof(so_type);
4497 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4498 (socklen_t *)&optlen)< 0) {
4499 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4504 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4506 return net_socket_fd_init_stream(vlan, fd, is_connected);
4508 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4509 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4510 return net_socket_fd_init_stream(vlan, fd, is_connected);
4515 static void net_socket_accept(void *opaque)
4517 NetSocketListenState *s = opaque;
4519 struct sockaddr_in saddr;
4524 len = sizeof(saddr);
4525 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4526 if (fd < 0 && errno != EINTR) {
4528 } else if (fd >= 0) {
4532 s1 = net_socket_fd_init(s->vlan, fd, 1);
4536 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4537 "socket: connection from %s:%d",
4538 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4542 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4544 NetSocketListenState *s;
4546 struct sockaddr_in saddr;
4548 if (parse_host_port(&saddr, host_str) < 0)
4551 s = qemu_mallocz(sizeof(NetSocketListenState));
4555 fd = socket(PF_INET, SOCK_STREAM, 0);
4560 socket_set_nonblock(fd);
4562 /* allow fast reuse */
4564 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4566 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4571 ret = listen(fd, 0);
4578 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4582 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4585 int fd, connected, ret, err;
4586 struct sockaddr_in saddr;
4588 if (parse_host_port(&saddr, host_str) < 0)
4591 fd = socket(PF_INET, SOCK_STREAM, 0);
4596 socket_set_nonblock(fd);
4600 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4602 err = socket_error();
4603 if (err == EINTR || err == EWOULDBLOCK) {
4604 } else if (err == EINPROGRESS) {
4607 } else if (err == WSAEALREADY) {
4620 s = net_socket_fd_init(vlan, fd, connected);
4623 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4624 "socket: connect to %s:%d",
4625 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4629 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4633 struct sockaddr_in saddr;
4635 if (parse_host_port(&saddr, host_str) < 0)
4639 fd = net_socket_mcast_create(&saddr);
4643 s = net_socket_fd_init(vlan, fd, 0);
4647 s->dgram_dst = saddr;
4649 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4650 "socket: mcast=%s:%d",
4651 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4656 static const char *get_opt_name(char *buf, int buf_size, const char *p)
4661 while (*p != '\0' && *p != '=') {
4662 if (q && (q - buf) < buf_size - 1)
4672 static const char *get_opt_value(char *buf, int buf_size, const char *p)
4677 while (*p != '\0') {
4679 if (*(p + 1) != ',')
4683 if (q && (q - buf) < buf_size - 1)
4693 static int get_param_value(char *buf, int buf_size,
4694 const char *tag, const char *str)
4701 p = get_opt_name(option, sizeof(option), p);
4705 if (!strcmp(tag, option)) {
4706 (void)get_opt_value(buf, buf_size, p);
4709 p = get_opt_value(NULL, 0, p);
4718 static int check_params(char *buf, int buf_size,
4719 char **params, const char *str)
4726 p = get_opt_name(buf, buf_size, p);
4730 for(i = 0; params[i] != NULL; i++)
4731 if (!strcmp(params[i], buf))
4733 if (params[i] == NULL)
4735 p = get_opt_value(NULL, 0, p);
4744 static int net_client_init(const char *str)
4755 while (*p != '\0' && *p != ',') {
4756 if ((q - device) < sizeof(device) - 1)
4764 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4765 vlan_id = strtol(buf, NULL, 0);
4767 vlan = qemu_find_vlan(vlan_id);
4769 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4772 if (!strcmp(device, "nic")) {
4776 if (nb_nics >= MAX_NICS) {
4777 fprintf(stderr, "Too Many NICs\n");
4780 nd = &nd_table[nb_nics];
4781 macaddr = nd->macaddr;
4787 macaddr[5] = 0x56 + nb_nics;
4789 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4790 if (parse_macaddr(macaddr, buf) < 0) {
4791 fprintf(stderr, "invalid syntax for ethernet address\n");
4795 if (get_param_value(buf, sizeof(buf), "model", p)) {
4796 nd->model = strdup(buf);
4800 vlan->nb_guest_devs++;
4803 if (!strcmp(device, "none")) {
4804 /* does nothing. It is needed to signal that no network cards
4809 if (!strcmp(device, "user")) {
4810 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4811 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4813 vlan->nb_host_devs++;
4814 ret = net_slirp_init(vlan);
4818 if (!strcmp(device, "tap")) {
4820 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4821 fprintf(stderr, "tap: no interface name\n");
4824 vlan->nb_host_devs++;
4825 ret = tap_win32_init(vlan, ifname);
4828 if (!strcmp(device, "tap")) {
4830 char setup_script[1024], down_script[1024];
4832 vlan->nb_host_devs++;
4833 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4834 fd = strtol(buf, NULL, 0);
4835 fcntl(fd, F_SETFL, O_NONBLOCK);
4837 if (net_tap_fd_init(vlan, fd))
4840 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4843 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4844 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4846 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4847 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4849 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4853 if (!strcmp(device, "socket")) {
4854 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4856 fd = strtol(buf, NULL, 0);
4858 if (net_socket_fd_init(vlan, fd, 1))
4860 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4861 ret = net_socket_listen_init(vlan, buf);
4862 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4863 ret = net_socket_connect_init(vlan, buf);
4864 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4865 ret = net_socket_mcast_init(vlan, buf);
4867 fprintf(stderr, "Unknown socket options: %s\n", p);
4870 vlan->nb_host_devs++;
4873 fprintf(stderr, "Unknown network device: %s\n", device);
4877 fprintf(stderr, "Could not initialize device '%s'\n", device);
4883 void do_info_network(void)
4886 VLANClientState *vc;
4888 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4889 term_printf("VLAN %d devices:\n", vlan->id);
4890 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4891 term_printf(" %s\n", vc->info_str);
4895 #define HD_ALIAS "index=%d,media=disk"
4897 #define CDROM_ALIAS "index=1,media=cdrom"
4899 #define CDROM_ALIAS "index=2,media=cdrom"
4901 #define FD_ALIAS "index=%d,if=floppy"
4902 #define PFLASH_ALIAS "if=pflash"
4903 #define MTD_ALIAS "if=mtd"
4904 #define SD_ALIAS "index=0,if=sd"
4906 static int drive_add(const char *file, const char *fmt, ...)
4910 if (nb_drives_opt >= MAX_DRIVES) {
4911 fprintf(stderr, "qemu: too many drives\n");
4915 drives_opt[nb_drives_opt].file = file;
4917 vsnprintf(drives_opt[nb_drives_opt].opt,
4918 sizeof(drives_opt[0].opt), fmt, ap);
4921 return nb_drives_opt++;
4924 int drive_get_index(BlockInterfaceType type, int bus, int unit)
4928 /* seek interface, bus and unit */
4930 for (index = 0; index < nb_drives; index++)
4931 if (drives_table[index].type == type &&
4932 drives_table[index].bus == bus &&
4933 drives_table[index].unit == unit)
4939 int drive_get_max_bus(BlockInterfaceType type)
4945 for (index = 0; index < nb_drives; index++) {
4946 if(drives_table[index].type == type &&
4947 drives_table[index].bus > max_bus)
4948 max_bus = drives_table[index].bus;
4953 static int drive_init(struct drive_opt *arg, int snapshot,
4954 QEMUMachine *machine)
4959 const char *mediastr = "";
4960 BlockInterfaceType type;
4961 enum { MEDIA_DISK, MEDIA_CDROM } media;
4962 int bus_id, unit_id;
4963 int cyls, heads, secs, translation;
4964 BlockDriverState *bdrv;
4969 char *str = arg->opt;
4970 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4971 "secs", "trans", "media", "snapshot", "file",
4974 if (check_params(buf, sizeof(buf), params, str) < 0) {
4975 fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
4981 cyls = heads = secs = 0;
4984 translation = BIOS_ATA_TRANSLATION_AUTO;
4988 if (!strcmp(machine->name, "realview") ||
4989 !strcmp(machine->name, "SS-5") ||
4990 !strcmp(machine->name, "SS-10") ||
4991 !strcmp(machine->name, "SS-600MP") ||
4992 !strcmp(machine->name, "versatilepb") ||
4993 !strcmp(machine->name, "versatileab")) {
4995 max_devs = MAX_SCSI_DEVS;
4996 strcpy(devname, "scsi");
4999 max_devs = MAX_IDE_DEVS;
5000 strcpy(devname, "ide");
5004 /* extract parameters */
5006 if (get_param_value(buf, sizeof(buf), "bus", str)) {
5007 bus_id = strtol(buf, NULL, 0);
5009 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5014 if (get_param_value(buf, sizeof(buf), "unit", str)) {
5015 unit_id = strtol(buf, NULL, 0);
5017 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5022 if (get_param_value(buf, sizeof(buf), "if", str)) {
5023 strncpy(devname, buf, sizeof(devname));
5024 if (!strcmp(buf, "ide")) {
5026 max_devs = MAX_IDE_DEVS;
5027 } else if (!strcmp(buf, "scsi")) {
5029 max_devs = MAX_SCSI_DEVS;
5030 } else if (!strcmp(buf, "floppy")) {
5033 } else if (!strcmp(buf, "pflash")) {
5036 } else if (!strcmp(buf, "mtd")) {
5039 } else if (!strcmp(buf, "sd")) {
5043 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5048 if (get_param_value(buf, sizeof(buf), "index", str)) {
5049 index = strtol(buf, NULL, 0);
5051 fprintf(stderr, "qemu: '%s' invalid index\n", str);
5056 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5057 cyls = strtol(buf, NULL, 0);
5060 if (get_param_value(buf, sizeof(buf), "heads", str)) {
5061 heads = strtol(buf, NULL, 0);
5064 if (get_param_value(buf, sizeof(buf), "secs", str)) {
5065 secs = strtol(buf, NULL, 0);
5068 if (cyls || heads || secs) {
5069 if (cyls < 1 || cyls > 16383) {
5070 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5073 if (heads < 1 || heads > 16) {
5074 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5077 if (secs < 1 || secs > 63) {
5078 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5083 if (get_param_value(buf, sizeof(buf), "trans", str)) {
5086 "qemu: '%s' trans must be used with cyls,heads and secs\n",
5090 if (!strcmp(buf, "none"))
5091 translation = BIOS_ATA_TRANSLATION_NONE;
5092 else if (!strcmp(buf, "lba"))
5093 translation = BIOS_ATA_TRANSLATION_LBA;
5094 else if (!strcmp(buf, "auto"))
5095 translation = BIOS_ATA_TRANSLATION_AUTO;
5097 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5102 if (get_param_value(buf, sizeof(buf), "media", str)) {
5103 if (!strcmp(buf, "disk")) {
5105 } else if (!strcmp(buf, "cdrom")) {
5106 if (cyls || secs || heads) {
5108 "qemu: '%s' invalid physical CHS format\n", str);
5111 media = MEDIA_CDROM;
5113 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5118 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5119 if (!strcmp(buf, "on"))
5121 else if (!strcmp(buf, "off"))
5124 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5129 if (get_param_value(buf, sizeof(buf), "cache", str)) {
5130 if (!strcmp(buf, "off"))
5132 else if (!strcmp(buf, "on"))
5135 fprintf(stderr, "qemu: invalid cache option\n");
5140 if (arg->file == NULL)
5141 get_param_value(file, sizeof(file), "file", str);
5143 pstrcpy(file, sizeof(file), arg->file);
5145 /* compute bus and unit according index */
5148 if (bus_id != 0 || unit_id != -1) {
5150 "qemu: '%s' index cannot be used with bus and unit\n", str);
5158 unit_id = index % max_devs;
5159 bus_id = index / max_devs;
5163 /* if user doesn't specify a unit_id,
5164 * try to find the first free
5167 if (unit_id == -1) {
5169 while (drive_get_index(type, bus_id, unit_id) != -1) {
5171 if (max_devs && unit_id >= max_devs) {
5172 unit_id -= max_devs;
5180 if (max_devs && unit_id >= max_devs) {
5181 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5182 str, unit_id, max_devs - 1);
5187 * ignore multiple definitions
5190 if (drive_get_index(type, bus_id, unit_id) != -1)
5195 if (type == IF_IDE || type == IF_SCSI)
5196 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5198 snprintf(buf, sizeof(buf), "%s%i%s%i",
5199 devname, bus_id, mediastr, unit_id);
5201 snprintf(buf, sizeof(buf), "%s%s%i",
5202 devname, mediastr, unit_id);
5203 bdrv = bdrv_new(buf);
5204 drives_table[nb_drives].bdrv = bdrv;
5205 drives_table[nb_drives].type = type;
5206 drives_table[nb_drives].bus = bus_id;
5207 drives_table[nb_drives].unit = unit_id;
5216 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5217 bdrv_set_translation_hint(bdrv, translation);
5221 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5226 /* FIXME: This isn't really a floppy, but it's a reasonable
5229 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5239 bdrv_flags |= BDRV_O_SNAPSHOT;
5241 bdrv_flags |= BDRV_O_DIRECT;
5242 if (bdrv_open(bdrv, file, bdrv_flags) < 0 || qemu_key_check(bdrv, file)) {
5243 fprintf(stderr, "qemu: could not open disk image %s\n",
5250 /***********************************************************/
5253 static USBPort *used_usb_ports;
5254 static USBPort *free_usb_ports;
5256 /* ??? Maybe change this to register a hub to keep track of the topology. */
5257 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5258 usb_attachfn attach)
5260 port->opaque = opaque;
5261 port->index = index;
5262 port->attach = attach;
5263 port->next = free_usb_ports;
5264 free_usb_ports = port;
5267 static int usb_device_add(const char *devname)
5273 if (!free_usb_ports)
5276 if (strstart(devname, "host:", &p)) {
5277 dev = usb_host_device_open(p);
5278 } else if (!strcmp(devname, "mouse")) {
5279 dev = usb_mouse_init();
5280 } else if (!strcmp(devname, "tablet")) {
5281 dev = usb_tablet_init();
5282 } else if (!strcmp(devname, "keyboard")) {
5283 dev = usb_keyboard_init();
5284 } else if (strstart(devname, "disk:", &p)) {
5285 dev = usb_msd_init(p);
5286 } else if (!strcmp(devname, "wacom-tablet")) {
5287 dev = usb_wacom_init();
5288 } else if (strstart(devname, "serial:", &p)) {
5289 dev = usb_serial_init(p);
5290 #ifdef CONFIG_BRLAPI
5291 } else if (!strcmp(devname, "braille")) {
5292 dev = usb_baum_init();
5300 /* Find a USB port to add the device to. */
5301 port = free_usb_ports;
5305 /* Create a new hub and chain it on. */
5306 free_usb_ports = NULL;
5307 port->next = used_usb_ports;
5308 used_usb_ports = port;
5310 hub = usb_hub_init(VM_USB_HUB_SIZE);
5311 usb_attach(port, hub);
5312 port = free_usb_ports;
5315 free_usb_ports = port->next;
5316 port->next = used_usb_ports;
5317 used_usb_ports = port;
5318 usb_attach(port, dev);
5322 static int usb_device_del(const char *devname)
5330 if (!used_usb_ports)
5333 p = strchr(devname, '.');
5336 bus_num = strtoul(devname, NULL, 0);
5337 addr = strtoul(p + 1, NULL, 0);
5341 lastp = &used_usb_ports;
5342 port = used_usb_ports;
5343 while (port && port->dev->addr != addr) {
5344 lastp = &port->next;
5352 *lastp = port->next;
5353 usb_attach(port, NULL);
5354 dev->handle_destroy(dev);
5355 port->next = free_usb_ports;
5356 free_usb_ports = port;
5360 void do_usb_add(const char *devname)
5363 ret = usb_device_add(devname);
5365 term_printf("Could not add USB device '%s'\n", devname);
5368 void do_usb_del(const char *devname)
5371 ret = usb_device_del(devname);
5373 term_printf("Could not remove USB device '%s'\n", devname);
5380 const char *speed_str;
5383 term_printf("USB support not enabled\n");
5387 for (port = used_usb_ports; port; port = port->next) {
5391 switch(dev->speed) {
5395 case USB_SPEED_FULL:
5398 case USB_SPEED_HIGH:
5405 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5406 0, dev->addr, speed_str, dev->devname);
5410 /***********************************************************/
5411 /* PCMCIA/Cardbus */
5413 static struct pcmcia_socket_entry_s {
5414 struct pcmcia_socket_s *socket;
5415 struct pcmcia_socket_entry_s *next;
5416 } *pcmcia_sockets = 0;
5418 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5420 struct pcmcia_socket_entry_s *entry;
5422 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5423 entry->socket = socket;
5424 entry->next = pcmcia_sockets;
5425 pcmcia_sockets = entry;
5428 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5430 struct pcmcia_socket_entry_s *entry, **ptr;
5432 ptr = &pcmcia_sockets;
5433 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5434 if (entry->socket == socket) {
5440 void pcmcia_info(void)
5442 struct pcmcia_socket_entry_s *iter;
5443 if (!pcmcia_sockets)
5444 term_printf("No PCMCIA sockets\n");
5446 for (iter = pcmcia_sockets; iter; iter = iter->next)
5447 term_printf("%s: %s\n", iter->socket->slot_string,
5448 iter->socket->attached ? iter->socket->card_string :
5452 /***********************************************************/
5455 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5459 static void dumb_resize(DisplayState *ds, int w, int h)
5463 static void dumb_refresh(DisplayState *ds)
5465 #if defined(CONFIG_SDL)
5470 static void dumb_display_init(DisplayState *ds)
5475 ds->dpy_update = dumb_update;
5476 ds->dpy_resize = dumb_resize;
5477 ds->dpy_refresh = dumb_refresh;
5480 /***********************************************************/
5483 #define MAX_IO_HANDLERS 64
5485 typedef struct IOHandlerRecord {
5487 IOCanRWHandler *fd_read_poll;
5489 IOHandler *fd_write;
5492 /* temporary data */
5494 struct IOHandlerRecord *next;
5497 static IOHandlerRecord *first_io_handler;
5499 /* XXX: fd_read_poll should be suppressed, but an API change is
5500 necessary in the character devices to suppress fd_can_read(). */
5501 int qemu_set_fd_handler2(int fd,
5502 IOCanRWHandler *fd_read_poll,
5504 IOHandler *fd_write,
5507 IOHandlerRecord **pioh, *ioh;
5509 if (!fd_read && !fd_write) {
5510 pioh = &first_io_handler;
5515 if (ioh->fd == fd) {
5522 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5526 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5529 ioh->next = first_io_handler;
5530 first_io_handler = ioh;
5533 ioh->fd_read_poll = fd_read_poll;
5534 ioh->fd_read = fd_read;
5535 ioh->fd_write = fd_write;
5536 ioh->opaque = opaque;
5542 int qemu_set_fd_handler(int fd,
5544 IOHandler *fd_write,
5547 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5550 /***********************************************************/
5551 /* Polling handling */
5553 typedef struct PollingEntry {
5556 struct PollingEntry *next;
5559 static PollingEntry *first_polling_entry;
5561 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5563 PollingEntry **ppe, *pe;
5564 pe = qemu_mallocz(sizeof(PollingEntry));
5568 pe->opaque = opaque;
5569 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5574 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5576 PollingEntry **ppe, *pe;
5577 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5579 if (pe->func == func && pe->opaque == opaque) {
5588 /***********************************************************/
5589 /* Wait objects support */
5590 typedef struct WaitObjects {
5592 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5593 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5594 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5597 static WaitObjects wait_objects = {0};
5599 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5601 WaitObjects *w = &wait_objects;
5603 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5605 w->events[w->num] = handle;
5606 w->func[w->num] = func;
5607 w->opaque[w->num] = opaque;
5612 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5615 WaitObjects *w = &wait_objects;
5618 for (i = 0; i < w->num; i++) {
5619 if (w->events[i] == handle)
5622 w->events[i] = w->events[i + 1];
5623 w->func[i] = w->func[i + 1];
5624 w->opaque[i] = w->opaque[i + 1];
5632 /***********************************************************/
5633 /* savevm/loadvm support */
5635 #define IO_BUF_SIZE 32768
5639 BlockDriverState *bs;
5642 int64_t base_offset;
5643 int64_t buf_offset; /* start of buffer when writing, end of buffer
5646 int buf_size; /* 0 when writing */
5647 uint8_t buf[IO_BUF_SIZE];
5650 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5654 f = qemu_mallocz(sizeof(QEMUFile));
5657 if (!strcmp(mode, "wb")) {
5659 } else if (!strcmp(mode, "rb")) {
5664 f->outfile = fopen(filename, mode);
5676 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5680 f = qemu_mallocz(sizeof(QEMUFile));
5685 f->is_writable = is_writable;
5686 f->base_offset = offset;
5690 void qemu_fflush(QEMUFile *f)
5692 if (!f->is_writable)
5694 if (f->buf_index > 0) {
5696 fseek(f->outfile, f->buf_offset, SEEK_SET);
5697 fwrite(f->buf, 1, f->buf_index, f->outfile);
5699 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5700 f->buf, f->buf_index);
5702 f->buf_offset += f->buf_index;
5707 static void qemu_fill_buffer(QEMUFile *f)
5714 fseek(f->outfile, f->buf_offset, SEEK_SET);
5715 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5719 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5720 f->buf, IO_BUF_SIZE);
5726 f->buf_offset += len;
5729 void qemu_fclose(QEMUFile *f)
5739 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5743 l = IO_BUF_SIZE - f->buf_index;
5746 memcpy(f->buf + f->buf_index, buf, l);
5750 if (f->buf_index >= IO_BUF_SIZE)
5755 void qemu_put_byte(QEMUFile *f, int v)
5757 f->buf[f->buf_index++] = v;
5758 if (f->buf_index >= IO_BUF_SIZE)
5762 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5768 l = f->buf_size - f->buf_index;
5770 qemu_fill_buffer(f);
5771 l = f->buf_size - f->buf_index;
5777 memcpy(buf, f->buf + f->buf_index, l);
5782 return size1 - size;
5785 int qemu_get_byte(QEMUFile *f)
5787 if (f->buf_index >= f->buf_size) {
5788 qemu_fill_buffer(f);
5789 if (f->buf_index >= f->buf_size)
5792 return f->buf[f->buf_index++];
5795 int64_t qemu_ftell(QEMUFile *f)
5797 return f->buf_offset - f->buf_size + f->buf_index;
5800 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5802 if (whence == SEEK_SET) {
5804 } else if (whence == SEEK_CUR) {
5805 pos += qemu_ftell(f);
5807 /* SEEK_END not supported */
5810 if (f->is_writable) {
5812 f->buf_offset = pos;
5814 f->buf_offset = pos;
5821 void qemu_put_be16(QEMUFile *f, unsigned int v)
5823 qemu_put_byte(f, v >> 8);
5824 qemu_put_byte(f, v);
5827 void qemu_put_be32(QEMUFile *f, unsigned int v)
5829 qemu_put_byte(f, v >> 24);
5830 qemu_put_byte(f, v >> 16);
5831 qemu_put_byte(f, v >> 8);
5832 qemu_put_byte(f, v);
5835 void qemu_put_be64(QEMUFile *f, uint64_t v)
5837 qemu_put_be32(f, v >> 32);
5838 qemu_put_be32(f, v);
5841 unsigned int qemu_get_be16(QEMUFile *f)
5844 v = qemu_get_byte(f) << 8;
5845 v |= qemu_get_byte(f);
5849 unsigned int qemu_get_be32(QEMUFile *f)
5852 v = qemu_get_byte(f) << 24;
5853 v |= qemu_get_byte(f) << 16;
5854 v |= qemu_get_byte(f) << 8;
5855 v |= qemu_get_byte(f);
5859 uint64_t qemu_get_be64(QEMUFile *f)
5862 v = (uint64_t)qemu_get_be32(f) << 32;
5863 v |= qemu_get_be32(f);
5867 typedef struct SaveStateEntry {
5871 SaveStateHandler *save_state;
5872 LoadStateHandler *load_state;
5874 struct SaveStateEntry *next;
5877 static SaveStateEntry *first_se;
5879 int register_savevm(const char *idstr,
5882 SaveStateHandler *save_state,
5883 LoadStateHandler *load_state,
5886 SaveStateEntry *se, **pse;
5888 se = qemu_malloc(sizeof(SaveStateEntry));
5891 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5892 se->instance_id = instance_id;
5893 se->version_id = version_id;
5894 se->save_state = save_state;
5895 se->load_state = load_state;
5896 se->opaque = opaque;
5899 /* add at the end of list */
5901 while (*pse != NULL)
5902 pse = &(*pse)->next;
5907 #define QEMU_VM_FILE_MAGIC 0x5145564d
5908 #define QEMU_VM_FILE_VERSION 0x00000002
5910 static int qemu_savevm_state(QEMUFile *f)
5914 int64_t cur_pos, len_pos, total_len_pos;
5916 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5917 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5918 total_len_pos = qemu_ftell(f);
5919 qemu_put_be64(f, 0); /* total size */
5921 for(se = first_se; se != NULL; se = se->next) {
5923 len = strlen(se->idstr);
5924 qemu_put_byte(f, len);
5925 qemu_put_buffer(f, (uint8_t *)se->idstr, len);
5927 qemu_put_be32(f, se->instance_id);
5928 qemu_put_be32(f, se->version_id);
5930 /* record size: filled later */
5931 len_pos = qemu_ftell(f);
5932 qemu_put_be32(f, 0);
5933 se->save_state(f, se->opaque);
5935 /* fill record size */
5936 cur_pos = qemu_ftell(f);
5937 len = cur_pos - len_pos - 4;
5938 qemu_fseek(f, len_pos, SEEK_SET);
5939 qemu_put_be32(f, len);
5940 qemu_fseek(f, cur_pos, SEEK_SET);
5942 cur_pos = qemu_ftell(f);
5943 qemu_fseek(f, total_len_pos, SEEK_SET);
5944 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5945 qemu_fseek(f, cur_pos, SEEK_SET);
5951 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5955 for(se = first_se; se != NULL; se = se->next) {
5956 if (!strcmp(se->idstr, idstr) &&
5957 instance_id == se->instance_id)
5963 static int qemu_loadvm_state(QEMUFile *f)
5966 int len, ret, instance_id, record_len, version_id;
5967 int64_t total_len, end_pos, cur_pos;
5971 v = qemu_get_be32(f);
5972 if (v != QEMU_VM_FILE_MAGIC)
5974 v = qemu_get_be32(f);
5975 if (v != QEMU_VM_FILE_VERSION) {
5980 total_len = qemu_get_be64(f);
5981 end_pos = total_len + qemu_ftell(f);
5983 if (qemu_ftell(f) >= end_pos)
5985 len = qemu_get_byte(f);
5986 qemu_get_buffer(f, (uint8_t *)idstr, len);
5988 instance_id = qemu_get_be32(f);
5989 version_id = qemu_get_be32(f);
5990 record_len = qemu_get_be32(f);
5992 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5993 idstr, instance_id, version_id, record_len);
5995 cur_pos = qemu_ftell(f);
5996 se = find_se(idstr, instance_id);
5998 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5999 instance_id, idstr);
6001 ret = se->load_state(f, se->opaque, version_id);
6003 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6004 instance_id, idstr);
6007 /* always seek to exact end of record */
6008 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6015 /* device can contain snapshots */
6016 static int bdrv_can_snapshot(BlockDriverState *bs)
6019 !bdrv_is_removable(bs) &&
6020 !bdrv_is_read_only(bs));
6023 /* device must be snapshots in order to have a reliable snapshot */
6024 static int bdrv_has_snapshot(BlockDriverState *bs)
6027 !bdrv_is_removable(bs) &&
6028 !bdrv_is_read_only(bs));
6031 static BlockDriverState *get_bs_snapshots(void)
6033 BlockDriverState *bs;
6037 return bs_snapshots;
6038 for(i = 0; i <= nb_drives; i++) {
6039 bs = drives_table[i].bdrv;
6040 if (bdrv_can_snapshot(bs))
6049 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6052 QEMUSnapshotInfo *sn_tab, *sn;
6056 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6059 for(i = 0; i < nb_sns; i++) {
6061 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6071 void do_savevm(const char *name)
6073 BlockDriverState *bs, *bs1;
6074 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6075 int must_delete, ret, i;
6076 BlockDriverInfo bdi1, *bdi = &bdi1;
6078 int saved_vm_running;
6085 bs = get_bs_snapshots();
6087 term_printf("No block device can accept snapshots\n");
6091 /* ??? Should this occur after vm_stop? */
6094 saved_vm_running = vm_running;
6099 ret = bdrv_snapshot_find(bs, old_sn, name);
6104 memset(sn, 0, sizeof(*sn));
6106 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6107 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6110 pstrcpy(sn->name, sizeof(sn->name), name);
6113 /* fill auxiliary fields */
6116 sn->date_sec = tb.time;
6117 sn->date_nsec = tb.millitm * 1000000;
6119 gettimeofday(&tv, NULL);
6120 sn->date_sec = tv.tv_sec;
6121 sn->date_nsec = tv.tv_usec * 1000;
6123 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6125 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6126 term_printf("Device %s does not support VM state snapshots\n",
6127 bdrv_get_device_name(bs));
6131 /* save the VM state */
6132 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6134 term_printf("Could not open VM state file\n");
6137 ret = qemu_savevm_state(f);
6138 sn->vm_state_size = qemu_ftell(f);
6141 term_printf("Error %d while writing VM\n", ret);
6145 /* create the snapshots */
6147 for(i = 0; i < nb_drives; i++) {
6148 bs1 = drives_table[i].bdrv;
6149 if (bdrv_has_snapshot(bs1)) {
6151 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6153 term_printf("Error while deleting snapshot on '%s'\n",
6154 bdrv_get_device_name(bs1));
6157 ret = bdrv_snapshot_create(bs1, sn);
6159 term_printf("Error while creating snapshot on '%s'\n",
6160 bdrv_get_device_name(bs1));
6166 if (saved_vm_running)
6170 void do_loadvm(const char *name)
6172 BlockDriverState *bs, *bs1;
6173 BlockDriverInfo bdi1, *bdi = &bdi1;
6176 int saved_vm_running;
6178 bs = get_bs_snapshots();
6180 term_printf("No block device supports snapshots\n");
6184 /* Flush all IO requests so they don't interfere with the new state. */
6187 saved_vm_running = vm_running;
6190 for(i = 0; i <= nb_drives; i++) {
6191 bs1 = drives_table[i].bdrv;
6192 if (bdrv_has_snapshot(bs1)) {
6193 ret = bdrv_snapshot_goto(bs1, name);
6196 term_printf("Warning: ");
6199 term_printf("Snapshots not supported on device '%s'\n",
6200 bdrv_get_device_name(bs1));
6203 term_printf("Could not find snapshot '%s' on device '%s'\n",
6204 name, bdrv_get_device_name(bs1));
6207 term_printf("Error %d while activating snapshot on '%s'\n",
6208 ret, bdrv_get_device_name(bs1));
6211 /* fatal on snapshot block device */
6218 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6219 term_printf("Device %s does not support VM state snapshots\n",
6220 bdrv_get_device_name(bs));
6224 /* restore the VM state */
6225 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6227 term_printf("Could not open VM state file\n");
6230 ret = qemu_loadvm_state(f);
6233 term_printf("Error %d while loading VM state\n", ret);
6236 if (saved_vm_running)
6240 void do_delvm(const char *name)
6242 BlockDriverState *bs, *bs1;
6245 bs = get_bs_snapshots();
6247 term_printf("No block device supports snapshots\n");
6251 for(i = 0; i <= nb_drives; i++) {
6252 bs1 = drives_table[i].bdrv;
6253 if (bdrv_has_snapshot(bs1)) {
6254 ret = bdrv_snapshot_delete(bs1, name);
6256 if (ret == -ENOTSUP)
6257 term_printf("Snapshots not supported on device '%s'\n",
6258 bdrv_get_device_name(bs1));
6260 term_printf("Error %d while deleting snapshot on '%s'\n",
6261 ret, bdrv_get_device_name(bs1));
6267 void do_info_snapshots(void)
6269 BlockDriverState *bs, *bs1;
6270 QEMUSnapshotInfo *sn_tab, *sn;
6274 bs = get_bs_snapshots();
6276 term_printf("No available block device supports snapshots\n");
6279 term_printf("Snapshot devices:");
6280 for(i = 0; i <= nb_drives; i++) {
6281 bs1 = drives_table[i].bdrv;
6282 if (bdrv_has_snapshot(bs1)) {
6284 term_printf(" %s", bdrv_get_device_name(bs1));
6289 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6291 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6294 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6295 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6296 for(i = 0; i < nb_sns; i++) {
6298 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6303 /***********************************************************/
6304 /* cpu save/restore */
6306 #if defined(TARGET_I386)
6308 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6310 qemu_put_be32(f, dt->selector);
6311 qemu_put_betl(f, dt->base);
6312 qemu_put_be32(f, dt->limit);
6313 qemu_put_be32(f, dt->flags);
6316 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6318 dt->selector = qemu_get_be32(f);
6319 dt->base = qemu_get_betl(f);
6320 dt->limit = qemu_get_be32(f);
6321 dt->flags = qemu_get_be32(f);
6324 void cpu_save(QEMUFile *f, void *opaque)
6326 CPUState *env = opaque;
6327 uint16_t fptag, fpus, fpuc, fpregs_format;
6331 for(i = 0; i < CPU_NB_REGS; i++)
6332 qemu_put_betls(f, &env->regs[i]);
6333 qemu_put_betls(f, &env->eip);
6334 qemu_put_betls(f, &env->eflags);
6335 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6336 qemu_put_be32s(f, &hflags);
6340 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6342 for(i = 0; i < 8; i++) {
6343 fptag |= ((!env->fptags[i]) << i);
6346 qemu_put_be16s(f, &fpuc);
6347 qemu_put_be16s(f, &fpus);
6348 qemu_put_be16s(f, &fptag);
6350 #ifdef USE_X86LDOUBLE
6355 qemu_put_be16s(f, &fpregs_format);
6357 for(i = 0; i < 8; i++) {
6358 #ifdef USE_X86LDOUBLE
6362 /* we save the real CPU data (in case of MMX usage only 'mant'
6363 contains the MMX register */
6364 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6365 qemu_put_be64(f, mant);
6366 qemu_put_be16(f, exp);
6369 /* if we use doubles for float emulation, we save the doubles to
6370 avoid losing information in case of MMX usage. It can give
6371 problems if the image is restored on a CPU where long
6372 doubles are used instead. */
6373 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6377 for(i = 0; i < 6; i++)
6378 cpu_put_seg(f, &env->segs[i]);
6379 cpu_put_seg(f, &env->ldt);
6380 cpu_put_seg(f, &env->tr);
6381 cpu_put_seg(f, &env->gdt);
6382 cpu_put_seg(f, &env->idt);
6384 qemu_put_be32s(f, &env->sysenter_cs);
6385 qemu_put_be32s(f, &env->sysenter_esp);
6386 qemu_put_be32s(f, &env->sysenter_eip);
6388 qemu_put_betls(f, &env->cr[0]);
6389 qemu_put_betls(f, &env->cr[2]);
6390 qemu_put_betls(f, &env->cr[3]);
6391 qemu_put_betls(f, &env->cr[4]);
6393 for(i = 0; i < 8; i++)
6394 qemu_put_betls(f, &env->dr[i]);
6397 qemu_put_be32s(f, &env->a20_mask);
6400 qemu_put_be32s(f, &env->mxcsr);
6401 for(i = 0; i < CPU_NB_REGS; i++) {
6402 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6403 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6406 #ifdef TARGET_X86_64
6407 qemu_put_be64s(f, &env->efer);
6408 qemu_put_be64s(f, &env->star);
6409 qemu_put_be64s(f, &env->lstar);
6410 qemu_put_be64s(f, &env->cstar);
6411 qemu_put_be64s(f, &env->fmask);
6412 qemu_put_be64s(f, &env->kernelgsbase);
6414 qemu_put_be32s(f, &env->smbase);
6417 #ifdef USE_X86LDOUBLE
6418 /* XXX: add that in a FPU generic layer */
6419 union x86_longdouble {
6424 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6425 #define EXPBIAS1 1023
6426 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6427 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6429 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6433 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6434 /* exponent + sign */
6435 e = EXPD1(temp) - EXPBIAS1 + 16383;
6436 e |= SIGND1(temp) >> 16;
6441 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6443 CPUState *env = opaque;
6446 uint16_t fpus, fpuc, fptag, fpregs_format;
6448 if (version_id != 3 && version_id != 4)
6450 for(i = 0; i < CPU_NB_REGS; i++)
6451 qemu_get_betls(f, &env->regs[i]);
6452 qemu_get_betls(f, &env->eip);
6453 qemu_get_betls(f, &env->eflags);
6454 qemu_get_be32s(f, &hflags);
6456 qemu_get_be16s(f, &fpuc);
6457 qemu_get_be16s(f, &fpus);
6458 qemu_get_be16s(f, &fptag);
6459 qemu_get_be16s(f, &fpregs_format);
6461 /* NOTE: we cannot always restore the FPU state if the image come
6462 from a host with a different 'USE_X86LDOUBLE' define. We guess
6463 if we are in an MMX state to restore correctly in that case. */
6464 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6465 for(i = 0; i < 8; i++) {
6469 switch(fpregs_format) {
6471 mant = qemu_get_be64(f);
6472 exp = qemu_get_be16(f);
6473 #ifdef USE_X86LDOUBLE
6474 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6476 /* difficult case */
6478 env->fpregs[i].mmx.MMX_Q(0) = mant;
6480 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6484 mant = qemu_get_be64(f);
6485 #ifdef USE_X86LDOUBLE
6487 union x86_longdouble *p;
6488 /* difficult case */
6489 p = (void *)&env->fpregs[i];
6494 fp64_to_fp80(p, mant);
6498 env->fpregs[i].mmx.MMX_Q(0) = mant;
6507 /* XXX: restore FPU round state */
6508 env->fpstt = (fpus >> 11) & 7;
6509 env->fpus = fpus & ~0x3800;
6511 for(i = 0; i < 8; i++) {
6512 env->fptags[i] = (fptag >> i) & 1;
6515 for(i = 0; i < 6; i++)
6516 cpu_get_seg(f, &env->segs[i]);
6517 cpu_get_seg(f, &env->ldt);
6518 cpu_get_seg(f, &env->tr);
6519 cpu_get_seg(f, &env->gdt);
6520 cpu_get_seg(f, &env->idt);
6522 qemu_get_be32s(f, &env->sysenter_cs);
6523 qemu_get_be32s(f, &env->sysenter_esp);
6524 qemu_get_be32s(f, &env->sysenter_eip);
6526 qemu_get_betls(f, &env->cr[0]);
6527 qemu_get_betls(f, &env->cr[2]);
6528 qemu_get_betls(f, &env->cr[3]);
6529 qemu_get_betls(f, &env->cr[4]);
6531 for(i = 0; i < 8; i++)
6532 qemu_get_betls(f, &env->dr[i]);
6535 qemu_get_be32s(f, &env->a20_mask);
6537 qemu_get_be32s(f, &env->mxcsr);
6538 for(i = 0; i < CPU_NB_REGS; i++) {
6539 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6540 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6543 #ifdef TARGET_X86_64
6544 qemu_get_be64s(f, &env->efer);
6545 qemu_get_be64s(f, &env->star);
6546 qemu_get_be64s(f, &env->lstar);
6547 qemu_get_be64s(f, &env->cstar);
6548 qemu_get_be64s(f, &env->fmask);
6549 qemu_get_be64s(f, &env->kernelgsbase);
6551 if (version_id >= 4)
6552 qemu_get_be32s(f, &env->smbase);
6554 /* XXX: compute hflags from scratch, except for CPL and IIF */
6555 env->hflags = hflags;
6560 #elif defined(TARGET_PPC)
6561 void cpu_save(QEMUFile *f, void *opaque)
6565 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6570 #elif defined(TARGET_MIPS)
6571 void cpu_save(QEMUFile *f, void *opaque)
6575 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6580 #elif defined(TARGET_SPARC)
6581 void cpu_save(QEMUFile *f, void *opaque)
6583 CPUState *env = opaque;
6587 for(i = 0; i < 8; i++)
6588 qemu_put_betls(f, &env->gregs[i]);
6589 for(i = 0; i < NWINDOWS * 16; i++)
6590 qemu_put_betls(f, &env->regbase[i]);
6593 for(i = 0; i < TARGET_FPREGS; i++) {
6599 qemu_put_be32(f, u.i);
6602 qemu_put_betls(f, &env->pc);
6603 qemu_put_betls(f, &env->npc);
6604 qemu_put_betls(f, &env->y);
6606 qemu_put_be32(f, tmp);
6607 qemu_put_betls(f, &env->fsr);
6608 qemu_put_betls(f, &env->tbr);
6609 #ifndef TARGET_SPARC64
6610 qemu_put_be32s(f, &env->wim);
6612 for(i = 0; i < 16; i++)
6613 qemu_put_be32s(f, &env->mmuregs[i]);
6617 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6619 CPUState *env = opaque;
6623 for(i = 0; i < 8; i++)
6624 qemu_get_betls(f, &env->gregs[i]);
6625 for(i = 0; i < NWINDOWS * 16; i++)
6626 qemu_get_betls(f, &env->regbase[i]);
6629 for(i = 0; i < TARGET_FPREGS; i++) {
6634 u.i = qemu_get_be32(f);
6638 qemu_get_betls(f, &env->pc);
6639 qemu_get_betls(f, &env->npc);
6640 qemu_get_betls(f, &env->y);
6641 tmp = qemu_get_be32(f);
6642 env->cwp = 0; /* needed to ensure that the wrapping registers are
6643 correctly updated */
6645 qemu_get_betls(f, &env->fsr);
6646 qemu_get_betls(f, &env->tbr);
6647 #ifndef TARGET_SPARC64
6648 qemu_get_be32s(f, &env->wim);
6650 for(i = 0; i < 16; i++)
6651 qemu_get_be32s(f, &env->mmuregs[i]);
6657 #elif defined(TARGET_ARM)
6659 void cpu_save(QEMUFile *f, void *opaque)
6662 CPUARMState *env = (CPUARMState *)opaque;
6664 for (i = 0; i < 16; i++) {
6665 qemu_put_be32(f, env->regs[i]);
6667 qemu_put_be32(f, cpsr_read(env));
6668 qemu_put_be32(f, env->spsr);
6669 for (i = 0; i < 6; i++) {
6670 qemu_put_be32(f, env->banked_spsr[i]);
6671 qemu_put_be32(f, env->banked_r13[i]);
6672 qemu_put_be32(f, env->banked_r14[i]);
6674 for (i = 0; i < 5; i++) {
6675 qemu_put_be32(f, env->usr_regs[i]);
6676 qemu_put_be32(f, env->fiq_regs[i]);
6678 qemu_put_be32(f, env->cp15.c0_cpuid);
6679 qemu_put_be32(f, env->cp15.c0_cachetype);
6680 qemu_put_be32(f, env->cp15.c1_sys);
6681 qemu_put_be32(f, env->cp15.c1_coproc);
6682 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6683 qemu_put_be32(f, env->cp15.c2_base0);
6684 qemu_put_be32(f, env->cp15.c2_base1);
6685 qemu_put_be32(f, env->cp15.c2_mask);
6686 qemu_put_be32(f, env->cp15.c2_data);
6687 qemu_put_be32(f, env->cp15.c2_insn);
6688 qemu_put_be32(f, env->cp15.c3);
6689 qemu_put_be32(f, env->cp15.c5_insn);
6690 qemu_put_be32(f, env->cp15.c5_data);
6691 for (i = 0; i < 8; i++) {
6692 qemu_put_be32(f, env->cp15.c6_region[i]);
6694 qemu_put_be32(f, env->cp15.c6_insn);
6695 qemu_put_be32(f, env->cp15.c6_data);
6696 qemu_put_be32(f, env->cp15.c9_insn);
6697 qemu_put_be32(f, env->cp15.c9_data);
6698 qemu_put_be32(f, env->cp15.c13_fcse);
6699 qemu_put_be32(f, env->cp15.c13_context);
6700 qemu_put_be32(f, env->cp15.c13_tls1);
6701 qemu_put_be32(f, env->cp15.c13_tls2);
6702 qemu_put_be32(f, env->cp15.c13_tls3);
6703 qemu_put_be32(f, env->cp15.c15_cpar);
6705 qemu_put_be32(f, env->features);
6707 if (arm_feature(env, ARM_FEATURE_VFP)) {
6708 for (i = 0; i < 16; i++) {
6710 u.d = env->vfp.regs[i];
6711 qemu_put_be32(f, u.l.upper);
6712 qemu_put_be32(f, u.l.lower);
6714 for (i = 0; i < 16; i++) {
6715 qemu_put_be32(f, env->vfp.xregs[i]);
6718 /* TODO: Should use proper FPSCR access functions. */
6719 qemu_put_be32(f, env->vfp.vec_len);
6720 qemu_put_be32(f, env->vfp.vec_stride);
6722 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6723 for (i = 16; i < 32; i++) {
6725 u.d = env->vfp.regs[i];
6726 qemu_put_be32(f, u.l.upper);
6727 qemu_put_be32(f, u.l.lower);
6732 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6733 for (i = 0; i < 16; i++) {
6734 qemu_put_be64(f, env->iwmmxt.regs[i]);
6736 for (i = 0; i < 16; i++) {
6737 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6741 if (arm_feature(env, ARM_FEATURE_M)) {
6742 qemu_put_be32(f, env->v7m.other_sp);
6743 qemu_put_be32(f, env->v7m.vecbase);
6744 qemu_put_be32(f, env->v7m.basepri);
6745 qemu_put_be32(f, env->v7m.control);
6746 qemu_put_be32(f, env->v7m.current_sp);
6747 qemu_put_be32(f, env->v7m.exception);
6751 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6753 CPUARMState *env = (CPUARMState *)opaque;
6756 if (version_id != ARM_CPU_SAVE_VERSION)
6759 for (i = 0; i < 16; i++) {
6760 env->regs[i] = qemu_get_be32(f);
6762 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6763 env->spsr = qemu_get_be32(f);
6764 for (i = 0; i < 6; i++) {
6765 env->banked_spsr[i] = qemu_get_be32(f);
6766 env->banked_r13[i] = qemu_get_be32(f);
6767 env->banked_r14[i] = qemu_get_be32(f);
6769 for (i = 0; i < 5; i++) {
6770 env->usr_regs[i] = qemu_get_be32(f);
6771 env->fiq_regs[i] = qemu_get_be32(f);
6773 env->cp15.c0_cpuid = qemu_get_be32(f);
6774 env->cp15.c0_cachetype = qemu_get_be32(f);
6775 env->cp15.c1_sys = qemu_get_be32(f);
6776 env->cp15.c1_coproc = qemu_get_be32(f);
6777 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6778 env->cp15.c2_base0 = qemu_get_be32(f);
6779 env->cp15.c2_base1 = qemu_get_be32(f);
6780 env->cp15.c2_mask = qemu_get_be32(f);
6781 env->cp15.c2_data = qemu_get_be32(f);
6782 env->cp15.c2_insn = qemu_get_be32(f);
6783 env->cp15.c3 = qemu_get_be32(f);
6784 env->cp15.c5_insn = qemu_get_be32(f);
6785 env->cp15.c5_data = qemu_get_be32(f);
6786 for (i = 0; i < 8; i++) {
6787 env->cp15.c6_region[i] = qemu_get_be32(f);
6789 env->cp15.c6_insn = qemu_get_be32(f);
6790 env->cp15.c6_data = qemu_get_be32(f);
6791 env->cp15.c9_insn = qemu_get_be32(f);
6792 env->cp15.c9_data = qemu_get_be32(f);
6793 env->cp15.c13_fcse = qemu_get_be32(f);
6794 env->cp15.c13_context = qemu_get_be32(f);
6795 env->cp15.c13_tls1 = qemu_get_be32(f);
6796 env->cp15.c13_tls2 = qemu_get_be32(f);
6797 env->cp15.c13_tls3 = qemu_get_be32(f);
6798 env->cp15.c15_cpar = qemu_get_be32(f);
6800 env->features = qemu_get_be32(f);
6802 if (arm_feature(env, ARM_FEATURE_VFP)) {
6803 for (i = 0; i < 16; i++) {
6805 u.l.upper = qemu_get_be32(f);
6806 u.l.lower = qemu_get_be32(f);
6807 env->vfp.regs[i] = u.d;
6809 for (i = 0; i < 16; i++) {
6810 env->vfp.xregs[i] = qemu_get_be32(f);
6813 /* TODO: Should use proper FPSCR access functions. */
6814 env->vfp.vec_len = qemu_get_be32(f);
6815 env->vfp.vec_stride = qemu_get_be32(f);
6817 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6818 for (i = 0; i < 16; i++) {
6820 u.l.upper = qemu_get_be32(f);
6821 u.l.lower = qemu_get_be32(f);
6822 env->vfp.regs[i] = u.d;
6827 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6828 for (i = 0; i < 16; i++) {
6829 env->iwmmxt.regs[i] = qemu_get_be64(f);
6831 for (i = 0; i < 16; i++) {
6832 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6836 if (arm_feature(env, ARM_FEATURE_M)) {
6837 env->v7m.other_sp = qemu_get_be32(f);
6838 env->v7m.vecbase = qemu_get_be32(f);
6839 env->v7m.basepri = qemu_get_be32(f);
6840 env->v7m.control = qemu_get_be32(f);
6841 env->v7m.current_sp = qemu_get_be32(f);
6842 env->v7m.exception = qemu_get_be32(f);
6850 //#warning No CPU save/restore functions
6854 /***********************************************************/
6855 /* ram save/restore */
6857 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6861 v = qemu_get_byte(f);
6864 if (qemu_get_buffer(f, buf, len) != len)
6868 v = qemu_get_byte(f);
6869 memset(buf, v, len);
6877 static int ram_load_v1(QEMUFile *f, void *opaque)
6881 if (qemu_get_be32(f) != phys_ram_size)
6883 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6884 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6891 #define BDRV_HASH_BLOCK_SIZE 1024
6892 #define IOBUF_SIZE 4096
6893 #define RAM_CBLOCK_MAGIC 0xfabe
6895 typedef struct RamCompressState {
6898 uint8_t buf[IOBUF_SIZE];
6901 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6904 memset(s, 0, sizeof(*s));
6906 ret = deflateInit2(&s->zstream, 1,
6908 9, Z_DEFAULT_STRATEGY);
6911 s->zstream.avail_out = IOBUF_SIZE;
6912 s->zstream.next_out = s->buf;
6916 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6918 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6919 qemu_put_be16(s->f, len);
6920 qemu_put_buffer(s->f, buf, len);
6923 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6927 s->zstream.avail_in = len;
6928 s->zstream.next_in = (uint8_t *)buf;
6929 while (s->zstream.avail_in > 0) {
6930 ret = deflate(&s->zstream, Z_NO_FLUSH);
6933 if (s->zstream.avail_out == 0) {
6934 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6935 s->zstream.avail_out = IOBUF_SIZE;
6936 s->zstream.next_out = s->buf;
6942 static void ram_compress_close(RamCompressState *s)
6946 /* compress last bytes */
6948 ret = deflate(&s->zstream, Z_FINISH);
6949 if (ret == Z_OK || ret == Z_STREAM_END) {
6950 len = IOBUF_SIZE - s->zstream.avail_out;
6952 ram_put_cblock(s, s->buf, len);
6954 s->zstream.avail_out = IOBUF_SIZE;
6955 s->zstream.next_out = s->buf;
6956 if (ret == Z_STREAM_END)
6963 deflateEnd(&s->zstream);
6966 typedef struct RamDecompressState {
6969 uint8_t buf[IOBUF_SIZE];
6970 } RamDecompressState;
6972 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6975 memset(s, 0, sizeof(*s));
6977 ret = inflateInit(&s->zstream);
6983 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6987 s->zstream.avail_out = len;
6988 s->zstream.next_out = buf;
6989 while (s->zstream.avail_out > 0) {
6990 if (s->zstream.avail_in == 0) {
6991 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6993 clen = qemu_get_be16(s->f);
6994 if (clen > IOBUF_SIZE)
6996 qemu_get_buffer(s->f, s->buf, clen);
6997 s->zstream.avail_in = clen;
6998 s->zstream.next_in = s->buf;
7000 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
7001 if (ret != Z_OK && ret != Z_STREAM_END) {
7008 static void ram_decompress_close(RamDecompressState *s)
7010 inflateEnd(&s->zstream);
7013 static void ram_save(QEMUFile *f, void *opaque)
7016 RamCompressState s1, *s = &s1;
7019 qemu_put_be32(f, phys_ram_size);
7020 if (ram_compress_open(s, f) < 0)
7022 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7024 if (tight_savevm_enabled) {
7028 /* find if the memory block is available on a virtual
7031 for(j = 0; j < nb_drives; j++) {
7032 sector_num = bdrv_hash_find(drives_table[j].bdrv,
7034 BDRV_HASH_BLOCK_SIZE);
7035 if (sector_num >= 0)
7039 goto normal_compress;
7042 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7043 ram_compress_buf(s, buf, 10);
7049 ram_compress_buf(s, buf, 1);
7050 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7053 ram_compress_close(s);
7056 static int ram_load(QEMUFile *f, void *opaque, int version_id)
7058 RamDecompressState s1, *s = &s1;
7062 if (version_id == 1)
7063 return ram_load_v1(f, opaque);
7064 if (version_id != 2)
7066 if (qemu_get_be32(f) != phys_ram_size)
7068 if (ram_decompress_open(s, f) < 0)
7070 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7071 if (ram_decompress_buf(s, buf, 1) < 0) {
7072 fprintf(stderr, "Error while reading ram block header\n");
7076 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7077 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
7086 ram_decompress_buf(s, buf + 1, 9);
7088 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7089 if (bs_index >= nb_drives) {
7090 fprintf(stderr, "Invalid block device index %d\n", bs_index);
7093 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7095 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7096 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7097 bs_index, sector_num);
7104 printf("Error block header\n");
7108 ram_decompress_close(s);
7112 /***********************************************************/
7113 /* bottom halves (can be seen as timers which expire ASAP) */
7122 static QEMUBH *first_bh = NULL;
7124 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7127 bh = qemu_mallocz(sizeof(QEMUBH));
7131 bh->opaque = opaque;
7135 int qemu_bh_poll(void)
7154 void qemu_bh_schedule(QEMUBH *bh)
7156 CPUState *env = cpu_single_env;
7160 bh->next = first_bh;
7163 /* stop the currently executing CPU to execute the BH ASAP */
7165 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7169 void qemu_bh_cancel(QEMUBH *bh)
7172 if (bh->scheduled) {
7175 pbh = &(*pbh)->next;
7181 void qemu_bh_delete(QEMUBH *bh)
7187 /***********************************************************/
7188 /* machine registration */
7190 QEMUMachine *first_machine = NULL;
7192 int qemu_register_machine(QEMUMachine *m)
7195 pm = &first_machine;
7203 static QEMUMachine *find_machine(const char *name)
7207 for(m = first_machine; m != NULL; m = m->next) {
7208 if (!strcmp(m->name, name))
7214 /***********************************************************/
7215 /* main execution loop */
7217 static void gui_update(void *opaque)
7219 DisplayState *ds = opaque;
7220 ds->dpy_refresh(ds);
7221 qemu_mod_timer(ds->gui_timer,
7222 (ds->gui_timer_interval ?
7223 ds->gui_timer_interval :
7224 GUI_REFRESH_INTERVAL)
7225 + qemu_get_clock(rt_clock));
7228 struct vm_change_state_entry {
7229 VMChangeStateHandler *cb;
7231 LIST_ENTRY (vm_change_state_entry) entries;
7234 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7236 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7239 VMChangeStateEntry *e;
7241 e = qemu_mallocz(sizeof (*e));
7247 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7251 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7253 LIST_REMOVE (e, entries);
7257 static void vm_state_notify(int running)
7259 VMChangeStateEntry *e;
7261 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7262 e->cb(e->opaque, running);
7266 /* XXX: support several handlers */
7267 static VMStopHandler *vm_stop_cb;
7268 static void *vm_stop_opaque;
7270 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7273 vm_stop_opaque = opaque;
7277 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7288 qemu_rearm_alarm_timer(alarm_timer);
7292 void vm_stop(int reason)
7295 cpu_disable_ticks();
7299 vm_stop_cb(vm_stop_opaque, reason);
7306 /* reset/shutdown handler */
7308 typedef struct QEMUResetEntry {
7309 QEMUResetHandler *func;
7311 struct QEMUResetEntry *next;
7314 static QEMUResetEntry *first_reset_entry;
7315 static int reset_requested;
7316 static int shutdown_requested;
7317 static int powerdown_requested;
7319 int qemu_shutdown_requested(void)
7321 int r = shutdown_requested;
7322 shutdown_requested = 0;
7326 int qemu_reset_requested(void)
7328 int r = reset_requested;
7329 reset_requested = 0;
7333 int qemu_powerdown_requested(void)
7335 int r = powerdown_requested;
7336 powerdown_requested = 0;
7340 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7342 QEMUResetEntry **pre, *re;
7344 pre = &first_reset_entry;
7345 while (*pre != NULL)
7346 pre = &(*pre)->next;
7347 re = qemu_mallocz(sizeof(QEMUResetEntry));
7349 re->opaque = opaque;
7354 void qemu_system_reset(void)
7358 /* reset all devices */
7359 for(re = first_reset_entry; re != NULL; re = re->next) {
7360 re->func(re->opaque);
7364 void qemu_system_reset_request(void)
7367 shutdown_requested = 1;
7369 reset_requested = 1;
7372 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7375 void qemu_system_shutdown_request(void)
7377 shutdown_requested = 1;
7379 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7382 void qemu_system_powerdown_request(void)
7384 powerdown_requested = 1;
7386 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7389 void main_loop_wait(int timeout)
7391 IOHandlerRecord *ioh;
7392 fd_set rfds, wfds, xfds;
7401 /* XXX: need to suppress polling by better using win32 events */
7403 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7404 ret |= pe->func(pe->opaque);
7409 WaitObjects *w = &wait_objects;
7411 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7412 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7413 if (w->func[ret - WAIT_OBJECT_0])
7414 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7416 /* Check for additional signaled events */
7417 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7419 /* Check if event is signaled */
7420 ret2 = WaitForSingleObject(w->events[i], 0);
7421 if(ret2 == WAIT_OBJECT_0) {
7423 w->func[i](w->opaque[i]);
7424 } else if (ret2 == WAIT_TIMEOUT) {
7426 err = GetLastError();
7427 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7430 } else if (ret == WAIT_TIMEOUT) {
7432 err = GetLastError();
7433 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7437 /* poll any events */
7438 /* XXX: separate device handlers from system ones */
7443 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7447 (!ioh->fd_read_poll ||
7448 ioh->fd_read_poll(ioh->opaque) != 0)) {
7449 FD_SET(ioh->fd, &rfds);
7453 if (ioh->fd_write) {
7454 FD_SET(ioh->fd, &wfds);
7464 tv.tv_usec = timeout * 1000;
7466 #if defined(CONFIG_SLIRP)
7468 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7471 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7473 IOHandlerRecord **pioh;
7475 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7476 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7477 ioh->fd_read(ioh->opaque);
7479 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7480 ioh->fd_write(ioh->opaque);
7484 /* remove deleted IO handlers */
7485 pioh = &first_io_handler;
7495 #if defined(CONFIG_SLIRP)
7502 slirp_select_poll(&rfds, &wfds, &xfds);
7508 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7509 qemu_get_clock(vm_clock));
7510 /* run dma transfers, if any */
7514 /* real time timers */
7515 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7516 qemu_get_clock(rt_clock));
7518 if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7519 alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7520 qemu_rearm_alarm_timer(alarm_timer);
7523 /* Check bottom-halves last in case any of the earlier events triggered
7529 static int main_loop(void)
7532 #ifdef CONFIG_PROFILER
7537 cur_cpu = first_cpu;
7538 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7545 #ifdef CONFIG_PROFILER
7546 ti = profile_getclock();
7548 ret = cpu_exec(env);
7549 #ifdef CONFIG_PROFILER
7550 qemu_time += profile_getclock() - ti;
7552 next_cpu = env->next_cpu ?: first_cpu;
7553 if (event_pending && likely(ret != EXCP_DEBUG)) {
7554 ret = EXCP_INTERRUPT;
7558 if (ret == EXCP_HLT) {
7559 /* Give the next CPU a chance to run. */
7563 if (ret != EXCP_HALTED)
7565 /* all CPUs are halted ? */
7571 if (shutdown_requested) {
7572 ret = EXCP_INTERRUPT;
7575 if (reset_requested) {
7576 reset_requested = 0;
7577 qemu_system_reset();
7578 ret = EXCP_INTERRUPT;
7580 if (powerdown_requested) {
7581 powerdown_requested = 0;
7582 qemu_system_powerdown();
7583 ret = EXCP_INTERRUPT;
7585 if (unlikely(ret == EXCP_DEBUG)) {
7586 vm_stop(EXCP_DEBUG);
7588 /* If all cpus are halted then wait until the next IRQ */
7589 /* XXX: use timeout computed from timers */
7590 if (ret == EXCP_HALTED)
7597 #ifdef CONFIG_PROFILER
7598 ti = profile_getclock();
7600 main_loop_wait(timeout);
7601 #ifdef CONFIG_PROFILER
7602 dev_time += profile_getclock() - ti;
7605 cpu_disable_ticks();
7609 static void help(int exitcode)
7611 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7612 "usage: %s [options] [disk_image]\n"
7614 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7616 "Standard options:\n"
7617 "-M machine select emulated machine (-M ? for list)\n"
7618 "-cpu cpu select CPU (-cpu ? for list)\n"
7619 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7620 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7621 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7622 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7623 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7624 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]"
7625 " [,cache=on|off]\n"
7626 " use 'file' as a drive image\n"
7627 "-mtdblock file use 'file' as on-board Flash memory image\n"
7628 "-sd file use 'file' as SecureDigital card image\n"
7629 "-pflash file use 'file' as a parallel flash image\n"
7630 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7631 "-snapshot write to temporary files instead of disk image files\n"
7633 "-no-frame open SDL window without a frame and window decorations\n"
7634 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7635 "-no-quit disable SDL window close capability\n"
7638 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7640 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7641 "-smp n set the number of CPUs to 'n' [default=1]\n"
7642 "-nographic disable graphical output and redirect serial I/Os to console\n"
7643 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7645 "-k language use keyboard layout (for example \"fr\" for French)\n"
7648 "-audio-help print list of audio drivers and their options\n"
7649 "-soundhw c1,... enable audio support\n"
7650 " and only specified sound cards (comma separated list)\n"
7651 " use -soundhw ? to get the list of supported cards\n"
7652 " use -soundhw all to enable all of them\n"
7654 "-localtime set the real time clock to local time [default=utc]\n"
7655 "-full-screen start in full screen\n"
7657 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7659 "-usb enable the USB driver (will be the default soon)\n"
7660 "-usbdevice name add the host or guest USB device 'name'\n"
7661 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7662 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7664 "-name string set the name of the guest\n"
7666 "Network options:\n"
7667 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7668 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7670 "-net user[,vlan=n][,hostname=host]\n"
7671 " connect the user mode network stack to VLAN 'n' and send\n"
7672 " hostname 'host' to DHCP clients\n"
7675 "-net tap[,vlan=n],ifname=name\n"
7676 " connect the host TAP network interface to VLAN 'n'\n"
7678 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7679 " connect the host TAP network interface to VLAN 'n' and use the\n"
7680 " network scripts 'file' (default=%s)\n"
7681 " and 'dfile' (default=%s);\n"
7682 " use '[down]script=no' to disable script execution;\n"
7683 " use 'fd=h' to connect to an already opened TAP interface\n"
7685 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7686 " connect the vlan 'n' to another VLAN using a socket connection\n"
7687 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7688 " connect the vlan 'n' to multicast maddr and port\n"
7689 "-net none use it alone to have zero network devices; if no -net option\n"
7690 " is provided, the default is '-net nic -net user'\n"
7693 "-tftp dir allow tftp access to files in dir [-net user]\n"
7694 "-bootp file advertise file in BOOTP replies\n"
7696 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7698 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7699 " redirect TCP or UDP connections from host to guest [-net user]\n"
7702 "Linux boot specific:\n"
7703 "-kernel bzImage use 'bzImage' as kernel image\n"
7704 "-append cmdline use 'cmdline' as kernel command line\n"
7705 "-initrd file use 'file' as initial ram disk\n"
7707 "Debug/Expert options:\n"
7708 "-monitor dev redirect the monitor to char device 'dev'\n"
7709 "-serial dev redirect the serial port to char device 'dev'\n"
7710 "-parallel dev redirect the parallel port to char device 'dev'\n"
7711 "-pidfile file Write PID to 'file'\n"
7712 "-S freeze CPU at startup (use 'c' to start execution)\n"
7713 "-s wait gdb connection to port\n"
7714 "-p port set gdb connection port [default=%s]\n"
7715 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7716 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7717 " translation (t=none or lba) (usually qemu can guess them)\n"
7718 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7720 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7721 "-no-kqemu disable KQEMU kernel module usage\n"
7724 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7725 " (default is CL-GD5446 PCI VGA)\n"
7726 "-no-acpi disable ACPI\n"
7728 #ifdef CONFIG_CURSES
7729 "-curses use a curses/ncurses interface instead of SDL\n"
7731 "-no-reboot exit instead of rebooting\n"
7732 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7733 "-vnc display start a VNC server on display\n"
7735 "-daemonize daemonize QEMU after initializing\n"
7737 "-option-rom rom load a file, rom, into the option ROM space\n"
7739 "-prom-env variable=value set OpenBIOS nvram variables\n"
7741 "-clock force the use of the given methods for timer alarm.\n"
7742 " To see what timers are available use -clock ?\n"
7743 "-startdate select initial date of the clock\n"
7745 "During emulation, the following keys are useful:\n"
7746 "ctrl-alt-f toggle full screen\n"
7747 "ctrl-alt-n switch to virtual console 'n'\n"
7748 "ctrl-alt toggle mouse and keyboard grab\n"
7750 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7755 DEFAULT_NETWORK_SCRIPT,
7756 DEFAULT_NETWORK_DOWN_SCRIPT,
7758 DEFAULT_GDBSTUB_PORT,
7763 #define HAS_ARG 0x0001
7778 QEMU_OPTION_mtdblock,
7782 QEMU_OPTION_snapshot,
7784 QEMU_OPTION_no_fd_bootchk,
7787 QEMU_OPTION_nographic,
7788 QEMU_OPTION_portrait,
7790 QEMU_OPTION_audio_help,
7791 QEMU_OPTION_soundhw,
7811 QEMU_OPTION_no_code_copy,
7813 QEMU_OPTION_localtime,
7814 QEMU_OPTION_cirrusvga,
7817 QEMU_OPTION_std_vga,
7819 QEMU_OPTION_monitor,
7821 QEMU_OPTION_parallel,
7823 QEMU_OPTION_full_screen,
7824 QEMU_OPTION_no_frame,
7825 QEMU_OPTION_alt_grab,
7826 QEMU_OPTION_no_quit,
7827 QEMU_OPTION_pidfile,
7828 QEMU_OPTION_no_kqemu,
7829 QEMU_OPTION_kernel_kqemu,
7830 QEMU_OPTION_win2k_hack,
7832 QEMU_OPTION_usbdevice,
7835 QEMU_OPTION_no_acpi,
7837 QEMU_OPTION_no_reboot,
7838 QEMU_OPTION_show_cursor,
7839 QEMU_OPTION_daemonize,
7840 QEMU_OPTION_option_rom,
7841 QEMU_OPTION_semihosting,
7843 QEMU_OPTION_prom_env,
7844 QEMU_OPTION_old_param,
7846 QEMU_OPTION_startdate,
7849 typedef struct QEMUOption {
7855 const QEMUOption qemu_options[] = {
7856 { "h", 0, QEMU_OPTION_h },
7857 { "help", 0, QEMU_OPTION_h },
7859 { "M", HAS_ARG, QEMU_OPTION_M },
7860 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7861 { "fda", HAS_ARG, QEMU_OPTION_fda },
7862 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7863 { "hda", HAS_ARG, QEMU_OPTION_hda },
7864 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7865 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7866 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7867 { "drive", HAS_ARG, QEMU_OPTION_drive },
7868 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7869 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7870 { "sd", HAS_ARG, QEMU_OPTION_sd },
7871 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7872 { "boot", HAS_ARG, QEMU_OPTION_boot },
7873 { "snapshot", 0, QEMU_OPTION_snapshot },
7875 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7877 { "m", HAS_ARG, QEMU_OPTION_m },
7878 { "nographic", 0, QEMU_OPTION_nographic },
7879 { "portrait", 0, QEMU_OPTION_portrait },
7880 { "k", HAS_ARG, QEMU_OPTION_k },
7882 { "audio-help", 0, QEMU_OPTION_audio_help },
7883 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7886 { "net", HAS_ARG, QEMU_OPTION_net},
7888 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7889 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7891 { "smb", HAS_ARG, QEMU_OPTION_smb },
7893 { "redir", HAS_ARG, QEMU_OPTION_redir },
7896 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7897 { "append", HAS_ARG, QEMU_OPTION_append },
7898 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7900 { "S", 0, QEMU_OPTION_S },
7901 { "s", 0, QEMU_OPTION_s },
7902 { "p", HAS_ARG, QEMU_OPTION_p },
7903 { "d", HAS_ARG, QEMU_OPTION_d },
7904 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7905 { "L", HAS_ARG, QEMU_OPTION_L },
7906 { "bios", HAS_ARG, QEMU_OPTION_bios },
7907 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7909 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7910 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7912 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7913 { "g", 1, QEMU_OPTION_g },
7915 { "localtime", 0, QEMU_OPTION_localtime },
7916 { "std-vga", 0, QEMU_OPTION_std_vga },
7917 { "echr", HAS_ARG, QEMU_OPTION_echr },
7918 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7919 { "serial", HAS_ARG, QEMU_OPTION_serial },
7920 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7921 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7922 { "full-screen", 0, QEMU_OPTION_full_screen },
7924 { "no-frame", 0, QEMU_OPTION_no_frame },
7925 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7926 { "no-quit", 0, QEMU_OPTION_no_quit },
7928 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7929 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7930 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7931 { "smp", HAS_ARG, QEMU_OPTION_smp },
7932 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7933 #ifdef CONFIG_CURSES
7934 { "curses", 0, QEMU_OPTION_curses },
7937 /* temporary options */
7938 { "usb", 0, QEMU_OPTION_usb },
7939 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7940 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7941 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7942 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7943 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7944 { "daemonize", 0, QEMU_OPTION_daemonize },
7945 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7946 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7947 { "semihosting", 0, QEMU_OPTION_semihosting },
7949 { "name", HAS_ARG, QEMU_OPTION_name },
7950 #if defined(TARGET_SPARC)
7951 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7953 #if defined(TARGET_ARM)
7954 { "old-param", 0, QEMU_OPTION_old_param },
7956 { "clock", HAS_ARG, QEMU_OPTION_clock },
7957 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7961 /* password input */
7963 int qemu_key_check(BlockDriverState *bs, const char *name)
7968 if (!bdrv_is_encrypted(bs))
7971 term_printf("%s is encrypted.\n", name);
7972 for(i = 0; i < 3; i++) {
7973 monitor_readline("Password: ", 1, password, sizeof(password));
7974 if (bdrv_set_key(bs, password) == 0)
7976 term_printf("invalid password\n");
7981 static BlockDriverState *get_bdrv(int index)
7983 if (index > nb_drives)
7985 return drives_table[index].bdrv;
7988 static void read_passwords(void)
7990 BlockDriverState *bs;
7993 for(i = 0; i < 6; i++) {
7996 qemu_key_check(bs, bdrv_get_device_name(bs));
8000 /* XXX: currently we cannot use simultaneously different CPUs */
8001 static void register_machines(void)
8003 #if defined(TARGET_I386)
8004 qemu_register_machine(&pc_machine);
8005 qemu_register_machine(&isapc_machine);
8006 #elif defined(TARGET_PPC)
8007 qemu_register_machine(&heathrow_machine);
8008 qemu_register_machine(&core99_machine);
8009 qemu_register_machine(&prep_machine);
8010 qemu_register_machine(&ref405ep_machine);
8011 qemu_register_machine(&taihu_machine);
8012 #elif defined(TARGET_MIPS)
8013 qemu_register_machine(&mips_machine);
8014 qemu_register_machine(&mips_magnum_machine);
8015 qemu_register_machine(&mips_malta_machine);
8016 qemu_register_machine(&mips_pica61_machine);
8017 qemu_register_machine(&mips_mipssim_machine);
8018 #elif defined(TARGET_SPARC)
8019 #ifdef TARGET_SPARC64
8020 qemu_register_machine(&sun4u_machine);
8022 qemu_register_machine(&ss5_machine);
8023 qemu_register_machine(&ss10_machine);
8024 qemu_register_machine(&ss600mp_machine);
8025 qemu_register_machine(&ss20_machine);
8026 qemu_register_machine(&ss2_machine);
8027 qemu_register_machine(&voyager_machine);
8028 qemu_register_machine(&ss_lx_machine);
8029 qemu_register_machine(&ss4_machine);
8030 qemu_register_machine(&scls_machine);
8031 qemu_register_machine(&sbook_machine);
8032 qemu_register_machine(&ss1000_machine);
8033 qemu_register_machine(&ss2000_machine);
8035 #elif defined(TARGET_ARM)
8036 qemu_register_machine(&integratorcp_machine);
8037 qemu_register_machine(&versatilepb_machine);
8038 qemu_register_machine(&versatileab_machine);
8039 qemu_register_machine(&realview_machine);
8040 qemu_register_machine(&akitapda_machine);
8041 qemu_register_machine(&spitzpda_machine);
8042 qemu_register_machine(&borzoipda_machine);
8043 qemu_register_machine(&terrierpda_machine);
8044 qemu_register_machine(&palmte_machine);
8045 qemu_register_machine(&lm3s811evb_machine);
8046 qemu_register_machine(&lm3s6965evb_machine);
8047 qemu_register_machine(&connex_machine);
8048 qemu_register_machine(&verdex_machine);
8049 qemu_register_machine(&mainstone2_machine);
8050 #elif defined(TARGET_SH4)
8051 qemu_register_machine(&shix_machine);
8052 qemu_register_machine(&r2d_machine);
8053 #elif defined(TARGET_ALPHA)
8055 #elif defined(TARGET_M68K)
8056 qemu_register_machine(&mcf5208evb_machine);
8057 qemu_register_machine(&an5206_machine);
8058 qemu_register_machine(&dummy_m68k_machine);
8059 #elif defined(TARGET_CRIS)
8060 qemu_register_machine(&bareetraxfs_machine);
8062 #error unsupported CPU
8067 struct soundhw soundhw[] = {
8068 #ifdef HAS_AUDIO_CHOICE
8069 #if defined(TARGET_I386) || defined(TARGET_MIPS)
8075 { .init_isa = pcspk_audio_init }
8080 "Creative Sound Blaster 16",
8083 { .init_isa = SB16_init }
8090 "Yamaha YMF262 (OPL3)",
8092 "Yamaha YM3812 (OPL2)",
8096 { .init_isa = Adlib_init }
8103 "Gravis Ultrasound GF1",
8106 { .init_isa = GUS_init }
8113 "Intel 82801AA AC97 Audio",
8116 { .init_pci = ac97_init }
8122 "ENSONIQ AudioPCI ES1370",
8125 { .init_pci = es1370_init }
8129 { NULL, NULL, 0, 0, { NULL } }
8132 static void select_soundhw (const char *optarg)
8136 if (*optarg == '?') {
8139 printf ("Valid sound card names (comma separated):\n");
8140 for (c = soundhw; c->name; ++c) {
8141 printf ("%-11s %s\n", c->name, c->descr);
8143 printf ("\n-soundhw all will enable all of the above\n");
8144 exit (*optarg != '?');
8152 if (!strcmp (optarg, "all")) {
8153 for (c = soundhw; c->name; ++c) {
8161 e = strchr (p, ',');
8162 l = !e ? strlen (p) : (size_t) (e - p);
8164 for (c = soundhw; c->name; ++c) {
8165 if (!strncmp (c->name, p, l)) {
8174 "Unknown sound card name (too big to show)\n");
8177 fprintf (stderr, "Unknown sound card name `%.*s'\n",
8182 p += l + (e != NULL);
8186 goto show_valid_cards;
8192 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8194 exit(STATUS_CONTROL_C_EXIT);
8199 #define MAX_NET_CLIENTS 32
8201 int main(int argc, char **argv)
8203 #ifdef CONFIG_GDBSTUB
8205 const char *gdbstub_port;
8207 uint32_t boot_devices_bitmap = 0;
8209 int snapshot, linux_boot, net_boot;
8210 const char *initrd_filename;
8211 const char *kernel_filename, *kernel_cmdline;
8212 const char *boot_devices = "";
8213 DisplayState *ds = &display_state;
8214 int cyls, heads, secs, translation;
8215 const char *net_clients[MAX_NET_CLIENTS];
8219 const char *r, *optarg;
8220 CharDriverState *monitor_hd;
8221 const char *monitor_device;
8222 const char *serial_devices[MAX_SERIAL_PORTS];
8223 int serial_device_index;
8224 const char *parallel_devices[MAX_PARALLEL_PORTS];
8225 int parallel_device_index;
8226 const char *loadvm = NULL;
8227 QEMUMachine *machine;
8228 const char *cpu_model;
8229 const char *usb_devices[MAX_USB_CMDLINE];
8230 int usb_devices_index;
8232 const char *pid_file = NULL;
8235 LIST_INIT (&vm_change_state_head);
8238 struct sigaction act;
8239 sigfillset(&act.sa_mask);
8241 act.sa_handler = SIG_IGN;
8242 sigaction(SIGPIPE, &act, NULL);
8245 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8246 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8247 QEMU to run on a single CPU */
8252 h = GetCurrentProcess();
8253 if (GetProcessAffinityMask(h, &mask, &smask)) {
8254 for(i = 0; i < 32; i++) {
8255 if (mask & (1 << i))
8260 SetProcessAffinityMask(h, mask);
8266 register_machines();
8267 machine = first_machine;
8269 initrd_filename = NULL;
8270 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8271 vga_ram_size = VGA_RAM_SIZE;
8272 #ifdef CONFIG_GDBSTUB
8274 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8279 kernel_filename = NULL;
8280 kernel_cmdline = "";
8281 cyls = heads = secs = 0;
8282 translation = BIOS_ATA_TRANSLATION_AUTO;
8283 monitor_device = "vc";
8285 serial_devices[0] = "vc";
8286 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8287 serial_devices[i] = NULL;
8288 serial_device_index = 0;
8290 parallel_devices[0] = "vc";
8291 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8292 parallel_devices[i] = NULL;
8293 parallel_device_index = 0;
8295 usb_devices_index = 0;
8303 /* default mac address of the first network interface */
8311 hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8313 const QEMUOption *popt;
8316 /* Treat --foo the same as -foo. */
8319 popt = qemu_options;
8322 fprintf(stderr, "%s: invalid option -- '%s'\n",
8326 if (!strcmp(popt->name, r + 1))
8330 if (popt->flags & HAS_ARG) {
8331 if (optind >= argc) {
8332 fprintf(stderr, "%s: option '%s' requires an argument\n",
8336 optarg = argv[optind++];
8341 switch(popt->index) {
8343 machine = find_machine(optarg);
8346 printf("Supported machines are:\n");
8347 for(m = first_machine; m != NULL; m = m->next) {
8348 printf("%-10s %s%s\n",
8350 m == first_machine ? " (default)" : "");
8352 exit(*optarg != '?');
8355 case QEMU_OPTION_cpu:
8356 /* hw initialization will check this */
8357 if (*optarg == '?') {
8358 /* XXX: implement xxx_cpu_list for targets that still miss it */
8359 #if defined(cpu_list)
8360 cpu_list(stdout, &fprintf);
8367 case QEMU_OPTION_initrd:
8368 initrd_filename = optarg;
8370 case QEMU_OPTION_hda:
8372 hda_index = drive_add(optarg, HD_ALIAS, 0);
8374 hda_index = drive_add(optarg, HD_ALIAS
8375 ",cyls=%d,heads=%d,secs=%d%s",
8376 0, cyls, heads, secs,
8377 translation == BIOS_ATA_TRANSLATION_LBA ?
8379 translation == BIOS_ATA_TRANSLATION_NONE ?
8380 ",trans=none" : "");
8382 case QEMU_OPTION_hdb:
8383 case QEMU_OPTION_hdc:
8384 case QEMU_OPTION_hdd:
8385 drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8387 case QEMU_OPTION_drive:
8388 drive_add(NULL, "%s", optarg);
8390 case QEMU_OPTION_mtdblock:
8391 drive_add(optarg, MTD_ALIAS);
8393 case QEMU_OPTION_sd:
8394 drive_add(optarg, SD_ALIAS);
8396 case QEMU_OPTION_pflash:
8397 drive_add(optarg, PFLASH_ALIAS);
8399 case QEMU_OPTION_snapshot:
8402 case QEMU_OPTION_hdachs:
8406 cyls = strtol(p, (char **)&p, 0);
8407 if (cyls < 1 || cyls > 16383)
8412 heads = strtol(p, (char **)&p, 0);
8413 if (heads < 1 || heads > 16)
8418 secs = strtol(p, (char **)&p, 0);
8419 if (secs < 1 || secs > 63)
8423 if (!strcmp(p, "none"))
8424 translation = BIOS_ATA_TRANSLATION_NONE;
8425 else if (!strcmp(p, "lba"))
8426 translation = BIOS_ATA_TRANSLATION_LBA;
8427 else if (!strcmp(p, "auto"))
8428 translation = BIOS_ATA_TRANSLATION_AUTO;
8431 } else if (*p != '\0') {
8433 fprintf(stderr, "qemu: invalid physical CHS format\n");
8436 if (hda_index != -1)
8437 snprintf(drives_opt[hda_index].opt,
8438 sizeof(drives_opt[hda_index].opt),
8439 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8440 0, cyls, heads, secs,
8441 translation == BIOS_ATA_TRANSLATION_LBA ?
8443 translation == BIOS_ATA_TRANSLATION_NONE ?
8444 ",trans=none" : "");
8447 case QEMU_OPTION_nographic:
8448 serial_devices[0] = "stdio";
8449 parallel_devices[0] = "null";
8450 monitor_device = "stdio";
8453 #ifdef CONFIG_CURSES
8454 case QEMU_OPTION_curses:
8458 case QEMU_OPTION_portrait:
8461 case QEMU_OPTION_kernel:
8462 kernel_filename = optarg;
8464 case QEMU_OPTION_append:
8465 kernel_cmdline = optarg;
8467 case QEMU_OPTION_cdrom:
8468 drive_add(optarg, CDROM_ALIAS);
8470 case QEMU_OPTION_boot:
8471 boot_devices = optarg;
8472 /* We just do some generic consistency checks */
8474 /* Could easily be extended to 64 devices if needed */
8477 boot_devices_bitmap = 0;
8478 for (p = boot_devices; *p != '\0'; p++) {
8479 /* Allowed boot devices are:
8480 * a b : floppy disk drives
8481 * c ... f : IDE disk drives
8482 * g ... m : machine implementation dependant drives
8483 * n ... p : network devices
8484 * It's up to each machine implementation to check
8485 * if the given boot devices match the actual hardware
8486 * implementation and firmware features.
8488 if (*p < 'a' || *p > 'q') {
8489 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8492 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8494 "Boot device '%c' was given twice\n",*p);
8497 boot_devices_bitmap |= 1 << (*p - 'a');
8501 case QEMU_OPTION_fda:
8502 case QEMU_OPTION_fdb:
8503 drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8506 case QEMU_OPTION_no_fd_bootchk:
8510 case QEMU_OPTION_no_code_copy:
8511 code_copy_enabled = 0;
8513 case QEMU_OPTION_net:
8514 if (nb_net_clients >= MAX_NET_CLIENTS) {
8515 fprintf(stderr, "qemu: too many network clients\n");
8518 net_clients[nb_net_clients] = optarg;
8522 case QEMU_OPTION_tftp:
8523 tftp_prefix = optarg;
8525 case QEMU_OPTION_bootp:
8526 bootp_filename = optarg;
8529 case QEMU_OPTION_smb:
8530 net_slirp_smb(optarg);
8533 case QEMU_OPTION_redir:
8534 net_slirp_redir(optarg);
8538 case QEMU_OPTION_audio_help:
8542 case QEMU_OPTION_soundhw:
8543 select_soundhw (optarg);
8550 ram_size = atoi(optarg) * 1024 * 1024;
8553 if (ram_size > PHYS_RAM_MAX_SIZE) {
8554 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8555 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8564 mask = cpu_str_to_log_mask(optarg);
8566 printf("Log items (comma separated):\n");
8567 for(item = cpu_log_items; item->mask != 0; item++) {
8568 printf("%-10s %s\n", item->name, item->help);
8575 #ifdef CONFIG_GDBSTUB
8580 gdbstub_port = optarg;
8586 case QEMU_OPTION_bios:
8593 keyboard_layout = optarg;
8595 case QEMU_OPTION_localtime:
8598 case QEMU_OPTION_cirrusvga:
8599 cirrus_vga_enabled = 1;
8602 case QEMU_OPTION_vmsvga:
8603 cirrus_vga_enabled = 0;
8606 case QEMU_OPTION_std_vga:
8607 cirrus_vga_enabled = 0;
8615 w = strtol(p, (char **)&p, 10);
8618 fprintf(stderr, "qemu: invalid resolution or depth\n");
8624 h = strtol(p, (char **)&p, 10);
8629 depth = strtol(p, (char **)&p, 10);
8630 if (depth != 8 && depth != 15 && depth != 16 &&
8631 depth != 24 && depth != 32)
8633 } else if (*p == '\0') {
8634 depth = graphic_depth;
8641 graphic_depth = depth;
8644 case QEMU_OPTION_echr:
8647 term_escape_char = strtol(optarg, &r, 0);
8649 printf("Bad argument to echr\n");
8652 case QEMU_OPTION_monitor:
8653 monitor_device = optarg;
8655 case QEMU_OPTION_serial:
8656 if (serial_device_index >= MAX_SERIAL_PORTS) {
8657 fprintf(stderr, "qemu: too many serial ports\n");
8660 serial_devices[serial_device_index] = optarg;
8661 serial_device_index++;
8663 case QEMU_OPTION_parallel:
8664 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8665 fprintf(stderr, "qemu: too many parallel ports\n");
8668 parallel_devices[parallel_device_index] = optarg;
8669 parallel_device_index++;
8671 case QEMU_OPTION_loadvm:
8674 case QEMU_OPTION_full_screen:
8678 case QEMU_OPTION_no_frame:
8681 case QEMU_OPTION_alt_grab:
8684 case QEMU_OPTION_no_quit:
8688 case QEMU_OPTION_pidfile:
8692 case QEMU_OPTION_win2k_hack:
8693 win2k_install_hack = 1;
8697 case QEMU_OPTION_no_kqemu:
8700 case QEMU_OPTION_kernel_kqemu:
8704 case QEMU_OPTION_usb:
8707 case QEMU_OPTION_usbdevice:
8709 if (usb_devices_index >= MAX_USB_CMDLINE) {
8710 fprintf(stderr, "Too many USB devices\n");
8713 usb_devices[usb_devices_index] = optarg;
8714 usb_devices_index++;
8716 case QEMU_OPTION_smp:
8717 smp_cpus = atoi(optarg);
8718 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8719 fprintf(stderr, "Invalid number of CPUs\n");
8723 case QEMU_OPTION_vnc:
8724 vnc_display = optarg;
8726 case QEMU_OPTION_no_acpi:
8729 case QEMU_OPTION_no_reboot:
8732 case QEMU_OPTION_show_cursor:
8735 case QEMU_OPTION_daemonize:
8738 case QEMU_OPTION_option_rom:
8739 if (nb_option_roms >= MAX_OPTION_ROMS) {
8740 fprintf(stderr, "Too many option ROMs\n");
8743 option_rom[nb_option_roms] = optarg;
8746 case QEMU_OPTION_semihosting:
8747 semihosting_enabled = 1;
8749 case QEMU_OPTION_name:
8753 case QEMU_OPTION_prom_env:
8754 if (nb_prom_envs >= MAX_PROM_ENVS) {
8755 fprintf(stderr, "Too many prom variables\n");
8758 prom_envs[nb_prom_envs] = optarg;
8763 case QEMU_OPTION_old_param:
8767 case QEMU_OPTION_clock:
8768 configure_alarms(optarg);
8770 case QEMU_OPTION_startdate:
8773 time_t rtc_start_date;
8774 if (!strcmp(optarg, "now")) {
8775 rtc_date_offset = -1;
8777 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8785 } else if (sscanf(optarg, "%d-%d-%d",
8788 &tm.tm_mday) == 3) {
8797 rtc_start_date = mktimegm(&tm);
8798 if (rtc_start_date == -1) {
8800 fprintf(stderr, "Invalid date format. Valid format are:\n"
8801 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8804 rtc_date_offset = time(NULL) - rtc_start_date;
8813 if (daemonize && !nographic && vnc_display == NULL) {
8814 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8821 if (pipe(fds) == -1)
8832 len = read(fds[0], &status, 1);
8833 if (len == -1 && (errno == EINTR))
8838 else if (status == 1) {
8839 fprintf(stderr, "Could not acquire pidfile\n");
8857 signal(SIGTSTP, SIG_IGN);
8858 signal(SIGTTOU, SIG_IGN);
8859 signal(SIGTTIN, SIG_IGN);
8863 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8866 write(fds[1], &status, 1);
8868 fprintf(stderr, "Could not acquire pid file\n");
8876 linux_boot = (kernel_filename != NULL);
8877 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8879 /* XXX: this should not be: some embedded targets just have flash */
8880 if (!linux_boot && net_boot == 0 &&
8884 /* boot to floppy or the default cd if no hard disk defined yet */
8885 if (!boot_devices[0]) {
8886 boot_devices = "cad";
8888 setvbuf(stdout, NULL, _IOLBF, 0);
8898 /* init network clients */
8899 if (nb_net_clients == 0) {
8900 /* if no clients, we use a default config */
8901 net_clients[0] = "nic";
8902 net_clients[1] = "user";
8906 for(i = 0;i < nb_net_clients; i++) {
8907 if (net_client_init(net_clients[i]) < 0)
8910 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8911 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8913 if (vlan->nb_guest_devs == 0) {
8914 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8917 if (vlan->nb_host_devs == 0)
8919 "Warning: vlan %d is not connected to host network\n",
8924 /* XXX: this should be moved in the PC machine instantiation code */
8925 if (net_boot != 0) {
8927 for (i = 0; i < nb_nics && i < 4; i++) {
8928 const char *model = nd_table[i].model;
8930 if (net_boot & (1 << i)) {
8933 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8934 if (get_image_size(buf) > 0) {
8935 if (nb_option_roms >= MAX_OPTION_ROMS) {
8936 fprintf(stderr, "Too many option ROMs\n");
8939 option_rom[nb_option_roms] = strdup(buf);
8946 fprintf(stderr, "No valid PXE rom found for network device\n");
8952 /* init the memory */
8953 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8955 phys_ram_base = qemu_vmalloc(phys_ram_size);
8956 if (!phys_ram_base) {
8957 fprintf(stderr, "Could not allocate physical memory\n");
8963 /* we always create the cdrom drive, even if no disk is there */
8965 if (nb_drives_opt < MAX_DRIVES)
8966 drive_add(NULL, CDROM_ALIAS);
8968 /* we always create at least one floppy */
8970 if (nb_drives_opt < MAX_DRIVES)
8971 drive_add(NULL, FD_ALIAS, 0);
8973 /* we always create one sd slot, even if no card is in it */
8975 if (nb_drives_opt < MAX_DRIVES)
8976 drive_add(NULL, SD_ALIAS);
8978 /* open the virtual block devices */
8980 for(i = 0; i < nb_drives_opt; i++)
8981 if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8984 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8985 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8990 memset(&display_state, 0, sizeof(display_state));
8993 fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8996 /* nearly nothing to do */
8997 dumb_display_init(ds);
8998 } else if (vnc_display != NULL) {
8999 vnc_display_init(ds);
9000 if (vnc_display_open(ds, vnc_display) < 0)
9003 #if defined(CONFIG_CURSES)
9005 curses_display_init(ds, full_screen);
9009 #if defined(CONFIG_SDL)
9010 sdl_display_init(ds, full_screen, no_frame);
9011 #elif defined(CONFIG_COCOA)
9012 cocoa_display_init(ds, full_screen);
9014 dumb_display_init(ds);
9018 /* Maintain compatibility with multiple stdio monitors */
9019 if (!strcmp(monitor_device,"stdio")) {
9020 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9021 const char *devname = serial_devices[i];
9022 if (devname && !strcmp(devname,"mon:stdio")) {
9023 monitor_device = NULL;
9025 } else if (devname && !strcmp(devname,"stdio")) {
9026 monitor_device = NULL;
9027 serial_devices[i] = "mon:stdio";
9032 if (monitor_device) {
9033 monitor_hd = qemu_chr_open(monitor_device);
9035 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9038 monitor_init(monitor_hd, !nographic);
9041 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9042 const char *devname = serial_devices[i];
9043 if (devname && strcmp(devname, "none")) {
9044 serial_hds[i] = qemu_chr_open(devname);
9045 if (!serial_hds[i]) {
9046 fprintf(stderr, "qemu: could not open serial device '%s'\n",
9050 if (strstart(devname, "vc", 0))
9051 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9055 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9056 const char *devname = parallel_devices[i];
9057 if (devname && strcmp(devname, "none")) {
9058 parallel_hds[i] = qemu_chr_open(devname);
9059 if (!parallel_hds[i]) {
9060 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9064 if (strstart(devname, "vc", 0))
9065 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9069 machine->init(ram_size, vga_ram_size, boot_devices, ds,
9070 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9072 /* init USB devices */
9074 for(i = 0; i < usb_devices_index; i++) {
9075 if (usb_device_add(usb_devices[i]) < 0) {
9076 fprintf(stderr, "Warning: could not add USB device %s\n",
9082 if (display_state.dpy_refresh) {
9083 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9084 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9087 #ifdef CONFIG_GDBSTUB
9089 /* XXX: use standard host:port notation and modify options
9091 if (gdbserver_start(gdbstub_port) < 0) {
9092 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9103 /* XXX: simplify init */
9116 len = write(fds[1], &status, 1);
9117 if (len == -1 && (errno == EINTR))
9123 TFR(fd = open("/dev/null", O_RDWR));
9137 #if !defined(_WIN32)
9138 /* close network clients */
9139 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9140 VLANClientState *vc;
9142 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9143 if (vc->fd_read == tap_receive) {
9145 TAPState *s = vc->opaque;
9147 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9149 launch_script(s->down_script, ifname, s->fd);