4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "hw/boards.h"
27 #include "hw/pcmcia.h"
30 #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>
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 char phys_ram_file[1024];
164 void *ioport_opaque[MAX_IOPORTS];
165 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
166 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
167 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
168 to store the VM snapshots */
169 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
170 BlockDriverState *pflash_table[MAX_PFLASH];
171 BlockDriverState *sd_bdrv;
172 BlockDriverState *mtd_bdrv;
173 /* point to the block driver where the snapshots are managed */
174 BlockDriverState *bs_snapshots;
176 static DisplayState display_state;
178 const char* keyboard_layout = NULL;
179 int64_t ticks_per_sec;
181 int pit_min_timer_count = 0;
183 NICInfo nd_table[MAX_NICS];
186 int rtc_start_date = -1; /* -1 means now */
187 int cirrus_vga_enabled = 1;
188 int vmsvga_enabled = 0;
190 int graphic_width = 1024;
191 int graphic_height = 768;
192 int graphic_depth = 8;
194 int graphic_width = 800;
195 int graphic_height = 600;
196 int graphic_depth = 15;
201 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
202 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
204 int win2k_install_hack = 0;
207 static VLANState *first_vlan;
209 const char *vnc_display;
210 #if defined(TARGET_SPARC)
212 #elif defined(TARGET_I386)
217 int acpi_enabled = 1;
221 int graphic_rotate = 0;
223 const char *option_rom[MAX_OPTION_ROMS];
225 int semihosting_enabled = 0;
230 const char *qemu_name;
233 unsigned int nb_prom_envs = 0;
234 const char *prom_envs[MAX_PROM_ENVS];
237 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
239 /***********************************************************/
240 /* x86 ISA bus support */
242 target_phys_addr_t isa_mem_base = 0;
245 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
247 #ifdef DEBUG_UNUSED_IOPORT
248 fprintf(stderr, "unused inb: port=0x%04x\n", address);
253 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
255 #ifdef DEBUG_UNUSED_IOPORT
256 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
260 /* default is to make two byte accesses */
261 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
264 data = ioport_read_table[0][address](ioport_opaque[address], address);
265 address = (address + 1) & (MAX_IOPORTS - 1);
266 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
270 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
272 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
273 address = (address + 1) & (MAX_IOPORTS - 1);
274 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
277 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
279 #ifdef DEBUG_UNUSED_IOPORT
280 fprintf(stderr, "unused inl: port=0x%04x\n", address);
285 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
287 #ifdef DEBUG_UNUSED_IOPORT
288 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
292 static void init_ioports(void)
296 for(i = 0; i < MAX_IOPORTS; i++) {
297 ioport_read_table[0][i] = default_ioport_readb;
298 ioport_write_table[0][i] = default_ioport_writeb;
299 ioport_read_table[1][i] = default_ioport_readw;
300 ioport_write_table[1][i] = default_ioport_writew;
301 ioport_read_table[2][i] = default_ioport_readl;
302 ioport_write_table[2][i] = default_ioport_writel;
306 /* size is the word size in byte */
307 int register_ioport_read(int start, int length, int size,
308 IOPortReadFunc *func, void *opaque)
314 } else if (size == 2) {
316 } else if (size == 4) {
319 hw_error("register_ioport_read: invalid size");
322 for(i = start; i < start + length; i += size) {
323 ioport_read_table[bsize][i] = func;
324 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
325 hw_error("register_ioport_read: invalid opaque");
326 ioport_opaque[i] = opaque;
331 /* size is the word size in byte */
332 int register_ioport_write(int start, int length, int size,
333 IOPortWriteFunc *func, void *opaque)
339 } else if (size == 2) {
341 } else if (size == 4) {
344 hw_error("register_ioport_write: invalid size");
347 for(i = start; i < start + length; i += size) {
348 ioport_write_table[bsize][i] = func;
349 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
350 hw_error("register_ioport_write: invalid opaque");
351 ioport_opaque[i] = opaque;
356 void isa_unassign_ioport(int start, int length)
360 for(i = start; i < start + length; i++) {
361 ioport_read_table[0][i] = default_ioport_readb;
362 ioport_read_table[1][i] = default_ioport_readw;
363 ioport_read_table[2][i] = default_ioport_readl;
365 ioport_write_table[0][i] = default_ioport_writeb;
366 ioport_write_table[1][i] = default_ioport_writew;
367 ioport_write_table[2][i] = default_ioport_writel;
371 /***********************************************************/
373 void cpu_outb(CPUState *env, int addr, int val)
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "outb: %04x %02x\n", addr, val);
379 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
382 env->last_io_time = cpu_get_time_fast();
386 void cpu_outw(CPUState *env, int addr, int val)
389 if (loglevel & CPU_LOG_IOPORT)
390 fprintf(logfile, "outw: %04x %04x\n", addr, val);
392 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
395 env->last_io_time = cpu_get_time_fast();
399 void cpu_outl(CPUState *env, int addr, int val)
402 if (loglevel & CPU_LOG_IOPORT)
403 fprintf(logfile, "outl: %04x %08x\n", addr, val);
405 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
408 env->last_io_time = cpu_get_time_fast();
412 int cpu_inb(CPUState *env, int addr)
415 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
417 if (loglevel & CPU_LOG_IOPORT)
418 fprintf(logfile, "inb : %04x %02x\n", addr, val);
422 env->last_io_time = cpu_get_time_fast();
427 int cpu_inw(CPUState *env, int addr)
430 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
432 if (loglevel & CPU_LOG_IOPORT)
433 fprintf(logfile, "inw : %04x %04x\n", addr, val);
437 env->last_io_time = cpu_get_time_fast();
442 int cpu_inl(CPUState *env, int addr)
445 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
447 if (loglevel & CPU_LOG_IOPORT)
448 fprintf(logfile, "inl : %04x %08x\n", addr, val);
452 env->last_io_time = cpu_get_time_fast();
457 /***********************************************************/
458 void hw_error(const char *fmt, ...)
464 fprintf(stderr, "qemu: hardware error: ");
465 vfprintf(stderr, fmt, ap);
466 fprintf(stderr, "\n");
467 for(env = first_cpu; env != NULL; env = env->next_cpu) {
468 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
470 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
472 cpu_dump_state(env, stderr, fprintf, 0);
479 /***********************************************************/
482 static QEMUPutKBDEvent *qemu_put_kbd_event;
483 static void *qemu_put_kbd_event_opaque;
484 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
485 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
487 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
489 qemu_put_kbd_event_opaque = opaque;
490 qemu_put_kbd_event = func;
493 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
494 void *opaque, int absolute,
497 QEMUPutMouseEntry *s, *cursor;
499 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
503 s->qemu_put_mouse_event = func;
504 s->qemu_put_mouse_event_opaque = opaque;
505 s->qemu_put_mouse_event_absolute = absolute;
506 s->qemu_put_mouse_event_name = qemu_strdup(name);
509 if (!qemu_put_mouse_event_head) {
510 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
514 cursor = qemu_put_mouse_event_head;
515 while (cursor->next != NULL)
516 cursor = cursor->next;
519 qemu_put_mouse_event_current = s;
524 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
526 QEMUPutMouseEntry *prev = NULL, *cursor;
528 if (!qemu_put_mouse_event_head || entry == NULL)
531 cursor = qemu_put_mouse_event_head;
532 while (cursor != NULL && cursor != entry) {
534 cursor = cursor->next;
537 if (cursor == NULL) // does not exist or list empty
539 else if (prev == NULL) { // entry is head
540 qemu_put_mouse_event_head = cursor->next;
541 if (qemu_put_mouse_event_current == entry)
542 qemu_put_mouse_event_current = cursor->next;
543 qemu_free(entry->qemu_put_mouse_event_name);
548 prev->next = entry->next;
550 if (qemu_put_mouse_event_current == entry)
551 qemu_put_mouse_event_current = prev;
553 qemu_free(entry->qemu_put_mouse_event_name);
557 void kbd_put_keycode(int keycode)
559 if (qemu_put_kbd_event) {
560 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
564 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
566 QEMUPutMouseEvent *mouse_event;
567 void *mouse_event_opaque;
570 if (!qemu_put_mouse_event_current) {
575 qemu_put_mouse_event_current->qemu_put_mouse_event;
577 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
580 if (graphic_rotate) {
581 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
584 width = graphic_width;
585 mouse_event(mouse_event_opaque,
586 width - dy, dx, dz, buttons_state);
588 mouse_event(mouse_event_opaque,
589 dx, dy, dz, buttons_state);
593 int kbd_mouse_is_absolute(void)
595 if (!qemu_put_mouse_event_current)
598 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
601 void do_info_mice(void)
603 QEMUPutMouseEntry *cursor;
606 if (!qemu_put_mouse_event_head) {
607 term_printf("No mouse devices connected\n");
611 term_printf("Mouse devices available:\n");
612 cursor = qemu_put_mouse_event_head;
613 while (cursor != NULL) {
614 term_printf("%c Mouse #%d: %s\n",
615 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
616 index, cursor->qemu_put_mouse_event_name);
618 cursor = cursor->next;
622 void do_mouse_set(int index)
624 QEMUPutMouseEntry *cursor;
627 if (!qemu_put_mouse_event_head) {
628 term_printf("No mouse devices connected\n");
632 cursor = qemu_put_mouse_event_head;
633 while (cursor != NULL && index != i) {
635 cursor = cursor->next;
639 qemu_put_mouse_event_current = cursor;
641 term_printf("Mouse at given index not found\n");
644 /* compute with 96 bit intermediate result: (a*b)/c */
645 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
650 #ifdef WORDS_BIGENDIAN
660 rl = (uint64_t)u.l.low * (uint64_t)b;
661 rh = (uint64_t)u.l.high * (uint64_t)b;
664 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
668 /***********************************************************/
669 /* real time host monotonic timer */
671 #define QEMU_TIMER_BASE 1000000000LL
675 static int64_t clock_freq;
677 static void init_get_clock(void)
681 ret = QueryPerformanceFrequency(&freq);
683 fprintf(stderr, "Could not calibrate ticks\n");
686 clock_freq = freq.QuadPart;
689 static int64_t get_clock(void)
692 QueryPerformanceCounter(&ti);
693 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
698 static int use_rt_clock;
700 static void init_get_clock(void)
703 #if defined(__linux__)
706 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
713 static int64_t get_clock(void)
715 #if defined(__linux__)
718 clock_gettime(CLOCK_MONOTONIC, &ts);
719 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
723 /* XXX: using gettimeofday leads to problems if the date
724 changes, so it should be avoided. */
726 gettimeofday(&tv, NULL);
727 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
733 /***********************************************************/
734 /* guest cycle counter */
736 static int64_t cpu_ticks_prev;
737 static int64_t cpu_ticks_offset;
738 static int64_t cpu_clock_offset;
739 static int cpu_ticks_enabled;
741 /* return the host CPU cycle counter and handle stop/restart */
742 int64_t cpu_get_ticks(void)
744 if (!cpu_ticks_enabled) {
745 return cpu_ticks_offset;
748 ticks = cpu_get_real_ticks();
749 if (cpu_ticks_prev > ticks) {
750 /* Note: non increasing ticks may happen if the host uses
752 cpu_ticks_offset += cpu_ticks_prev - ticks;
754 cpu_ticks_prev = ticks;
755 return ticks + cpu_ticks_offset;
759 /* return the host CPU monotonic timer and handle stop/restart */
760 static int64_t cpu_get_clock(void)
763 if (!cpu_ticks_enabled) {
764 return cpu_clock_offset;
767 return ti + cpu_clock_offset;
771 /* enable cpu_get_ticks() */
772 void cpu_enable_ticks(void)
774 if (!cpu_ticks_enabled) {
775 cpu_ticks_offset -= cpu_get_real_ticks();
776 cpu_clock_offset -= get_clock();
777 cpu_ticks_enabled = 1;
781 /* disable cpu_get_ticks() : the clock is stopped. You must not call
782 cpu_get_ticks() after that. */
783 void cpu_disable_ticks(void)
785 if (cpu_ticks_enabled) {
786 cpu_ticks_offset = cpu_get_ticks();
787 cpu_clock_offset = cpu_get_clock();
788 cpu_ticks_enabled = 0;
792 /***********************************************************/
795 #define QEMU_TIMER_REALTIME 0
796 #define QEMU_TIMER_VIRTUAL 1
800 /* XXX: add frequency */
808 struct QEMUTimer *next;
811 struct qemu_alarm_timer {
815 int (*start)(struct qemu_alarm_timer *t);
816 void (*stop)(struct qemu_alarm_timer *t);
817 void (*rearm)(struct qemu_alarm_timer *t);
821 #define ALARM_FLAG_DYNTICKS 0x1
823 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
825 return t->flags & ALARM_FLAG_DYNTICKS;
828 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
830 if (!alarm_has_dynticks(t))
836 /* TODO: MIN_TIMER_REARM_US should be optimized */
837 #define MIN_TIMER_REARM_US 250
839 static struct qemu_alarm_timer *alarm_timer;
843 struct qemu_alarm_win32 {
847 } alarm_win32_data = {0, NULL, -1};
849 static int win32_start_timer(struct qemu_alarm_timer *t);
850 static void win32_stop_timer(struct qemu_alarm_timer *t);
851 static void win32_rearm_timer(struct qemu_alarm_timer *t);
855 static int unix_start_timer(struct qemu_alarm_timer *t);
856 static void unix_stop_timer(struct qemu_alarm_timer *t);
860 static int dynticks_start_timer(struct qemu_alarm_timer *t);
861 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
862 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
864 static int hpet_start_timer(struct qemu_alarm_timer *t);
865 static void hpet_stop_timer(struct qemu_alarm_timer *t);
867 static int rtc_start_timer(struct qemu_alarm_timer *t);
868 static void rtc_stop_timer(struct qemu_alarm_timer *t);
870 #endif /* __linux__ */
874 static struct qemu_alarm_timer alarm_timers[] = {
877 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
878 dynticks_stop_timer, dynticks_rearm_timer, NULL},
879 /* HPET - if available - is preferred */
880 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
881 /* ...otherwise try RTC */
882 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
884 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
886 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
887 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
888 {"win32", 0, win32_start_timer,
889 win32_stop_timer, NULL, &alarm_win32_data},
894 static void show_available_alarms()
898 printf("Available alarm timers, in order of precedence:\n");
899 for (i = 0; alarm_timers[i].name; i++)
900 printf("%s\n", alarm_timers[i].name);
903 static void configure_alarms(char const *opt)
907 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
911 if (!strcmp(opt, "help")) {
912 show_available_alarms();
918 /* Reorder the array */
919 name = strtok(arg, ",");
921 struct qemu_alarm_timer tmp;
923 for (i = 0; i < count && alarm_timers[i].name; i++) {
924 if (!strcmp(alarm_timers[i].name, name))
929 fprintf(stderr, "Unknown clock %s\n", name);
938 tmp = alarm_timers[i];
939 alarm_timers[i] = alarm_timers[cur];
940 alarm_timers[cur] = tmp;
944 name = strtok(NULL, ",");
950 /* Disable remaining timers */
951 for (i = cur; i < count; i++)
952 alarm_timers[i].name = NULL;
956 show_available_alarms();
962 static QEMUTimer *active_timers[2];
964 static QEMUClock *qemu_new_clock(int type)
967 clock = qemu_mallocz(sizeof(QEMUClock));
974 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
978 ts = qemu_mallocz(sizeof(QEMUTimer));
985 void qemu_free_timer(QEMUTimer *ts)
990 /* stop a timer, but do not dealloc it */
991 void qemu_del_timer(QEMUTimer *ts)
995 /* NOTE: this code must be signal safe because
996 qemu_timer_expired() can be called from a signal. */
997 pt = &active_timers[ts->clock->type];
1010 /* modify the current timer so that it will be fired when current_time
1011 >= expire_time. The corresponding callback will be called. */
1012 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1018 /* add the timer in the sorted list */
1019 /* NOTE: this code must be signal safe because
1020 qemu_timer_expired() can be called from a signal. */
1021 pt = &active_timers[ts->clock->type];
1026 if (t->expire_time > expire_time)
1030 ts->expire_time = expire_time;
1035 int qemu_timer_pending(QEMUTimer *ts)
1038 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1045 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1049 return (timer_head->expire_time <= current_time);
1052 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1058 if (!ts || ts->expire_time > current_time)
1060 /* remove timer from the list before calling the callback */
1061 *ptimer_head = ts->next;
1064 /* run the callback (the timer list can be modified) */
1067 qemu_rearm_alarm_timer(alarm_timer);
1070 int64_t qemu_get_clock(QEMUClock *clock)
1072 switch(clock->type) {
1073 case QEMU_TIMER_REALTIME:
1074 return get_clock() / 1000000;
1076 case QEMU_TIMER_VIRTUAL:
1077 return cpu_get_clock();
1081 static void init_timers(void)
1084 ticks_per_sec = QEMU_TIMER_BASE;
1085 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1086 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1090 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1092 uint64_t expire_time;
1094 if (qemu_timer_pending(ts)) {
1095 expire_time = ts->expire_time;
1099 qemu_put_be64(f, expire_time);
1102 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1104 uint64_t expire_time;
1106 expire_time = qemu_get_be64(f);
1107 if (expire_time != -1) {
1108 qemu_mod_timer(ts, expire_time);
1114 static void timer_save(QEMUFile *f, void *opaque)
1116 if (cpu_ticks_enabled) {
1117 hw_error("cannot save state if virtual timers are running");
1119 qemu_put_be64s(f, &cpu_ticks_offset);
1120 qemu_put_be64s(f, &ticks_per_sec);
1121 qemu_put_be64s(f, &cpu_clock_offset);
1124 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1126 if (version_id != 1 && version_id != 2)
1128 if (cpu_ticks_enabled) {
1131 qemu_get_be64s(f, &cpu_ticks_offset);
1132 qemu_get_be64s(f, &ticks_per_sec);
1133 if (version_id == 2) {
1134 qemu_get_be64s(f, &cpu_clock_offset);
1140 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1141 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1143 static void host_alarm_handler(int host_signum)
1147 #define DISP_FREQ 1000
1149 static int64_t delta_min = INT64_MAX;
1150 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1152 ti = qemu_get_clock(vm_clock);
1153 if (last_clock != 0) {
1154 delta = ti - last_clock;
1155 if (delta < delta_min)
1157 if (delta > delta_max)
1160 if (++count == DISP_FREQ) {
1161 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1162 muldiv64(delta_min, 1000000, ticks_per_sec),
1163 muldiv64(delta_max, 1000000, ticks_per_sec),
1164 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1165 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1167 delta_min = INT64_MAX;
1175 if (alarm_has_dynticks(alarm_timer) ||
1176 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1177 qemu_get_clock(vm_clock)) ||
1178 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1179 qemu_get_clock(rt_clock))) {
1181 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1182 SetEvent(data->host_alarm);
1184 CPUState *env = cpu_single_env;
1186 /* stop the currently executing cpu because a timer occured */
1187 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1189 if (env->kqemu_enabled) {
1190 kqemu_cpu_interrupt(env);
1197 static uint64_t qemu_next_deadline(void)
1199 int64_t nearest_delta_us = INT64_MAX;
1202 if (active_timers[QEMU_TIMER_REALTIME])
1203 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1204 qemu_get_clock(rt_clock))*1000;
1206 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1208 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1209 qemu_get_clock(vm_clock)+999)/1000;
1210 if (vmdelta_us < nearest_delta_us)
1211 nearest_delta_us = vmdelta_us;
1214 /* Avoid arming the timer to negative, zero, or too low values */
1215 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1216 nearest_delta_us = MIN_TIMER_REARM_US;
1218 return nearest_delta_us;
1223 #if defined(__linux__)
1225 #define RTC_FREQ 1024
1227 static void enable_sigio_timer(int fd)
1229 struct sigaction act;
1232 sigfillset(&act.sa_mask);
1234 act.sa_handler = host_alarm_handler;
1236 sigaction(SIGIO, &act, NULL);
1237 fcntl(fd, F_SETFL, O_ASYNC);
1238 fcntl(fd, F_SETOWN, getpid());
1241 static int hpet_start_timer(struct qemu_alarm_timer *t)
1243 struct hpet_info info;
1246 fd = open("/dev/hpet", O_RDONLY);
1251 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1253 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1254 "error, but for better emulation accuracy type:\n"
1255 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1259 /* Check capabilities */
1260 r = ioctl(fd, HPET_INFO, &info);
1264 /* Enable periodic mode */
1265 r = ioctl(fd, HPET_EPI, 0);
1266 if (info.hi_flags && (r < 0))
1269 /* Enable interrupt */
1270 r = ioctl(fd, HPET_IE_ON, 0);
1274 enable_sigio_timer(fd);
1275 t->priv = (void *)(long)fd;
1283 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1285 int fd = (long)t->priv;
1290 static int rtc_start_timer(struct qemu_alarm_timer *t)
1294 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1297 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1298 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1299 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1300 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1303 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1309 enable_sigio_timer(rtc_fd);
1311 t->priv = (void *)(long)rtc_fd;
1316 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1318 int rtc_fd = (long)t->priv;
1323 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1327 struct sigaction act;
1329 sigfillset(&act.sa_mask);
1331 act.sa_handler = host_alarm_handler;
1333 sigaction(SIGALRM, &act, NULL);
1335 ev.sigev_value.sival_int = 0;
1336 ev.sigev_notify = SIGEV_SIGNAL;
1337 ev.sigev_signo = SIGALRM;
1339 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1340 perror("timer_create");
1342 /* disable dynticks */
1343 fprintf(stderr, "Dynamic Ticks disabled\n");
1348 t->priv = (void *)host_timer;
1353 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1355 timer_t host_timer = (timer_t)t->priv;
1357 timer_delete(host_timer);
1360 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1362 timer_t host_timer = (timer_t)t->priv;
1363 struct itimerspec timeout;
1364 int64_t nearest_delta_us = INT64_MAX;
1367 if (!active_timers[QEMU_TIMER_REALTIME] &&
1368 !active_timers[QEMU_TIMER_VIRTUAL])
1371 nearest_delta_us = qemu_next_deadline();
1373 /* check whether a timer is already running */
1374 if (timer_gettime(host_timer, &timeout)) {
1376 fprintf(stderr, "Internal timer error: aborting\n");
1379 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1380 if (current_us && current_us <= nearest_delta_us)
1383 timeout.it_interval.tv_sec = 0;
1384 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1385 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1386 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1387 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1389 fprintf(stderr, "Internal timer error: aborting\n");
1394 #endif /* defined(__linux__) */
1396 static int unix_start_timer(struct qemu_alarm_timer *t)
1398 struct sigaction act;
1399 struct itimerval itv;
1403 sigfillset(&act.sa_mask);
1405 act.sa_handler = host_alarm_handler;
1407 sigaction(SIGALRM, &act, NULL);
1409 itv.it_interval.tv_sec = 0;
1410 /* for i386 kernel 2.6 to get 1 ms */
1411 itv.it_interval.tv_usec = 999;
1412 itv.it_value.tv_sec = 0;
1413 itv.it_value.tv_usec = 10 * 1000;
1415 err = setitimer(ITIMER_REAL, &itv, NULL);
1422 static void unix_stop_timer(struct qemu_alarm_timer *t)
1424 struct itimerval itv;
1426 memset(&itv, 0, sizeof(itv));
1427 setitimer(ITIMER_REAL, &itv, NULL);
1430 #endif /* !defined(_WIN32) */
1434 static int win32_start_timer(struct qemu_alarm_timer *t)
1437 struct qemu_alarm_win32 *data = t->priv;
1440 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1441 if (!data->host_alarm) {
1442 perror("Failed CreateEvent");
1446 memset(&tc, 0, sizeof(tc));
1447 timeGetDevCaps(&tc, sizeof(tc));
1449 if (data->period < tc.wPeriodMin)
1450 data->period = tc.wPeriodMin;
1452 timeBeginPeriod(data->period);
1454 flags = TIME_CALLBACK_FUNCTION;
1455 if (alarm_has_dynticks(t))
1456 flags |= TIME_ONESHOT;
1458 flags |= TIME_PERIODIC;
1460 data->timerId = timeSetEvent(1, // interval (ms)
1461 data->period, // resolution
1462 host_alarm_handler, // function
1463 (DWORD)t, // parameter
1466 if (!data->timerId) {
1467 perror("Failed to initialize win32 alarm timer");
1469 timeEndPeriod(data->period);
1470 CloseHandle(data->host_alarm);
1474 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1479 static void win32_stop_timer(struct qemu_alarm_timer *t)
1481 struct qemu_alarm_win32 *data = t->priv;
1483 timeKillEvent(data->timerId);
1484 timeEndPeriod(data->period);
1486 CloseHandle(data->host_alarm);
1489 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1491 struct qemu_alarm_win32 *data = t->priv;
1492 uint64_t nearest_delta_us;
1494 if (!active_timers[QEMU_TIMER_REALTIME] &&
1495 !active_timers[QEMU_TIMER_VIRTUAL])
1498 nearest_delta_us = qemu_next_deadline();
1499 nearest_delta_us /= 1000;
1501 timeKillEvent(data->timerId);
1503 data->timerId = timeSetEvent(1,
1507 TIME_ONESHOT | TIME_PERIODIC);
1509 if (!data->timerId) {
1510 perror("Failed to re-arm win32 alarm timer");
1512 timeEndPeriod(data->period);
1513 CloseHandle(data->host_alarm);
1520 static void init_timer_alarm(void)
1522 struct qemu_alarm_timer *t;
1525 for (i = 0; alarm_timers[i].name; i++) {
1526 t = &alarm_timers[i];
1534 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1535 fprintf(stderr, "Terminating\n");
1542 static void quit_timers(void)
1544 alarm_timer->stop(alarm_timer);
1548 /***********************************************************/
1549 /* character device */
1551 static void qemu_chr_event(CharDriverState *s, int event)
1555 s->chr_event(s->handler_opaque, event);
1558 static void qemu_chr_reset_bh(void *opaque)
1560 CharDriverState *s = opaque;
1561 qemu_chr_event(s, CHR_EVENT_RESET);
1562 qemu_bh_delete(s->bh);
1566 void qemu_chr_reset(CharDriverState *s)
1568 if (s->bh == NULL) {
1569 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1570 qemu_bh_schedule(s->bh);
1574 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1576 return s->chr_write(s, buf, len);
1579 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1583 return s->chr_ioctl(s, cmd, arg);
1586 int qemu_chr_can_read(CharDriverState *s)
1588 if (!s->chr_can_read)
1590 return s->chr_can_read(s->handler_opaque);
1593 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1595 s->chr_read(s->handler_opaque, buf, len);
1599 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1604 vsnprintf(buf, sizeof(buf), fmt, ap);
1605 qemu_chr_write(s, buf, strlen(buf));
1609 void qemu_chr_send_event(CharDriverState *s, int event)
1611 if (s->chr_send_event)
1612 s->chr_send_event(s, event);
1615 void qemu_chr_add_handlers(CharDriverState *s,
1616 IOCanRWHandler *fd_can_read,
1617 IOReadHandler *fd_read,
1618 IOEventHandler *fd_event,
1621 s->chr_can_read = fd_can_read;
1622 s->chr_read = fd_read;
1623 s->chr_event = fd_event;
1624 s->handler_opaque = opaque;
1625 if (s->chr_update_read_handler)
1626 s->chr_update_read_handler(s);
1629 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1634 static CharDriverState *qemu_chr_open_null(void)
1636 CharDriverState *chr;
1638 chr = qemu_mallocz(sizeof(CharDriverState));
1641 chr->chr_write = null_chr_write;
1645 /* MUX driver for serial I/O splitting */
1646 static int term_timestamps;
1647 static int64_t term_timestamps_start;
1650 IOCanRWHandler *chr_can_read[MAX_MUX];
1651 IOReadHandler *chr_read[MAX_MUX];
1652 IOEventHandler *chr_event[MAX_MUX];
1653 void *ext_opaque[MAX_MUX];
1654 CharDriverState *drv;
1656 int term_got_escape;
1661 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1663 MuxDriver *d = chr->opaque;
1665 if (!term_timestamps) {
1666 ret = d->drv->chr_write(d->drv, buf, len);
1671 for(i = 0; i < len; i++) {
1672 ret += d->drv->chr_write(d->drv, buf+i, 1);
1673 if (buf[i] == '\n') {
1679 if (term_timestamps_start == -1)
1680 term_timestamps_start = ti;
1681 ti -= term_timestamps_start;
1682 secs = ti / 1000000000;
1683 snprintf(buf1, sizeof(buf1),
1684 "[%02d:%02d:%02d.%03d] ",
1688 (int)((ti / 1000000) % 1000));
1689 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1696 static char *mux_help[] = {
1697 "% h print this help\n\r",
1698 "% x exit emulator\n\r",
1699 "% s save disk data back to file (if -snapshot)\n\r",
1700 "% t toggle console timestamps\n\r"
1701 "% b send break (magic sysrq)\n\r",
1702 "% c switch between console and monitor\n\r",
1707 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1708 static void mux_print_help(CharDriverState *chr)
1711 char ebuf[15] = "Escape-Char";
1712 char cbuf[50] = "\n\r";
1714 if (term_escape_char > 0 && term_escape_char < 26) {
1715 sprintf(cbuf,"\n\r");
1716 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1718 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1720 chr->chr_write(chr, cbuf, strlen(cbuf));
1721 for (i = 0; mux_help[i] != NULL; i++) {
1722 for (j=0; mux_help[i][j] != '\0'; j++) {
1723 if (mux_help[i][j] == '%')
1724 chr->chr_write(chr, ebuf, strlen(ebuf));
1726 chr->chr_write(chr, &mux_help[i][j], 1);
1731 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1733 if (d->term_got_escape) {
1734 d->term_got_escape = 0;
1735 if (ch == term_escape_char)
1740 mux_print_help(chr);
1744 char *term = "QEMU: Terminated\n\r";
1745 chr->chr_write(chr,term,strlen(term));
1752 for (i = 0; i < MAX_DISKS; i++) {
1754 bdrv_commit(bs_table[i]);
1757 bdrv_commit(mtd_bdrv);
1761 qemu_chr_event(chr, CHR_EVENT_BREAK);
1764 /* Switch to the next registered device */
1766 if (chr->focus >= d->mux_cnt)
1770 term_timestamps = !term_timestamps;
1771 term_timestamps_start = -1;
1774 } else if (ch == term_escape_char) {
1775 d->term_got_escape = 1;
1783 static int mux_chr_can_read(void *opaque)
1785 CharDriverState *chr = opaque;
1786 MuxDriver *d = chr->opaque;
1787 if (d->chr_can_read[chr->focus])
1788 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1792 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1794 CharDriverState *chr = opaque;
1795 MuxDriver *d = chr->opaque;
1797 for(i = 0; i < size; i++)
1798 if (mux_proc_byte(chr, d, buf[i]))
1799 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1802 static void mux_chr_event(void *opaque, int event)
1804 CharDriverState *chr = opaque;
1805 MuxDriver *d = chr->opaque;
1808 /* Send the event to all registered listeners */
1809 for (i = 0; i < d->mux_cnt; i++)
1810 if (d->chr_event[i])
1811 d->chr_event[i](d->ext_opaque[i], event);
1814 static void mux_chr_update_read_handler(CharDriverState *chr)
1816 MuxDriver *d = chr->opaque;
1818 if (d->mux_cnt >= MAX_MUX) {
1819 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1822 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1823 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1824 d->chr_read[d->mux_cnt] = chr->chr_read;
1825 d->chr_event[d->mux_cnt] = chr->chr_event;
1826 /* Fix up the real driver with mux routines */
1827 if (d->mux_cnt == 0) {
1828 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1829 mux_chr_event, chr);
1831 chr->focus = d->mux_cnt;
1835 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1837 CharDriverState *chr;
1840 chr = qemu_mallocz(sizeof(CharDriverState));
1843 d = qemu_mallocz(sizeof(MuxDriver));
1852 chr->chr_write = mux_chr_write;
1853 chr->chr_update_read_handler = mux_chr_update_read_handler;
1860 static void socket_cleanup(void)
1865 static int socket_init(void)
1870 ret = WSAStartup(MAKEWORD(2,2), &Data);
1872 err = WSAGetLastError();
1873 fprintf(stderr, "WSAStartup: %d\n", err);
1876 atexit(socket_cleanup);
1880 static int send_all(int fd, const uint8_t *buf, int len1)
1886 ret = send(fd, buf, len, 0);
1889 errno = WSAGetLastError();
1890 if (errno != WSAEWOULDBLOCK) {
1893 } else if (ret == 0) {
1903 void socket_set_nonblock(int fd)
1905 unsigned long opt = 1;
1906 ioctlsocket(fd, FIONBIO, &opt);
1911 static int unix_write(int fd, const uint8_t *buf, int len1)
1917 ret = write(fd, buf, len);
1919 if (errno != EINTR && errno != EAGAIN)
1921 } else if (ret == 0) {
1931 static inline int send_all(int fd, const uint8_t *buf, int len1)
1933 return unix_write(fd, buf, len1);
1936 void socket_set_nonblock(int fd)
1938 fcntl(fd, F_SETFL, O_NONBLOCK);
1940 #endif /* !_WIN32 */
1949 #define STDIO_MAX_CLIENTS 1
1950 static int stdio_nb_clients = 0;
1952 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1954 FDCharDriver *s = chr->opaque;
1955 return unix_write(s->fd_out, buf, len);
1958 static int fd_chr_read_poll(void *opaque)
1960 CharDriverState *chr = opaque;
1961 FDCharDriver *s = chr->opaque;
1963 s->max_size = qemu_chr_can_read(chr);
1967 static void fd_chr_read(void *opaque)
1969 CharDriverState *chr = opaque;
1970 FDCharDriver *s = chr->opaque;
1975 if (len > s->max_size)
1979 size = read(s->fd_in, buf, len);
1981 /* FD has been closed. Remove it from the active list. */
1982 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1986 qemu_chr_read(chr, buf, size);
1990 static void fd_chr_update_read_handler(CharDriverState *chr)
1992 FDCharDriver *s = chr->opaque;
1994 if (s->fd_in >= 0) {
1995 if (nographic && s->fd_in == 0) {
1997 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1998 fd_chr_read, NULL, chr);
2003 /* open a character device to a unix fd */
2004 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2006 CharDriverState *chr;
2009 chr = qemu_mallocz(sizeof(CharDriverState));
2012 s = qemu_mallocz(sizeof(FDCharDriver));
2020 chr->chr_write = fd_chr_write;
2021 chr->chr_update_read_handler = fd_chr_update_read_handler;
2023 qemu_chr_reset(chr);
2028 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2032 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2035 return qemu_chr_open_fd(-1, fd_out);
2038 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2041 char filename_in[256], filename_out[256];
2043 snprintf(filename_in, 256, "%s.in", filename);
2044 snprintf(filename_out, 256, "%s.out", filename);
2045 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2046 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2047 if (fd_in < 0 || fd_out < 0) {
2052 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2056 return qemu_chr_open_fd(fd_in, fd_out);
2060 /* for STDIO, we handle the case where several clients use it
2063 #define TERM_FIFO_MAX_SIZE 1
2065 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2066 static int term_fifo_size;
2068 static int stdio_read_poll(void *opaque)
2070 CharDriverState *chr = opaque;
2072 /* try to flush the queue if needed */
2073 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2074 qemu_chr_read(chr, term_fifo, 1);
2077 /* see if we can absorb more chars */
2078 if (term_fifo_size == 0)
2084 static void stdio_read(void *opaque)
2088 CharDriverState *chr = opaque;
2090 size = read(0, buf, 1);
2092 /* stdin has been closed. Remove it from the active list. */
2093 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2097 if (qemu_chr_can_read(chr) > 0) {
2098 qemu_chr_read(chr, buf, 1);
2099 } else if (term_fifo_size == 0) {
2100 term_fifo[term_fifo_size++] = buf[0];
2105 /* init terminal so that we can grab keys */
2106 static struct termios oldtty;
2107 static int old_fd0_flags;
2109 static void term_exit(void)
2111 tcsetattr (0, TCSANOW, &oldtty);
2112 fcntl(0, F_SETFL, old_fd0_flags);
2115 static void term_init(void)
2119 tcgetattr (0, &tty);
2121 old_fd0_flags = fcntl(0, F_GETFL);
2123 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2124 |INLCR|IGNCR|ICRNL|IXON);
2125 tty.c_oflag |= OPOST;
2126 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2127 /* if graphical mode, we allow Ctrl-C handling */
2129 tty.c_lflag &= ~ISIG;
2130 tty.c_cflag &= ~(CSIZE|PARENB);
2133 tty.c_cc[VTIME] = 0;
2135 tcsetattr (0, TCSANOW, &tty);
2139 fcntl(0, F_SETFL, O_NONBLOCK);
2142 static CharDriverState *qemu_chr_open_stdio(void)
2144 CharDriverState *chr;
2146 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2148 chr = qemu_chr_open_fd(0, 1);
2149 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2156 #if defined(__linux__) || defined(__sun__)
2157 static CharDriverState *qemu_chr_open_pty(void)
2160 char slave_name[1024];
2161 int master_fd, slave_fd;
2163 #if defined(__linux__)
2164 /* Not satisfying */
2165 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2170 /* Disabling local echo and line-buffered output */
2171 tcgetattr (master_fd, &tty);
2172 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2174 tty.c_cc[VTIME] = 0;
2175 tcsetattr (master_fd, TCSAFLUSH, &tty);
2177 fprintf(stderr, "char device redirected to %s\n", slave_name);
2178 return qemu_chr_open_fd(master_fd, master_fd);
2181 static void tty_serial_init(int fd, int speed,
2182 int parity, int data_bits, int stop_bits)
2188 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2189 speed, parity, data_bits, stop_bits);
2191 tcgetattr (fd, &tty);
2233 cfsetispeed(&tty, spd);
2234 cfsetospeed(&tty, spd);
2236 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2237 |INLCR|IGNCR|ICRNL|IXON);
2238 tty.c_oflag |= OPOST;
2239 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2240 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2261 tty.c_cflag |= PARENB;
2264 tty.c_cflag |= PARENB | PARODD;
2268 tty.c_cflag |= CSTOPB;
2270 tcsetattr (fd, TCSANOW, &tty);
2273 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2275 FDCharDriver *s = chr->opaque;
2278 case CHR_IOCTL_SERIAL_SET_PARAMS:
2280 QEMUSerialSetParams *ssp = arg;
2281 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2282 ssp->data_bits, ssp->stop_bits);
2285 case CHR_IOCTL_SERIAL_SET_BREAK:
2287 int enable = *(int *)arg;
2289 tcsendbreak(s->fd_in, 1);
2298 static CharDriverState *qemu_chr_open_tty(const char *filename)
2300 CharDriverState *chr;
2303 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2304 fcntl(fd, F_SETFL, O_NONBLOCK);
2305 tty_serial_init(fd, 115200, 'N', 8, 1);
2306 chr = qemu_chr_open_fd(fd, fd);
2311 chr->chr_ioctl = tty_serial_ioctl;
2312 qemu_chr_reset(chr);
2315 #else /* ! __linux__ && ! __sun__ */
2316 static CharDriverState *qemu_chr_open_pty(void)
2320 #endif /* __linux__ || __sun__ */
2322 #if defined(__linux__)
2326 } ParallelCharDriver;
2328 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2330 if (s->mode != mode) {
2332 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2339 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2341 ParallelCharDriver *drv = chr->opaque;
2346 case CHR_IOCTL_PP_READ_DATA:
2347 if (ioctl(fd, PPRDATA, &b) < 0)
2349 *(uint8_t *)arg = b;
2351 case CHR_IOCTL_PP_WRITE_DATA:
2352 b = *(uint8_t *)arg;
2353 if (ioctl(fd, PPWDATA, &b) < 0)
2356 case CHR_IOCTL_PP_READ_CONTROL:
2357 if (ioctl(fd, PPRCONTROL, &b) < 0)
2359 /* Linux gives only the lowest bits, and no way to know data
2360 direction! For better compatibility set the fixed upper
2362 *(uint8_t *)arg = b | 0xc0;
2364 case CHR_IOCTL_PP_WRITE_CONTROL:
2365 b = *(uint8_t *)arg;
2366 if (ioctl(fd, PPWCONTROL, &b) < 0)
2369 case CHR_IOCTL_PP_READ_STATUS:
2370 if (ioctl(fd, PPRSTATUS, &b) < 0)
2372 *(uint8_t *)arg = b;
2374 case CHR_IOCTL_PP_EPP_READ_ADDR:
2375 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2376 struct ParallelIOArg *parg = arg;
2377 int n = read(fd, parg->buffer, parg->count);
2378 if (n != parg->count) {
2383 case CHR_IOCTL_PP_EPP_READ:
2384 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2385 struct ParallelIOArg *parg = arg;
2386 int n = read(fd, parg->buffer, parg->count);
2387 if (n != parg->count) {
2392 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2393 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2394 struct ParallelIOArg *parg = arg;
2395 int n = write(fd, parg->buffer, parg->count);
2396 if (n != parg->count) {
2401 case CHR_IOCTL_PP_EPP_WRITE:
2402 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2403 struct ParallelIOArg *parg = arg;
2404 int n = write(fd, parg->buffer, parg->count);
2405 if (n != parg->count) {
2416 static void pp_close(CharDriverState *chr)
2418 ParallelCharDriver *drv = chr->opaque;
2421 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2422 ioctl(fd, PPRELEASE);
2427 static CharDriverState *qemu_chr_open_pp(const char *filename)
2429 CharDriverState *chr;
2430 ParallelCharDriver *drv;
2433 TFR(fd = open(filename, O_RDWR));
2437 if (ioctl(fd, PPCLAIM) < 0) {
2442 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2448 drv->mode = IEEE1284_MODE_COMPAT;
2450 chr = qemu_mallocz(sizeof(CharDriverState));
2456 chr->chr_write = null_chr_write;
2457 chr->chr_ioctl = pp_ioctl;
2458 chr->chr_close = pp_close;
2461 qemu_chr_reset(chr);
2465 #endif /* __linux__ */
2471 HANDLE hcom, hrecv, hsend;
2472 OVERLAPPED orecv, osend;
2477 #define NSENDBUF 2048
2478 #define NRECVBUF 2048
2479 #define MAXCONNECT 1
2480 #define NTIMEOUT 5000
2482 static int win_chr_poll(void *opaque);
2483 static int win_chr_pipe_poll(void *opaque);
2485 static void win_chr_close(CharDriverState *chr)
2487 WinCharState *s = chr->opaque;
2490 CloseHandle(s->hsend);
2494 CloseHandle(s->hrecv);
2498 CloseHandle(s->hcom);
2502 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2504 qemu_del_polling_cb(win_chr_poll, chr);
2507 static int win_chr_init(CharDriverState *chr, const char *filename)
2509 WinCharState *s = chr->opaque;
2511 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2516 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2518 fprintf(stderr, "Failed CreateEvent\n");
2521 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2523 fprintf(stderr, "Failed CreateEvent\n");
2527 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2528 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2529 if (s->hcom == INVALID_HANDLE_VALUE) {
2530 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2535 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2536 fprintf(stderr, "Failed SetupComm\n");
2540 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2541 size = sizeof(COMMCONFIG);
2542 GetDefaultCommConfig(filename, &comcfg, &size);
2543 comcfg.dcb.DCBlength = sizeof(DCB);
2544 CommConfigDialog(filename, NULL, &comcfg);
2546 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2547 fprintf(stderr, "Failed SetCommState\n");
2551 if (!SetCommMask(s->hcom, EV_ERR)) {
2552 fprintf(stderr, "Failed SetCommMask\n");
2556 cto.ReadIntervalTimeout = MAXDWORD;
2557 if (!SetCommTimeouts(s->hcom, &cto)) {
2558 fprintf(stderr, "Failed SetCommTimeouts\n");
2562 if (!ClearCommError(s->hcom, &err, &comstat)) {
2563 fprintf(stderr, "Failed ClearCommError\n");
2566 qemu_add_polling_cb(win_chr_poll, chr);
2574 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2576 WinCharState *s = chr->opaque;
2577 DWORD len, ret, size, err;
2580 ZeroMemory(&s->osend, sizeof(s->osend));
2581 s->osend.hEvent = s->hsend;
2584 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2586 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2588 err = GetLastError();
2589 if (err == ERROR_IO_PENDING) {
2590 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2608 static int win_chr_read_poll(CharDriverState *chr)
2610 WinCharState *s = chr->opaque;
2612 s->max_size = qemu_chr_can_read(chr);
2616 static void win_chr_readfile(CharDriverState *chr)
2618 WinCharState *s = chr->opaque;
2623 ZeroMemory(&s->orecv, sizeof(s->orecv));
2624 s->orecv.hEvent = s->hrecv;
2625 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2627 err = GetLastError();
2628 if (err == ERROR_IO_PENDING) {
2629 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2634 qemu_chr_read(chr, buf, size);
2638 static void win_chr_read(CharDriverState *chr)
2640 WinCharState *s = chr->opaque;
2642 if (s->len > s->max_size)
2643 s->len = s->max_size;
2647 win_chr_readfile(chr);
2650 static int win_chr_poll(void *opaque)
2652 CharDriverState *chr = opaque;
2653 WinCharState *s = chr->opaque;
2657 ClearCommError(s->hcom, &comerr, &status);
2658 if (status.cbInQue > 0) {
2659 s->len = status.cbInQue;
2660 win_chr_read_poll(chr);
2667 static CharDriverState *qemu_chr_open_win(const char *filename)
2669 CharDriverState *chr;
2672 chr = qemu_mallocz(sizeof(CharDriverState));
2675 s = qemu_mallocz(sizeof(WinCharState));
2681 chr->chr_write = win_chr_write;
2682 chr->chr_close = win_chr_close;
2684 if (win_chr_init(chr, filename) < 0) {
2689 qemu_chr_reset(chr);
2693 static int win_chr_pipe_poll(void *opaque)
2695 CharDriverState *chr = opaque;
2696 WinCharState *s = chr->opaque;
2699 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2702 win_chr_read_poll(chr);
2709 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2711 WinCharState *s = chr->opaque;
2719 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2721 fprintf(stderr, "Failed CreateEvent\n");
2724 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2726 fprintf(stderr, "Failed CreateEvent\n");
2730 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2731 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2732 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2734 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2735 if (s->hcom == INVALID_HANDLE_VALUE) {
2736 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2741 ZeroMemory(&ov, sizeof(ov));
2742 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2743 ret = ConnectNamedPipe(s->hcom, &ov);
2745 fprintf(stderr, "Failed ConnectNamedPipe\n");
2749 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2751 fprintf(stderr, "Failed GetOverlappedResult\n");
2753 CloseHandle(ov.hEvent);
2760 CloseHandle(ov.hEvent);
2763 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2772 static CharDriverState *qemu_chr_open_win_pipe(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_pipe_init(chr, filename) < 0) {
2794 qemu_chr_reset(chr);
2798 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2800 CharDriverState *chr;
2803 chr = qemu_mallocz(sizeof(CharDriverState));
2806 s = qemu_mallocz(sizeof(WinCharState));
2813 chr->chr_write = win_chr_write;
2814 qemu_chr_reset(chr);
2818 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2820 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2823 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2827 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2828 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2829 if (fd_out == INVALID_HANDLE_VALUE)
2832 return qemu_chr_open_win_file(fd_out);
2834 #endif /* !_WIN32 */
2836 /***********************************************************/
2837 /* UDP Net console */
2841 struct sockaddr_in daddr;
2848 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2850 NetCharDriver *s = chr->opaque;
2852 return sendto(s->fd, buf, len, 0,
2853 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2856 static int udp_chr_read_poll(void *opaque)
2858 CharDriverState *chr = opaque;
2859 NetCharDriver *s = chr->opaque;
2861 s->max_size = qemu_chr_can_read(chr);
2863 /* If there were any stray characters in the queue process them
2866 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2867 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2869 s->max_size = qemu_chr_can_read(chr);
2874 static void udp_chr_read(void *opaque)
2876 CharDriverState *chr = opaque;
2877 NetCharDriver *s = chr->opaque;
2879 if (s->max_size == 0)
2881 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2882 s->bufptr = s->bufcnt;
2887 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2888 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2890 s->max_size = qemu_chr_can_read(chr);
2894 static void udp_chr_update_read_handler(CharDriverState *chr)
2896 NetCharDriver *s = chr->opaque;
2899 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2900 udp_chr_read, NULL, chr);
2904 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2906 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2908 int parse_host_src_port(struct sockaddr_in *haddr,
2909 struct sockaddr_in *saddr,
2912 static CharDriverState *qemu_chr_open_udp(const char *def)
2914 CharDriverState *chr = NULL;
2915 NetCharDriver *s = NULL;
2917 struct sockaddr_in saddr;
2919 chr = qemu_mallocz(sizeof(CharDriverState));
2922 s = qemu_mallocz(sizeof(NetCharDriver));
2926 fd = socket(PF_INET, SOCK_DGRAM, 0);
2928 perror("socket(PF_INET, SOCK_DGRAM)");
2932 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2933 printf("Could not parse: %s\n", def);
2937 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2947 chr->chr_write = udp_chr_write;
2948 chr->chr_update_read_handler = udp_chr_update_read_handler;
2961 /***********************************************************/
2962 /* TCP Net console */
2973 static void tcp_chr_accept(void *opaque);
2975 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2977 TCPCharDriver *s = chr->opaque;
2979 return send_all(s->fd, buf, len);
2981 /* XXX: indicate an error ? */
2986 static int tcp_chr_read_poll(void *opaque)
2988 CharDriverState *chr = opaque;
2989 TCPCharDriver *s = chr->opaque;
2992 s->max_size = qemu_chr_can_read(chr);
2997 #define IAC_BREAK 243
2998 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3000 char *buf, int *size)
3002 /* Handle any telnet client's basic IAC options to satisfy char by
3003 * char mode with no echo. All IAC options will be removed from
3004 * the buf and the do_telnetopt variable will be used to track the
3005 * state of the width of the IAC information.
3007 * IAC commands come in sets of 3 bytes with the exception of the
3008 * "IAC BREAK" command and the double IAC.
3014 for (i = 0; i < *size; i++) {
3015 if (s->do_telnetopt > 1) {
3016 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3017 /* Double IAC means send an IAC */
3021 s->do_telnetopt = 1;
3023 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3024 /* Handle IAC break commands by sending a serial break */
3025 qemu_chr_event(chr, CHR_EVENT_BREAK);
3030 if (s->do_telnetopt >= 4) {
3031 s->do_telnetopt = 1;
3034 if ((unsigned char)buf[i] == IAC) {
3035 s->do_telnetopt = 2;
3046 static void tcp_chr_read(void *opaque)
3048 CharDriverState *chr = opaque;
3049 TCPCharDriver *s = chr->opaque;
3053 if (!s->connected || s->max_size <= 0)
3056 if (len > s->max_size)
3058 size = recv(s->fd, buf, len, 0);
3060 /* connection closed */
3062 if (s->listen_fd >= 0) {
3063 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3065 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3068 } else if (size > 0) {
3069 if (s->do_telnetopt)
3070 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3072 qemu_chr_read(chr, buf, size);
3076 static void tcp_chr_connect(void *opaque)
3078 CharDriverState *chr = opaque;
3079 TCPCharDriver *s = chr->opaque;
3082 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3083 tcp_chr_read, NULL, chr);
3084 qemu_chr_reset(chr);
3087 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3088 static void tcp_chr_telnet_init(int fd)
3091 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3092 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3093 send(fd, (char *)buf, 3, 0);
3094 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3095 send(fd, (char *)buf, 3, 0);
3096 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3097 send(fd, (char *)buf, 3, 0);
3098 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3099 send(fd, (char *)buf, 3, 0);
3102 static void socket_set_nodelay(int fd)
3105 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3108 static void tcp_chr_accept(void *opaque)
3110 CharDriverState *chr = opaque;
3111 TCPCharDriver *s = chr->opaque;
3112 struct sockaddr_in saddr;
3114 struct sockaddr_un uaddr;
3116 struct sockaddr *addr;
3123 len = sizeof(uaddr);
3124 addr = (struct sockaddr *)&uaddr;
3128 len = sizeof(saddr);
3129 addr = (struct sockaddr *)&saddr;
3131 fd = accept(s->listen_fd, addr, &len);
3132 if (fd < 0 && errno != EINTR) {
3134 } else if (fd >= 0) {
3135 if (s->do_telnetopt)
3136 tcp_chr_telnet_init(fd);
3140 socket_set_nonblock(fd);
3142 socket_set_nodelay(fd);
3144 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3145 tcp_chr_connect(chr);
3148 static void tcp_chr_close(CharDriverState *chr)
3150 TCPCharDriver *s = chr->opaque;
3153 if (s->listen_fd >= 0)
3154 closesocket(s->listen_fd);
3158 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3162 CharDriverState *chr = NULL;
3163 TCPCharDriver *s = NULL;
3164 int fd = -1, ret, err, val;
3166 int is_waitconnect = 1;
3169 struct sockaddr_in saddr;
3171 struct sockaddr_un uaddr;
3173 struct sockaddr *addr;
3178 addr = (struct sockaddr *)&uaddr;
3179 addrlen = sizeof(uaddr);
3180 if (parse_unix_path(&uaddr, host_str) < 0)
3185 addr = (struct sockaddr *)&saddr;
3186 addrlen = sizeof(saddr);
3187 if (parse_host_port(&saddr, host_str) < 0)
3192 while((ptr = strchr(ptr,','))) {
3194 if (!strncmp(ptr,"server",6)) {
3196 } else if (!strncmp(ptr,"nowait",6)) {
3198 } else if (!strncmp(ptr,"nodelay",6)) {
3201 printf("Unknown option: %s\n", ptr);
3208 chr = qemu_mallocz(sizeof(CharDriverState));
3211 s = qemu_mallocz(sizeof(TCPCharDriver));
3217 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3220 fd = socket(PF_INET, SOCK_STREAM, 0);
3225 if (!is_waitconnect)
3226 socket_set_nonblock(fd);
3231 s->is_unix = is_unix;
3232 s->do_nodelay = do_nodelay && !is_unix;
3235 chr->chr_write = tcp_chr_write;
3236 chr->chr_close = tcp_chr_close;
3239 /* allow fast reuse */
3243 strncpy(path, uaddr.sun_path, 108);
3250 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3253 ret = bind(fd, addr, addrlen);
3257 ret = listen(fd, 0);
3262 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3264 s->do_telnetopt = 1;
3267 ret = connect(fd, addr, addrlen);
3269 err = socket_error();
3270 if (err == EINTR || err == EWOULDBLOCK) {
3271 } else if (err == EINPROGRESS) {
3274 } else if (err == WSAEALREADY) {
3286 socket_set_nodelay(fd);
3288 tcp_chr_connect(chr);
3290 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3293 if (is_listen && is_waitconnect) {
3294 printf("QEMU waiting for connection on: %s\n", host_str);
3295 tcp_chr_accept(chr);
3296 socket_set_nonblock(s->listen_fd);
3308 CharDriverState *qemu_chr_open(const char *filename)
3312 if (!strcmp(filename, "vc")) {
3313 return text_console_init(&display_state, 0);
3314 } else if (strstart(filename, "vc:", &p)) {
3315 return text_console_init(&display_state, p);
3316 } else if (!strcmp(filename, "null")) {
3317 return qemu_chr_open_null();
3319 if (strstart(filename, "tcp:", &p)) {
3320 return qemu_chr_open_tcp(p, 0, 0);
3322 if (strstart(filename, "telnet:", &p)) {
3323 return qemu_chr_open_tcp(p, 1, 0);
3325 if (strstart(filename, "udp:", &p)) {
3326 return qemu_chr_open_udp(p);
3328 if (strstart(filename, "mon:", &p)) {
3329 CharDriverState *drv = qemu_chr_open(p);
3331 drv = qemu_chr_open_mux(drv);
3332 monitor_init(drv, !nographic);
3335 printf("Unable to open driver: %s\n", p);
3339 if (strstart(filename, "unix:", &p)) {
3340 return qemu_chr_open_tcp(p, 0, 1);
3341 } else if (strstart(filename, "file:", &p)) {
3342 return qemu_chr_open_file_out(p);
3343 } else if (strstart(filename, "pipe:", &p)) {
3344 return qemu_chr_open_pipe(p);
3345 } else if (!strcmp(filename, "pty")) {
3346 return qemu_chr_open_pty();
3347 } else if (!strcmp(filename, "stdio")) {
3348 return qemu_chr_open_stdio();
3350 #if defined(__linux__)
3351 if (strstart(filename, "/dev/parport", NULL)) {
3352 return qemu_chr_open_pp(filename);
3355 #if defined(__linux__) || defined(__sun__)
3356 if (strstart(filename, "/dev/", NULL)) {
3357 return qemu_chr_open_tty(filename);
3361 if (strstart(filename, "COM", NULL)) {
3362 return qemu_chr_open_win(filename);
3364 if (strstart(filename, "pipe:", &p)) {
3365 return qemu_chr_open_win_pipe(p);
3367 if (strstart(filename, "con:", NULL)) {
3368 return qemu_chr_open_win_con(filename);
3370 if (strstart(filename, "file:", &p)) {
3371 return qemu_chr_open_win_file_out(p);
3379 void qemu_chr_close(CharDriverState *chr)
3382 chr->chr_close(chr);
3385 /***********************************************************/
3386 /* network device redirectors */
3388 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3392 for(i=0;i<size;i+=16) {
3396 fprintf(f, "%08x ", i);
3399 fprintf(f, " %02x", buf[i+j]);
3404 for(j=0;j<len;j++) {
3406 if (c < ' ' || c > '~')
3408 fprintf(f, "%c", c);
3414 static int parse_macaddr(uint8_t *macaddr, const char *p)
3417 for(i = 0; i < 6; i++) {
3418 macaddr[i] = strtol(p, (char **)&p, 16);
3431 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3436 p1 = strchr(p, sep);
3442 if (len > buf_size - 1)
3444 memcpy(buf, p, len);
3451 int parse_host_src_port(struct sockaddr_in *haddr,
3452 struct sockaddr_in *saddr,
3453 const char *input_str)
3455 char *str = strdup(input_str);
3456 char *host_str = str;
3461 * Chop off any extra arguments at the end of the string which
3462 * would start with a comma, then fill in the src port information
3463 * if it was provided else use the "any address" and "any port".
3465 if ((ptr = strchr(str,',')))
3468 if ((src_str = strchr(input_str,'@'))) {
3473 if (parse_host_port(haddr, host_str) < 0)
3476 if (!src_str || *src_str == '\0')
3479 if (parse_host_port(saddr, src_str) < 0)
3490 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3498 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3500 saddr->sin_family = AF_INET;
3501 if (buf[0] == '\0') {
3502 saddr->sin_addr.s_addr = 0;
3504 if (isdigit(buf[0])) {
3505 if (!inet_aton(buf, &saddr->sin_addr))
3508 if ((he = gethostbyname(buf)) == NULL)
3510 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3513 port = strtol(p, (char **)&r, 0);
3516 saddr->sin_port = htons(port);
3521 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3526 len = MIN(108, strlen(str));
3527 p = strchr(str, ',');
3529 len = MIN(len, p - str);
3531 memset(uaddr, 0, sizeof(*uaddr));
3533 uaddr->sun_family = AF_UNIX;
3534 memcpy(uaddr->sun_path, str, len);
3540 /* find or alloc a new VLAN */
3541 VLANState *qemu_find_vlan(int id)
3543 VLANState **pvlan, *vlan;
3544 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3548 vlan = qemu_mallocz(sizeof(VLANState));
3553 pvlan = &first_vlan;
3554 while (*pvlan != NULL)
3555 pvlan = &(*pvlan)->next;
3560 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3561 IOReadHandler *fd_read,
3562 IOCanRWHandler *fd_can_read,
3565 VLANClientState *vc, **pvc;
3566 vc = qemu_mallocz(sizeof(VLANClientState));
3569 vc->fd_read = fd_read;
3570 vc->fd_can_read = fd_can_read;
3571 vc->opaque = opaque;
3575 pvc = &vlan->first_client;
3576 while (*pvc != NULL)
3577 pvc = &(*pvc)->next;
3582 int qemu_can_send_packet(VLANClientState *vc1)
3584 VLANState *vlan = vc1->vlan;
3585 VLANClientState *vc;
3587 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3589 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3596 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3598 VLANState *vlan = vc1->vlan;
3599 VLANClientState *vc;
3602 printf("vlan %d send:\n", vlan->id);
3603 hex_dump(stdout, buf, size);
3605 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3607 vc->fd_read(vc->opaque, buf, size);
3612 #if defined(CONFIG_SLIRP)
3614 /* slirp network adapter */
3616 static int slirp_inited;
3617 static VLANClientState *slirp_vc;
3619 int slirp_can_output(void)
3621 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3624 void slirp_output(const uint8_t *pkt, int pkt_len)
3627 printf("slirp output:\n");
3628 hex_dump(stdout, pkt, pkt_len);
3632 qemu_send_packet(slirp_vc, pkt, pkt_len);
3635 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3638 printf("slirp input:\n");
3639 hex_dump(stdout, buf, size);
3641 slirp_input(buf, size);
3644 static int net_slirp_init(VLANState *vlan)
3646 if (!slirp_inited) {
3650 slirp_vc = qemu_new_vlan_client(vlan,
3651 slirp_receive, NULL, NULL);
3652 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3656 static void net_slirp_redir(const char *redir_str)
3661 struct in_addr guest_addr;
3662 int host_port, guest_port;
3664 if (!slirp_inited) {
3670 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3672 if (!strcmp(buf, "tcp")) {
3674 } else if (!strcmp(buf, "udp")) {
3680 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3682 host_port = strtol(buf, &r, 0);
3686 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3688 if (buf[0] == '\0') {
3689 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3691 if (!inet_aton(buf, &guest_addr))
3694 guest_port = strtol(p, &r, 0);
3698 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3699 fprintf(stderr, "qemu: could not set up redirection\n");
3704 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3712 static void smb_exit(void)
3716 char filename[1024];
3718 /* erase all the files in the directory */
3719 d = opendir(smb_dir);
3724 if (strcmp(de->d_name, ".") != 0 &&
3725 strcmp(de->d_name, "..") != 0) {
3726 snprintf(filename, sizeof(filename), "%s/%s",
3727 smb_dir, de->d_name);
3735 /* automatic user mode samba server configuration */
3736 static void net_slirp_smb(const char *exported_dir)
3738 char smb_conf[1024];
3739 char smb_cmdline[1024];
3742 if (!slirp_inited) {
3747 /* XXX: better tmp dir construction */
3748 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3749 if (mkdir(smb_dir, 0700) < 0) {
3750 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3753 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3755 f = fopen(smb_conf, "w");
3757 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3764 "socket address=127.0.0.1\n"
3765 "pid directory=%s\n"
3766 "lock directory=%s\n"
3767 "log file=%s/log.smbd\n"
3768 "smb passwd file=%s/smbpasswd\n"
3769 "security = share\n"
3784 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3785 SMBD_COMMAND, smb_conf);
3787 slirp_add_exec(0, smb_cmdline, 4, 139);
3790 #endif /* !defined(_WIN32) */
3791 void do_info_slirp(void)
3796 #endif /* CONFIG_SLIRP */
3798 #if !defined(_WIN32)
3800 typedef struct TAPState {
3801 VLANClientState *vc;
3803 char down_script[1024];
3806 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3808 TAPState *s = opaque;
3811 ret = write(s->fd, buf, size);
3812 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3819 static void tap_send(void *opaque)
3821 TAPState *s = opaque;
3828 sbuf.maxlen = sizeof(buf);
3830 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3832 size = read(s->fd, buf, sizeof(buf));
3835 qemu_send_packet(s->vc, buf, size);
3841 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3845 s = qemu_mallocz(sizeof(TAPState));
3849 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3850 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3851 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3855 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3856 static int tap_open(char *ifname, int ifname_size)
3862 TFR(fd = open("/dev/tap", O_RDWR));
3864 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3869 dev = devname(s.st_rdev, S_IFCHR);
3870 pstrcpy(ifname, ifname_size, dev);
3872 fcntl(fd, F_SETFL, O_NONBLOCK);
3875 #elif defined(__sun__)
3876 #define TUNNEWPPA (('T'<<16) | 0x0001)
3878 * Allocate TAP device, returns opened fd.
3879 * Stores dev name in the first arg(must be large enough).
3881 int tap_alloc(char *dev)
3883 int tap_fd, if_fd, ppa = -1;
3884 static int ip_fd = 0;
3887 static int arp_fd = 0;
3888 int ip_muxid, arp_muxid;
3889 struct strioctl strioc_if, strioc_ppa;
3890 int link_type = I_PLINK;;
3892 char actual_name[32] = "";
3894 memset(&ifr, 0x0, sizeof(ifr));
3898 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3902 /* Check if IP device was opened */
3906 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3908 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3912 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3914 syslog(LOG_ERR, "Can't open /dev/tap");
3918 /* Assign a new PPA and get its unit number. */
3919 strioc_ppa.ic_cmd = TUNNEWPPA;
3920 strioc_ppa.ic_timout = 0;
3921 strioc_ppa.ic_len = sizeof(ppa);
3922 strioc_ppa.ic_dp = (char *)&ppa;
3923 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3924 syslog (LOG_ERR, "Can't assign new interface");
3926 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3928 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3931 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3932 syslog(LOG_ERR, "Can't push IP module");
3936 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3937 syslog(LOG_ERR, "Can't get flags\n");
3939 snprintf (actual_name, 32, "tap%d", ppa);
3940 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3943 /* Assign ppa according to the unit number returned by tun device */
3945 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3946 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3947 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3948 syslog (LOG_ERR, "Can't get flags\n");
3949 /* Push arp module to if_fd */
3950 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3951 syslog (LOG_ERR, "Can't push ARP module (2)");
3953 /* Push arp module to ip_fd */
3954 if (ioctl (ip_fd, I_POP, NULL) < 0)
3955 syslog (LOG_ERR, "I_POP failed\n");
3956 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3957 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3959 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3961 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3963 /* Set ifname to arp */
3964 strioc_if.ic_cmd = SIOCSLIFNAME;
3965 strioc_if.ic_timout = 0;
3966 strioc_if.ic_len = sizeof(ifr);
3967 strioc_if.ic_dp = (char *)𝔦
3968 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3969 syslog (LOG_ERR, "Can't set ifname to arp\n");
3972 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3973 syslog(LOG_ERR, "Can't link TAP device to IP");
3977 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3978 syslog (LOG_ERR, "Can't link TAP device to ARP");
3982 memset(&ifr, 0x0, sizeof(ifr));
3983 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3984 ifr.lifr_ip_muxid = ip_muxid;
3985 ifr.lifr_arp_muxid = arp_muxid;
3987 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3989 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3990 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3991 syslog (LOG_ERR, "Can't set multiplexor id");
3994 sprintf(dev, "tap%d", ppa);
3998 static int tap_open(char *ifname, int ifname_size)
4002 if( (fd = tap_alloc(dev)) < 0 ){
4003 fprintf(stderr, "Cannot allocate TAP device\n");
4006 pstrcpy(ifname, ifname_size, dev);
4007 fcntl(fd, F_SETFL, O_NONBLOCK);
4011 static int tap_open(char *ifname, int ifname_size)
4016 TFR(fd = open("/dev/net/tun", O_RDWR));
4018 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4021 memset(&ifr, 0, sizeof(ifr));
4022 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4023 if (ifname[0] != '\0')
4024 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4026 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4027 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4029 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4033 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4034 fcntl(fd, F_SETFL, O_NONBLOCK);
4039 static int launch_script(const char *setup_script, const char *ifname, int fd)
4045 /* try to launch network script */
4049 int open_max = sysconf (_SC_OPEN_MAX), i;
4050 for (i = 0; i < open_max; i++)
4051 if (i != STDIN_FILENO &&
4052 i != STDOUT_FILENO &&
4053 i != STDERR_FILENO &&
4058 *parg++ = (char *)setup_script;
4059 *parg++ = (char *)ifname;
4061 execv(setup_script, args);
4064 while (waitpid(pid, &status, 0) != pid);
4065 if (!WIFEXITED(status) ||
4066 WEXITSTATUS(status) != 0) {
4067 fprintf(stderr, "%s: could not launch network script\n",
4075 static int net_tap_init(VLANState *vlan, const char *ifname1,
4076 const char *setup_script, const char *down_script)
4082 if (ifname1 != NULL)
4083 pstrcpy(ifname, sizeof(ifname), ifname1);
4086 TFR(fd = tap_open(ifname, sizeof(ifname)));
4090 if (!setup_script || !strcmp(setup_script, "no"))
4092 if (setup_script[0] != '\0') {
4093 if (launch_script(setup_script, ifname, fd))
4096 s = net_tap_fd_init(vlan, fd);
4099 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4100 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4101 if (down_script && strcmp(down_script, "no"))
4102 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4106 #endif /* !_WIN32 */
4108 /* network connection */
4109 typedef struct NetSocketState {
4110 VLANClientState *vc;
4112 int state; /* 0 = getting length, 1 = getting data */
4116 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4119 typedef struct NetSocketListenState {
4122 } NetSocketListenState;
4124 /* XXX: we consider we can send the whole packet without blocking */
4125 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4127 NetSocketState *s = opaque;
4131 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4132 send_all(s->fd, buf, size);
4135 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4137 NetSocketState *s = opaque;
4138 sendto(s->fd, buf, size, 0,
4139 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4142 static void net_socket_send(void *opaque)
4144 NetSocketState *s = opaque;
4149 size = recv(s->fd, buf1, sizeof(buf1), 0);
4151 err = socket_error();
4152 if (err != EWOULDBLOCK)
4154 } else if (size == 0) {
4155 /* end of connection */
4157 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4163 /* reassemble a packet from the network */
4169 memcpy(s->buf + s->index, buf, l);
4173 if (s->index == 4) {
4175 s->packet_len = ntohl(*(uint32_t *)s->buf);
4181 l = s->packet_len - s->index;
4184 memcpy(s->buf + s->index, buf, l);
4188 if (s->index >= s->packet_len) {
4189 qemu_send_packet(s->vc, s->buf, s->packet_len);
4198 static void net_socket_send_dgram(void *opaque)
4200 NetSocketState *s = opaque;
4203 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4207 /* end of connection */
4208 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4211 qemu_send_packet(s->vc, s->buf, size);
4214 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4219 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4220 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4221 inet_ntoa(mcastaddr->sin_addr),
4222 (int)ntohl(mcastaddr->sin_addr.s_addr));
4226 fd = socket(PF_INET, SOCK_DGRAM, 0);
4228 perror("socket(PF_INET, SOCK_DGRAM)");
4233 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4234 (const char *)&val, sizeof(val));
4236 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4240 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4246 /* Add host to multicast group */
4247 imr.imr_multiaddr = mcastaddr->sin_addr;
4248 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4250 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4251 (const char *)&imr, sizeof(struct ip_mreq));
4253 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4257 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4259 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4260 (const char *)&val, sizeof(val));
4262 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4266 socket_set_nonblock(fd);
4274 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4277 struct sockaddr_in saddr;
4279 socklen_t saddr_len;
4282 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4283 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4284 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4288 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4290 if (saddr.sin_addr.s_addr==0) {
4291 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4295 /* clone dgram socket */
4296 newfd = net_socket_mcast_create(&saddr);
4298 /* error already reported by net_socket_mcast_create() */
4302 /* clone newfd to fd, close newfd */
4307 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4308 fd, strerror(errno));
4313 s = qemu_mallocz(sizeof(NetSocketState));
4318 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4319 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4321 /* mcast: save bound address as dst */
4322 if (is_connected) s->dgram_dst=saddr;
4324 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4325 "socket: fd=%d (%s mcast=%s:%d)",
4326 fd, is_connected? "cloned" : "",
4327 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4331 static void net_socket_connect(void *opaque)
4333 NetSocketState *s = opaque;
4334 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4337 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4341 s = qemu_mallocz(sizeof(NetSocketState));
4345 s->vc = qemu_new_vlan_client(vlan,
4346 net_socket_receive, NULL, s);
4347 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4348 "socket: fd=%d", fd);
4350 net_socket_connect(s);
4352 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4357 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4360 int so_type=-1, optlen=sizeof(so_type);
4362 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4363 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4368 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4370 return net_socket_fd_init_stream(vlan, fd, is_connected);
4372 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4373 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4374 return net_socket_fd_init_stream(vlan, fd, is_connected);
4379 static void net_socket_accept(void *opaque)
4381 NetSocketListenState *s = opaque;
4383 struct sockaddr_in saddr;
4388 len = sizeof(saddr);
4389 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4390 if (fd < 0 && errno != EINTR) {
4392 } else if (fd >= 0) {
4396 s1 = net_socket_fd_init(s->vlan, fd, 1);
4400 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4401 "socket: connection from %s:%d",
4402 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4406 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4408 NetSocketListenState *s;
4410 struct sockaddr_in saddr;
4412 if (parse_host_port(&saddr, host_str) < 0)
4415 s = qemu_mallocz(sizeof(NetSocketListenState));
4419 fd = socket(PF_INET, SOCK_STREAM, 0);
4424 socket_set_nonblock(fd);
4426 /* allow fast reuse */
4428 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4430 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4435 ret = listen(fd, 0);
4442 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4446 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4449 int fd, connected, ret, err;
4450 struct sockaddr_in saddr;
4452 if (parse_host_port(&saddr, host_str) < 0)
4455 fd = socket(PF_INET, SOCK_STREAM, 0);
4460 socket_set_nonblock(fd);
4464 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4466 err = socket_error();
4467 if (err == EINTR || err == EWOULDBLOCK) {
4468 } else if (err == EINPROGRESS) {
4471 } else if (err == WSAEALREADY) {
4484 s = net_socket_fd_init(vlan, fd, connected);
4487 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4488 "socket: connect to %s:%d",
4489 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4493 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4497 struct sockaddr_in saddr;
4499 if (parse_host_port(&saddr, host_str) < 0)
4503 fd = net_socket_mcast_create(&saddr);
4507 s = net_socket_fd_init(vlan, fd, 0);
4511 s->dgram_dst = saddr;
4513 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4514 "socket: mcast=%s:%d",
4515 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4520 static int get_param_value(char *buf, int buf_size,
4521 const char *tag, const char *str)
4530 while (*p != '\0' && *p != '=') {
4531 if ((q - option) < sizeof(option) - 1)
4539 if (!strcmp(tag, option)) {
4541 while (*p != '\0' && *p != ',') {
4542 if ((q - buf) < buf_size - 1)
4549 while (*p != '\0' && *p != ',') {
4560 static int net_client_init(const char *str)
4571 while (*p != '\0' && *p != ',') {
4572 if ((q - device) < sizeof(device) - 1)
4580 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4581 vlan_id = strtol(buf, NULL, 0);
4583 vlan = qemu_find_vlan(vlan_id);
4585 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4588 if (!strcmp(device, "nic")) {
4592 if (nb_nics >= MAX_NICS) {
4593 fprintf(stderr, "Too Many NICs\n");
4596 nd = &nd_table[nb_nics];
4597 macaddr = nd->macaddr;
4603 macaddr[5] = 0x56 + nb_nics;
4605 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4606 if (parse_macaddr(macaddr, buf) < 0) {
4607 fprintf(stderr, "invalid syntax for ethernet address\n");
4611 if (get_param_value(buf, sizeof(buf), "model", p)) {
4612 nd->model = strdup(buf);
4616 vlan->nb_guest_devs++;
4619 if (!strcmp(device, "none")) {
4620 /* does nothing. It is needed to signal that no network cards
4625 if (!strcmp(device, "user")) {
4626 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4627 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4629 vlan->nb_host_devs++;
4630 ret = net_slirp_init(vlan);
4634 if (!strcmp(device, "tap")) {
4636 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4637 fprintf(stderr, "tap: no interface name\n");
4640 vlan->nb_host_devs++;
4641 ret = tap_win32_init(vlan, ifname);
4644 if (!strcmp(device, "tap")) {
4646 char setup_script[1024], down_script[1024];
4648 vlan->nb_host_devs++;
4649 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4650 fd = strtol(buf, NULL, 0);
4652 if (net_tap_fd_init(vlan, fd))
4655 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4658 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4659 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4661 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4662 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4664 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4668 if (!strcmp(device, "socket")) {
4669 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4671 fd = strtol(buf, NULL, 0);
4673 if (net_socket_fd_init(vlan, fd, 1))
4675 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4676 ret = net_socket_listen_init(vlan, buf);
4677 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4678 ret = net_socket_connect_init(vlan, buf);
4679 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4680 ret = net_socket_mcast_init(vlan, buf);
4682 fprintf(stderr, "Unknown socket options: %s\n", p);
4685 vlan->nb_host_devs++;
4688 fprintf(stderr, "Unknown network device: %s\n", device);
4692 fprintf(stderr, "Could not initialize device '%s'\n", device);
4698 void do_info_network(void)
4701 VLANClientState *vc;
4703 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4704 term_printf("VLAN %d devices:\n", vlan->id);
4705 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4706 term_printf(" %s\n", vc->info_str);
4710 /***********************************************************/
4713 static USBPort *used_usb_ports;
4714 static USBPort *free_usb_ports;
4716 /* ??? Maybe change this to register a hub to keep track of the topology. */
4717 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4718 usb_attachfn attach)
4720 port->opaque = opaque;
4721 port->index = index;
4722 port->attach = attach;
4723 port->next = free_usb_ports;
4724 free_usb_ports = port;
4727 static int usb_device_add(const char *devname)
4733 if (!free_usb_ports)
4736 if (strstart(devname, "host:", &p)) {
4737 dev = usb_host_device_open(p);
4738 } else if (!strcmp(devname, "mouse")) {
4739 dev = usb_mouse_init();
4740 } else if (!strcmp(devname, "tablet")) {
4741 dev = usb_tablet_init();
4742 } else if (!strcmp(devname, "keyboard")) {
4743 dev = usb_keyboard_init();
4744 } else if (strstart(devname, "disk:", &p)) {
4745 dev = usb_msd_init(p);
4746 } else if (!strcmp(devname, "wacom-tablet")) {
4747 dev = usb_wacom_init();
4754 /* Find a USB port to add the device to. */
4755 port = free_usb_ports;
4759 /* Create a new hub and chain it on. */
4760 free_usb_ports = NULL;
4761 port->next = used_usb_ports;
4762 used_usb_ports = port;
4764 hub = usb_hub_init(VM_USB_HUB_SIZE);
4765 usb_attach(port, hub);
4766 port = free_usb_ports;
4769 free_usb_ports = port->next;
4770 port->next = used_usb_ports;
4771 used_usb_ports = port;
4772 usb_attach(port, dev);
4776 static int usb_device_del(const char *devname)
4784 if (!used_usb_ports)
4787 p = strchr(devname, '.');
4790 bus_num = strtoul(devname, NULL, 0);
4791 addr = strtoul(p + 1, NULL, 0);
4795 lastp = &used_usb_ports;
4796 port = used_usb_ports;
4797 while (port && port->dev->addr != addr) {
4798 lastp = &port->next;
4806 *lastp = port->next;
4807 usb_attach(port, NULL);
4808 dev->handle_destroy(dev);
4809 port->next = free_usb_ports;
4810 free_usb_ports = port;
4814 void do_usb_add(const char *devname)
4817 ret = usb_device_add(devname);
4819 term_printf("Could not add USB device '%s'\n", devname);
4822 void do_usb_del(const char *devname)
4825 ret = usb_device_del(devname);
4827 term_printf("Could not remove USB device '%s'\n", devname);
4834 const char *speed_str;
4837 term_printf("USB support not enabled\n");
4841 for (port = used_usb_ports; port; port = port->next) {
4845 switch(dev->speed) {
4849 case USB_SPEED_FULL:
4852 case USB_SPEED_HIGH:
4859 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4860 0, dev->addr, speed_str, dev->devname);
4864 /***********************************************************/
4865 /* PCMCIA/Cardbus */
4867 static struct pcmcia_socket_entry_s {
4868 struct pcmcia_socket_s *socket;
4869 struct pcmcia_socket_entry_s *next;
4870 } *pcmcia_sockets = 0;
4872 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4874 struct pcmcia_socket_entry_s *entry;
4876 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4877 entry->socket = socket;
4878 entry->next = pcmcia_sockets;
4879 pcmcia_sockets = entry;
4882 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4884 struct pcmcia_socket_entry_s *entry, **ptr;
4886 ptr = &pcmcia_sockets;
4887 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4888 if (entry->socket == socket) {
4894 void pcmcia_info(void)
4896 struct pcmcia_socket_entry_s *iter;
4897 if (!pcmcia_sockets)
4898 term_printf("No PCMCIA sockets\n");
4900 for (iter = pcmcia_sockets; iter; iter = iter->next)
4901 term_printf("%s: %s\n", iter->socket->slot_string,
4902 iter->socket->attached ? iter->socket->card_string :
4906 /***********************************************************/
4909 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4913 static void dumb_resize(DisplayState *ds, int w, int h)
4917 static void dumb_refresh(DisplayState *ds)
4919 #if defined(CONFIG_SDL)
4924 static void dumb_display_init(DisplayState *ds)
4929 ds->dpy_update = dumb_update;
4930 ds->dpy_resize = dumb_resize;
4931 ds->dpy_refresh = dumb_refresh;
4934 /***********************************************************/
4937 #define MAX_IO_HANDLERS 64
4939 typedef struct IOHandlerRecord {
4941 IOCanRWHandler *fd_read_poll;
4943 IOHandler *fd_write;
4946 /* temporary data */
4948 struct IOHandlerRecord *next;
4951 static IOHandlerRecord *first_io_handler;
4953 /* XXX: fd_read_poll should be suppressed, but an API change is
4954 necessary in the character devices to suppress fd_can_read(). */
4955 int qemu_set_fd_handler2(int fd,
4956 IOCanRWHandler *fd_read_poll,
4958 IOHandler *fd_write,
4961 IOHandlerRecord **pioh, *ioh;
4963 if (!fd_read && !fd_write) {
4964 pioh = &first_io_handler;
4969 if (ioh->fd == fd) {
4976 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4980 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4983 ioh->next = first_io_handler;
4984 first_io_handler = ioh;
4987 ioh->fd_read_poll = fd_read_poll;
4988 ioh->fd_read = fd_read;
4989 ioh->fd_write = fd_write;
4990 ioh->opaque = opaque;
4996 int qemu_set_fd_handler(int fd,
4998 IOHandler *fd_write,
5001 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5004 /***********************************************************/
5005 /* Polling handling */
5007 typedef struct PollingEntry {
5010 struct PollingEntry *next;
5013 static PollingEntry *first_polling_entry;
5015 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5017 PollingEntry **ppe, *pe;
5018 pe = qemu_mallocz(sizeof(PollingEntry));
5022 pe->opaque = opaque;
5023 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5028 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5030 PollingEntry **ppe, *pe;
5031 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5033 if (pe->func == func && pe->opaque == opaque) {
5042 /***********************************************************/
5043 /* Wait objects support */
5044 typedef struct WaitObjects {
5046 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5047 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5048 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5051 static WaitObjects wait_objects = {0};
5053 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5055 WaitObjects *w = &wait_objects;
5057 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5059 w->events[w->num] = handle;
5060 w->func[w->num] = func;
5061 w->opaque[w->num] = opaque;
5066 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5069 WaitObjects *w = &wait_objects;
5072 for (i = 0; i < w->num; i++) {
5073 if (w->events[i] == handle)
5076 w->events[i] = w->events[i + 1];
5077 w->func[i] = w->func[i + 1];
5078 w->opaque[i] = w->opaque[i + 1];
5086 /***********************************************************/
5087 /* savevm/loadvm support */
5089 #define IO_BUF_SIZE 32768
5093 BlockDriverState *bs;
5096 int64_t base_offset;
5097 int64_t buf_offset; /* start of buffer when writing, end of buffer
5100 int buf_size; /* 0 when writing */
5101 uint8_t buf[IO_BUF_SIZE];
5104 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5108 f = qemu_mallocz(sizeof(QEMUFile));
5111 if (!strcmp(mode, "wb")) {
5113 } else if (!strcmp(mode, "rb")) {
5118 f->outfile = fopen(filename, mode);
5130 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5134 f = qemu_mallocz(sizeof(QEMUFile));
5139 f->is_writable = is_writable;
5140 f->base_offset = offset;
5144 void qemu_fflush(QEMUFile *f)
5146 if (!f->is_writable)
5148 if (f->buf_index > 0) {
5150 fseek(f->outfile, f->buf_offset, SEEK_SET);
5151 fwrite(f->buf, 1, f->buf_index, f->outfile);
5153 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5154 f->buf, f->buf_index);
5156 f->buf_offset += f->buf_index;
5161 static void qemu_fill_buffer(QEMUFile *f)
5168 fseek(f->outfile, f->buf_offset, SEEK_SET);
5169 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5173 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5174 f->buf, IO_BUF_SIZE);
5180 f->buf_offset += len;
5183 void qemu_fclose(QEMUFile *f)
5193 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5197 l = IO_BUF_SIZE - f->buf_index;
5200 memcpy(f->buf + f->buf_index, buf, l);
5204 if (f->buf_index >= IO_BUF_SIZE)
5209 void qemu_put_byte(QEMUFile *f, int v)
5211 f->buf[f->buf_index++] = v;
5212 if (f->buf_index >= IO_BUF_SIZE)
5216 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5222 l = f->buf_size - f->buf_index;
5224 qemu_fill_buffer(f);
5225 l = f->buf_size - f->buf_index;
5231 memcpy(buf, f->buf + f->buf_index, l);
5236 return size1 - size;
5239 int qemu_get_byte(QEMUFile *f)
5241 if (f->buf_index >= f->buf_size) {
5242 qemu_fill_buffer(f);
5243 if (f->buf_index >= f->buf_size)
5246 return f->buf[f->buf_index++];
5249 int64_t qemu_ftell(QEMUFile *f)
5251 return f->buf_offset - f->buf_size + f->buf_index;
5254 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5256 if (whence == SEEK_SET) {
5258 } else if (whence == SEEK_CUR) {
5259 pos += qemu_ftell(f);
5261 /* SEEK_END not supported */
5264 if (f->is_writable) {
5266 f->buf_offset = pos;
5268 f->buf_offset = pos;
5275 void qemu_put_be16(QEMUFile *f, unsigned int v)
5277 qemu_put_byte(f, v >> 8);
5278 qemu_put_byte(f, v);
5281 void qemu_put_be32(QEMUFile *f, unsigned int v)
5283 qemu_put_byte(f, v >> 24);
5284 qemu_put_byte(f, v >> 16);
5285 qemu_put_byte(f, v >> 8);
5286 qemu_put_byte(f, v);
5289 void qemu_put_be64(QEMUFile *f, uint64_t v)
5291 qemu_put_be32(f, v >> 32);
5292 qemu_put_be32(f, v);
5295 unsigned int qemu_get_be16(QEMUFile *f)
5298 v = qemu_get_byte(f) << 8;
5299 v |= qemu_get_byte(f);
5303 unsigned int qemu_get_be32(QEMUFile *f)
5306 v = qemu_get_byte(f) << 24;
5307 v |= qemu_get_byte(f) << 16;
5308 v |= qemu_get_byte(f) << 8;
5309 v |= qemu_get_byte(f);
5313 uint64_t qemu_get_be64(QEMUFile *f)
5316 v = (uint64_t)qemu_get_be32(f) << 32;
5317 v |= qemu_get_be32(f);
5321 typedef struct SaveStateEntry {
5325 SaveStateHandler *save_state;
5326 LoadStateHandler *load_state;
5328 struct SaveStateEntry *next;
5331 static SaveStateEntry *first_se;
5333 int register_savevm(const char *idstr,
5336 SaveStateHandler *save_state,
5337 LoadStateHandler *load_state,
5340 SaveStateEntry *se, **pse;
5342 se = qemu_malloc(sizeof(SaveStateEntry));
5345 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5346 se->instance_id = instance_id;
5347 se->version_id = version_id;
5348 se->save_state = save_state;
5349 se->load_state = load_state;
5350 se->opaque = opaque;
5353 /* add at the end of list */
5355 while (*pse != NULL)
5356 pse = &(*pse)->next;
5361 #define QEMU_VM_FILE_MAGIC 0x5145564d
5362 #define QEMU_VM_FILE_VERSION 0x00000002
5364 static int qemu_savevm_state(QEMUFile *f)
5368 int64_t cur_pos, len_pos, total_len_pos;
5370 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5371 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5372 total_len_pos = qemu_ftell(f);
5373 qemu_put_be64(f, 0); /* total size */
5375 for(se = first_se; se != NULL; se = se->next) {
5377 len = strlen(se->idstr);
5378 qemu_put_byte(f, len);
5379 qemu_put_buffer(f, se->idstr, len);
5381 qemu_put_be32(f, se->instance_id);
5382 qemu_put_be32(f, se->version_id);
5384 /* record size: filled later */
5385 len_pos = qemu_ftell(f);
5386 qemu_put_be32(f, 0);
5387 se->save_state(f, se->opaque);
5389 /* fill record size */
5390 cur_pos = qemu_ftell(f);
5391 len = cur_pos - len_pos - 4;
5392 qemu_fseek(f, len_pos, SEEK_SET);
5393 qemu_put_be32(f, len);
5394 qemu_fseek(f, cur_pos, SEEK_SET);
5396 cur_pos = qemu_ftell(f);
5397 qemu_fseek(f, total_len_pos, SEEK_SET);
5398 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5399 qemu_fseek(f, cur_pos, SEEK_SET);
5405 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5409 for(se = first_se; se != NULL; se = se->next) {
5410 if (!strcmp(se->idstr, idstr) &&
5411 instance_id == se->instance_id)
5417 static int qemu_loadvm_state(QEMUFile *f)
5420 int len, ret, instance_id, record_len, version_id;
5421 int64_t total_len, end_pos, cur_pos;
5425 v = qemu_get_be32(f);
5426 if (v != QEMU_VM_FILE_MAGIC)
5428 v = qemu_get_be32(f);
5429 if (v != QEMU_VM_FILE_VERSION) {
5434 total_len = qemu_get_be64(f);
5435 end_pos = total_len + qemu_ftell(f);
5437 if (qemu_ftell(f) >= end_pos)
5439 len = qemu_get_byte(f);
5440 qemu_get_buffer(f, idstr, len);
5442 instance_id = qemu_get_be32(f);
5443 version_id = qemu_get_be32(f);
5444 record_len = qemu_get_be32(f);
5446 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5447 idstr, instance_id, version_id, record_len);
5449 cur_pos = qemu_ftell(f);
5450 se = find_se(idstr, instance_id);
5452 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5453 instance_id, idstr);
5455 ret = se->load_state(f, se->opaque, version_id);
5457 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5458 instance_id, idstr);
5461 /* always seek to exact end of record */
5462 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5469 /* device can contain snapshots */
5470 static int bdrv_can_snapshot(BlockDriverState *bs)
5473 !bdrv_is_removable(bs) &&
5474 !bdrv_is_read_only(bs));
5477 /* device must be snapshots in order to have a reliable snapshot */
5478 static int bdrv_has_snapshot(BlockDriverState *bs)
5481 !bdrv_is_removable(bs) &&
5482 !bdrv_is_read_only(bs));
5485 static BlockDriverState *get_bs_snapshots(void)
5487 BlockDriverState *bs;
5491 return bs_snapshots;
5492 for(i = 0; i <= MAX_DISKS; i++) {
5494 if (bdrv_can_snapshot(bs))
5503 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5506 QEMUSnapshotInfo *sn_tab, *sn;
5510 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5513 for(i = 0; i < nb_sns; i++) {
5515 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5525 void do_savevm(const char *name)
5527 BlockDriverState *bs, *bs1;
5528 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5529 int must_delete, ret, i;
5530 BlockDriverInfo bdi1, *bdi = &bdi1;
5532 int saved_vm_running;
5539 bs = get_bs_snapshots();
5541 term_printf("No block device can accept snapshots\n");
5545 /* ??? Should this occur after vm_stop? */
5548 saved_vm_running = vm_running;
5553 ret = bdrv_snapshot_find(bs, old_sn, name);
5558 memset(sn, 0, sizeof(*sn));
5560 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5561 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5564 pstrcpy(sn->name, sizeof(sn->name), name);
5567 /* fill auxiliary fields */
5570 sn->date_sec = tb.time;
5571 sn->date_nsec = tb.millitm * 1000000;
5573 gettimeofday(&tv, NULL);
5574 sn->date_sec = tv.tv_sec;
5575 sn->date_nsec = tv.tv_usec * 1000;
5577 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5579 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5580 term_printf("Device %s does not support VM state snapshots\n",
5581 bdrv_get_device_name(bs));
5585 /* save the VM state */
5586 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5588 term_printf("Could not open VM state file\n");
5591 ret = qemu_savevm_state(f);
5592 sn->vm_state_size = qemu_ftell(f);
5595 term_printf("Error %d while writing VM\n", ret);
5599 /* create the snapshots */
5601 for(i = 0; i < MAX_DISKS; i++) {
5603 if (bdrv_has_snapshot(bs1)) {
5605 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5607 term_printf("Error while deleting snapshot on '%s'\n",
5608 bdrv_get_device_name(bs1));
5611 ret = bdrv_snapshot_create(bs1, sn);
5613 term_printf("Error while creating snapshot on '%s'\n",
5614 bdrv_get_device_name(bs1));
5620 if (saved_vm_running)
5624 void do_loadvm(const char *name)
5626 BlockDriverState *bs, *bs1;
5627 BlockDriverInfo bdi1, *bdi = &bdi1;
5630 int saved_vm_running;
5632 bs = get_bs_snapshots();
5634 term_printf("No block device supports snapshots\n");
5638 /* Flush all IO requests so they don't interfere with the new state. */
5641 saved_vm_running = vm_running;
5644 for(i = 0; i <= MAX_DISKS; i++) {
5646 if (bdrv_has_snapshot(bs1)) {
5647 ret = bdrv_snapshot_goto(bs1, name);
5650 term_printf("Warning: ");
5653 term_printf("Snapshots not supported on device '%s'\n",
5654 bdrv_get_device_name(bs1));
5657 term_printf("Could not find snapshot '%s' on device '%s'\n",
5658 name, bdrv_get_device_name(bs1));
5661 term_printf("Error %d while activating snapshot on '%s'\n",
5662 ret, bdrv_get_device_name(bs1));
5665 /* fatal on snapshot block device */
5672 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5673 term_printf("Device %s does not support VM state snapshots\n",
5674 bdrv_get_device_name(bs));
5678 /* restore the VM state */
5679 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5681 term_printf("Could not open VM state file\n");
5684 ret = qemu_loadvm_state(f);
5687 term_printf("Error %d while loading VM state\n", ret);
5690 if (saved_vm_running)
5694 void do_delvm(const char *name)
5696 BlockDriverState *bs, *bs1;
5699 bs = get_bs_snapshots();
5701 term_printf("No block device supports snapshots\n");
5705 for(i = 0; i <= MAX_DISKS; i++) {
5707 if (bdrv_has_snapshot(bs1)) {
5708 ret = bdrv_snapshot_delete(bs1, name);
5710 if (ret == -ENOTSUP)
5711 term_printf("Snapshots not supported on device '%s'\n",
5712 bdrv_get_device_name(bs1));
5714 term_printf("Error %d while deleting snapshot on '%s'\n",
5715 ret, bdrv_get_device_name(bs1));
5721 void do_info_snapshots(void)
5723 BlockDriverState *bs, *bs1;
5724 QEMUSnapshotInfo *sn_tab, *sn;
5728 bs = get_bs_snapshots();
5730 term_printf("No available block device supports snapshots\n");
5733 term_printf("Snapshot devices:");
5734 for(i = 0; i <= MAX_DISKS; i++) {
5736 if (bdrv_has_snapshot(bs1)) {
5738 term_printf(" %s", bdrv_get_device_name(bs1));
5743 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5745 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5748 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5749 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5750 for(i = 0; i < nb_sns; i++) {
5752 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5757 /***********************************************************/
5758 /* cpu save/restore */
5760 #if defined(TARGET_I386)
5762 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5764 qemu_put_be32(f, dt->selector);
5765 qemu_put_betl(f, dt->base);
5766 qemu_put_be32(f, dt->limit);
5767 qemu_put_be32(f, dt->flags);
5770 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5772 dt->selector = qemu_get_be32(f);
5773 dt->base = qemu_get_betl(f);
5774 dt->limit = qemu_get_be32(f);
5775 dt->flags = qemu_get_be32(f);
5778 void cpu_save(QEMUFile *f, void *opaque)
5780 CPUState *env = opaque;
5781 uint16_t fptag, fpus, fpuc, fpregs_format;
5785 for(i = 0; i < CPU_NB_REGS; i++)
5786 qemu_put_betls(f, &env->regs[i]);
5787 qemu_put_betls(f, &env->eip);
5788 qemu_put_betls(f, &env->eflags);
5789 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5790 qemu_put_be32s(f, &hflags);
5794 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5796 for(i = 0; i < 8; i++) {
5797 fptag |= ((!env->fptags[i]) << i);
5800 qemu_put_be16s(f, &fpuc);
5801 qemu_put_be16s(f, &fpus);
5802 qemu_put_be16s(f, &fptag);
5804 #ifdef USE_X86LDOUBLE
5809 qemu_put_be16s(f, &fpregs_format);
5811 for(i = 0; i < 8; i++) {
5812 #ifdef USE_X86LDOUBLE
5816 /* we save the real CPU data (in case of MMX usage only 'mant'
5817 contains the MMX register */
5818 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5819 qemu_put_be64(f, mant);
5820 qemu_put_be16(f, exp);
5823 /* if we use doubles for float emulation, we save the doubles to
5824 avoid losing information in case of MMX usage. It can give
5825 problems if the image is restored on a CPU where long
5826 doubles are used instead. */
5827 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5831 for(i = 0; i < 6; i++)
5832 cpu_put_seg(f, &env->segs[i]);
5833 cpu_put_seg(f, &env->ldt);
5834 cpu_put_seg(f, &env->tr);
5835 cpu_put_seg(f, &env->gdt);
5836 cpu_put_seg(f, &env->idt);
5838 qemu_put_be32s(f, &env->sysenter_cs);
5839 qemu_put_be32s(f, &env->sysenter_esp);
5840 qemu_put_be32s(f, &env->sysenter_eip);
5842 qemu_put_betls(f, &env->cr[0]);
5843 qemu_put_betls(f, &env->cr[2]);
5844 qemu_put_betls(f, &env->cr[3]);
5845 qemu_put_betls(f, &env->cr[4]);
5847 for(i = 0; i < 8; i++)
5848 qemu_put_betls(f, &env->dr[i]);
5851 qemu_put_be32s(f, &env->a20_mask);
5854 qemu_put_be32s(f, &env->mxcsr);
5855 for(i = 0; i < CPU_NB_REGS; i++) {
5856 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5857 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5860 #ifdef TARGET_X86_64
5861 qemu_put_be64s(f, &env->efer);
5862 qemu_put_be64s(f, &env->star);
5863 qemu_put_be64s(f, &env->lstar);
5864 qemu_put_be64s(f, &env->cstar);
5865 qemu_put_be64s(f, &env->fmask);
5866 qemu_put_be64s(f, &env->kernelgsbase);
5868 qemu_put_be32s(f, &env->smbase);
5871 #ifdef USE_X86LDOUBLE
5872 /* XXX: add that in a FPU generic layer */
5873 union x86_longdouble {
5878 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5879 #define EXPBIAS1 1023
5880 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5881 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5883 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5887 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5888 /* exponent + sign */
5889 e = EXPD1(temp) - EXPBIAS1 + 16383;
5890 e |= SIGND1(temp) >> 16;
5895 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5897 CPUState *env = opaque;
5900 uint16_t fpus, fpuc, fptag, fpregs_format;
5902 if (version_id != 3 && version_id != 4)
5904 for(i = 0; i < CPU_NB_REGS; i++)
5905 qemu_get_betls(f, &env->regs[i]);
5906 qemu_get_betls(f, &env->eip);
5907 qemu_get_betls(f, &env->eflags);
5908 qemu_get_be32s(f, &hflags);
5910 qemu_get_be16s(f, &fpuc);
5911 qemu_get_be16s(f, &fpus);
5912 qemu_get_be16s(f, &fptag);
5913 qemu_get_be16s(f, &fpregs_format);
5915 /* NOTE: we cannot always restore the FPU state if the image come
5916 from a host with a different 'USE_X86LDOUBLE' define. We guess
5917 if we are in an MMX state to restore correctly in that case. */
5918 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5919 for(i = 0; i < 8; i++) {
5923 switch(fpregs_format) {
5925 mant = qemu_get_be64(f);
5926 exp = qemu_get_be16(f);
5927 #ifdef USE_X86LDOUBLE
5928 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5930 /* difficult case */
5932 env->fpregs[i].mmx.MMX_Q(0) = mant;
5934 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5938 mant = qemu_get_be64(f);
5939 #ifdef USE_X86LDOUBLE
5941 union x86_longdouble *p;
5942 /* difficult case */
5943 p = (void *)&env->fpregs[i];
5948 fp64_to_fp80(p, mant);
5952 env->fpregs[i].mmx.MMX_Q(0) = mant;
5961 /* XXX: restore FPU round state */
5962 env->fpstt = (fpus >> 11) & 7;
5963 env->fpus = fpus & ~0x3800;
5965 for(i = 0; i < 8; i++) {
5966 env->fptags[i] = (fptag >> i) & 1;
5969 for(i = 0; i < 6; i++)
5970 cpu_get_seg(f, &env->segs[i]);
5971 cpu_get_seg(f, &env->ldt);
5972 cpu_get_seg(f, &env->tr);
5973 cpu_get_seg(f, &env->gdt);
5974 cpu_get_seg(f, &env->idt);
5976 qemu_get_be32s(f, &env->sysenter_cs);
5977 qemu_get_be32s(f, &env->sysenter_esp);
5978 qemu_get_be32s(f, &env->sysenter_eip);
5980 qemu_get_betls(f, &env->cr[0]);
5981 qemu_get_betls(f, &env->cr[2]);
5982 qemu_get_betls(f, &env->cr[3]);
5983 qemu_get_betls(f, &env->cr[4]);
5985 for(i = 0; i < 8; i++)
5986 qemu_get_betls(f, &env->dr[i]);
5989 qemu_get_be32s(f, &env->a20_mask);
5991 qemu_get_be32s(f, &env->mxcsr);
5992 for(i = 0; i < CPU_NB_REGS; i++) {
5993 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5994 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5997 #ifdef TARGET_X86_64
5998 qemu_get_be64s(f, &env->efer);
5999 qemu_get_be64s(f, &env->star);
6000 qemu_get_be64s(f, &env->lstar);
6001 qemu_get_be64s(f, &env->cstar);
6002 qemu_get_be64s(f, &env->fmask);
6003 qemu_get_be64s(f, &env->kernelgsbase);
6005 if (version_id >= 4)
6006 qemu_get_be32s(f, &env->smbase);
6008 /* XXX: compute hflags from scratch, except for CPL and IIF */
6009 env->hflags = hflags;
6014 #elif defined(TARGET_PPC)
6015 void cpu_save(QEMUFile *f, void *opaque)
6019 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6024 #elif defined(TARGET_MIPS)
6025 void cpu_save(QEMUFile *f, void *opaque)
6029 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6034 #elif defined(TARGET_SPARC)
6035 void cpu_save(QEMUFile *f, void *opaque)
6037 CPUState *env = opaque;
6041 for(i = 0; i < 8; i++)
6042 qemu_put_betls(f, &env->gregs[i]);
6043 for(i = 0; i < NWINDOWS * 16; i++)
6044 qemu_put_betls(f, &env->regbase[i]);
6047 for(i = 0; i < TARGET_FPREGS; i++) {
6053 qemu_put_be32(f, u.i);
6056 qemu_put_betls(f, &env->pc);
6057 qemu_put_betls(f, &env->npc);
6058 qemu_put_betls(f, &env->y);
6060 qemu_put_be32(f, tmp);
6061 qemu_put_betls(f, &env->fsr);
6062 qemu_put_betls(f, &env->tbr);
6063 #ifndef TARGET_SPARC64
6064 qemu_put_be32s(f, &env->wim);
6066 for(i = 0; i < 16; i++)
6067 qemu_put_be32s(f, &env->mmuregs[i]);
6071 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6073 CPUState *env = opaque;
6077 for(i = 0; i < 8; i++)
6078 qemu_get_betls(f, &env->gregs[i]);
6079 for(i = 0; i < NWINDOWS * 16; i++)
6080 qemu_get_betls(f, &env->regbase[i]);
6083 for(i = 0; i < TARGET_FPREGS; i++) {
6088 u.i = qemu_get_be32(f);
6092 qemu_get_betls(f, &env->pc);
6093 qemu_get_betls(f, &env->npc);
6094 qemu_get_betls(f, &env->y);
6095 tmp = qemu_get_be32(f);
6096 env->cwp = 0; /* needed to ensure that the wrapping registers are
6097 correctly updated */
6099 qemu_get_betls(f, &env->fsr);
6100 qemu_get_betls(f, &env->tbr);
6101 #ifndef TARGET_SPARC64
6102 qemu_get_be32s(f, &env->wim);
6104 for(i = 0; i < 16; i++)
6105 qemu_get_be32s(f, &env->mmuregs[i]);
6111 #elif defined(TARGET_ARM)
6113 void cpu_save(QEMUFile *f, void *opaque)
6116 CPUARMState *env = (CPUARMState *)opaque;
6118 for (i = 0; i < 16; i++) {
6119 qemu_put_be32(f, env->regs[i]);
6121 qemu_put_be32(f, cpsr_read(env));
6122 qemu_put_be32(f, env->spsr);
6123 for (i = 0; i < 6; i++) {
6124 qemu_put_be32(f, env->banked_spsr[i]);
6125 qemu_put_be32(f, env->banked_r13[i]);
6126 qemu_put_be32(f, env->banked_r14[i]);
6128 for (i = 0; i < 5; i++) {
6129 qemu_put_be32(f, env->usr_regs[i]);
6130 qemu_put_be32(f, env->fiq_regs[i]);
6132 qemu_put_be32(f, env->cp15.c0_cpuid);
6133 qemu_put_be32(f, env->cp15.c0_cachetype);
6134 qemu_put_be32(f, env->cp15.c1_sys);
6135 qemu_put_be32(f, env->cp15.c1_coproc);
6136 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6137 qemu_put_be32(f, env->cp15.c2_base0);
6138 qemu_put_be32(f, env->cp15.c2_base1);
6139 qemu_put_be32(f, env->cp15.c2_mask);
6140 qemu_put_be32(f, env->cp15.c2_data);
6141 qemu_put_be32(f, env->cp15.c2_insn);
6142 qemu_put_be32(f, env->cp15.c3);
6143 qemu_put_be32(f, env->cp15.c5_insn);
6144 qemu_put_be32(f, env->cp15.c5_data);
6145 for (i = 0; i < 8; i++) {
6146 qemu_put_be32(f, env->cp15.c6_region[i]);
6148 qemu_put_be32(f, env->cp15.c6_insn);
6149 qemu_put_be32(f, env->cp15.c6_data);
6150 qemu_put_be32(f, env->cp15.c9_insn);
6151 qemu_put_be32(f, env->cp15.c9_data);
6152 qemu_put_be32(f, env->cp15.c13_fcse);
6153 qemu_put_be32(f, env->cp15.c13_context);
6154 qemu_put_be32(f, env->cp15.c13_tls1);
6155 qemu_put_be32(f, env->cp15.c13_tls2);
6156 qemu_put_be32(f, env->cp15.c13_tls3);
6157 qemu_put_be32(f, env->cp15.c15_cpar);
6159 qemu_put_be32(f, env->features);
6161 if (arm_feature(env, ARM_FEATURE_VFP)) {
6162 for (i = 0; i < 16; i++) {
6164 u.d = env->vfp.regs[i];
6165 qemu_put_be32(f, u.l.upper);
6166 qemu_put_be32(f, u.l.lower);
6168 for (i = 0; i < 16; i++) {
6169 qemu_put_be32(f, env->vfp.xregs[i]);
6172 /* TODO: Should use proper FPSCR access functions. */
6173 qemu_put_be32(f, env->vfp.vec_len);
6174 qemu_put_be32(f, env->vfp.vec_stride);
6176 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6177 for (i = 16; i < 32; i++) {
6179 u.d = env->vfp.regs[i];
6180 qemu_put_be32(f, u.l.upper);
6181 qemu_put_be32(f, u.l.lower);
6186 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6187 for (i = 0; i < 16; i++) {
6188 qemu_put_be64(f, env->iwmmxt.regs[i]);
6190 for (i = 0; i < 16; i++) {
6191 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6195 if (arm_feature(env, ARM_FEATURE_M)) {
6196 qemu_put_be32(f, env->v7m.other_sp);
6197 qemu_put_be32(f, env->v7m.vecbase);
6198 qemu_put_be32(f, env->v7m.basepri);
6199 qemu_put_be32(f, env->v7m.control);
6200 qemu_put_be32(f, env->v7m.current_sp);
6201 qemu_put_be32(f, env->v7m.exception);
6205 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6207 CPUARMState *env = (CPUARMState *)opaque;
6210 if (version_id != ARM_CPU_SAVE_VERSION)
6213 for (i = 0; i < 16; i++) {
6214 env->regs[i] = qemu_get_be32(f);
6216 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6217 env->spsr = qemu_get_be32(f);
6218 for (i = 0; i < 6; i++) {
6219 env->banked_spsr[i] = qemu_get_be32(f);
6220 env->banked_r13[i] = qemu_get_be32(f);
6221 env->banked_r14[i] = qemu_get_be32(f);
6223 for (i = 0; i < 5; i++) {
6224 env->usr_regs[i] = qemu_get_be32(f);
6225 env->fiq_regs[i] = qemu_get_be32(f);
6227 env->cp15.c0_cpuid = qemu_get_be32(f);
6228 env->cp15.c0_cachetype = qemu_get_be32(f);
6229 env->cp15.c1_sys = qemu_get_be32(f);
6230 env->cp15.c1_coproc = qemu_get_be32(f);
6231 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6232 env->cp15.c2_base0 = qemu_get_be32(f);
6233 env->cp15.c2_base1 = qemu_get_be32(f);
6234 env->cp15.c2_mask = qemu_get_be32(f);
6235 env->cp15.c2_data = qemu_get_be32(f);
6236 env->cp15.c2_insn = qemu_get_be32(f);
6237 env->cp15.c3 = qemu_get_be32(f);
6238 env->cp15.c5_insn = qemu_get_be32(f);
6239 env->cp15.c5_data = qemu_get_be32(f);
6240 for (i = 0; i < 8; i++) {
6241 env->cp15.c6_region[i] = qemu_get_be32(f);
6243 env->cp15.c6_insn = qemu_get_be32(f);
6244 env->cp15.c6_data = qemu_get_be32(f);
6245 env->cp15.c9_insn = qemu_get_be32(f);
6246 env->cp15.c9_data = qemu_get_be32(f);
6247 env->cp15.c13_fcse = qemu_get_be32(f);
6248 env->cp15.c13_context = qemu_get_be32(f);
6249 env->cp15.c13_tls1 = qemu_get_be32(f);
6250 env->cp15.c13_tls2 = qemu_get_be32(f);
6251 env->cp15.c13_tls3 = qemu_get_be32(f);
6252 env->cp15.c15_cpar = qemu_get_be32(f);
6254 env->features = qemu_get_be32(f);
6256 if (arm_feature(env, ARM_FEATURE_VFP)) {
6257 for (i = 0; i < 16; i++) {
6259 u.l.upper = qemu_get_be32(f);
6260 u.l.lower = qemu_get_be32(f);
6261 env->vfp.regs[i] = u.d;
6263 for (i = 0; i < 16; i++) {
6264 env->vfp.xregs[i] = qemu_get_be32(f);
6267 /* TODO: Should use proper FPSCR access functions. */
6268 env->vfp.vec_len = qemu_get_be32(f);
6269 env->vfp.vec_stride = qemu_get_be32(f);
6271 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6272 for (i = 0; i < 16; i++) {
6274 u.l.upper = qemu_get_be32(f);
6275 u.l.lower = qemu_get_be32(f);
6276 env->vfp.regs[i] = u.d;
6281 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6282 for (i = 0; i < 16; i++) {
6283 env->iwmmxt.regs[i] = qemu_get_be64(f);
6285 for (i = 0; i < 16; i++) {
6286 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6290 if (arm_feature(env, ARM_FEATURE_M)) {
6291 env->v7m.other_sp = qemu_get_be32(f);
6292 env->v7m.vecbase = qemu_get_be32(f);
6293 env->v7m.basepri = qemu_get_be32(f);
6294 env->v7m.control = qemu_get_be32(f);
6295 env->v7m.current_sp = qemu_get_be32(f);
6296 env->v7m.exception = qemu_get_be32(f);
6304 //#warning No CPU save/restore functions
6308 /***********************************************************/
6309 /* ram save/restore */
6311 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6315 v = qemu_get_byte(f);
6318 if (qemu_get_buffer(f, buf, len) != len)
6322 v = qemu_get_byte(f);
6323 memset(buf, v, len);
6331 static int ram_load_v1(QEMUFile *f, void *opaque)
6335 if (qemu_get_be32(f) != phys_ram_size)
6337 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6338 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6345 #define BDRV_HASH_BLOCK_SIZE 1024
6346 #define IOBUF_SIZE 4096
6347 #define RAM_CBLOCK_MAGIC 0xfabe
6349 typedef struct RamCompressState {
6352 uint8_t buf[IOBUF_SIZE];
6355 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6358 memset(s, 0, sizeof(*s));
6360 ret = deflateInit2(&s->zstream, 1,
6362 9, Z_DEFAULT_STRATEGY);
6365 s->zstream.avail_out = IOBUF_SIZE;
6366 s->zstream.next_out = s->buf;
6370 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6372 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6373 qemu_put_be16(s->f, len);
6374 qemu_put_buffer(s->f, buf, len);
6377 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6381 s->zstream.avail_in = len;
6382 s->zstream.next_in = (uint8_t *)buf;
6383 while (s->zstream.avail_in > 0) {
6384 ret = deflate(&s->zstream, Z_NO_FLUSH);
6387 if (s->zstream.avail_out == 0) {
6388 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6389 s->zstream.avail_out = IOBUF_SIZE;
6390 s->zstream.next_out = s->buf;
6396 static void ram_compress_close(RamCompressState *s)
6400 /* compress last bytes */
6402 ret = deflate(&s->zstream, Z_FINISH);
6403 if (ret == Z_OK || ret == Z_STREAM_END) {
6404 len = IOBUF_SIZE - s->zstream.avail_out;
6406 ram_put_cblock(s, s->buf, len);
6408 s->zstream.avail_out = IOBUF_SIZE;
6409 s->zstream.next_out = s->buf;
6410 if (ret == Z_STREAM_END)
6417 deflateEnd(&s->zstream);
6420 typedef struct RamDecompressState {
6423 uint8_t buf[IOBUF_SIZE];
6424 } RamDecompressState;
6426 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6429 memset(s, 0, sizeof(*s));
6431 ret = inflateInit(&s->zstream);
6437 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6441 s->zstream.avail_out = len;
6442 s->zstream.next_out = buf;
6443 while (s->zstream.avail_out > 0) {
6444 if (s->zstream.avail_in == 0) {
6445 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6447 clen = qemu_get_be16(s->f);
6448 if (clen > IOBUF_SIZE)
6450 qemu_get_buffer(s->f, s->buf, clen);
6451 s->zstream.avail_in = clen;
6452 s->zstream.next_in = s->buf;
6454 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6455 if (ret != Z_OK && ret != Z_STREAM_END) {
6462 static void ram_decompress_close(RamDecompressState *s)
6464 inflateEnd(&s->zstream);
6467 static void ram_save(QEMUFile *f, void *opaque)
6470 RamCompressState s1, *s = &s1;
6473 qemu_put_be32(f, phys_ram_size);
6474 if (ram_compress_open(s, f) < 0)
6476 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6478 if (tight_savevm_enabled) {
6482 /* find if the memory block is available on a virtual
6485 for(j = 0; j < MAX_DISKS; j++) {
6487 sector_num = bdrv_hash_find(bs_table[j],
6488 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6489 if (sector_num >= 0)
6494 goto normal_compress;
6497 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6498 ram_compress_buf(s, buf, 10);
6504 ram_compress_buf(s, buf, 1);
6505 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6508 ram_compress_close(s);
6511 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6513 RamDecompressState s1, *s = &s1;
6517 if (version_id == 1)
6518 return ram_load_v1(f, opaque);
6519 if (version_id != 2)
6521 if (qemu_get_be32(f) != phys_ram_size)
6523 if (ram_decompress_open(s, f) < 0)
6525 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6526 if (ram_decompress_buf(s, buf, 1) < 0) {
6527 fprintf(stderr, "Error while reading ram block header\n");
6531 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6532 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6541 ram_decompress_buf(s, buf + 1, 9);
6543 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6544 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6545 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6548 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6549 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6550 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6551 bs_index, sector_num);
6558 printf("Error block header\n");
6562 ram_decompress_close(s);
6566 /***********************************************************/
6567 /* bottom halves (can be seen as timers which expire ASAP) */
6576 static QEMUBH *first_bh = NULL;
6578 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6581 bh = qemu_mallocz(sizeof(QEMUBH));
6585 bh->opaque = opaque;
6589 int qemu_bh_poll(void)
6608 void qemu_bh_schedule(QEMUBH *bh)
6610 CPUState *env = cpu_single_env;
6614 bh->next = first_bh;
6617 /* stop the currently executing CPU to execute the BH ASAP */
6619 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6623 void qemu_bh_cancel(QEMUBH *bh)
6626 if (bh->scheduled) {
6629 pbh = &(*pbh)->next;
6635 void qemu_bh_delete(QEMUBH *bh)
6641 /***********************************************************/
6642 /* machine registration */
6644 QEMUMachine *first_machine = NULL;
6646 int qemu_register_machine(QEMUMachine *m)
6649 pm = &first_machine;
6657 static QEMUMachine *find_machine(const char *name)
6661 for(m = first_machine; m != NULL; m = m->next) {
6662 if (!strcmp(m->name, name))
6668 /***********************************************************/
6669 /* main execution loop */
6671 static void gui_update(void *opaque)
6673 DisplayState *ds = opaque;
6674 ds->dpy_refresh(ds);
6675 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6678 struct vm_change_state_entry {
6679 VMChangeStateHandler *cb;
6681 LIST_ENTRY (vm_change_state_entry) entries;
6684 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6686 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6689 VMChangeStateEntry *e;
6691 e = qemu_mallocz(sizeof (*e));
6697 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6701 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6703 LIST_REMOVE (e, entries);
6707 static void vm_state_notify(int running)
6709 VMChangeStateEntry *e;
6711 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6712 e->cb(e->opaque, running);
6716 /* XXX: support several handlers */
6717 static VMStopHandler *vm_stop_cb;
6718 static void *vm_stop_opaque;
6720 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6723 vm_stop_opaque = opaque;
6727 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6738 qemu_rearm_alarm_timer(alarm_timer);
6742 void vm_stop(int reason)
6745 cpu_disable_ticks();
6749 vm_stop_cb(vm_stop_opaque, reason);
6756 /* reset/shutdown handler */
6758 typedef struct QEMUResetEntry {
6759 QEMUResetHandler *func;
6761 struct QEMUResetEntry *next;
6764 static QEMUResetEntry *first_reset_entry;
6765 static int reset_requested;
6766 static int shutdown_requested;
6767 static int powerdown_requested;
6769 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6771 QEMUResetEntry **pre, *re;
6773 pre = &first_reset_entry;
6774 while (*pre != NULL)
6775 pre = &(*pre)->next;
6776 re = qemu_mallocz(sizeof(QEMUResetEntry));
6778 re->opaque = opaque;
6783 static void qemu_system_reset(void)
6787 /* reset all devices */
6788 for(re = first_reset_entry; re != NULL; re = re->next) {
6789 re->func(re->opaque);
6793 void qemu_system_reset_request(void)
6796 shutdown_requested = 1;
6798 reset_requested = 1;
6801 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6804 void qemu_system_shutdown_request(void)
6806 shutdown_requested = 1;
6808 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6811 void qemu_system_powerdown_request(void)
6813 powerdown_requested = 1;
6815 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6818 void main_loop_wait(int timeout)
6820 IOHandlerRecord *ioh;
6821 fd_set rfds, wfds, xfds;
6830 /* XXX: need to suppress polling by better using win32 events */
6832 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6833 ret |= pe->func(pe->opaque);
6838 WaitObjects *w = &wait_objects;
6840 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6841 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6842 if (w->func[ret - WAIT_OBJECT_0])
6843 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6845 /* Check for additional signaled events */
6846 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6848 /* Check if event is signaled */
6849 ret2 = WaitForSingleObject(w->events[i], 0);
6850 if(ret2 == WAIT_OBJECT_0) {
6852 w->func[i](w->opaque[i]);
6853 } else if (ret2 == WAIT_TIMEOUT) {
6855 err = GetLastError();
6856 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6859 } else if (ret == WAIT_TIMEOUT) {
6861 err = GetLastError();
6862 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6866 /* poll any events */
6867 /* XXX: separate device handlers from system ones */
6872 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6876 (!ioh->fd_read_poll ||
6877 ioh->fd_read_poll(ioh->opaque) != 0)) {
6878 FD_SET(ioh->fd, &rfds);
6882 if (ioh->fd_write) {
6883 FD_SET(ioh->fd, &wfds);
6893 tv.tv_usec = timeout * 1000;
6895 #if defined(CONFIG_SLIRP)
6897 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6900 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6902 IOHandlerRecord **pioh;
6904 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6905 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6906 ioh->fd_read(ioh->opaque);
6908 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6909 ioh->fd_write(ioh->opaque);
6913 /* remove deleted IO handlers */
6914 pioh = &first_io_handler;
6924 #if defined(CONFIG_SLIRP)
6931 slirp_select_poll(&rfds, &wfds, &xfds);
6937 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6938 qemu_get_clock(vm_clock));
6939 /* run dma transfers, if any */
6943 /* real time timers */
6944 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6945 qemu_get_clock(rt_clock));
6947 /* Check bottom-halves last in case any of the earlier events triggered
6953 static CPUState *cur_cpu;
6955 static int main_loop(void)
6958 #ifdef CONFIG_PROFILER
6963 cur_cpu = first_cpu;
6970 env = env->next_cpu;
6973 #ifdef CONFIG_PROFILER
6974 ti = profile_getclock();
6976 ret = cpu_exec(env);
6977 #ifdef CONFIG_PROFILER
6978 qemu_time += profile_getclock() - ti;
6980 if (ret == EXCP_HLT) {
6981 /* Give the next CPU a chance to run. */
6985 if (ret != EXCP_HALTED)
6987 /* all CPUs are halted ? */
6993 if (shutdown_requested) {
6994 ret = EXCP_INTERRUPT;
6997 if (reset_requested) {
6998 reset_requested = 0;
6999 qemu_system_reset();
7000 ret = EXCP_INTERRUPT;
7002 if (powerdown_requested) {
7003 powerdown_requested = 0;
7004 qemu_system_powerdown();
7005 ret = EXCP_INTERRUPT;
7007 if (ret == EXCP_DEBUG) {
7008 vm_stop(EXCP_DEBUG);
7010 /* If all cpus are halted then wait until the next IRQ */
7011 /* XXX: use timeout computed from timers */
7012 if (ret == EXCP_HALTED)
7019 #ifdef CONFIG_PROFILER
7020 ti = profile_getclock();
7022 main_loop_wait(timeout);
7023 #ifdef CONFIG_PROFILER
7024 dev_time += profile_getclock() - ti;
7027 cpu_disable_ticks();
7031 static void help(int exitcode)
7033 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7034 "usage: %s [options] [disk_image]\n"
7036 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7038 "Standard options:\n"
7039 "-M machine select emulated machine (-M ? for list)\n"
7040 "-cpu cpu select CPU (-cpu ? for list)\n"
7041 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7042 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7043 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7044 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7045 "-mtdblock file use 'file' as on-board Flash memory image\n"
7046 "-sd file use 'file' as SecureDigital card image\n"
7047 "-pflash file use 'file' as a parallel flash image\n"
7048 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7049 "-snapshot write to temporary files instead of disk image files\n"
7051 "-no-frame open SDL window without a frame and window decorations\n"
7052 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7053 "-no-quit disable SDL window close capability\n"
7056 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7058 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7059 "-smp n set the number of CPUs to 'n' [default=1]\n"
7060 "-nographic disable graphical output and redirect serial I/Os to console\n"
7061 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7063 "-k language use keyboard layout (for example \"fr\" for French)\n"
7066 "-audio-help print list of audio drivers and their options\n"
7067 "-soundhw c1,... enable audio support\n"
7068 " and only specified sound cards (comma separated list)\n"
7069 " use -soundhw ? to get the list of supported cards\n"
7070 " use -soundhw all to enable all of them\n"
7072 "-localtime set the real time clock to local time [default=utc]\n"
7073 "-full-screen start in full screen\n"
7075 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7077 "-usb enable the USB driver (will be the default soon)\n"
7078 "-usbdevice name add the host or guest USB device 'name'\n"
7079 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7080 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7082 "-name string set the name of the guest\n"
7084 "Network options:\n"
7085 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7086 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7088 "-net user[,vlan=n][,hostname=host]\n"
7089 " connect the user mode network stack to VLAN 'n' and send\n"
7090 " hostname 'host' to DHCP clients\n"
7093 "-net tap[,vlan=n],ifname=name\n"
7094 " connect the host TAP network interface to VLAN 'n'\n"
7096 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7097 " connect the host TAP network interface to VLAN 'n' and use the\n"
7098 " network scripts 'file' (default=%s)\n"
7099 " and 'dfile' (default=%s);\n"
7100 " use '[down]script=no' to disable script execution;\n"
7101 " use 'fd=h' to connect to an already opened TAP interface\n"
7103 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7104 " connect the vlan 'n' to another VLAN using a socket connection\n"
7105 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7106 " connect the vlan 'n' to multicast maddr and port\n"
7107 "-net none use it alone to have zero network devices; if no -net option\n"
7108 " is provided, the default is '-net nic -net user'\n"
7111 "-tftp dir allow tftp access to files in dir [-net user]\n"
7112 "-bootp file advertise file in BOOTP replies\n"
7114 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7116 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7117 " redirect TCP or UDP connections from host to guest [-net user]\n"
7120 "Linux boot specific:\n"
7121 "-kernel bzImage use 'bzImage' as kernel image\n"
7122 "-append cmdline use 'cmdline' as kernel command line\n"
7123 "-initrd file use 'file' as initial ram disk\n"
7125 "Debug/Expert options:\n"
7126 "-monitor dev redirect the monitor to char device 'dev'\n"
7127 "-serial dev redirect the serial port to char device 'dev'\n"
7128 "-parallel dev redirect the parallel port to char device 'dev'\n"
7129 "-pidfile file Write PID to 'file'\n"
7130 "-S freeze CPU at startup (use 'c' to start execution)\n"
7131 "-s wait gdb connection to port\n"
7132 "-p port set gdb connection port [default=%s]\n"
7133 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7134 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7135 " translation (t=none or lba) (usually qemu can guess them)\n"
7136 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7138 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7139 "-no-kqemu disable KQEMU kernel module usage\n"
7142 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7143 " (default is CL-GD5446 PCI VGA)\n"
7144 "-no-acpi disable ACPI\n"
7146 "-no-reboot exit instead of rebooting\n"
7147 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7148 "-vnc display start a VNC server on display\n"
7150 "-daemonize daemonize QEMU after initializing\n"
7152 "-option-rom rom load a file, rom, into the option ROM space\n"
7154 "-prom-env variable=value set OpenBIOS nvram variables\n"
7156 "-clock force the use of the given methods for timer alarm.\n"
7157 " To see what timers are available use -clock help\n"
7159 "During emulation, the following keys are useful:\n"
7160 "ctrl-alt-f toggle full screen\n"
7161 "ctrl-alt-n switch to virtual console 'n'\n"
7162 "ctrl-alt toggle mouse and keyboard grab\n"
7164 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7169 DEFAULT_NETWORK_SCRIPT,
7170 DEFAULT_NETWORK_DOWN_SCRIPT,
7172 DEFAULT_GDBSTUB_PORT,
7177 #define HAS_ARG 0x0001
7191 QEMU_OPTION_mtdblock,
7195 QEMU_OPTION_snapshot,
7197 QEMU_OPTION_no_fd_bootchk,
7200 QEMU_OPTION_nographic,
7201 QEMU_OPTION_portrait,
7203 QEMU_OPTION_audio_help,
7204 QEMU_OPTION_soundhw,
7224 QEMU_OPTION_no_code_copy,
7226 QEMU_OPTION_localtime,
7227 QEMU_OPTION_cirrusvga,
7230 QEMU_OPTION_std_vga,
7232 QEMU_OPTION_monitor,
7234 QEMU_OPTION_parallel,
7236 QEMU_OPTION_full_screen,
7237 QEMU_OPTION_no_frame,
7238 QEMU_OPTION_alt_grab,
7239 QEMU_OPTION_no_quit,
7240 QEMU_OPTION_pidfile,
7241 QEMU_OPTION_no_kqemu,
7242 QEMU_OPTION_kernel_kqemu,
7243 QEMU_OPTION_win2k_hack,
7245 QEMU_OPTION_usbdevice,
7248 QEMU_OPTION_no_acpi,
7249 QEMU_OPTION_no_reboot,
7250 QEMU_OPTION_show_cursor,
7251 QEMU_OPTION_daemonize,
7252 QEMU_OPTION_option_rom,
7253 QEMU_OPTION_semihosting,
7255 QEMU_OPTION_prom_env,
7256 QEMU_OPTION_old_param,
7258 QEMU_OPTION_startdate,
7261 typedef struct QEMUOption {
7267 const QEMUOption qemu_options[] = {
7268 { "h", 0, QEMU_OPTION_h },
7269 { "help", 0, QEMU_OPTION_h },
7271 { "M", HAS_ARG, QEMU_OPTION_M },
7272 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7273 { "fda", HAS_ARG, QEMU_OPTION_fda },
7274 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7275 { "hda", HAS_ARG, QEMU_OPTION_hda },
7276 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7277 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7278 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7279 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7280 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7281 { "sd", HAS_ARG, QEMU_OPTION_sd },
7282 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7283 { "boot", HAS_ARG, QEMU_OPTION_boot },
7284 { "snapshot", 0, QEMU_OPTION_snapshot },
7286 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7288 { "m", HAS_ARG, QEMU_OPTION_m },
7289 { "nographic", 0, QEMU_OPTION_nographic },
7290 { "portrait", 0, QEMU_OPTION_portrait },
7291 { "k", HAS_ARG, QEMU_OPTION_k },
7293 { "audio-help", 0, QEMU_OPTION_audio_help },
7294 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7297 { "net", HAS_ARG, QEMU_OPTION_net},
7299 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7300 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7302 { "smb", HAS_ARG, QEMU_OPTION_smb },
7304 { "redir", HAS_ARG, QEMU_OPTION_redir },
7307 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7308 { "append", HAS_ARG, QEMU_OPTION_append },
7309 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7311 { "S", 0, QEMU_OPTION_S },
7312 { "s", 0, QEMU_OPTION_s },
7313 { "p", HAS_ARG, QEMU_OPTION_p },
7314 { "d", HAS_ARG, QEMU_OPTION_d },
7315 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7316 { "L", HAS_ARG, QEMU_OPTION_L },
7317 { "bios", HAS_ARG, QEMU_OPTION_bios },
7318 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7320 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7321 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7323 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7324 { "g", 1, QEMU_OPTION_g },
7326 { "localtime", 0, QEMU_OPTION_localtime },
7327 { "std-vga", 0, QEMU_OPTION_std_vga },
7328 { "echr", HAS_ARG, QEMU_OPTION_echr },
7329 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7330 { "serial", HAS_ARG, QEMU_OPTION_serial },
7331 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7332 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7333 { "full-screen", 0, QEMU_OPTION_full_screen },
7335 { "no-frame", 0, QEMU_OPTION_no_frame },
7336 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7337 { "no-quit", 0, QEMU_OPTION_no_quit },
7339 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7340 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7341 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7342 { "smp", HAS_ARG, QEMU_OPTION_smp },
7343 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7345 /* temporary options */
7346 { "usb", 0, QEMU_OPTION_usb },
7347 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7348 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7349 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7350 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7351 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7352 { "daemonize", 0, QEMU_OPTION_daemonize },
7353 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7354 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7355 { "semihosting", 0, QEMU_OPTION_semihosting },
7357 { "name", HAS_ARG, QEMU_OPTION_name },
7358 #if defined(TARGET_SPARC)
7359 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7361 #if defined(TARGET_ARM)
7362 { "old-param", 0, QEMU_OPTION_old_param },
7364 { "clock", HAS_ARG, QEMU_OPTION_clock },
7365 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7369 /* password input */
7371 int qemu_key_check(BlockDriverState *bs, const char *name)
7376 if (!bdrv_is_encrypted(bs))
7379 term_printf("%s is encrypted.\n", name);
7380 for(i = 0; i < 3; i++) {
7381 monitor_readline("Password: ", 1, password, sizeof(password));
7382 if (bdrv_set_key(bs, password) == 0)
7384 term_printf("invalid password\n");
7389 static BlockDriverState *get_bdrv(int index)
7391 BlockDriverState *bs;
7394 bs = bs_table[index];
7395 } else if (index < 6) {
7396 bs = fd_table[index - 4];
7403 static void read_passwords(void)
7405 BlockDriverState *bs;
7408 for(i = 0; i < 6; i++) {
7411 qemu_key_check(bs, bdrv_get_device_name(bs));
7415 /* XXX: currently we cannot use simultaneously different CPUs */
7416 static void register_machines(void)
7418 #if defined(TARGET_I386)
7419 qemu_register_machine(&pc_machine);
7420 qemu_register_machine(&isapc_machine);
7421 #elif defined(TARGET_PPC)
7422 qemu_register_machine(&heathrow_machine);
7423 qemu_register_machine(&core99_machine);
7424 qemu_register_machine(&prep_machine);
7425 qemu_register_machine(&ref405ep_machine);
7426 qemu_register_machine(&taihu_machine);
7427 #elif defined(TARGET_MIPS)
7428 qemu_register_machine(&mips_machine);
7429 qemu_register_machine(&mips_malta_machine);
7430 qemu_register_machine(&mips_pica61_machine);
7431 qemu_register_machine(&mips_mipssim_machine);
7432 #elif defined(TARGET_SPARC)
7433 #ifdef TARGET_SPARC64
7434 qemu_register_machine(&sun4u_machine);
7436 qemu_register_machine(&ss5_machine);
7437 qemu_register_machine(&ss10_machine);
7438 qemu_register_machine(&ss600mp_machine);
7440 #elif defined(TARGET_ARM)
7441 qemu_register_machine(&integratorcp_machine);
7442 qemu_register_machine(&versatilepb_machine);
7443 qemu_register_machine(&versatileab_machine);
7444 qemu_register_machine(&realview_machine);
7445 qemu_register_machine(&akitapda_machine);
7446 qemu_register_machine(&spitzpda_machine);
7447 qemu_register_machine(&borzoipda_machine);
7448 qemu_register_machine(&terrierpda_machine);
7449 qemu_register_machine(&palmte_machine);
7450 qemu_register_machine(&lm3s811evb_machine);
7451 qemu_register_machine(&lm3s6965evb_machine);
7452 qemu_register_machine(&connex_machine);
7453 #elif defined(TARGET_SH4)
7454 qemu_register_machine(&shix_machine);
7455 qemu_register_machine(&r2d_machine);
7456 #elif defined(TARGET_ALPHA)
7458 #elif defined(TARGET_M68K)
7459 qemu_register_machine(&mcf5208evb_machine);
7460 qemu_register_machine(&an5206_machine);
7461 qemu_register_machine(&dummy_m68k_machine);
7462 #elif defined(TARGET_CRIS)
7463 qemu_register_machine(&bareetraxfs_machine);
7465 #error unsupported CPU
7470 struct soundhw soundhw[] = {
7471 #ifdef HAS_AUDIO_CHOICE
7478 { .init_isa = pcspk_audio_init }
7483 "Creative Sound Blaster 16",
7486 { .init_isa = SB16_init }
7493 "Yamaha YMF262 (OPL3)",
7495 "Yamaha YM3812 (OPL2)",
7499 { .init_isa = Adlib_init }
7506 "Gravis Ultrasound GF1",
7509 { .init_isa = GUS_init }
7515 "ENSONIQ AudioPCI ES1370",
7518 { .init_pci = es1370_init }
7522 { NULL, NULL, 0, 0, { NULL } }
7525 static void select_soundhw (const char *optarg)
7529 if (*optarg == '?') {
7532 printf ("Valid sound card names (comma separated):\n");
7533 for (c = soundhw; c->name; ++c) {
7534 printf ("%-11s %s\n", c->name, c->descr);
7536 printf ("\n-soundhw all will enable all of the above\n");
7537 exit (*optarg != '?');
7545 if (!strcmp (optarg, "all")) {
7546 for (c = soundhw; c->name; ++c) {
7554 e = strchr (p, ',');
7555 l = !e ? strlen (p) : (size_t) (e - p);
7557 for (c = soundhw; c->name; ++c) {
7558 if (!strncmp (c->name, p, l)) {
7567 "Unknown sound card name (too big to show)\n");
7570 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7575 p += l + (e != NULL);
7579 goto show_valid_cards;
7585 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7587 exit(STATUS_CONTROL_C_EXIT);
7592 #define MAX_NET_CLIENTS 32
7594 int main(int argc, char **argv)
7596 #ifdef CONFIG_GDBSTUB
7598 const char *gdbstub_port;
7600 uint32_t boot_devices_bitmap = 0;
7601 int i, cdrom_index, pflash_index;
7602 int snapshot, linux_boot, net_boot;
7603 const char *initrd_filename;
7604 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7605 const char *pflash_filename[MAX_PFLASH];
7606 const char *sd_filename;
7607 const char *mtd_filename;
7608 const char *kernel_filename, *kernel_cmdline;
7609 const char *boot_devices = "";
7610 DisplayState *ds = &display_state;
7611 int cyls, heads, secs, translation;
7612 char net_clients[MAX_NET_CLIENTS][256];
7615 const char *r, *optarg;
7616 CharDriverState *monitor_hd;
7617 char monitor_device[128];
7618 char serial_devices[MAX_SERIAL_PORTS][128];
7619 int serial_device_index;
7620 char parallel_devices[MAX_PARALLEL_PORTS][128];
7621 int parallel_device_index;
7622 const char *loadvm = NULL;
7623 QEMUMachine *machine;
7624 const char *cpu_model;
7625 char usb_devices[MAX_USB_CMDLINE][128];
7626 int usb_devices_index;
7628 const char *pid_file = NULL;
7631 LIST_INIT (&vm_change_state_head);
7634 struct sigaction act;
7635 sigfillset(&act.sa_mask);
7637 act.sa_handler = SIG_IGN;
7638 sigaction(SIGPIPE, &act, NULL);
7641 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7642 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7643 QEMU to run on a single CPU */
7648 h = GetCurrentProcess();
7649 if (GetProcessAffinityMask(h, &mask, &smask)) {
7650 for(i = 0; i < 32; i++) {
7651 if (mask & (1 << i))
7656 SetProcessAffinityMask(h, mask);
7662 register_machines();
7663 machine = first_machine;
7665 initrd_filename = NULL;
7666 for(i = 0; i < MAX_FD; i++)
7667 fd_filename[i] = NULL;
7668 for(i = 0; i < MAX_DISKS; i++)
7669 hd_filename[i] = NULL;
7670 for(i = 0; i < MAX_PFLASH; i++)
7671 pflash_filename[i] = NULL;
7674 mtd_filename = NULL;
7675 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7676 vga_ram_size = VGA_RAM_SIZE;
7677 #ifdef CONFIG_GDBSTUB
7679 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7683 kernel_filename = NULL;
7684 kernel_cmdline = "";
7690 cyls = heads = secs = 0;
7691 translation = BIOS_ATA_TRANSLATION_AUTO;
7692 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7694 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7695 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7696 serial_devices[i][0] = '\0';
7697 serial_device_index = 0;
7699 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7700 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7701 parallel_devices[i][0] = '\0';
7702 parallel_device_index = 0;
7704 usb_devices_index = 0;
7709 /* default mac address of the first network interface */
7717 hd_filename[0] = argv[optind++];
7719 const QEMUOption *popt;
7722 /* Treat --foo the same as -foo. */
7725 popt = qemu_options;
7728 fprintf(stderr, "%s: invalid option -- '%s'\n",
7732 if (!strcmp(popt->name, r + 1))
7736 if (popt->flags & HAS_ARG) {
7737 if (optind >= argc) {
7738 fprintf(stderr, "%s: option '%s' requires an argument\n",
7742 optarg = argv[optind++];
7747 switch(popt->index) {
7749 machine = find_machine(optarg);
7752 printf("Supported machines are:\n");
7753 for(m = first_machine; m != NULL; m = m->next) {
7754 printf("%-10s %s%s\n",
7756 m == first_machine ? " (default)" : "");
7758 exit(*optarg != '?');
7761 case QEMU_OPTION_cpu:
7762 /* hw initialization will check this */
7763 if (*optarg == '?') {
7764 /* XXX: implement xxx_cpu_list for targets that still miss it */
7765 #if defined(cpu_list)
7766 cpu_list(stdout, &fprintf);
7773 case QEMU_OPTION_initrd:
7774 initrd_filename = optarg;
7776 case QEMU_OPTION_hda:
7777 case QEMU_OPTION_hdb:
7778 case QEMU_OPTION_hdc:
7779 case QEMU_OPTION_hdd:
7782 hd_index = popt->index - QEMU_OPTION_hda;
7783 hd_filename[hd_index] = optarg;
7784 if (hd_index == cdrom_index)
7788 case QEMU_OPTION_mtdblock:
7789 mtd_filename = optarg;
7791 case QEMU_OPTION_sd:
7792 sd_filename = optarg;
7794 case QEMU_OPTION_pflash:
7795 if (pflash_index >= MAX_PFLASH) {
7796 fprintf(stderr, "qemu: too many parallel flash images\n");
7799 pflash_filename[pflash_index++] = optarg;
7801 case QEMU_OPTION_snapshot:
7804 case QEMU_OPTION_hdachs:
7808 cyls = strtol(p, (char **)&p, 0);
7809 if (cyls < 1 || cyls > 16383)
7814 heads = strtol(p, (char **)&p, 0);
7815 if (heads < 1 || heads > 16)
7820 secs = strtol(p, (char **)&p, 0);
7821 if (secs < 1 || secs > 63)
7825 if (!strcmp(p, "none"))
7826 translation = BIOS_ATA_TRANSLATION_NONE;
7827 else if (!strcmp(p, "lba"))
7828 translation = BIOS_ATA_TRANSLATION_LBA;
7829 else if (!strcmp(p, "auto"))
7830 translation = BIOS_ATA_TRANSLATION_AUTO;
7833 } else if (*p != '\0') {
7835 fprintf(stderr, "qemu: invalid physical CHS format\n");
7840 case QEMU_OPTION_nographic:
7841 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7842 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7843 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7846 case QEMU_OPTION_portrait:
7849 case QEMU_OPTION_kernel:
7850 kernel_filename = optarg;
7852 case QEMU_OPTION_append:
7853 kernel_cmdline = optarg;
7855 case QEMU_OPTION_cdrom:
7856 if (cdrom_index >= 0) {
7857 hd_filename[cdrom_index] = optarg;
7860 case QEMU_OPTION_boot:
7861 boot_devices = optarg;
7862 /* We just do some generic consistency checks */
7864 /* Could easily be extended to 64 devices if needed */
7865 const unsigned char *p;
7867 boot_devices_bitmap = 0;
7868 for (p = boot_devices; *p != '\0'; p++) {
7869 /* Allowed boot devices are:
7870 * a b : floppy disk drives
7871 * c ... f : IDE disk drives
7872 * g ... m : machine implementation dependant drives
7873 * n ... p : network devices
7874 * It's up to each machine implementation to check
7875 * if the given boot devices match the actual hardware
7876 * implementation and firmware features.
7878 if (*p < 'a' || *p > 'q') {
7879 fprintf(stderr, "Invalid boot device '%c'\n", *p);
7882 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
7884 "Boot device '%c' was given twice\n",*p);
7887 boot_devices_bitmap |= 1 << (*p - 'a');
7891 case QEMU_OPTION_fda:
7892 fd_filename[0] = optarg;
7894 case QEMU_OPTION_fdb:
7895 fd_filename[1] = optarg;
7898 case QEMU_OPTION_no_fd_bootchk:
7902 case QEMU_OPTION_no_code_copy:
7903 code_copy_enabled = 0;
7905 case QEMU_OPTION_net:
7906 if (nb_net_clients >= MAX_NET_CLIENTS) {
7907 fprintf(stderr, "qemu: too many network clients\n");
7910 pstrcpy(net_clients[nb_net_clients],
7911 sizeof(net_clients[0]),
7916 case QEMU_OPTION_tftp:
7917 tftp_prefix = optarg;
7919 case QEMU_OPTION_bootp:
7920 bootp_filename = optarg;
7923 case QEMU_OPTION_smb:
7924 net_slirp_smb(optarg);
7927 case QEMU_OPTION_redir:
7928 net_slirp_redir(optarg);
7932 case QEMU_OPTION_audio_help:
7936 case QEMU_OPTION_soundhw:
7937 select_soundhw (optarg);
7944 ram_size = atoi(optarg) * 1024 * 1024;
7947 if (ram_size > PHYS_RAM_MAX_SIZE) {
7948 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7949 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7958 mask = cpu_str_to_log_mask(optarg);
7960 printf("Log items (comma separated):\n");
7961 for(item = cpu_log_items; item->mask != 0; item++) {
7962 printf("%-10s %s\n", item->name, item->help);
7969 #ifdef CONFIG_GDBSTUB
7974 gdbstub_port = optarg;
7980 case QEMU_OPTION_bios:
7987 keyboard_layout = optarg;
7989 case QEMU_OPTION_localtime:
7992 case QEMU_OPTION_cirrusvga:
7993 cirrus_vga_enabled = 1;
7996 case QEMU_OPTION_vmsvga:
7997 cirrus_vga_enabled = 0;
8000 case QEMU_OPTION_std_vga:
8001 cirrus_vga_enabled = 0;
8009 w = strtol(p, (char **)&p, 10);
8012 fprintf(stderr, "qemu: invalid resolution or depth\n");
8018 h = strtol(p, (char **)&p, 10);
8023 depth = strtol(p, (char **)&p, 10);
8024 if (depth != 8 && depth != 15 && depth != 16 &&
8025 depth != 24 && depth != 32)
8027 } else if (*p == '\0') {
8028 depth = graphic_depth;
8035 graphic_depth = depth;
8038 case QEMU_OPTION_echr:
8041 term_escape_char = strtol(optarg, &r, 0);
8043 printf("Bad argument to echr\n");
8046 case QEMU_OPTION_monitor:
8047 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8049 case QEMU_OPTION_serial:
8050 if (serial_device_index >= MAX_SERIAL_PORTS) {
8051 fprintf(stderr, "qemu: too many serial ports\n");
8054 pstrcpy(serial_devices[serial_device_index],
8055 sizeof(serial_devices[0]), optarg);
8056 serial_device_index++;
8058 case QEMU_OPTION_parallel:
8059 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8060 fprintf(stderr, "qemu: too many parallel ports\n");
8063 pstrcpy(parallel_devices[parallel_device_index],
8064 sizeof(parallel_devices[0]), optarg);
8065 parallel_device_index++;
8067 case QEMU_OPTION_loadvm:
8070 case QEMU_OPTION_full_screen:
8074 case QEMU_OPTION_no_frame:
8077 case QEMU_OPTION_alt_grab:
8080 case QEMU_OPTION_no_quit:
8084 case QEMU_OPTION_pidfile:
8088 case QEMU_OPTION_win2k_hack:
8089 win2k_install_hack = 1;
8093 case QEMU_OPTION_no_kqemu:
8096 case QEMU_OPTION_kernel_kqemu:
8100 case QEMU_OPTION_usb:
8103 case QEMU_OPTION_usbdevice:
8105 if (usb_devices_index >= MAX_USB_CMDLINE) {
8106 fprintf(stderr, "Too many USB devices\n");
8109 pstrcpy(usb_devices[usb_devices_index],
8110 sizeof(usb_devices[usb_devices_index]),
8112 usb_devices_index++;
8114 case QEMU_OPTION_smp:
8115 smp_cpus = atoi(optarg);
8116 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8117 fprintf(stderr, "Invalid number of CPUs\n");
8121 case QEMU_OPTION_vnc:
8122 vnc_display = optarg;
8124 case QEMU_OPTION_no_acpi:
8127 case QEMU_OPTION_no_reboot:
8130 case QEMU_OPTION_show_cursor:
8133 case QEMU_OPTION_daemonize:
8136 case QEMU_OPTION_option_rom:
8137 if (nb_option_roms >= MAX_OPTION_ROMS) {
8138 fprintf(stderr, "Too many option ROMs\n");
8141 option_rom[nb_option_roms] = optarg;
8144 case QEMU_OPTION_semihosting:
8145 semihosting_enabled = 1;
8147 case QEMU_OPTION_name:
8151 case QEMU_OPTION_prom_env:
8152 if (nb_prom_envs >= MAX_PROM_ENVS) {
8153 fprintf(stderr, "Too many prom variables\n");
8156 prom_envs[nb_prom_envs] = optarg;
8161 case QEMU_OPTION_old_param:
8164 case QEMU_OPTION_clock:
8165 configure_alarms(optarg);
8167 case QEMU_OPTION_startdate:
8170 if (!strcmp(optarg, "now")) {
8171 rtc_start_date = -1;
8173 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8181 } else if (sscanf(optarg, "%d-%d-%d",
8184 &tm.tm_mday) == 3) {
8193 rtc_start_date = mktimegm(&tm);
8194 if (rtc_start_date == -1) {
8196 fprintf(stderr, "Invalid date format. Valid format are:\n"
8197 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8208 if (daemonize && !nographic && vnc_display == NULL) {
8209 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8216 if (pipe(fds) == -1)
8227 len = read(fds[0], &status, 1);
8228 if (len == -1 && (errno == EINTR))
8233 else if (status == 1) {
8234 fprintf(stderr, "Could not acquire pidfile\n");
8252 signal(SIGTSTP, SIG_IGN);
8253 signal(SIGTTOU, SIG_IGN);
8254 signal(SIGTTIN, SIG_IGN);
8258 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8261 write(fds[1], &status, 1);
8263 fprintf(stderr, "Could not acquire pid file\n");
8271 linux_boot = (kernel_filename != NULL);
8272 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8274 /* XXX: this should not be: some embedded targets just have flash */
8275 if (!linux_boot && net_boot == 0 &&
8276 hd_filename[0] == NULL &&
8277 (cdrom_index >= 0 && hd_filename[cdrom_index] == NULL) &&
8278 fd_filename[0] == NULL &&
8279 pflash_filename[0] == NULL)
8282 /* boot to floppy or the default cd if no hard disk defined yet */
8283 if (!boot_devices[0]) {
8284 if (hd_filename[0] != NULL)
8286 else if (fd_filename[0] != NULL)
8291 setvbuf(stdout, NULL, _IOLBF, 0);
8301 /* init network clients */
8302 if (nb_net_clients == 0) {
8303 /* if no clients, we use a default config */
8304 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8306 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8311 for(i = 0;i < nb_net_clients; i++) {
8312 if (net_client_init(net_clients[i]) < 0)
8315 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8316 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8318 if (vlan->nb_guest_devs == 0) {
8319 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8322 if (vlan->nb_host_devs == 0)
8324 "Warning: vlan %d is not connected to host network\n",
8329 /* XXX: this should be moved in the PC machine instanciation code */
8330 if (net_boot != 0) {
8332 for (i = 0; i < nb_nics && i < 4; i++) {
8333 const char *model = nd_table[i].model;
8335 if (net_boot & (1 << i)) {
8338 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8339 if (get_image_size(buf) > 0) {
8340 if (nb_option_roms >= MAX_OPTION_ROMS) {
8341 fprintf(stderr, "Too many option ROMs\n");
8344 option_rom[nb_option_roms] = strdup(buf);
8351 fprintf(stderr, "No valid PXE rom found for network device\n");
8357 /* init the memory */
8358 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8360 phys_ram_base = qemu_vmalloc(phys_ram_size);
8361 if (!phys_ram_base) {
8362 fprintf(stderr, "Could not allocate physical memory\n");
8366 /* we always create the cdrom drive, even if no disk is there */
8368 if (cdrom_index >= 0) {
8369 bs_table[cdrom_index] = bdrv_new("cdrom");
8370 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8373 /* open the virtual block devices */
8374 for(i = 0; i < MAX_DISKS; i++) {
8375 if (hd_filename[i]) {
8378 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8379 bs_table[i] = bdrv_new(buf);
8381 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8382 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8386 if (i == 0 && cyls != 0) {
8387 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8388 bdrv_set_translation_hint(bs_table[i], translation);
8393 /* we always create at least one floppy disk */
8394 fd_table[0] = bdrv_new("fda");
8395 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8397 for(i = 0; i < MAX_FD; i++) {
8398 if (fd_filename[i]) {
8401 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8402 fd_table[i] = bdrv_new(buf);
8403 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8405 if (fd_filename[i][0] != '\0') {
8406 if (bdrv_open(fd_table[i], fd_filename[i],
8407 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8408 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8416 /* Open the virtual parallel flash block devices */
8417 for(i = 0; i < MAX_PFLASH; i++) {
8418 if (pflash_filename[i]) {
8419 if (!pflash_table[i]) {
8421 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8422 pflash_table[i] = bdrv_new(buf);
8424 if (bdrv_open(pflash_table[i], pflash_filename[i],
8425 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8426 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8427 pflash_filename[i]);
8433 sd_bdrv = bdrv_new ("sd");
8434 /* FIXME: This isn't really a floppy, but it's a reasonable
8436 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8438 if (bdrv_open(sd_bdrv, sd_filename,
8439 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8440 fprintf(stderr, "qemu: could not open SD card image %s\n",
8443 qemu_key_check(sd_bdrv, sd_filename);
8447 mtd_bdrv = bdrv_new ("mtd");
8448 if (bdrv_open(mtd_bdrv, mtd_filename,
8449 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8450 qemu_key_check(mtd_bdrv, mtd_filename)) {
8451 fprintf(stderr, "qemu: could not open Flash image %s\n",
8453 bdrv_delete(mtd_bdrv);
8458 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8459 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8464 memset(&display_state, 0, sizeof(display_state));
8466 /* nearly nothing to do */
8467 dumb_display_init(ds);
8468 } else if (vnc_display != NULL) {
8469 vnc_display_init(ds);
8470 if (vnc_display_open(ds, vnc_display) < 0)
8473 #if defined(CONFIG_SDL)
8474 sdl_display_init(ds, full_screen, no_frame);
8475 #elif defined(CONFIG_COCOA)
8476 cocoa_display_init(ds, full_screen);
8478 dumb_display_init(ds);
8482 /* Maintain compatibility with multiple stdio monitors */
8483 if (!strcmp(monitor_device,"stdio")) {
8484 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8485 if (!strcmp(serial_devices[i],"mon:stdio")) {
8486 monitor_device[0] = '\0';
8488 } else if (!strcmp(serial_devices[i],"stdio")) {
8489 monitor_device[0] = '\0';
8490 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8495 if (monitor_device[0] != '\0') {
8496 monitor_hd = qemu_chr_open(monitor_device);
8498 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8501 monitor_init(monitor_hd, !nographic);
8504 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8505 const char *devname = serial_devices[i];
8506 if (devname[0] != '\0' && strcmp(devname, "none")) {
8507 serial_hds[i] = qemu_chr_open(devname);
8508 if (!serial_hds[i]) {
8509 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8513 if (strstart(devname, "vc", 0))
8514 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8518 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8519 const char *devname = parallel_devices[i];
8520 if (devname[0] != '\0' && strcmp(devname, "none")) {
8521 parallel_hds[i] = qemu_chr_open(devname);
8522 if (!parallel_hds[i]) {
8523 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8527 if (strstart(devname, "vc", 0))
8528 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8532 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8533 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8535 /* init USB devices */
8537 for(i = 0; i < usb_devices_index; i++) {
8538 if (usb_device_add(usb_devices[i]) < 0) {
8539 fprintf(stderr, "Warning: could not add USB device %s\n",
8545 if (display_state.dpy_refresh) {
8546 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8547 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8550 #ifdef CONFIG_GDBSTUB
8552 /* XXX: use standard host:port notation and modify options
8554 if (gdbserver_start(gdbstub_port) < 0) {
8555 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8566 /* XXX: simplify init */
8579 len = write(fds[1], &status, 1);
8580 if (len == -1 && (errno == EINTR))
8586 TFR(fd = open("/dev/null", O_RDWR));
8600 #if !defined(_WIN32)
8601 /* close network clients */
8602 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8603 VLANClientState *vc;
8605 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8606 if (vc->fd_read == tap_receive) {
8608 TAPState *s = vc->opaque;
8610 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8612 launch_script(s->down_script, ifname, s->fd);