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 void *ioport_opaque[MAX_IOPORTS];
164 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166 /* Note: drives_table[MAX_DRIVES] is a dummy block driver if none available
167 to store the VM snapshots */
168 DriveInfo drives_table[MAX_DRIVES+1];
170 /* point to the block driver where the snapshots are managed */
171 BlockDriverState *bs_snapshots;
173 static DisplayState display_state;
175 const char* keyboard_layout = NULL;
176 int64_t ticks_per_sec;
178 int pit_min_timer_count = 0;
180 NICInfo nd_table[MAX_NICS];
183 int rtc_start_date = -1; /* -1 means now */
184 int cirrus_vga_enabled = 1;
185 int vmsvga_enabled = 0;
187 int graphic_width = 1024;
188 int graphic_height = 768;
189 int graphic_depth = 8;
191 int graphic_width = 800;
192 int graphic_height = 600;
193 int graphic_depth = 15;
198 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
199 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
201 int win2k_install_hack = 0;
204 static VLANState *first_vlan;
206 const char *vnc_display;
207 #if defined(TARGET_SPARC)
209 #elif defined(TARGET_I386)
214 int acpi_enabled = 1;
218 int graphic_rotate = 0;
220 const char *option_rom[MAX_OPTION_ROMS];
222 int semihosting_enabled = 0;
227 const char *qemu_name;
230 unsigned int nb_prom_envs = 0;
231 const char *prom_envs[MAX_PROM_ENVS];
234 char drives_opt[MAX_DRIVES][1024];
236 static CPUState *cur_cpu;
237 static CPUState *next_cpu;
238 static int event_pending;
240 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
242 /***********************************************************/
243 /* x86 ISA bus support */
245 target_phys_addr_t isa_mem_base = 0;
248 static uint32_t default_ioport_readb(void *opaque, uint32_t address)
250 #ifdef DEBUG_UNUSED_IOPORT
251 fprintf(stderr, "unused inb: port=0x%04x\n", address);
256 static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
258 #ifdef DEBUG_UNUSED_IOPORT
259 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
263 /* default is to make two byte accesses */
264 static uint32_t default_ioport_readw(void *opaque, uint32_t address)
267 data = ioport_read_table[0][address](ioport_opaque[address], address);
268 address = (address + 1) & (MAX_IOPORTS - 1);
269 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
273 static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
275 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
276 address = (address + 1) & (MAX_IOPORTS - 1);
277 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
280 static uint32_t default_ioport_readl(void *opaque, uint32_t address)
282 #ifdef DEBUG_UNUSED_IOPORT
283 fprintf(stderr, "unused inl: port=0x%04x\n", address);
288 static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
290 #ifdef DEBUG_UNUSED_IOPORT
291 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
295 static void init_ioports(void)
299 for(i = 0; i < MAX_IOPORTS; i++) {
300 ioport_read_table[0][i] = default_ioport_readb;
301 ioport_write_table[0][i] = default_ioport_writeb;
302 ioport_read_table[1][i] = default_ioport_readw;
303 ioport_write_table[1][i] = default_ioport_writew;
304 ioport_read_table[2][i] = default_ioport_readl;
305 ioport_write_table[2][i] = default_ioport_writel;
309 /* size is the word size in byte */
310 int register_ioport_read(int start, int length, int size,
311 IOPortReadFunc *func, void *opaque)
317 } else if (size == 2) {
319 } else if (size == 4) {
322 hw_error("register_ioport_read: invalid size");
325 for(i = start; i < start + length; i += size) {
326 ioport_read_table[bsize][i] = func;
327 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
328 hw_error("register_ioport_read: invalid opaque");
329 ioport_opaque[i] = opaque;
334 /* size is the word size in byte */
335 int register_ioport_write(int start, int length, int size,
336 IOPortWriteFunc *func, void *opaque)
342 } else if (size == 2) {
344 } else if (size == 4) {
347 hw_error("register_ioport_write: invalid size");
350 for(i = start; i < start + length; i += size) {
351 ioport_write_table[bsize][i] = func;
352 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
353 hw_error("register_ioport_write: invalid opaque");
354 ioport_opaque[i] = opaque;
359 void isa_unassign_ioport(int start, int length)
363 for(i = start; i < start + length; i++) {
364 ioport_read_table[0][i] = default_ioport_readb;
365 ioport_read_table[1][i] = default_ioport_readw;
366 ioport_read_table[2][i] = default_ioport_readl;
368 ioport_write_table[0][i] = default_ioport_writeb;
369 ioport_write_table[1][i] = default_ioport_writew;
370 ioport_write_table[2][i] = default_ioport_writel;
374 /***********************************************************/
376 void cpu_outb(CPUState *env, int addr, int val)
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "outb: %04x %02x\n", addr, val);
382 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
385 env->last_io_time = cpu_get_time_fast();
389 void cpu_outw(CPUState *env, int addr, int val)
392 if (loglevel & CPU_LOG_IOPORT)
393 fprintf(logfile, "outw: %04x %04x\n", addr, val);
395 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
398 env->last_io_time = cpu_get_time_fast();
402 void cpu_outl(CPUState *env, int addr, int val)
405 if (loglevel & CPU_LOG_IOPORT)
406 fprintf(logfile, "outl: %04x %08x\n", addr, val);
408 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
411 env->last_io_time = cpu_get_time_fast();
415 int cpu_inb(CPUState *env, int addr)
418 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
420 if (loglevel & CPU_LOG_IOPORT)
421 fprintf(logfile, "inb : %04x %02x\n", addr, val);
425 env->last_io_time = cpu_get_time_fast();
430 int cpu_inw(CPUState *env, int addr)
433 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
435 if (loglevel & CPU_LOG_IOPORT)
436 fprintf(logfile, "inw : %04x %04x\n", addr, val);
440 env->last_io_time = cpu_get_time_fast();
445 int cpu_inl(CPUState *env, int addr)
448 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
450 if (loglevel & CPU_LOG_IOPORT)
451 fprintf(logfile, "inl : %04x %08x\n", addr, val);
455 env->last_io_time = cpu_get_time_fast();
460 /***********************************************************/
461 void hw_error(const char *fmt, ...)
467 fprintf(stderr, "qemu: hardware error: ");
468 vfprintf(stderr, fmt, ap);
469 fprintf(stderr, "\n");
470 for(env = first_cpu; env != NULL; env = env->next_cpu) {
471 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
473 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
475 cpu_dump_state(env, stderr, fprintf, 0);
482 /***********************************************************/
485 static QEMUPutKBDEvent *qemu_put_kbd_event;
486 static void *qemu_put_kbd_event_opaque;
487 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
488 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
490 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
492 qemu_put_kbd_event_opaque = opaque;
493 qemu_put_kbd_event = func;
496 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
497 void *opaque, int absolute,
500 QEMUPutMouseEntry *s, *cursor;
502 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
506 s->qemu_put_mouse_event = func;
507 s->qemu_put_mouse_event_opaque = opaque;
508 s->qemu_put_mouse_event_absolute = absolute;
509 s->qemu_put_mouse_event_name = qemu_strdup(name);
512 if (!qemu_put_mouse_event_head) {
513 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
517 cursor = qemu_put_mouse_event_head;
518 while (cursor->next != NULL)
519 cursor = cursor->next;
522 qemu_put_mouse_event_current = s;
527 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
529 QEMUPutMouseEntry *prev = NULL, *cursor;
531 if (!qemu_put_mouse_event_head || entry == NULL)
534 cursor = qemu_put_mouse_event_head;
535 while (cursor != NULL && cursor != entry) {
537 cursor = cursor->next;
540 if (cursor == NULL) // does not exist or list empty
542 else if (prev == NULL) { // entry is head
543 qemu_put_mouse_event_head = cursor->next;
544 if (qemu_put_mouse_event_current == entry)
545 qemu_put_mouse_event_current = cursor->next;
546 qemu_free(entry->qemu_put_mouse_event_name);
551 prev->next = entry->next;
553 if (qemu_put_mouse_event_current == entry)
554 qemu_put_mouse_event_current = prev;
556 qemu_free(entry->qemu_put_mouse_event_name);
560 void kbd_put_keycode(int keycode)
562 if (qemu_put_kbd_event) {
563 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
567 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
569 QEMUPutMouseEvent *mouse_event;
570 void *mouse_event_opaque;
573 if (!qemu_put_mouse_event_current) {
578 qemu_put_mouse_event_current->qemu_put_mouse_event;
580 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
583 if (graphic_rotate) {
584 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
587 width = graphic_width;
588 mouse_event(mouse_event_opaque,
589 width - dy, dx, dz, buttons_state);
591 mouse_event(mouse_event_opaque,
592 dx, dy, dz, buttons_state);
596 int kbd_mouse_is_absolute(void)
598 if (!qemu_put_mouse_event_current)
601 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
604 void do_info_mice(void)
606 QEMUPutMouseEntry *cursor;
609 if (!qemu_put_mouse_event_head) {
610 term_printf("No mouse devices connected\n");
614 term_printf("Mouse devices available:\n");
615 cursor = qemu_put_mouse_event_head;
616 while (cursor != NULL) {
617 term_printf("%c Mouse #%d: %s\n",
618 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
619 index, cursor->qemu_put_mouse_event_name);
621 cursor = cursor->next;
625 void do_mouse_set(int index)
627 QEMUPutMouseEntry *cursor;
630 if (!qemu_put_mouse_event_head) {
631 term_printf("No mouse devices connected\n");
635 cursor = qemu_put_mouse_event_head;
636 while (cursor != NULL && index != i) {
638 cursor = cursor->next;
642 qemu_put_mouse_event_current = cursor;
644 term_printf("Mouse at given index not found\n");
647 /* compute with 96 bit intermediate result: (a*b)/c */
648 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
653 #ifdef WORDS_BIGENDIAN
663 rl = (uint64_t)u.l.low * (uint64_t)b;
664 rh = (uint64_t)u.l.high * (uint64_t)b;
667 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
671 /***********************************************************/
672 /* real time host monotonic timer */
674 #define QEMU_TIMER_BASE 1000000000LL
678 static int64_t clock_freq;
680 static void init_get_clock(void)
684 ret = QueryPerformanceFrequency(&freq);
686 fprintf(stderr, "Could not calibrate ticks\n");
689 clock_freq = freq.QuadPart;
692 static int64_t get_clock(void)
695 QueryPerformanceCounter(&ti);
696 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
701 static int use_rt_clock;
703 static void init_get_clock(void)
706 #if defined(__linux__)
709 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
716 static int64_t get_clock(void)
718 #if defined(__linux__)
721 clock_gettime(CLOCK_MONOTONIC, &ts);
722 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
726 /* XXX: using gettimeofday leads to problems if the date
727 changes, so it should be avoided. */
729 gettimeofday(&tv, NULL);
730 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
736 /***********************************************************/
737 /* guest cycle counter */
739 static int64_t cpu_ticks_prev;
740 static int64_t cpu_ticks_offset;
741 static int64_t cpu_clock_offset;
742 static int cpu_ticks_enabled;
744 /* return the host CPU cycle counter and handle stop/restart */
745 int64_t cpu_get_ticks(void)
747 if (!cpu_ticks_enabled) {
748 return cpu_ticks_offset;
751 ticks = cpu_get_real_ticks();
752 if (cpu_ticks_prev > ticks) {
753 /* Note: non increasing ticks may happen if the host uses
755 cpu_ticks_offset += cpu_ticks_prev - ticks;
757 cpu_ticks_prev = ticks;
758 return ticks + cpu_ticks_offset;
762 /* return the host CPU monotonic timer and handle stop/restart */
763 static int64_t cpu_get_clock(void)
766 if (!cpu_ticks_enabled) {
767 return cpu_clock_offset;
770 return ti + cpu_clock_offset;
774 /* enable cpu_get_ticks() */
775 void cpu_enable_ticks(void)
777 if (!cpu_ticks_enabled) {
778 cpu_ticks_offset -= cpu_get_real_ticks();
779 cpu_clock_offset -= get_clock();
780 cpu_ticks_enabled = 1;
784 /* disable cpu_get_ticks() : the clock is stopped. You must not call
785 cpu_get_ticks() after that. */
786 void cpu_disable_ticks(void)
788 if (cpu_ticks_enabled) {
789 cpu_ticks_offset = cpu_get_ticks();
790 cpu_clock_offset = cpu_get_clock();
791 cpu_ticks_enabled = 0;
795 /***********************************************************/
798 #define QEMU_TIMER_REALTIME 0
799 #define QEMU_TIMER_VIRTUAL 1
803 /* XXX: add frequency */
811 struct QEMUTimer *next;
814 struct qemu_alarm_timer {
818 int (*start)(struct qemu_alarm_timer *t);
819 void (*stop)(struct qemu_alarm_timer *t);
820 void (*rearm)(struct qemu_alarm_timer *t);
824 #define ALARM_FLAG_DYNTICKS 0x1
826 static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
828 return t->flags & ALARM_FLAG_DYNTICKS;
831 static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
833 if (!alarm_has_dynticks(t))
839 /* TODO: MIN_TIMER_REARM_US should be optimized */
840 #define MIN_TIMER_REARM_US 250
842 static struct qemu_alarm_timer *alarm_timer;
846 struct qemu_alarm_win32 {
850 } alarm_win32_data = {0, NULL, -1};
852 static int win32_start_timer(struct qemu_alarm_timer *t);
853 static void win32_stop_timer(struct qemu_alarm_timer *t);
854 static void win32_rearm_timer(struct qemu_alarm_timer *t);
858 static int unix_start_timer(struct qemu_alarm_timer *t);
859 static void unix_stop_timer(struct qemu_alarm_timer *t);
863 static int dynticks_start_timer(struct qemu_alarm_timer *t);
864 static void dynticks_stop_timer(struct qemu_alarm_timer *t);
865 static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
867 static int hpet_start_timer(struct qemu_alarm_timer *t);
868 static void hpet_stop_timer(struct qemu_alarm_timer *t);
870 static int rtc_start_timer(struct qemu_alarm_timer *t);
871 static void rtc_stop_timer(struct qemu_alarm_timer *t);
873 #endif /* __linux__ */
877 static struct qemu_alarm_timer alarm_timers[] = {
880 {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
881 dynticks_stop_timer, dynticks_rearm_timer, NULL},
882 /* HPET - if available - is preferred */
883 {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
884 /* ...otherwise try RTC */
885 {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
887 {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
889 {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
890 win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
891 {"win32", 0, win32_start_timer,
892 win32_stop_timer, NULL, &alarm_win32_data},
897 static void show_available_alarms()
901 printf("Available alarm timers, in order of precedence:\n");
902 for (i = 0; alarm_timers[i].name; i++)
903 printf("%s\n", alarm_timers[i].name);
906 static void configure_alarms(char const *opt)
910 int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
914 if (!strcmp(opt, "help")) {
915 show_available_alarms();
921 /* Reorder the array */
922 name = strtok(arg, ",");
924 struct qemu_alarm_timer tmp;
926 for (i = 0; i < count && alarm_timers[i].name; i++) {
927 if (!strcmp(alarm_timers[i].name, name))
932 fprintf(stderr, "Unknown clock %s\n", name);
941 tmp = alarm_timers[i];
942 alarm_timers[i] = alarm_timers[cur];
943 alarm_timers[cur] = tmp;
947 name = strtok(NULL, ",");
953 /* Disable remaining timers */
954 for (i = cur; i < count; i++)
955 alarm_timers[i].name = NULL;
959 show_available_alarms();
965 static QEMUTimer *active_timers[2];
967 static QEMUClock *qemu_new_clock(int type)
970 clock = qemu_mallocz(sizeof(QEMUClock));
977 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
981 ts = qemu_mallocz(sizeof(QEMUTimer));
988 void qemu_free_timer(QEMUTimer *ts)
993 /* stop a timer, but do not dealloc it */
994 void qemu_del_timer(QEMUTimer *ts)
998 /* NOTE: this code must be signal safe because
999 qemu_timer_expired() can be called from a signal. */
1000 pt = &active_timers[ts->clock->type];
1013 /* modify the current timer so that it will be fired when current_time
1014 >= expire_time. The corresponding callback will be called. */
1015 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1021 /* add the timer in the sorted list */
1022 /* NOTE: this code must be signal safe because
1023 qemu_timer_expired() can be called from a signal. */
1024 pt = &active_timers[ts->clock->type];
1029 if (t->expire_time > expire_time)
1033 ts->expire_time = expire_time;
1038 int qemu_timer_pending(QEMUTimer *ts)
1041 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1048 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1052 return (timer_head->expire_time <= current_time);
1055 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1061 if (!ts || ts->expire_time > current_time)
1063 /* remove timer from the list before calling the callback */
1064 *ptimer_head = ts->next;
1067 /* run the callback (the timer list can be modified) */
1070 qemu_rearm_alarm_timer(alarm_timer);
1073 int64_t qemu_get_clock(QEMUClock *clock)
1075 switch(clock->type) {
1076 case QEMU_TIMER_REALTIME:
1077 return get_clock() / 1000000;
1079 case QEMU_TIMER_VIRTUAL:
1080 return cpu_get_clock();
1084 static void init_timers(void)
1087 ticks_per_sec = QEMU_TIMER_BASE;
1088 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1089 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1093 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1095 uint64_t expire_time;
1097 if (qemu_timer_pending(ts)) {
1098 expire_time = ts->expire_time;
1102 qemu_put_be64(f, expire_time);
1105 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1107 uint64_t expire_time;
1109 expire_time = qemu_get_be64(f);
1110 if (expire_time != -1) {
1111 qemu_mod_timer(ts, expire_time);
1117 static void timer_save(QEMUFile *f, void *opaque)
1119 if (cpu_ticks_enabled) {
1120 hw_error("cannot save state if virtual timers are running");
1122 qemu_put_be64s(f, &cpu_ticks_offset);
1123 qemu_put_be64s(f, &ticks_per_sec);
1124 qemu_put_be64s(f, &cpu_clock_offset);
1127 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1129 if (version_id != 1 && version_id != 2)
1131 if (cpu_ticks_enabled) {
1134 qemu_get_be64s(f, &cpu_ticks_offset);
1135 qemu_get_be64s(f, &ticks_per_sec);
1136 if (version_id == 2) {
1137 qemu_get_be64s(f, &cpu_clock_offset);
1143 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1144 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1146 static void host_alarm_handler(int host_signum)
1150 #define DISP_FREQ 1000
1152 static int64_t delta_min = INT64_MAX;
1153 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1155 ti = qemu_get_clock(vm_clock);
1156 if (last_clock != 0) {
1157 delta = ti - last_clock;
1158 if (delta < delta_min)
1160 if (delta > delta_max)
1163 if (++count == DISP_FREQ) {
1164 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1165 muldiv64(delta_min, 1000000, ticks_per_sec),
1166 muldiv64(delta_max, 1000000, ticks_per_sec),
1167 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1168 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1170 delta_min = INT64_MAX;
1178 if (alarm_has_dynticks(alarm_timer) ||
1179 qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1180 qemu_get_clock(vm_clock)) ||
1181 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1182 qemu_get_clock(rt_clock))) {
1184 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1185 SetEvent(data->host_alarm);
1187 CPUState *env = next_cpu;
1189 /* stop the currently executing cpu because a timer occured */
1190 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1192 if (env->kqemu_enabled) {
1193 kqemu_cpu_interrupt(env);
1200 static uint64_t qemu_next_deadline(void)
1202 int64_t nearest_delta_us = INT64_MAX;
1205 if (active_timers[QEMU_TIMER_REALTIME])
1206 nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1207 qemu_get_clock(rt_clock))*1000;
1209 if (active_timers[QEMU_TIMER_VIRTUAL]) {
1211 vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1212 qemu_get_clock(vm_clock)+999)/1000;
1213 if (vmdelta_us < nearest_delta_us)
1214 nearest_delta_us = vmdelta_us;
1217 /* Avoid arming the timer to negative, zero, or too low values */
1218 if (nearest_delta_us <= MIN_TIMER_REARM_US)
1219 nearest_delta_us = MIN_TIMER_REARM_US;
1221 return nearest_delta_us;
1226 #if defined(__linux__)
1228 #define RTC_FREQ 1024
1230 static void enable_sigio_timer(int fd)
1232 struct sigaction act;
1235 sigfillset(&act.sa_mask);
1237 act.sa_handler = host_alarm_handler;
1239 sigaction(SIGIO, &act, NULL);
1240 fcntl(fd, F_SETFL, O_ASYNC);
1241 fcntl(fd, F_SETOWN, getpid());
1244 static int hpet_start_timer(struct qemu_alarm_timer *t)
1246 struct hpet_info info;
1249 fd = open("/dev/hpet", O_RDONLY);
1254 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1256 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1257 "error, but for better emulation accuracy type:\n"
1258 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1262 /* Check capabilities */
1263 r = ioctl(fd, HPET_INFO, &info);
1267 /* Enable periodic mode */
1268 r = ioctl(fd, HPET_EPI, 0);
1269 if (info.hi_flags && (r < 0))
1272 /* Enable interrupt */
1273 r = ioctl(fd, HPET_IE_ON, 0);
1277 enable_sigio_timer(fd);
1278 t->priv = (void *)(long)fd;
1286 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1288 int fd = (long)t->priv;
1293 static int rtc_start_timer(struct qemu_alarm_timer *t)
1297 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1300 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1301 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1302 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1303 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1306 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1312 enable_sigio_timer(rtc_fd);
1314 t->priv = (void *)(long)rtc_fd;
1319 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1321 int rtc_fd = (long)t->priv;
1326 static int dynticks_start_timer(struct qemu_alarm_timer *t)
1330 struct sigaction act;
1332 sigfillset(&act.sa_mask);
1334 act.sa_handler = host_alarm_handler;
1336 sigaction(SIGALRM, &act, NULL);
1338 ev.sigev_value.sival_int = 0;
1339 ev.sigev_notify = SIGEV_SIGNAL;
1340 ev.sigev_signo = SIGALRM;
1342 if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1343 perror("timer_create");
1345 /* disable dynticks */
1346 fprintf(stderr, "Dynamic Ticks disabled\n");
1351 t->priv = (void *)host_timer;
1356 static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1358 timer_t host_timer = (timer_t)t->priv;
1360 timer_delete(host_timer);
1363 static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1365 timer_t host_timer = (timer_t)t->priv;
1366 struct itimerspec timeout;
1367 int64_t nearest_delta_us = INT64_MAX;
1370 if (!active_timers[QEMU_TIMER_REALTIME] &&
1371 !active_timers[QEMU_TIMER_VIRTUAL])
1374 nearest_delta_us = qemu_next_deadline();
1376 /* check whether a timer is already running */
1377 if (timer_gettime(host_timer, &timeout)) {
1379 fprintf(stderr, "Internal timer error: aborting\n");
1382 current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1383 if (current_us && current_us <= nearest_delta_us)
1386 timeout.it_interval.tv_sec = 0;
1387 timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1388 timeout.it_value.tv_sec = nearest_delta_us / 1000000;
1389 timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1390 if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1392 fprintf(stderr, "Internal timer error: aborting\n");
1397 #endif /* defined(__linux__) */
1399 static int unix_start_timer(struct qemu_alarm_timer *t)
1401 struct sigaction act;
1402 struct itimerval itv;
1406 sigfillset(&act.sa_mask);
1408 act.sa_handler = host_alarm_handler;
1410 sigaction(SIGALRM, &act, NULL);
1412 itv.it_interval.tv_sec = 0;
1413 /* for i386 kernel 2.6 to get 1 ms */
1414 itv.it_interval.tv_usec = 999;
1415 itv.it_value.tv_sec = 0;
1416 itv.it_value.tv_usec = 10 * 1000;
1418 err = setitimer(ITIMER_REAL, &itv, NULL);
1425 static void unix_stop_timer(struct qemu_alarm_timer *t)
1427 struct itimerval itv;
1429 memset(&itv, 0, sizeof(itv));
1430 setitimer(ITIMER_REAL, &itv, NULL);
1433 #endif /* !defined(_WIN32) */
1437 static int win32_start_timer(struct qemu_alarm_timer *t)
1440 struct qemu_alarm_win32 *data = t->priv;
1443 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1444 if (!data->host_alarm) {
1445 perror("Failed CreateEvent");
1449 memset(&tc, 0, sizeof(tc));
1450 timeGetDevCaps(&tc, sizeof(tc));
1452 if (data->period < tc.wPeriodMin)
1453 data->period = tc.wPeriodMin;
1455 timeBeginPeriod(data->period);
1457 flags = TIME_CALLBACK_FUNCTION;
1458 if (alarm_has_dynticks(t))
1459 flags |= TIME_ONESHOT;
1461 flags |= TIME_PERIODIC;
1463 data->timerId = timeSetEvent(1, // interval (ms)
1464 data->period, // resolution
1465 host_alarm_handler, // function
1466 (DWORD)t, // parameter
1469 if (!data->timerId) {
1470 perror("Failed to initialize win32 alarm timer");
1472 timeEndPeriod(data->period);
1473 CloseHandle(data->host_alarm);
1477 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1482 static void win32_stop_timer(struct qemu_alarm_timer *t)
1484 struct qemu_alarm_win32 *data = t->priv;
1486 timeKillEvent(data->timerId);
1487 timeEndPeriod(data->period);
1489 CloseHandle(data->host_alarm);
1492 static void win32_rearm_timer(struct qemu_alarm_timer *t)
1494 struct qemu_alarm_win32 *data = t->priv;
1495 uint64_t nearest_delta_us;
1497 if (!active_timers[QEMU_TIMER_REALTIME] &&
1498 !active_timers[QEMU_TIMER_VIRTUAL])
1501 nearest_delta_us = qemu_next_deadline();
1502 nearest_delta_us /= 1000;
1504 timeKillEvent(data->timerId);
1506 data->timerId = timeSetEvent(1,
1510 TIME_ONESHOT | TIME_PERIODIC);
1512 if (!data->timerId) {
1513 perror("Failed to re-arm win32 alarm timer");
1515 timeEndPeriod(data->period);
1516 CloseHandle(data->host_alarm);
1523 static void init_timer_alarm(void)
1525 struct qemu_alarm_timer *t;
1528 for (i = 0; alarm_timers[i].name; i++) {
1529 t = &alarm_timers[i];
1537 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1538 fprintf(stderr, "Terminating\n");
1545 static void quit_timers(void)
1547 alarm_timer->stop(alarm_timer);
1551 /***********************************************************/
1552 /* character device */
1554 static void qemu_chr_event(CharDriverState *s, int event)
1558 s->chr_event(s->handler_opaque, event);
1561 static void qemu_chr_reset_bh(void *opaque)
1563 CharDriverState *s = opaque;
1564 qemu_chr_event(s, CHR_EVENT_RESET);
1565 qemu_bh_delete(s->bh);
1569 void qemu_chr_reset(CharDriverState *s)
1571 if (s->bh == NULL) {
1572 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1573 qemu_bh_schedule(s->bh);
1577 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1579 return s->chr_write(s, buf, len);
1582 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1586 return s->chr_ioctl(s, cmd, arg);
1589 int qemu_chr_can_read(CharDriverState *s)
1591 if (!s->chr_can_read)
1593 return s->chr_can_read(s->handler_opaque);
1596 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1598 s->chr_read(s->handler_opaque, buf, len);
1601 void qemu_chr_accept_input(CharDriverState *s)
1603 if (s->chr_accept_input)
1604 s->chr_accept_input(s);
1607 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1612 vsnprintf(buf, sizeof(buf), fmt, ap);
1613 qemu_chr_write(s, buf, strlen(buf));
1617 void qemu_chr_send_event(CharDriverState *s, int event)
1619 if (s->chr_send_event)
1620 s->chr_send_event(s, event);
1623 void qemu_chr_add_handlers(CharDriverState *s,
1624 IOCanRWHandler *fd_can_read,
1625 IOReadHandler *fd_read,
1626 IOEventHandler *fd_event,
1629 s->chr_can_read = fd_can_read;
1630 s->chr_read = fd_read;
1631 s->chr_event = fd_event;
1632 s->handler_opaque = opaque;
1633 if (s->chr_update_read_handler)
1634 s->chr_update_read_handler(s);
1637 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1642 static CharDriverState *qemu_chr_open_null(void)
1644 CharDriverState *chr;
1646 chr = qemu_mallocz(sizeof(CharDriverState));
1649 chr->chr_write = null_chr_write;
1653 /* MUX driver for serial I/O splitting */
1654 static int term_timestamps;
1655 static int64_t term_timestamps_start;
1657 #define MUX_BUFFER_SIZE 32 /* Must be a power of 2. */
1658 #define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1660 IOCanRWHandler *chr_can_read[MAX_MUX];
1661 IOReadHandler *chr_read[MAX_MUX];
1662 IOEventHandler *chr_event[MAX_MUX];
1663 void *ext_opaque[MAX_MUX];
1664 CharDriverState *drv;
1665 unsigned char buffer[MUX_BUFFER_SIZE];
1669 int term_got_escape;
1674 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1676 MuxDriver *d = chr->opaque;
1678 if (!term_timestamps) {
1679 ret = d->drv->chr_write(d->drv, buf, len);
1684 for(i = 0; i < len; i++) {
1685 ret += d->drv->chr_write(d->drv, buf+i, 1);
1686 if (buf[i] == '\n') {
1692 if (term_timestamps_start == -1)
1693 term_timestamps_start = ti;
1694 ti -= term_timestamps_start;
1695 secs = ti / 1000000000;
1696 snprintf(buf1, sizeof(buf1),
1697 "[%02d:%02d:%02d.%03d] ",
1701 (int)((ti / 1000000) % 1000));
1702 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1709 static char *mux_help[] = {
1710 "% h print this help\n\r",
1711 "% x exit emulator\n\r",
1712 "% s save disk data back to file (if -snapshot)\n\r",
1713 "% t toggle console timestamps\n\r"
1714 "% b send break (magic sysrq)\n\r",
1715 "% c switch between console and monitor\n\r",
1720 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1721 static void mux_print_help(CharDriverState *chr)
1724 char ebuf[15] = "Escape-Char";
1725 char cbuf[50] = "\n\r";
1727 if (term_escape_char > 0 && term_escape_char < 26) {
1728 sprintf(cbuf,"\n\r");
1729 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1731 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1733 chr->chr_write(chr, cbuf, strlen(cbuf));
1734 for (i = 0; mux_help[i] != NULL; i++) {
1735 for (j=0; mux_help[i][j] != '\0'; j++) {
1736 if (mux_help[i][j] == '%')
1737 chr->chr_write(chr, ebuf, strlen(ebuf));
1739 chr->chr_write(chr, &mux_help[i][j], 1);
1744 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1746 if (d->term_got_escape) {
1747 d->term_got_escape = 0;
1748 if (ch == term_escape_char)
1753 mux_print_help(chr);
1757 char *term = "QEMU: Terminated\n\r";
1758 chr->chr_write(chr,term,strlen(term));
1765 for (i = 0; i < nb_drives; i++) {
1766 bdrv_commit(drives_table[i].bdrv);
1771 qemu_chr_event(chr, CHR_EVENT_BREAK);
1774 /* Switch to the next registered device */
1776 if (chr->focus >= d->mux_cnt)
1780 term_timestamps = !term_timestamps;
1781 term_timestamps_start = -1;
1784 } else if (ch == term_escape_char) {
1785 d->term_got_escape = 1;
1793 static void mux_chr_accept_input(CharDriverState *chr)
1796 MuxDriver *d = chr->opaque;
1798 while (d->prod != d->cons &&
1799 d->chr_can_read[m] &&
1800 d->chr_can_read[m](d->ext_opaque[m])) {
1801 d->chr_read[m](d->ext_opaque[m],
1802 &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1806 static int mux_chr_can_read(void *opaque)
1808 CharDriverState *chr = opaque;
1809 MuxDriver *d = chr->opaque;
1811 if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1813 if (d->chr_can_read[chr->focus])
1814 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1818 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1820 CharDriverState *chr = opaque;
1821 MuxDriver *d = chr->opaque;
1825 mux_chr_accept_input (opaque);
1827 for(i = 0; i < size; i++)
1828 if (mux_proc_byte(chr, d, buf[i])) {
1829 if (d->prod == d->cons &&
1830 d->chr_can_read[m] &&
1831 d->chr_can_read[m](d->ext_opaque[m]))
1832 d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1834 d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1838 static void mux_chr_event(void *opaque, int event)
1840 CharDriverState *chr = opaque;
1841 MuxDriver *d = chr->opaque;
1844 /* Send the event to all registered listeners */
1845 for (i = 0; i < d->mux_cnt; i++)
1846 if (d->chr_event[i])
1847 d->chr_event[i](d->ext_opaque[i], event);
1850 static void mux_chr_update_read_handler(CharDriverState *chr)
1852 MuxDriver *d = chr->opaque;
1854 if (d->mux_cnt >= MAX_MUX) {
1855 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1858 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1859 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1860 d->chr_read[d->mux_cnt] = chr->chr_read;
1861 d->chr_event[d->mux_cnt] = chr->chr_event;
1862 /* Fix up the real driver with mux routines */
1863 if (d->mux_cnt == 0) {
1864 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1865 mux_chr_event, chr);
1867 chr->focus = d->mux_cnt;
1871 static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1873 CharDriverState *chr;
1876 chr = qemu_mallocz(sizeof(CharDriverState));
1879 d = qemu_mallocz(sizeof(MuxDriver));
1888 chr->chr_write = mux_chr_write;
1889 chr->chr_update_read_handler = mux_chr_update_read_handler;
1890 chr->chr_accept_input = mux_chr_accept_input;
1897 static void socket_cleanup(void)
1902 static int socket_init(void)
1907 ret = WSAStartup(MAKEWORD(2,2), &Data);
1909 err = WSAGetLastError();
1910 fprintf(stderr, "WSAStartup: %d\n", err);
1913 atexit(socket_cleanup);
1917 static int send_all(int fd, const uint8_t *buf, int len1)
1923 ret = send(fd, buf, len, 0);
1926 errno = WSAGetLastError();
1927 if (errno != WSAEWOULDBLOCK) {
1930 } else if (ret == 0) {
1940 void socket_set_nonblock(int fd)
1942 unsigned long opt = 1;
1943 ioctlsocket(fd, FIONBIO, &opt);
1948 static int unix_write(int fd, const uint8_t *buf, int len1)
1954 ret = write(fd, buf, len);
1956 if (errno != EINTR && errno != EAGAIN)
1958 } else if (ret == 0) {
1968 static inline int send_all(int fd, const uint8_t *buf, int len1)
1970 return unix_write(fd, buf, len1);
1973 void socket_set_nonblock(int fd)
1975 fcntl(fd, F_SETFL, O_NONBLOCK);
1977 #endif /* !_WIN32 */
1986 #define STDIO_MAX_CLIENTS 1
1987 static int stdio_nb_clients = 0;
1989 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1991 FDCharDriver *s = chr->opaque;
1992 return unix_write(s->fd_out, buf, len);
1995 static int fd_chr_read_poll(void *opaque)
1997 CharDriverState *chr = opaque;
1998 FDCharDriver *s = chr->opaque;
2000 s->max_size = qemu_chr_can_read(chr);
2004 static void fd_chr_read(void *opaque)
2006 CharDriverState *chr = opaque;
2007 FDCharDriver *s = chr->opaque;
2012 if (len > s->max_size)
2016 size = read(s->fd_in, buf, len);
2018 /* FD has been closed. Remove it from the active list. */
2019 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2023 qemu_chr_read(chr, buf, size);
2027 static void fd_chr_update_read_handler(CharDriverState *chr)
2029 FDCharDriver *s = chr->opaque;
2031 if (s->fd_in >= 0) {
2032 if (nographic && s->fd_in == 0) {
2034 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2035 fd_chr_read, NULL, chr);
2040 /* open a character device to a unix fd */
2041 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2043 CharDriverState *chr;
2046 chr = qemu_mallocz(sizeof(CharDriverState));
2049 s = qemu_mallocz(sizeof(FDCharDriver));
2057 chr->chr_write = fd_chr_write;
2058 chr->chr_update_read_handler = fd_chr_update_read_handler;
2060 qemu_chr_reset(chr);
2065 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2069 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2072 return qemu_chr_open_fd(-1, fd_out);
2075 static CharDriverState *qemu_chr_open_pipe(const char *filename)
2078 char filename_in[256], filename_out[256];
2080 snprintf(filename_in, 256, "%s.in", filename);
2081 snprintf(filename_out, 256, "%s.out", filename);
2082 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2083 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2084 if (fd_in < 0 || fd_out < 0) {
2089 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2093 return qemu_chr_open_fd(fd_in, fd_out);
2097 /* for STDIO, we handle the case where several clients use it
2100 #define TERM_FIFO_MAX_SIZE 1
2102 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2103 static int term_fifo_size;
2105 static int stdio_read_poll(void *opaque)
2107 CharDriverState *chr = opaque;
2109 /* try to flush the queue if needed */
2110 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2111 qemu_chr_read(chr, term_fifo, 1);
2114 /* see if we can absorb more chars */
2115 if (term_fifo_size == 0)
2121 static void stdio_read(void *opaque)
2125 CharDriverState *chr = opaque;
2127 size = read(0, buf, 1);
2129 /* stdin has been closed. Remove it from the active list. */
2130 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2134 if (qemu_chr_can_read(chr) > 0) {
2135 qemu_chr_read(chr, buf, 1);
2136 } else if (term_fifo_size == 0) {
2137 term_fifo[term_fifo_size++] = buf[0];
2142 /* init terminal so that we can grab keys */
2143 static struct termios oldtty;
2144 static int old_fd0_flags;
2146 static void term_exit(void)
2148 tcsetattr (0, TCSANOW, &oldtty);
2149 fcntl(0, F_SETFL, old_fd0_flags);
2152 static void term_init(void)
2156 tcgetattr (0, &tty);
2158 old_fd0_flags = fcntl(0, F_GETFL);
2160 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2161 |INLCR|IGNCR|ICRNL|IXON);
2162 tty.c_oflag |= OPOST;
2163 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2164 /* if graphical mode, we allow Ctrl-C handling */
2166 tty.c_lflag &= ~ISIG;
2167 tty.c_cflag &= ~(CSIZE|PARENB);
2170 tty.c_cc[VTIME] = 0;
2172 tcsetattr (0, TCSANOW, &tty);
2176 fcntl(0, F_SETFL, O_NONBLOCK);
2179 static CharDriverState *qemu_chr_open_stdio(void)
2181 CharDriverState *chr;
2183 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2185 chr = qemu_chr_open_fd(0, 1);
2186 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2193 #if defined(__linux__) || defined(__sun__)
2194 static CharDriverState *qemu_chr_open_pty(void)
2197 char slave_name[1024];
2198 int master_fd, slave_fd;
2200 #if defined(__linux__)
2201 /* Not satisfying */
2202 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2207 /* Disabling local echo and line-buffered output */
2208 tcgetattr (master_fd, &tty);
2209 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2211 tty.c_cc[VTIME] = 0;
2212 tcsetattr (master_fd, TCSAFLUSH, &tty);
2214 fprintf(stderr, "char device redirected to %s\n", slave_name);
2215 return qemu_chr_open_fd(master_fd, master_fd);
2218 static void tty_serial_init(int fd, int speed,
2219 int parity, int data_bits, int stop_bits)
2225 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2226 speed, parity, data_bits, stop_bits);
2228 tcgetattr (fd, &tty);
2270 cfsetispeed(&tty, spd);
2271 cfsetospeed(&tty, spd);
2273 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2274 |INLCR|IGNCR|ICRNL|IXON);
2275 tty.c_oflag |= OPOST;
2276 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2277 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2298 tty.c_cflag |= PARENB;
2301 tty.c_cflag |= PARENB | PARODD;
2305 tty.c_cflag |= CSTOPB;
2307 tcsetattr (fd, TCSANOW, &tty);
2310 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2312 FDCharDriver *s = chr->opaque;
2315 case CHR_IOCTL_SERIAL_SET_PARAMS:
2317 QEMUSerialSetParams *ssp = arg;
2318 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2319 ssp->data_bits, ssp->stop_bits);
2322 case CHR_IOCTL_SERIAL_SET_BREAK:
2324 int enable = *(int *)arg;
2326 tcsendbreak(s->fd_in, 1);
2335 static CharDriverState *qemu_chr_open_tty(const char *filename)
2337 CharDriverState *chr;
2340 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2341 fcntl(fd, F_SETFL, O_NONBLOCK);
2342 tty_serial_init(fd, 115200, 'N', 8, 1);
2343 chr = qemu_chr_open_fd(fd, fd);
2348 chr->chr_ioctl = tty_serial_ioctl;
2349 qemu_chr_reset(chr);
2352 #else /* ! __linux__ && ! __sun__ */
2353 static CharDriverState *qemu_chr_open_pty(void)
2357 #endif /* __linux__ || __sun__ */
2359 #if defined(__linux__)
2363 } ParallelCharDriver;
2365 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2367 if (s->mode != mode) {
2369 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2376 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2378 ParallelCharDriver *drv = chr->opaque;
2383 case CHR_IOCTL_PP_READ_DATA:
2384 if (ioctl(fd, PPRDATA, &b) < 0)
2386 *(uint8_t *)arg = b;
2388 case CHR_IOCTL_PP_WRITE_DATA:
2389 b = *(uint8_t *)arg;
2390 if (ioctl(fd, PPWDATA, &b) < 0)
2393 case CHR_IOCTL_PP_READ_CONTROL:
2394 if (ioctl(fd, PPRCONTROL, &b) < 0)
2396 /* Linux gives only the lowest bits, and no way to know data
2397 direction! For better compatibility set the fixed upper
2399 *(uint8_t *)arg = b | 0xc0;
2401 case CHR_IOCTL_PP_WRITE_CONTROL:
2402 b = *(uint8_t *)arg;
2403 if (ioctl(fd, PPWCONTROL, &b) < 0)
2406 case CHR_IOCTL_PP_READ_STATUS:
2407 if (ioctl(fd, PPRSTATUS, &b) < 0)
2409 *(uint8_t *)arg = b;
2411 case CHR_IOCTL_PP_EPP_READ_ADDR:
2412 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2413 struct ParallelIOArg *parg = arg;
2414 int n = read(fd, parg->buffer, parg->count);
2415 if (n != parg->count) {
2420 case CHR_IOCTL_PP_EPP_READ:
2421 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2422 struct ParallelIOArg *parg = arg;
2423 int n = read(fd, parg->buffer, parg->count);
2424 if (n != parg->count) {
2429 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2430 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2431 struct ParallelIOArg *parg = arg;
2432 int n = write(fd, parg->buffer, parg->count);
2433 if (n != parg->count) {
2438 case CHR_IOCTL_PP_EPP_WRITE:
2439 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2440 struct ParallelIOArg *parg = arg;
2441 int n = write(fd, parg->buffer, parg->count);
2442 if (n != parg->count) {
2453 static void pp_close(CharDriverState *chr)
2455 ParallelCharDriver *drv = chr->opaque;
2458 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2459 ioctl(fd, PPRELEASE);
2464 static CharDriverState *qemu_chr_open_pp(const char *filename)
2466 CharDriverState *chr;
2467 ParallelCharDriver *drv;
2470 TFR(fd = open(filename, O_RDWR));
2474 if (ioctl(fd, PPCLAIM) < 0) {
2479 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2485 drv->mode = IEEE1284_MODE_COMPAT;
2487 chr = qemu_mallocz(sizeof(CharDriverState));
2493 chr->chr_write = null_chr_write;
2494 chr->chr_ioctl = pp_ioctl;
2495 chr->chr_close = pp_close;
2498 qemu_chr_reset(chr);
2502 #endif /* __linux__ */
2508 HANDLE hcom, hrecv, hsend;
2509 OVERLAPPED orecv, osend;
2514 #define NSENDBUF 2048
2515 #define NRECVBUF 2048
2516 #define MAXCONNECT 1
2517 #define NTIMEOUT 5000
2519 static int win_chr_poll(void *opaque);
2520 static int win_chr_pipe_poll(void *opaque);
2522 static void win_chr_close(CharDriverState *chr)
2524 WinCharState *s = chr->opaque;
2527 CloseHandle(s->hsend);
2531 CloseHandle(s->hrecv);
2535 CloseHandle(s->hcom);
2539 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2541 qemu_del_polling_cb(win_chr_poll, chr);
2544 static int win_chr_init(CharDriverState *chr, const char *filename)
2546 WinCharState *s = chr->opaque;
2548 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2553 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2555 fprintf(stderr, "Failed CreateEvent\n");
2558 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2560 fprintf(stderr, "Failed CreateEvent\n");
2564 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2565 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2566 if (s->hcom == INVALID_HANDLE_VALUE) {
2567 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2572 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2573 fprintf(stderr, "Failed SetupComm\n");
2577 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2578 size = sizeof(COMMCONFIG);
2579 GetDefaultCommConfig(filename, &comcfg, &size);
2580 comcfg.dcb.DCBlength = sizeof(DCB);
2581 CommConfigDialog(filename, NULL, &comcfg);
2583 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2584 fprintf(stderr, "Failed SetCommState\n");
2588 if (!SetCommMask(s->hcom, EV_ERR)) {
2589 fprintf(stderr, "Failed SetCommMask\n");
2593 cto.ReadIntervalTimeout = MAXDWORD;
2594 if (!SetCommTimeouts(s->hcom, &cto)) {
2595 fprintf(stderr, "Failed SetCommTimeouts\n");
2599 if (!ClearCommError(s->hcom, &err, &comstat)) {
2600 fprintf(stderr, "Failed ClearCommError\n");
2603 qemu_add_polling_cb(win_chr_poll, chr);
2611 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2613 WinCharState *s = chr->opaque;
2614 DWORD len, ret, size, err;
2617 ZeroMemory(&s->osend, sizeof(s->osend));
2618 s->osend.hEvent = s->hsend;
2621 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2623 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2625 err = GetLastError();
2626 if (err == ERROR_IO_PENDING) {
2627 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2645 static int win_chr_read_poll(CharDriverState *chr)
2647 WinCharState *s = chr->opaque;
2649 s->max_size = qemu_chr_can_read(chr);
2653 static void win_chr_readfile(CharDriverState *chr)
2655 WinCharState *s = chr->opaque;
2660 ZeroMemory(&s->orecv, sizeof(s->orecv));
2661 s->orecv.hEvent = s->hrecv;
2662 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2664 err = GetLastError();
2665 if (err == ERROR_IO_PENDING) {
2666 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2671 qemu_chr_read(chr, buf, size);
2675 static void win_chr_read(CharDriverState *chr)
2677 WinCharState *s = chr->opaque;
2679 if (s->len > s->max_size)
2680 s->len = s->max_size;
2684 win_chr_readfile(chr);
2687 static int win_chr_poll(void *opaque)
2689 CharDriverState *chr = opaque;
2690 WinCharState *s = chr->opaque;
2694 ClearCommError(s->hcom, &comerr, &status);
2695 if (status.cbInQue > 0) {
2696 s->len = status.cbInQue;
2697 win_chr_read_poll(chr);
2704 static CharDriverState *qemu_chr_open_win(const char *filename)
2706 CharDriverState *chr;
2709 chr = qemu_mallocz(sizeof(CharDriverState));
2712 s = qemu_mallocz(sizeof(WinCharState));
2718 chr->chr_write = win_chr_write;
2719 chr->chr_close = win_chr_close;
2721 if (win_chr_init(chr, filename) < 0) {
2726 qemu_chr_reset(chr);
2730 static int win_chr_pipe_poll(void *opaque)
2732 CharDriverState *chr = opaque;
2733 WinCharState *s = chr->opaque;
2736 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2739 win_chr_read_poll(chr);
2746 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2748 WinCharState *s = chr->opaque;
2756 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2758 fprintf(stderr, "Failed CreateEvent\n");
2761 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2763 fprintf(stderr, "Failed CreateEvent\n");
2767 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2768 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2769 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2771 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2772 if (s->hcom == INVALID_HANDLE_VALUE) {
2773 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2778 ZeroMemory(&ov, sizeof(ov));
2779 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2780 ret = ConnectNamedPipe(s->hcom, &ov);
2782 fprintf(stderr, "Failed ConnectNamedPipe\n");
2786 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2788 fprintf(stderr, "Failed GetOverlappedResult\n");
2790 CloseHandle(ov.hEvent);
2797 CloseHandle(ov.hEvent);
2800 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2809 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2811 CharDriverState *chr;
2814 chr = qemu_mallocz(sizeof(CharDriverState));
2817 s = qemu_mallocz(sizeof(WinCharState));
2823 chr->chr_write = win_chr_write;
2824 chr->chr_close = win_chr_close;
2826 if (win_chr_pipe_init(chr, filename) < 0) {
2831 qemu_chr_reset(chr);
2835 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2837 CharDriverState *chr;
2840 chr = qemu_mallocz(sizeof(CharDriverState));
2843 s = qemu_mallocz(sizeof(WinCharState));
2850 chr->chr_write = win_chr_write;
2851 qemu_chr_reset(chr);
2855 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2857 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2860 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2864 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2865 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2866 if (fd_out == INVALID_HANDLE_VALUE)
2869 return qemu_chr_open_win_file(fd_out);
2871 #endif /* !_WIN32 */
2873 /***********************************************************/
2874 /* UDP Net console */
2878 struct sockaddr_in daddr;
2885 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2887 NetCharDriver *s = chr->opaque;
2889 return sendto(s->fd, buf, len, 0,
2890 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2893 static int udp_chr_read_poll(void *opaque)
2895 CharDriverState *chr = opaque;
2896 NetCharDriver *s = chr->opaque;
2898 s->max_size = qemu_chr_can_read(chr);
2900 /* If there were any stray characters in the queue process them
2903 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2904 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2906 s->max_size = qemu_chr_can_read(chr);
2911 static void udp_chr_read(void *opaque)
2913 CharDriverState *chr = opaque;
2914 NetCharDriver *s = chr->opaque;
2916 if (s->max_size == 0)
2918 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2919 s->bufptr = s->bufcnt;
2924 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2925 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2927 s->max_size = qemu_chr_can_read(chr);
2931 static void udp_chr_update_read_handler(CharDriverState *chr)
2933 NetCharDriver *s = chr->opaque;
2936 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2937 udp_chr_read, NULL, chr);
2941 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2943 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2945 int parse_host_src_port(struct sockaddr_in *haddr,
2946 struct sockaddr_in *saddr,
2949 static CharDriverState *qemu_chr_open_udp(const char *def)
2951 CharDriverState *chr = NULL;
2952 NetCharDriver *s = NULL;
2954 struct sockaddr_in saddr;
2956 chr = qemu_mallocz(sizeof(CharDriverState));
2959 s = qemu_mallocz(sizeof(NetCharDriver));
2963 fd = socket(PF_INET, SOCK_DGRAM, 0);
2965 perror("socket(PF_INET, SOCK_DGRAM)");
2969 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2970 printf("Could not parse: %s\n", def);
2974 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2984 chr->chr_write = udp_chr_write;
2985 chr->chr_update_read_handler = udp_chr_update_read_handler;
2998 /***********************************************************/
2999 /* TCP Net console */
3010 static void tcp_chr_accept(void *opaque);
3012 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3014 TCPCharDriver *s = chr->opaque;
3016 return send_all(s->fd, buf, len);
3018 /* XXX: indicate an error ? */
3023 static int tcp_chr_read_poll(void *opaque)
3025 CharDriverState *chr = opaque;
3026 TCPCharDriver *s = chr->opaque;
3029 s->max_size = qemu_chr_can_read(chr);
3034 #define IAC_BREAK 243
3035 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3037 char *buf, int *size)
3039 /* Handle any telnet client's basic IAC options to satisfy char by
3040 * char mode with no echo. All IAC options will be removed from
3041 * the buf and the do_telnetopt variable will be used to track the
3042 * state of the width of the IAC information.
3044 * IAC commands come in sets of 3 bytes with the exception of the
3045 * "IAC BREAK" command and the double IAC.
3051 for (i = 0; i < *size; i++) {
3052 if (s->do_telnetopt > 1) {
3053 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3054 /* Double IAC means send an IAC */
3058 s->do_telnetopt = 1;
3060 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3061 /* Handle IAC break commands by sending a serial break */
3062 qemu_chr_event(chr, CHR_EVENT_BREAK);
3067 if (s->do_telnetopt >= 4) {
3068 s->do_telnetopt = 1;
3071 if ((unsigned char)buf[i] == IAC) {
3072 s->do_telnetopt = 2;
3083 static void tcp_chr_read(void *opaque)
3085 CharDriverState *chr = opaque;
3086 TCPCharDriver *s = chr->opaque;
3090 if (!s->connected || s->max_size <= 0)
3093 if (len > s->max_size)
3095 size = recv(s->fd, buf, len, 0);
3097 /* connection closed */
3099 if (s->listen_fd >= 0) {
3100 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3102 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3105 } else if (size > 0) {
3106 if (s->do_telnetopt)
3107 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3109 qemu_chr_read(chr, buf, size);
3113 static void tcp_chr_connect(void *opaque)
3115 CharDriverState *chr = opaque;
3116 TCPCharDriver *s = chr->opaque;
3119 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3120 tcp_chr_read, NULL, chr);
3121 qemu_chr_reset(chr);
3124 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3125 static void tcp_chr_telnet_init(int fd)
3128 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3129 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
3130 send(fd, (char *)buf, 3, 0);
3131 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
3132 send(fd, (char *)buf, 3, 0);
3133 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
3134 send(fd, (char *)buf, 3, 0);
3135 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
3136 send(fd, (char *)buf, 3, 0);
3139 static void socket_set_nodelay(int fd)
3142 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3145 static void tcp_chr_accept(void *opaque)
3147 CharDriverState *chr = opaque;
3148 TCPCharDriver *s = chr->opaque;
3149 struct sockaddr_in saddr;
3151 struct sockaddr_un uaddr;
3153 struct sockaddr *addr;
3160 len = sizeof(uaddr);
3161 addr = (struct sockaddr *)&uaddr;
3165 len = sizeof(saddr);
3166 addr = (struct sockaddr *)&saddr;
3168 fd = accept(s->listen_fd, addr, &len);
3169 if (fd < 0 && errno != EINTR) {
3171 } else if (fd >= 0) {
3172 if (s->do_telnetopt)
3173 tcp_chr_telnet_init(fd);
3177 socket_set_nonblock(fd);
3179 socket_set_nodelay(fd);
3181 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3182 tcp_chr_connect(chr);
3185 static void tcp_chr_close(CharDriverState *chr)
3187 TCPCharDriver *s = chr->opaque;
3190 if (s->listen_fd >= 0)
3191 closesocket(s->listen_fd);
3195 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3199 CharDriverState *chr = NULL;
3200 TCPCharDriver *s = NULL;
3201 int fd = -1, ret, err, val;
3203 int is_waitconnect = 1;
3206 struct sockaddr_in saddr;
3208 struct sockaddr_un uaddr;
3210 struct sockaddr *addr;
3215 addr = (struct sockaddr *)&uaddr;
3216 addrlen = sizeof(uaddr);
3217 if (parse_unix_path(&uaddr, host_str) < 0)
3222 addr = (struct sockaddr *)&saddr;
3223 addrlen = sizeof(saddr);
3224 if (parse_host_port(&saddr, host_str) < 0)
3229 while((ptr = strchr(ptr,','))) {
3231 if (!strncmp(ptr,"server",6)) {
3233 } else if (!strncmp(ptr,"nowait",6)) {
3235 } else if (!strncmp(ptr,"nodelay",6)) {
3238 printf("Unknown option: %s\n", ptr);
3245 chr = qemu_mallocz(sizeof(CharDriverState));
3248 s = qemu_mallocz(sizeof(TCPCharDriver));
3254 fd = socket(PF_UNIX, SOCK_STREAM, 0);
3257 fd = socket(PF_INET, SOCK_STREAM, 0);
3262 if (!is_waitconnect)
3263 socket_set_nonblock(fd);
3268 s->is_unix = is_unix;
3269 s->do_nodelay = do_nodelay && !is_unix;
3272 chr->chr_write = tcp_chr_write;
3273 chr->chr_close = tcp_chr_close;
3276 /* allow fast reuse */
3280 strncpy(path, uaddr.sun_path, 108);
3287 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3290 ret = bind(fd, addr, addrlen);
3294 ret = listen(fd, 0);
3299 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3301 s->do_telnetopt = 1;
3304 ret = connect(fd, addr, addrlen);
3306 err = socket_error();
3307 if (err == EINTR || err == EWOULDBLOCK) {
3308 } else if (err == EINPROGRESS) {
3311 } else if (err == WSAEALREADY) {
3323 socket_set_nodelay(fd);
3325 tcp_chr_connect(chr);
3327 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3330 if (is_listen && is_waitconnect) {
3331 printf("QEMU waiting for connection on: %s\n", host_str);
3332 tcp_chr_accept(chr);
3333 socket_set_nonblock(s->listen_fd);
3345 CharDriverState *qemu_chr_open(const char *filename)
3349 if (!strcmp(filename, "vc")) {
3350 return text_console_init(&display_state, 0);
3351 } else if (strstart(filename, "vc:", &p)) {
3352 return text_console_init(&display_state, p);
3353 } else if (!strcmp(filename, "null")) {
3354 return qemu_chr_open_null();
3356 if (strstart(filename, "tcp:", &p)) {
3357 return qemu_chr_open_tcp(p, 0, 0);
3359 if (strstart(filename, "telnet:", &p)) {
3360 return qemu_chr_open_tcp(p, 1, 0);
3362 if (strstart(filename, "udp:", &p)) {
3363 return qemu_chr_open_udp(p);
3365 if (strstart(filename, "mon:", &p)) {
3366 CharDriverState *drv = qemu_chr_open(p);
3368 drv = qemu_chr_open_mux(drv);
3369 monitor_init(drv, !nographic);
3372 printf("Unable to open driver: %s\n", p);
3376 if (strstart(filename, "unix:", &p)) {
3377 return qemu_chr_open_tcp(p, 0, 1);
3378 } else if (strstart(filename, "file:", &p)) {
3379 return qemu_chr_open_file_out(p);
3380 } else if (strstart(filename, "pipe:", &p)) {
3381 return qemu_chr_open_pipe(p);
3382 } else if (!strcmp(filename, "pty")) {
3383 return qemu_chr_open_pty();
3384 } else if (!strcmp(filename, "stdio")) {
3385 return qemu_chr_open_stdio();
3387 #if defined(__linux__)
3388 if (strstart(filename, "/dev/parport", NULL)) {
3389 return qemu_chr_open_pp(filename);
3392 #if defined(__linux__) || defined(__sun__)
3393 if (strstart(filename, "/dev/", NULL)) {
3394 return qemu_chr_open_tty(filename);
3398 if (strstart(filename, "COM", NULL)) {
3399 return qemu_chr_open_win(filename);
3401 if (strstart(filename, "pipe:", &p)) {
3402 return qemu_chr_open_win_pipe(p);
3404 if (strstart(filename, "con:", NULL)) {
3405 return qemu_chr_open_win_con(filename);
3407 if (strstart(filename, "file:", &p)) {
3408 return qemu_chr_open_win_file_out(p);
3416 void qemu_chr_close(CharDriverState *chr)
3419 chr->chr_close(chr);
3422 /***********************************************************/
3423 /* network device redirectors */
3425 __attribute__ (( unused ))
3426 static void hex_dump(FILE *f, const uint8_t *buf, int size)
3430 for(i=0;i<size;i+=16) {
3434 fprintf(f, "%08x ", i);
3437 fprintf(f, " %02x", buf[i+j]);
3442 for(j=0;j<len;j++) {
3444 if (c < ' ' || c > '~')
3446 fprintf(f, "%c", c);
3452 static int parse_macaddr(uint8_t *macaddr, const char *p)
3455 for(i = 0; i < 6; i++) {
3456 macaddr[i] = strtol(p, (char **)&p, 16);
3469 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3474 p1 = strchr(p, sep);
3480 if (len > buf_size - 1)
3482 memcpy(buf, p, len);
3489 int parse_host_src_port(struct sockaddr_in *haddr,
3490 struct sockaddr_in *saddr,
3491 const char *input_str)
3493 char *str = strdup(input_str);
3494 char *host_str = str;
3499 * Chop off any extra arguments at the end of the string which
3500 * would start with a comma, then fill in the src port information
3501 * if it was provided else use the "any address" and "any port".
3503 if ((ptr = strchr(str,',')))
3506 if ((src_str = strchr(input_str,'@'))) {
3511 if (parse_host_port(haddr, host_str) < 0)
3514 if (!src_str || *src_str == '\0')
3517 if (parse_host_port(saddr, src_str) < 0)
3528 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3536 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3538 saddr->sin_family = AF_INET;
3539 if (buf[0] == '\0') {
3540 saddr->sin_addr.s_addr = 0;
3542 if (isdigit(buf[0])) {
3543 if (!inet_aton(buf, &saddr->sin_addr))
3546 if ((he = gethostbyname(buf)) == NULL)
3548 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3551 port = strtol(p, (char **)&r, 0);
3554 saddr->sin_port = htons(port);
3559 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3564 len = MIN(108, strlen(str));
3565 p = strchr(str, ',');
3567 len = MIN(len, p - str);
3569 memset(uaddr, 0, sizeof(*uaddr));
3571 uaddr->sun_family = AF_UNIX;
3572 memcpy(uaddr->sun_path, str, len);
3578 /* find or alloc a new VLAN */
3579 VLANState *qemu_find_vlan(int id)
3581 VLANState **pvlan, *vlan;
3582 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3586 vlan = qemu_mallocz(sizeof(VLANState));
3591 pvlan = &first_vlan;
3592 while (*pvlan != NULL)
3593 pvlan = &(*pvlan)->next;
3598 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3599 IOReadHandler *fd_read,
3600 IOCanRWHandler *fd_can_read,
3603 VLANClientState *vc, **pvc;
3604 vc = qemu_mallocz(sizeof(VLANClientState));
3607 vc->fd_read = fd_read;
3608 vc->fd_can_read = fd_can_read;
3609 vc->opaque = opaque;
3613 pvc = &vlan->first_client;
3614 while (*pvc != NULL)
3615 pvc = &(*pvc)->next;
3620 int qemu_can_send_packet(VLANClientState *vc1)
3622 VLANState *vlan = vc1->vlan;
3623 VLANClientState *vc;
3625 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3627 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3634 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3636 VLANState *vlan = vc1->vlan;
3637 VLANClientState *vc;
3640 printf("vlan %d send:\n", vlan->id);
3641 hex_dump(stdout, buf, size);
3643 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3645 vc->fd_read(vc->opaque, buf, size);
3650 #if defined(CONFIG_SLIRP)
3652 /* slirp network adapter */
3654 static int slirp_inited;
3655 static VLANClientState *slirp_vc;
3657 int slirp_can_output(void)
3659 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3662 void slirp_output(const uint8_t *pkt, int pkt_len)
3665 printf("slirp output:\n");
3666 hex_dump(stdout, pkt, pkt_len);
3670 qemu_send_packet(slirp_vc, pkt, pkt_len);
3673 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3676 printf("slirp input:\n");
3677 hex_dump(stdout, buf, size);
3679 slirp_input(buf, size);
3682 static int net_slirp_init(VLANState *vlan)
3684 if (!slirp_inited) {
3688 slirp_vc = qemu_new_vlan_client(vlan,
3689 slirp_receive, NULL, NULL);
3690 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3694 static void net_slirp_redir(const char *redir_str)
3699 struct in_addr guest_addr;
3700 int host_port, guest_port;
3702 if (!slirp_inited) {
3708 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3710 if (!strcmp(buf, "tcp")) {
3712 } else if (!strcmp(buf, "udp")) {
3718 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3720 host_port = strtol(buf, &r, 0);
3724 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3726 if (buf[0] == '\0') {
3727 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3729 if (!inet_aton(buf, &guest_addr))
3732 guest_port = strtol(p, &r, 0);
3736 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3737 fprintf(stderr, "qemu: could not set up redirection\n");
3742 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3750 static void smb_exit(void)
3754 char filename[1024];
3756 /* erase all the files in the directory */
3757 d = opendir(smb_dir);
3762 if (strcmp(de->d_name, ".") != 0 &&
3763 strcmp(de->d_name, "..") != 0) {
3764 snprintf(filename, sizeof(filename), "%s/%s",
3765 smb_dir, de->d_name);
3773 /* automatic user mode samba server configuration */
3774 static void net_slirp_smb(const char *exported_dir)
3776 char smb_conf[1024];
3777 char smb_cmdline[1024];
3780 if (!slirp_inited) {
3785 /* XXX: better tmp dir construction */
3786 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3787 if (mkdir(smb_dir, 0700) < 0) {
3788 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3791 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3793 f = fopen(smb_conf, "w");
3795 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3802 "socket address=127.0.0.1\n"
3803 "pid directory=%s\n"
3804 "lock directory=%s\n"
3805 "log file=%s/log.smbd\n"
3806 "smb passwd file=%s/smbpasswd\n"
3807 "security = share\n"
3822 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3823 SMBD_COMMAND, smb_conf);
3825 slirp_add_exec(0, smb_cmdline, 4, 139);
3828 #endif /* !defined(_WIN32) */
3829 void do_info_slirp(void)
3834 #endif /* CONFIG_SLIRP */
3836 #if !defined(_WIN32)
3838 typedef struct TAPState {
3839 VLANClientState *vc;
3841 char down_script[1024];
3844 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3846 TAPState *s = opaque;
3849 ret = write(s->fd, buf, size);
3850 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3857 static void tap_send(void *opaque)
3859 TAPState *s = opaque;
3866 sbuf.maxlen = sizeof(buf);
3868 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3870 size = read(s->fd, buf, sizeof(buf));
3873 qemu_send_packet(s->vc, buf, size);
3879 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3883 s = qemu_mallocz(sizeof(TAPState));
3887 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3888 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3889 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3893 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3894 static int tap_open(char *ifname, int ifname_size)
3900 TFR(fd = open("/dev/tap", O_RDWR));
3902 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3907 dev = devname(s.st_rdev, S_IFCHR);
3908 pstrcpy(ifname, ifname_size, dev);
3910 fcntl(fd, F_SETFL, O_NONBLOCK);
3913 #elif defined(__sun__)
3914 #define TUNNEWPPA (('T'<<16) | 0x0001)
3916 * Allocate TAP device, returns opened fd.
3917 * Stores dev name in the first arg(must be large enough).
3919 int tap_alloc(char *dev)
3921 int tap_fd, if_fd, ppa = -1;
3922 static int ip_fd = 0;
3925 static int arp_fd = 0;
3926 int ip_muxid, arp_muxid;
3927 struct strioctl strioc_if, strioc_ppa;
3928 int link_type = I_PLINK;;
3930 char actual_name[32] = "";
3932 memset(&ifr, 0x0, sizeof(ifr));
3936 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3940 /* Check if IP device was opened */
3944 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3946 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3950 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3952 syslog(LOG_ERR, "Can't open /dev/tap");
3956 /* Assign a new PPA and get its unit number. */
3957 strioc_ppa.ic_cmd = TUNNEWPPA;
3958 strioc_ppa.ic_timout = 0;
3959 strioc_ppa.ic_len = sizeof(ppa);
3960 strioc_ppa.ic_dp = (char *)&ppa;
3961 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3962 syslog (LOG_ERR, "Can't assign new interface");
3964 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3966 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3969 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3970 syslog(LOG_ERR, "Can't push IP module");
3974 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3975 syslog(LOG_ERR, "Can't get flags\n");
3977 snprintf (actual_name, 32, "tap%d", ppa);
3978 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3981 /* Assign ppa according to the unit number returned by tun device */
3983 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3984 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3985 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3986 syslog (LOG_ERR, "Can't get flags\n");
3987 /* Push arp module to if_fd */
3988 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3989 syslog (LOG_ERR, "Can't push ARP module (2)");
3991 /* Push arp module to ip_fd */
3992 if (ioctl (ip_fd, I_POP, NULL) < 0)
3993 syslog (LOG_ERR, "I_POP failed\n");
3994 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3995 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3997 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3999 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4001 /* Set ifname to arp */
4002 strioc_if.ic_cmd = SIOCSLIFNAME;
4003 strioc_if.ic_timout = 0;
4004 strioc_if.ic_len = sizeof(ifr);
4005 strioc_if.ic_dp = (char *)𝔦
4006 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4007 syslog (LOG_ERR, "Can't set ifname to arp\n");
4010 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4011 syslog(LOG_ERR, "Can't link TAP device to IP");
4015 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4016 syslog (LOG_ERR, "Can't link TAP device to ARP");
4020 memset(&ifr, 0x0, sizeof(ifr));
4021 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4022 ifr.lifr_ip_muxid = ip_muxid;
4023 ifr.lifr_arp_muxid = arp_muxid;
4025 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4027 ioctl (ip_fd, I_PUNLINK , arp_muxid);
4028 ioctl (ip_fd, I_PUNLINK, ip_muxid);
4029 syslog (LOG_ERR, "Can't set multiplexor id");
4032 sprintf(dev, "tap%d", ppa);
4036 static int tap_open(char *ifname, int ifname_size)
4040 if( (fd = tap_alloc(dev)) < 0 ){
4041 fprintf(stderr, "Cannot allocate TAP device\n");
4044 pstrcpy(ifname, ifname_size, dev);
4045 fcntl(fd, F_SETFL, O_NONBLOCK);
4049 static int tap_open(char *ifname, int ifname_size)
4054 TFR(fd = open("/dev/net/tun", O_RDWR));
4056 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4059 memset(&ifr, 0, sizeof(ifr));
4060 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4061 if (ifname[0] != '\0')
4062 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4064 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4065 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4067 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4071 pstrcpy(ifname, ifname_size, ifr.ifr_name);
4072 fcntl(fd, F_SETFL, O_NONBLOCK);
4077 static int launch_script(const char *setup_script, const char *ifname, int fd)
4083 /* try to launch network script */
4087 int open_max = sysconf (_SC_OPEN_MAX), i;
4088 for (i = 0; i < open_max; i++)
4089 if (i != STDIN_FILENO &&
4090 i != STDOUT_FILENO &&
4091 i != STDERR_FILENO &&
4096 *parg++ = (char *)setup_script;
4097 *parg++ = (char *)ifname;
4099 execv(setup_script, args);
4102 while (waitpid(pid, &status, 0) != pid);
4103 if (!WIFEXITED(status) ||
4104 WEXITSTATUS(status) != 0) {
4105 fprintf(stderr, "%s: could not launch network script\n",
4113 static int net_tap_init(VLANState *vlan, const char *ifname1,
4114 const char *setup_script, const char *down_script)
4120 if (ifname1 != NULL)
4121 pstrcpy(ifname, sizeof(ifname), ifname1);
4124 TFR(fd = tap_open(ifname, sizeof(ifname)));
4128 if (!setup_script || !strcmp(setup_script, "no"))
4130 if (setup_script[0] != '\0') {
4131 if (launch_script(setup_script, ifname, fd))
4134 s = net_tap_fd_init(vlan, fd);
4137 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4138 "tap: ifname=%s setup_script=%s", ifname, setup_script);
4139 if (down_script && strcmp(down_script, "no"))
4140 snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4144 #endif /* !_WIN32 */
4146 /* network connection */
4147 typedef struct NetSocketState {
4148 VLANClientState *vc;
4150 int state; /* 0 = getting length, 1 = getting data */
4154 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4157 typedef struct NetSocketListenState {
4160 } NetSocketListenState;
4162 /* XXX: we consider we can send the whole packet without blocking */
4163 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4165 NetSocketState *s = opaque;
4169 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4170 send_all(s->fd, buf, size);
4173 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4175 NetSocketState *s = opaque;
4176 sendto(s->fd, buf, size, 0,
4177 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4180 static void net_socket_send(void *opaque)
4182 NetSocketState *s = opaque;
4187 size = recv(s->fd, buf1, sizeof(buf1), 0);
4189 err = socket_error();
4190 if (err != EWOULDBLOCK)
4192 } else if (size == 0) {
4193 /* end of connection */
4195 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4201 /* reassemble a packet from the network */
4207 memcpy(s->buf + s->index, buf, l);
4211 if (s->index == 4) {
4213 s->packet_len = ntohl(*(uint32_t *)s->buf);
4219 l = s->packet_len - s->index;
4222 memcpy(s->buf + s->index, buf, l);
4226 if (s->index >= s->packet_len) {
4227 qemu_send_packet(s->vc, s->buf, s->packet_len);
4236 static void net_socket_send_dgram(void *opaque)
4238 NetSocketState *s = opaque;
4241 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4245 /* end of connection */
4246 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4249 qemu_send_packet(s->vc, s->buf, size);
4252 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4257 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4258 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4259 inet_ntoa(mcastaddr->sin_addr),
4260 (int)ntohl(mcastaddr->sin_addr.s_addr));
4264 fd = socket(PF_INET, SOCK_DGRAM, 0);
4266 perror("socket(PF_INET, SOCK_DGRAM)");
4271 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4272 (const char *)&val, sizeof(val));
4274 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4278 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4284 /* Add host to multicast group */
4285 imr.imr_multiaddr = mcastaddr->sin_addr;
4286 imr.imr_interface.s_addr = htonl(INADDR_ANY);
4288 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4289 (const char *)&imr, sizeof(struct ip_mreq));
4291 perror("setsockopt(IP_ADD_MEMBERSHIP)");
4295 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4297 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4298 (const char *)&val, sizeof(val));
4300 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4304 socket_set_nonblock(fd);
4312 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4315 struct sockaddr_in saddr;
4317 socklen_t saddr_len;
4320 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4321 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4322 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4326 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4328 if (saddr.sin_addr.s_addr==0) {
4329 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4333 /* clone dgram socket */
4334 newfd = net_socket_mcast_create(&saddr);
4336 /* error already reported by net_socket_mcast_create() */
4340 /* clone newfd to fd, close newfd */
4345 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4346 fd, strerror(errno));
4351 s = qemu_mallocz(sizeof(NetSocketState));
4356 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4357 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4359 /* mcast: save bound address as dst */
4360 if (is_connected) s->dgram_dst=saddr;
4362 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4363 "socket: fd=%d (%s mcast=%s:%d)",
4364 fd, is_connected? "cloned" : "",
4365 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4369 static void net_socket_connect(void *opaque)
4371 NetSocketState *s = opaque;
4372 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4375 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4379 s = qemu_mallocz(sizeof(NetSocketState));
4383 s->vc = qemu_new_vlan_client(vlan,
4384 net_socket_receive, NULL, s);
4385 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4386 "socket: fd=%d", fd);
4388 net_socket_connect(s);
4390 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4395 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4398 int so_type=-1, optlen=sizeof(so_type);
4400 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4401 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4406 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4408 return net_socket_fd_init_stream(vlan, fd, is_connected);
4410 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4411 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4412 return net_socket_fd_init_stream(vlan, fd, is_connected);
4417 static void net_socket_accept(void *opaque)
4419 NetSocketListenState *s = opaque;
4421 struct sockaddr_in saddr;
4426 len = sizeof(saddr);
4427 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4428 if (fd < 0 && errno != EINTR) {
4430 } else if (fd >= 0) {
4434 s1 = net_socket_fd_init(s->vlan, fd, 1);
4438 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4439 "socket: connection from %s:%d",
4440 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4444 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4446 NetSocketListenState *s;
4448 struct sockaddr_in saddr;
4450 if (parse_host_port(&saddr, host_str) < 0)
4453 s = qemu_mallocz(sizeof(NetSocketListenState));
4457 fd = socket(PF_INET, SOCK_STREAM, 0);
4462 socket_set_nonblock(fd);
4464 /* allow fast reuse */
4466 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4468 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4473 ret = listen(fd, 0);
4480 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4484 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4487 int fd, connected, ret, err;
4488 struct sockaddr_in saddr;
4490 if (parse_host_port(&saddr, host_str) < 0)
4493 fd = socket(PF_INET, SOCK_STREAM, 0);
4498 socket_set_nonblock(fd);
4502 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4504 err = socket_error();
4505 if (err == EINTR || err == EWOULDBLOCK) {
4506 } else if (err == EINPROGRESS) {
4509 } else if (err == WSAEALREADY) {
4522 s = net_socket_fd_init(vlan, fd, connected);
4525 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4526 "socket: connect to %s:%d",
4527 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4531 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4535 struct sockaddr_in saddr;
4537 if (parse_host_port(&saddr, host_str) < 0)
4541 fd = net_socket_mcast_create(&saddr);
4545 s = net_socket_fd_init(vlan, fd, 0);
4549 s->dgram_dst = saddr;
4551 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4552 "socket: mcast=%s:%d",
4553 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4558 static const char *get_word(char *buf, int buf_size, const char *p)
4565 while (*p != '\0') {
4570 } else if (*p == '\"') {
4571 substring = !substring;
4574 } else if (!substring && (*p == ',' || *p == '='))
4576 if (q && (q - buf) < buf_size - 1)
4586 static int get_param_value(char *buf, int buf_size,
4587 const char *tag, const char *str)
4594 p = get_word(option, sizeof(option), p);
4598 if (!strcmp(tag, option)) {
4599 (void)get_word(buf, buf_size, p);
4602 p = get_word(NULL, 0, p);
4611 static int check_params(char *buf, int buf_size,
4612 char **params, const char *str)
4619 p = get_word(buf, buf_size, p);
4623 for(i = 0; params[i] != NULL; i++)
4624 if (!strcmp(params[i], buf))
4626 if (params[i] == NULL)
4628 p = get_word(NULL, 0, p);
4637 static int net_client_init(const char *str)
4648 while (*p != '\0' && *p != ',') {
4649 if ((q - device) < sizeof(device) - 1)
4657 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4658 vlan_id = strtol(buf, NULL, 0);
4660 vlan = qemu_find_vlan(vlan_id);
4662 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4665 if (!strcmp(device, "nic")) {
4669 if (nb_nics >= MAX_NICS) {
4670 fprintf(stderr, "Too Many NICs\n");
4673 nd = &nd_table[nb_nics];
4674 macaddr = nd->macaddr;
4680 macaddr[5] = 0x56 + nb_nics;
4682 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4683 if (parse_macaddr(macaddr, buf) < 0) {
4684 fprintf(stderr, "invalid syntax for ethernet address\n");
4688 if (get_param_value(buf, sizeof(buf), "model", p)) {
4689 nd->model = strdup(buf);
4693 vlan->nb_guest_devs++;
4696 if (!strcmp(device, "none")) {
4697 /* does nothing. It is needed to signal that no network cards
4702 if (!strcmp(device, "user")) {
4703 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4704 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4706 vlan->nb_host_devs++;
4707 ret = net_slirp_init(vlan);
4711 if (!strcmp(device, "tap")) {
4713 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4714 fprintf(stderr, "tap: no interface name\n");
4717 vlan->nb_host_devs++;
4718 ret = tap_win32_init(vlan, ifname);
4721 if (!strcmp(device, "tap")) {
4723 char setup_script[1024], down_script[1024];
4725 vlan->nb_host_devs++;
4726 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4727 fd = strtol(buf, NULL, 0);
4729 if (net_tap_fd_init(vlan, fd))
4732 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4735 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4736 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4738 if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4739 pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4741 ret = net_tap_init(vlan, ifname, setup_script, down_script);
4745 if (!strcmp(device, "socket")) {
4746 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4748 fd = strtol(buf, NULL, 0);
4750 if (net_socket_fd_init(vlan, fd, 1))
4752 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4753 ret = net_socket_listen_init(vlan, buf);
4754 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4755 ret = net_socket_connect_init(vlan, buf);
4756 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4757 ret = net_socket_mcast_init(vlan, buf);
4759 fprintf(stderr, "Unknown socket options: %s\n", p);
4762 vlan->nb_host_devs++;
4765 fprintf(stderr, "Unknown network device: %s\n", device);
4769 fprintf(stderr, "Could not initialize device '%s'\n", device);
4775 void do_info_network(void)
4778 VLANClientState *vc;
4780 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4781 term_printf("VLAN %d devices:\n", vlan->id);
4782 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4783 term_printf(" %s\n", vc->info_str);
4787 #define HD_ALIAS "file=\"%s\",index=%d,media=disk"
4789 #define CDROM_ALIAS "index=1,media=cdrom"
4791 #define CDROM_ALIAS "index=2,media=cdrom"
4793 #define FD_ALIAS "index=%d,if=floppy"
4794 #define PFLASH_ALIAS "file=\"%s\",if=pflash"
4795 #define MTD_ALIAS "file=\"%s\",if=mtd"
4796 #define SD_ALIAS "index=0,if=sd"
4798 static int drive_add(const char *fmt, ...)
4802 if (nb_drives_opt >= MAX_DRIVES) {
4803 fprintf(stderr, "qemu: too many drives\n");
4808 vsnprintf(drives_opt[nb_drives_opt], sizeof(drives_opt[0]), fmt, ap);
4811 return nb_drives_opt++;
4814 int drive_get_index(BlockInterfaceType interface, int bus, int unit)
4818 /* seek interface, bus and unit */
4820 for (index = 0; index < nb_drives; index++)
4821 if (drives_table[index].interface == interface &&
4822 drives_table[index].bus == bus &&
4823 drives_table[index].unit == unit)
4829 int drive_get_max_bus(BlockInterfaceType interface)
4835 for (index = 0; index < nb_drives; index++) {
4836 if(drives_table[index].interface == interface &&
4837 drives_table[index].bus > max_bus)
4838 max_bus = drives_table[index].bus;
4843 static int drive_init(const char *str, int snapshot, QEMUMachine *machine)
4848 const char *mediastr = "";
4849 BlockInterfaceType interface;
4850 enum { MEDIA_DISK, MEDIA_CDROM } media;
4851 int bus_id, unit_id;
4852 int cyls, heads, secs, translation;
4853 BlockDriverState *bdrv;
4856 char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
4857 "secs", "trans", "media", "snapshot", "file", NULL };
4859 if (check_params(buf, sizeof(buf), params, str) < 0) {
4860 fprintf(stderr, "qemu: unknowm parameter '%s' in '%s'\n",
4866 cyls = heads = secs = 0;
4869 translation = BIOS_ATA_TRANSLATION_AUTO;
4872 if (!strcmp(machine->name, "realview") ||
4873 !strcmp(machine->name, "SS-5") ||
4874 !strcmp(machine->name, "SS-10") ||
4875 !strcmp(machine->name, "SS-600MP") ||
4876 !strcmp(machine->name, "versatilepb") ||
4877 !strcmp(machine->name, "versatileab")) {
4878 interface = IF_SCSI;
4879 max_devs = MAX_SCSI_DEVS;
4880 strcpy(devname, "scsi");
4883 max_devs = MAX_IDE_DEVS;
4884 strcpy(devname, "ide");
4888 /* extract parameters */
4890 if (get_param_value(buf, sizeof(buf), "bus", str)) {
4891 bus_id = strtol(buf, NULL, 0);
4893 fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
4898 if (get_param_value(buf, sizeof(buf), "unit", str)) {
4899 unit_id = strtol(buf, NULL, 0);
4901 fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
4906 if (get_param_value(buf, sizeof(buf), "if", str)) {
4907 strncpy(devname, buf, sizeof(devname));
4908 if (!strcmp(buf, "ide")) {
4910 max_devs = MAX_IDE_DEVS;
4911 } else if (!strcmp(buf, "scsi")) {
4912 interface = IF_SCSI;
4913 max_devs = MAX_SCSI_DEVS;
4914 } else if (!strcmp(buf, "floppy")) {
4915 interface = IF_FLOPPY;
4917 } else if (!strcmp(buf, "pflash")) {
4918 interface = IF_PFLASH;
4920 } else if (!strcmp(buf, "mtd")) {
4923 } else if (!strcmp(buf, "sd")) {
4927 fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
4932 if (get_param_value(buf, sizeof(buf), "index", str)) {
4933 index = strtol(buf, NULL, 0);
4935 fprintf(stderr, "qemu: '%s' invalid index\n", str);
4940 if (get_param_value(buf, sizeof(buf), "cyls", str)) {
4941 cyls = strtol(buf, NULL, 0);
4944 if (get_param_value(buf, sizeof(buf), "heads", str)) {
4945 heads = strtol(buf, NULL, 0);
4948 if (get_param_value(buf, sizeof(buf), "secs", str)) {
4949 secs = strtol(buf, NULL, 0);
4952 if (cyls || heads || secs) {
4953 if (cyls < 1 || cyls > 16383) {
4954 fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
4957 if (heads < 1 || heads > 16) {
4958 fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
4961 if (secs < 1 || secs > 63) {
4962 fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
4967 if (get_param_value(buf, sizeof(buf), "trans", str)) {
4970 "qemu: '%s' trans must be used with cyls,heads and secs\n",
4974 if (!strcmp(buf, "none"))
4975 translation = BIOS_ATA_TRANSLATION_NONE;
4976 else if (!strcmp(buf, "lba"))
4977 translation = BIOS_ATA_TRANSLATION_LBA;
4978 else if (!strcmp(buf, "auto"))
4979 translation = BIOS_ATA_TRANSLATION_AUTO;
4981 fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
4986 if (get_param_value(buf, sizeof(buf), "media", str)) {
4987 if (!strcmp(buf, "disk")) {
4989 } else if (!strcmp(buf, "cdrom")) {
4990 if (cyls || secs || heads) {
4992 "qemu: '%s' invalid physical CHS format\n", str);
4995 media = MEDIA_CDROM;
4997 fprintf(stderr, "qemu: '%s' invalid media\n", str);
5002 if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5003 if (!strcmp(buf, "on"))
5005 else if (!strcmp(buf, "off"))
5008 fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5013 get_param_value(file, sizeof(file), "file", str);
5015 /* compute bus and unit according index */
5018 if (bus_id != 0 || unit_id != -1) {
5020 "qemu: '%s' index cannot be used with bus and unit\n", str);
5028 unit_id = index % max_devs;
5029 bus_id = index / max_devs;
5033 /* if user doesn't specify a unit_id,
5034 * try to find the first free
5037 if (unit_id == -1) {
5039 while (drive_get_index(interface, bus_id, unit_id) != -1) {
5041 if (max_devs && unit_id >= max_devs) {
5042 unit_id -= max_devs;
5050 if (max_devs && unit_id >= max_devs) {
5051 fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5052 str, unit_id, max_devs - 1);
5057 * ignore multiple definitions
5060 if (drive_get_index(interface, bus_id, unit_id) != -1)
5065 if (interface == IF_IDE || interface == IF_SCSI)
5066 mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5067 snprintf(buf, sizeof(buf), max_devs ? "%1$s%4$i%2$s%3$i" : "%s%s%i",
5068 devname, mediastr, unit_id, bus_id);
5069 bdrv = bdrv_new(buf);
5070 drives_table[nb_drives].bdrv = bdrv;
5071 drives_table[nb_drives].interface = interface;
5072 drives_table[nb_drives].bus = bus_id;
5073 drives_table[nb_drives].unit = unit_id;
5082 bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5083 bdrv_set_translation_hint(bdrv, translation);
5087 bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5092 /* FIXME: This isn't really a floppy, but it's a reasonable
5095 bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5103 if (bdrv_open(bdrv, file, snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
5104 qemu_key_check(bdrv, file)) {
5105 fprintf(stderr, "qemu: could not open disk image %s\n",
5112 /***********************************************************/
5115 static USBPort *used_usb_ports;
5116 static USBPort *free_usb_ports;
5118 /* ??? Maybe change this to register a hub to keep track of the topology. */
5119 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5120 usb_attachfn attach)
5122 port->opaque = opaque;
5123 port->index = index;
5124 port->attach = attach;
5125 port->next = free_usb_ports;
5126 free_usb_ports = port;
5129 static int usb_device_add(const char *devname)
5135 if (!free_usb_ports)
5138 if (strstart(devname, "host:", &p)) {
5139 dev = usb_host_device_open(p);
5140 } else if (!strcmp(devname, "mouse")) {
5141 dev = usb_mouse_init();
5142 } else if (!strcmp(devname, "tablet")) {
5143 dev = usb_tablet_init();
5144 } else if (!strcmp(devname, "keyboard")) {
5145 dev = usb_keyboard_init();
5146 } else if (strstart(devname, "disk:", &p)) {
5147 dev = usb_msd_init(p);
5148 } else if (!strcmp(devname, "wacom-tablet")) {
5149 dev = usb_wacom_init();
5156 /* Find a USB port to add the device to. */
5157 port = free_usb_ports;
5161 /* Create a new hub and chain it on. */
5162 free_usb_ports = NULL;
5163 port->next = used_usb_ports;
5164 used_usb_ports = port;
5166 hub = usb_hub_init(VM_USB_HUB_SIZE);
5167 usb_attach(port, hub);
5168 port = free_usb_ports;
5171 free_usb_ports = port->next;
5172 port->next = used_usb_ports;
5173 used_usb_ports = port;
5174 usb_attach(port, dev);
5178 static int usb_device_del(const char *devname)
5186 if (!used_usb_ports)
5189 p = strchr(devname, '.');
5192 bus_num = strtoul(devname, NULL, 0);
5193 addr = strtoul(p + 1, NULL, 0);
5197 lastp = &used_usb_ports;
5198 port = used_usb_ports;
5199 while (port && port->dev->addr != addr) {
5200 lastp = &port->next;
5208 *lastp = port->next;
5209 usb_attach(port, NULL);
5210 dev->handle_destroy(dev);
5211 port->next = free_usb_ports;
5212 free_usb_ports = port;
5216 void do_usb_add(const char *devname)
5219 ret = usb_device_add(devname);
5221 term_printf("Could not add USB device '%s'\n", devname);
5224 void do_usb_del(const char *devname)
5227 ret = usb_device_del(devname);
5229 term_printf("Could not remove USB device '%s'\n", devname);
5236 const char *speed_str;
5239 term_printf("USB support not enabled\n");
5243 for (port = used_usb_ports; port; port = port->next) {
5247 switch(dev->speed) {
5251 case USB_SPEED_FULL:
5254 case USB_SPEED_HIGH:
5261 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
5262 0, dev->addr, speed_str, dev->devname);
5266 /***********************************************************/
5267 /* PCMCIA/Cardbus */
5269 static struct pcmcia_socket_entry_s {
5270 struct pcmcia_socket_s *socket;
5271 struct pcmcia_socket_entry_s *next;
5272 } *pcmcia_sockets = 0;
5274 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5276 struct pcmcia_socket_entry_s *entry;
5278 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5279 entry->socket = socket;
5280 entry->next = pcmcia_sockets;
5281 pcmcia_sockets = entry;
5284 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5286 struct pcmcia_socket_entry_s *entry, **ptr;
5288 ptr = &pcmcia_sockets;
5289 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5290 if (entry->socket == socket) {
5296 void pcmcia_info(void)
5298 struct pcmcia_socket_entry_s *iter;
5299 if (!pcmcia_sockets)
5300 term_printf("No PCMCIA sockets\n");
5302 for (iter = pcmcia_sockets; iter; iter = iter->next)
5303 term_printf("%s: %s\n", iter->socket->slot_string,
5304 iter->socket->attached ? iter->socket->card_string :
5308 /***********************************************************/
5311 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5315 static void dumb_resize(DisplayState *ds, int w, int h)
5319 static void dumb_refresh(DisplayState *ds)
5321 #if defined(CONFIG_SDL)
5326 static void dumb_display_init(DisplayState *ds)
5331 ds->dpy_update = dumb_update;
5332 ds->dpy_resize = dumb_resize;
5333 ds->dpy_refresh = dumb_refresh;
5336 /***********************************************************/
5339 #define MAX_IO_HANDLERS 64
5341 typedef struct IOHandlerRecord {
5343 IOCanRWHandler *fd_read_poll;
5345 IOHandler *fd_write;
5348 /* temporary data */
5350 struct IOHandlerRecord *next;
5353 static IOHandlerRecord *first_io_handler;
5355 /* XXX: fd_read_poll should be suppressed, but an API change is
5356 necessary in the character devices to suppress fd_can_read(). */
5357 int qemu_set_fd_handler2(int fd,
5358 IOCanRWHandler *fd_read_poll,
5360 IOHandler *fd_write,
5363 IOHandlerRecord **pioh, *ioh;
5365 if (!fd_read && !fd_write) {
5366 pioh = &first_io_handler;
5371 if (ioh->fd == fd) {
5378 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5382 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5385 ioh->next = first_io_handler;
5386 first_io_handler = ioh;
5389 ioh->fd_read_poll = fd_read_poll;
5390 ioh->fd_read = fd_read;
5391 ioh->fd_write = fd_write;
5392 ioh->opaque = opaque;
5398 int qemu_set_fd_handler(int fd,
5400 IOHandler *fd_write,
5403 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5406 /***********************************************************/
5407 /* Polling handling */
5409 typedef struct PollingEntry {
5412 struct PollingEntry *next;
5415 static PollingEntry *first_polling_entry;
5417 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5419 PollingEntry **ppe, *pe;
5420 pe = qemu_mallocz(sizeof(PollingEntry));
5424 pe->opaque = opaque;
5425 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5430 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5432 PollingEntry **ppe, *pe;
5433 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5435 if (pe->func == func && pe->opaque == opaque) {
5444 /***********************************************************/
5445 /* Wait objects support */
5446 typedef struct WaitObjects {
5448 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5449 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5450 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5453 static WaitObjects wait_objects = {0};
5455 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5457 WaitObjects *w = &wait_objects;
5459 if (w->num >= MAXIMUM_WAIT_OBJECTS)
5461 w->events[w->num] = handle;
5462 w->func[w->num] = func;
5463 w->opaque[w->num] = opaque;
5468 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5471 WaitObjects *w = &wait_objects;
5474 for (i = 0; i < w->num; i++) {
5475 if (w->events[i] == handle)
5478 w->events[i] = w->events[i + 1];
5479 w->func[i] = w->func[i + 1];
5480 w->opaque[i] = w->opaque[i + 1];
5488 /***********************************************************/
5489 /* savevm/loadvm support */
5491 #define IO_BUF_SIZE 32768
5495 BlockDriverState *bs;
5498 int64_t base_offset;
5499 int64_t buf_offset; /* start of buffer when writing, end of buffer
5502 int buf_size; /* 0 when writing */
5503 uint8_t buf[IO_BUF_SIZE];
5506 QEMUFile *qemu_fopen(const char *filename, const char *mode)
5510 f = qemu_mallocz(sizeof(QEMUFile));
5513 if (!strcmp(mode, "wb")) {
5515 } else if (!strcmp(mode, "rb")) {
5520 f->outfile = fopen(filename, mode);
5532 static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5536 f = qemu_mallocz(sizeof(QEMUFile));
5541 f->is_writable = is_writable;
5542 f->base_offset = offset;
5546 void qemu_fflush(QEMUFile *f)
5548 if (!f->is_writable)
5550 if (f->buf_index > 0) {
5552 fseek(f->outfile, f->buf_offset, SEEK_SET);
5553 fwrite(f->buf, 1, f->buf_index, f->outfile);
5555 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5556 f->buf, f->buf_index);
5558 f->buf_offset += f->buf_index;
5563 static void qemu_fill_buffer(QEMUFile *f)
5570 fseek(f->outfile, f->buf_offset, SEEK_SET);
5571 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5575 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5576 f->buf, IO_BUF_SIZE);
5582 f->buf_offset += len;
5585 void qemu_fclose(QEMUFile *f)
5595 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5599 l = IO_BUF_SIZE - f->buf_index;
5602 memcpy(f->buf + f->buf_index, buf, l);
5606 if (f->buf_index >= IO_BUF_SIZE)
5611 void qemu_put_byte(QEMUFile *f, int v)
5613 f->buf[f->buf_index++] = v;
5614 if (f->buf_index >= IO_BUF_SIZE)
5618 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5624 l = f->buf_size - f->buf_index;
5626 qemu_fill_buffer(f);
5627 l = f->buf_size - f->buf_index;
5633 memcpy(buf, f->buf + f->buf_index, l);
5638 return size1 - size;
5641 int qemu_get_byte(QEMUFile *f)
5643 if (f->buf_index >= f->buf_size) {
5644 qemu_fill_buffer(f);
5645 if (f->buf_index >= f->buf_size)
5648 return f->buf[f->buf_index++];
5651 int64_t qemu_ftell(QEMUFile *f)
5653 return f->buf_offset - f->buf_size + f->buf_index;
5656 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5658 if (whence == SEEK_SET) {
5660 } else if (whence == SEEK_CUR) {
5661 pos += qemu_ftell(f);
5663 /* SEEK_END not supported */
5666 if (f->is_writable) {
5668 f->buf_offset = pos;
5670 f->buf_offset = pos;
5677 void qemu_put_be16(QEMUFile *f, unsigned int v)
5679 qemu_put_byte(f, v >> 8);
5680 qemu_put_byte(f, v);
5683 void qemu_put_be32(QEMUFile *f, unsigned int v)
5685 qemu_put_byte(f, v >> 24);
5686 qemu_put_byte(f, v >> 16);
5687 qemu_put_byte(f, v >> 8);
5688 qemu_put_byte(f, v);
5691 void qemu_put_be64(QEMUFile *f, uint64_t v)
5693 qemu_put_be32(f, v >> 32);
5694 qemu_put_be32(f, v);
5697 unsigned int qemu_get_be16(QEMUFile *f)
5700 v = qemu_get_byte(f) << 8;
5701 v |= qemu_get_byte(f);
5705 unsigned int qemu_get_be32(QEMUFile *f)
5708 v = qemu_get_byte(f) << 24;
5709 v |= qemu_get_byte(f) << 16;
5710 v |= qemu_get_byte(f) << 8;
5711 v |= qemu_get_byte(f);
5715 uint64_t qemu_get_be64(QEMUFile *f)
5718 v = (uint64_t)qemu_get_be32(f) << 32;
5719 v |= qemu_get_be32(f);
5723 typedef struct SaveStateEntry {
5727 SaveStateHandler *save_state;
5728 LoadStateHandler *load_state;
5730 struct SaveStateEntry *next;
5733 static SaveStateEntry *first_se;
5735 int register_savevm(const char *idstr,
5738 SaveStateHandler *save_state,
5739 LoadStateHandler *load_state,
5742 SaveStateEntry *se, **pse;
5744 se = qemu_malloc(sizeof(SaveStateEntry));
5747 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5748 se->instance_id = instance_id;
5749 se->version_id = version_id;
5750 se->save_state = save_state;
5751 se->load_state = load_state;
5752 se->opaque = opaque;
5755 /* add at the end of list */
5757 while (*pse != NULL)
5758 pse = &(*pse)->next;
5763 #define QEMU_VM_FILE_MAGIC 0x5145564d
5764 #define QEMU_VM_FILE_VERSION 0x00000002
5766 static int qemu_savevm_state(QEMUFile *f)
5770 int64_t cur_pos, len_pos, total_len_pos;
5772 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5773 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5774 total_len_pos = qemu_ftell(f);
5775 qemu_put_be64(f, 0); /* total size */
5777 for(se = first_se; se != NULL; se = se->next) {
5779 len = strlen(se->idstr);
5780 qemu_put_byte(f, len);
5781 qemu_put_buffer(f, se->idstr, len);
5783 qemu_put_be32(f, se->instance_id);
5784 qemu_put_be32(f, se->version_id);
5786 /* record size: filled later */
5787 len_pos = qemu_ftell(f);
5788 qemu_put_be32(f, 0);
5789 se->save_state(f, se->opaque);
5791 /* fill record size */
5792 cur_pos = qemu_ftell(f);
5793 len = cur_pos - len_pos - 4;
5794 qemu_fseek(f, len_pos, SEEK_SET);
5795 qemu_put_be32(f, len);
5796 qemu_fseek(f, cur_pos, SEEK_SET);
5798 cur_pos = qemu_ftell(f);
5799 qemu_fseek(f, total_len_pos, SEEK_SET);
5800 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5801 qemu_fseek(f, cur_pos, SEEK_SET);
5807 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5811 for(se = first_se; se != NULL; se = se->next) {
5812 if (!strcmp(se->idstr, idstr) &&
5813 instance_id == se->instance_id)
5819 static int qemu_loadvm_state(QEMUFile *f)
5822 int len, ret, instance_id, record_len, version_id;
5823 int64_t total_len, end_pos, cur_pos;
5827 v = qemu_get_be32(f);
5828 if (v != QEMU_VM_FILE_MAGIC)
5830 v = qemu_get_be32(f);
5831 if (v != QEMU_VM_FILE_VERSION) {
5836 total_len = qemu_get_be64(f);
5837 end_pos = total_len + qemu_ftell(f);
5839 if (qemu_ftell(f) >= end_pos)
5841 len = qemu_get_byte(f);
5842 qemu_get_buffer(f, idstr, len);
5844 instance_id = qemu_get_be32(f);
5845 version_id = qemu_get_be32(f);
5846 record_len = qemu_get_be32(f);
5848 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5849 idstr, instance_id, version_id, record_len);
5851 cur_pos = qemu_ftell(f);
5852 se = find_se(idstr, instance_id);
5854 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5855 instance_id, idstr);
5857 ret = se->load_state(f, se->opaque, version_id);
5859 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5860 instance_id, idstr);
5863 /* always seek to exact end of record */
5864 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5871 /* device can contain snapshots */
5872 static int bdrv_can_snapshot(BlockDriverState *bs)
5875 !bdrv_is_removable(bs) &&
5876 !bdrv_is_read_only(bs));
5879 /* device must be snapshots in order to have a reliable snapshot */
5880 static int bdrv_has_snapshot(BlockDriverState *bs)
5883 !bdrv_is_removable(bs) &&
5884 !bdrv_is_read_only(bs));
5887 static BlockDriverState *get_bs_snapshots(void)
5889 BlockDriverState *bs;
5893 return bs_snapshots;
5894 for(i = 0; i <= nb_drives; i++) {
5895 bs = drives_table[i].bdrv;
5896 if (bdrv_can_snapshot(bs))
5905 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5908 QEMUSnapshotInfo *sn_tab, *sn;
5912 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5915 for(i = 0; i < nb_sns; i++) {
5917 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5927 void do_savevm(const char *name)
5929 BlockDriverState *bs, *bs1;
5930 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5931 int must_delete, ret, i;
5932 BlockDriverInfo bdi1, *bdi = &bdi1;
5934 int saved_vm_running;
5941 bs = get_bs_snapshots();
5943 term_printf("No block device can accept snapshots\n");
5947 /* ??? Should this occur after vm_stop? */
5950 saved_vm_running = vm_running;
5955 ret = bdrv_snapshot_find(bs, old_sn, name);
5960 memset(sn, 0, sizeof(*sn));
5962 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5963 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5966 pstrcpy(sn->name, sizeof(sn->name), name);
5969 /* fill auxiliary fields */
5972 sn->date_sec = tb.time;
5973 sn->date_nsec = tb.millitm * 1000000;
5975 gettimeofday(&tv, NULL);
5976 sn->date_sec = tv.tv_sec;
5977 sn->date_nsec = tv.tv_usec * 1000;
5979 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5981 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5982 term_printf("Device %s does not support VM state snapshots\n",
5983 bdrv_get_device_name(bs));
5987 /* save the VM state */
5988 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5990 term_printf("Could not open VM state file\n");
5993 ret = qemu_savevm_state(f);
5994 sn->vm_state_size = qemu_ftell(f);
5997 term_printf("Error %d while writing VM\n", ret);
6001 /* create the snapshots */
6003 for(i = 0; i < nb_drives; i++) {
6004 bs1 = drives_table[i].bdrv;
6005 if (bdrv_has_snapshot(bs1)) {
6007 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6009 term_printf("Error while deleting snapshot on '%s'\n",
6010 bdrv_get_device_name(bs1));
6013 ret = bdrv_snapshot_create(bs1, sn);
6015 term_printf("Error while creating snapshot on '%s'\n",
6016 bdrv_get_device_name(bs1));
6022 if (saved_vm_running)
6026 void do_loadvm(const char *name)
6028 BlockDriverState *bs, *bs1;
6029 BlockDriverInfo bdi1, *bdi = &bdi1;
6032 int saved_vm_running;
6034 bs = get_bs_snapshots();
6036 term_printf("No block device supports snapshots\n");
6040 /* Flush all IO requests so they don't interfere with the new state. */
6043 saved_vm_running = vm_running;
6046 for(i = 0; i <= nb_drives; i++) {
6047 bs1 = drives_table[i].bdrv;
6048 if (bdrv_has_snapshot(bs1)) {
6049 ret = bdrv_snapshot_goto(bs1, name);
6052 term_printf("Warning: ");
6055 term_printf("Snapshots not supported on device '%s'\n",
6056 bdrv_get_device_name(bs1));
6059 term_printf("Could not find snapshot '%s' on device '%s'\n",
6060 name, bdrv_get_device_name(bs1));
6063 term_printf("Error %d while activating snapshot on '%s'\n",
6064 ret, bdrv_get_device_name(bs1));
6067 /* fatal on snapshot block device */
6074 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6075 term_printf("Device %s does not support VM state snapshots\n",
6076 bdrv_get_device_name(bs));
6080 /* restore the VM state */
6081 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6083 term_printf("Could not open VM state file\n");
6086 ret = qemu_loadvm_state(f);
6089 term_printf("Error %d while loading VM state\n", ret);
6092 if (saved_vm_running)
6096 void do_delvm(const char *name)
6098 BlockDriverState *bs, *bs1;
6101 bs = get_bs_snapshots();
6103 term_printf("No block device supports snapshots\n");
6107 for(i = 0; i <= nb_drives; i++) {
6108 bs1 = drives_table[i].bdrv;
6109 if (bdrv_has_snapshot(bs1)) {
6110 ret = bdrv_snapshot_delete(bs1, name);
6112 if (ret == -ENOTSUP)
6113 term_printf("Snapshots not supported on device '%s'\n",
6114 bdrv_get_device_name(bs1));
6116 term_printf("Error %d while deleting snapshot on '%s'\n",
6117 ret, bdrv_get_device_name(bs1));
6123 void do_info_snapshots(void)
6125 BlockDriverState *bs, *bs1;
6126 QEMUSnapshotInfo *sn_tab, *sn;
6130 bs = get_bs_snapshots();
6132 term_printf("No available block device supports snapshots\n");
6135 term_printf("Snapshot devices:");
6136 for(i = 0; i <= nb_drives; i++) {
6137 bs1 = drives_table[i].bdrv;
6138 if (bdrv_has_snapshot(bs1)) {
6140 term_printf(" %s", bdrv_get_device_name(bs1));
6145 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6147 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6150 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6151 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6152 for(i = 0; i < nb_sns; i++) {
6154 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6159 /***********************************************************/
6160 /* cpu save/restore */
6162 #if defined(TARGET_I386)
6164 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
6166 qemu_put_be32(f, dt->selector);
6167 qemu_put_betl(f, dt->base);
6168 qemu_put_be32(f, dt->limit);
6169 qemu_put_be32(f, dt->flags);
6172 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
6174 dt->selector = qemu_get_be32(f);
6175 dt->base = qemu_get_betl(f);
6176 dt->limit = qemu_get_be32(f);
6177 dt->flags = qemu_get_be32(f);
6180 void cpu_save(QEMUFile *f, void *opaque)
6182 CPUState *env = opaque;
6183 uint16_t fptag, fpus, fpuc, fpregs_format;
6187 for(i = 0; i < CPU_NB_REGS; i++)
6188 qemu_put_betls(f, &env->regs[i]);
6189 qemu_put_betls(f, &env->eip);
6190 qemu_put_betls(f, &env->eflags);
6191 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
6192 qemu_put_be32s(f, &hflags);
6196 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
6198 for(i = 0; i < 8; i++) {
6199 fptag |= ((!env->fptags[i]) << i);
6202 qemu_put_be16s(f, &fpuc);
6203 qemu_put_be16s(f, &fpus);
6204 qemu_put_be16s(f, &fptag);
6206 #ifdef USE_X86LDOUBLE
6211 qemu_put_be16s(f, &fpregs_format);
6213 for(i = 0; i < 8; i++) {
6214 #ifdef USE_X86LDOUBLE
6218 /* we save the real CPU data (in case of MMX usage only 'mant'
6219 contains the MMX register */
6220 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
6221 qemu_put_be64(f, mant);
6222 qemu_put_be16(f, exp);
6225 /* if we use doubles for float emulation, we save the doubles to
6226 avoid losing information in case of MMX usage. It can give
6227 problems if the image is restored on a CPU where long
6228 doubles are used instead. */
6229 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
6233 for(i = 0; i < 6; i++)
6234 cpu_put_seg(f, &env->segs[i]);
6235 cpu_put_seg(f, &env->ldt);
6236 cpu_put_seg(f, &env->tr);
6237 cpu_put_seg(f, &env->gdt);
6238 cpu_put_seg(f, &env->idt);
6240 qemu_put_be32s(f, &env->sysenter_cs);
6241 qemu_put_be32s(f, &env->sysenter_esp);
6242 qemu_put_be32s(f, &env->sysenter_eip);
6244 qemu_put_betls(f, &env->cr[0]);
6245 qemu_put_betls(f, &env->cr[2]);
6246 qemu_put_betls(f, &env->cr[3]);
6247 qemu_put_betls(f, &env->cr[4]);
6249 for(i = 0; i < 8; i++)
6250 qemu_put_betls(f, &env->dr[i]);
6253 qemu_put_be32s(f, &env->a20_mask);
6256 qemu_put_be32s(f, &env->mxcsr);
6257 for(i = 0; i < CPU_NB_REGS; i++) {
6258 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6259 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6262 #ifdef TARGET_X86_64
6263 qemu_put_be64s(f, &env->efer);
6264 qemu_put_be64s(f, &env->star);
6265 qemu_put_be64s(f, &env->lstar);
6266 qemu_put_be64s(f, &env->cstar);
6267 qemu_put_be64s(f, &env->fmask);
6268 qemu_put_be64s(f, &env->kernelgsbase);
6270 qemu_put_be32s(f, &env->smbase);
6273 #ifdef USE_X86LDOUBLE
6274 /* XXX: add that in a FPU generic layer */
6275 union x86_longdouble {
6280 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
6281 #define EXPBIAS1 1023
6282 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
6283 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
6285 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
6289 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
6290 /* exponent + sign */
6291 e = EXPD1(temp) - EXPBIAS1 + 16383;
6292 e |= SIGND1(temp) >> 16;
6297 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6299 CPUState *env = opaque;
6302 uint16_t fpus, fpuc, fptag, fpregs_format;
6304 if (version_id != 3 && version_id != 4)
6306 for(i = 0; i < CPU_NB_REGS; i++)
6307 qemu_get_betls(f, &env->regs[i]);
6308 qemu_get_betls(f, &env->eip);
6309 qemu_get_betls(f, &env->eflags);
6310 qemu_get_be32s(f, &hflags);
6312 qemu_get_be16s(f, &fpuc);
6313 qemu_get_be16s(f, &fpus);
6314 qemu_get_be16s(f, &fptag);
6315 qemu_get_be16s(f, &fpregs_format);
6317 /* NOTE: we cannot always restore the FPU state if the image come
6318 from a host with a different 'USE_X86LDOUBLE' define. We guess
6319 if we are in an MMX state to restore correctly in that case. */
6320 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
6321 for(i = 0; i < 8; i++) {
6325 switch(fpregs_format) {
6327 mant = qemu_get_be64(f);
6328 exp = qemu_get_be16(f);
6329 #ifdef USE_X86LDOUBLE
6330 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6332 /* difficult case */
6334 env->fpregs[i].mmx.MMX_Q(0) = mant;
6336 env->fpregs[i].d = cpu_set_fp80(mant, exp);
6340 mant = qemu_get_be64(f);
6341 #ifdef USE_X86LDOUBLE
6343 union x86_longdouble *p;
6344 /* difficult case */
6345 p = (void *)&env->fpregs[i];
6350 fp64_to_fp80(p, mant);
6354 env->fpregs[i].mmx.MMX_Q(0) = mant;
6363 /* XXX: restore FPU round state */
6364 env->fpstt = (fpus >> 11) & 7;
6365 env->fpus = fpus & ~0x3800;
6367 for(i = 0; i < 8; i++) {
6368 env->fptags[i] = (fptag >> i) & 1;
6371 for(i = 0; i < 6; i++)
6372 cpu_get_seg(f, &env->segs[i]);
6373 cpu_get_seg(f, &env->ldt);
6374 cpu_get_seg(f, &env->tr);
6375 cpu_get_seg(f, &env->gdt);
6376 cpu_get_seg(f, &env->idt);
6378 qemu_get_be32s(f, &env->sysenter_cs);
6379 qemu_get_be32s(f, &env->sysenter_esp);
6380 qemu_get_be32s(f, &env->sysenter_eip);
6382 qemu_get_betls(f, &env->cr[0]);
6383 qemu_get_betls(f, &env->cr[2]);
6384 qemu_get_betls(f, &env->cr[3]);
6385 qemu_get_betls(f, &env->cr[4]);
6387 for(i = 0; i < 8; i++)
6388 qemu_get_betls(f, &env->dr[i]);
6391 qemu_get_be32s(f, &env->a20_mask);
6393 qemu_get_be32s(f, &env->mxcsr);
6394 for(i = 0; i < CPU_NB_REGS; i++) {
6395 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6396 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6399 #ifdef TARGET_X86_64
6400 qemu_get_be64s(f, &env->efer);
6401 qemu_get_be64s(f, &env->star);
6402 qemu_get_be64s(f, &env->lstar);
6403 qemu_get_be64s(f, &env->cstar);
6404 qemu_get_be64s(f, &env->fmask);
6405 qemu_get_be64s(f, &env->kernelgsbase);
6407 if (version_id >= 4)
6408 qemu_get_be32s(f, &env->smbase);
6410 /* XXX: compute hflags from scratch, except for CPL and IIF */
6411 env->hflags = hflags;
6416 #elif defined(TARGET_PPC)
6417 void cpu_save(QEMUFile *f, void *opaque)
6421 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6426 #elif defined(TARGET_MIPS)
6427 void cpu_save(QEMUFile *f, void *opaque)
6431 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6436 #elif defined(TARGET_SPARC)
6437 void cpu_save(QEMUFile *f, void *opaque)
6439 CPUState *env = opaque;
6443 for(i = 0; i < 8; i++)
6444 qemu_put_betls(f, &env->gregs[i]);
6445 for(i = 0; i < NWINDOWS * 16; i++)
6446 qemu_put_betls(f, &env->regbase[i]);
6449 for(i = 0; i < TARGET_FPREGS; i++) {
6455 qemu_put_be32(f, u.i);
6458 qemu_put_betls(f, &env->pc);
6459 qemu_put_betls(f, &env->npc);
6460 qemu_put_betls(f, &env->y);
6462 qemu_put_be32(f, tmp);
6463 qemu_put_betls(f, &env->fsr);
6464 qemu_put_betls(f, &env->tbr);
6465 #ifndef TARGET_SPARC64
6466 qemu_put_be32s(f, &env->wim);
6468 for(i = 0; i < 16; i++)
6469 qemu_put_be32s(f, &env->mmuregs[i]);
6473 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6475 CPUState *env = opaque;
6479 for(i = 0; i < 8; i++)
6480 qemu_get_betls(f, &env->gregs[i]);
6481 for(i = 0; i < NWINDOWS * 16; i++)
6482 qemu_get_betls(f, &env->regbase[i]);
6485 for(i = 0; i < TARGET_FPREGS; i++) {
6490 u.i = qemu_get_be32(f);
6494 qemu_get_betls(f, &env->pc);
6495 qemu_get_betls(f, &env->npc);
6496 qemu_get_betls(f, &env->y);
6497 tmp = qemu_get_be32(f);
6498 env->cwp = 0; /* needed to ensure that the wrapping registers are
6499 correctly updated */
6501 qemu_get_betls(f, &env->fsr);
6502 qemu_get_betls(f, &env->tbr);
6503 #ifndef TARGET_SPARC64
6504 qemu_get_be32s(f, &env->wim);
6506 for(i = 0; i < 16; i++)
6507 qemu_get_be32s(f, &env->mmuregs[i]);
6513 #elif defined(TARGET_ARM)
6515 void cpu_save(QEMUFile *f, void *opaque)
6518 CPUARMState *env = (CPUARMState *)opaque;
6520 for (i = 0; i < 16; i++) {
6521 qemu_put_be32(f, env->regs[i]);
6523 qemu_put_be32(f, cpsr_read(env));
6524 qemu_put_be32(f, env->spsr);
6525 for (i = 0; i < 6; i++) {
6526 qemu_put_be32(f, env->banked_spsr[i]);
6527 qemu_put_be32(f, env->banked_r13[i]);
6528 qemu_put_be32(f, env->banked_r14[i]);
6530 for (i = 0; i < 5; i++) {
6531 qemu_put_be32(f, env->usr_regs[i]);
6532 qemu_put_be32(f, env->fiq_regs[i]);
6534 qemu_put_be32(f, env->cp15.c0_cpuid);
6535 qemu_put_be32(f, env->cp15.c0_cachetype);
6536 qemu_put_be32(f, env->cp15.c1_sys);
6537 qemu_put_be32(f, env->cp15.c1_coproc);
6538 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6539 qemu_put_be32(f, env->cp15.c2_base0);
6540 qemu_put_be32(f, env->cp15.c2_base1);
6541 qemu_put_be32(f, env->cp15.c2_mask);
6542 qemu_put_be32(f, env->cp15.c2_data);
6543 qemu_put_be32(f, env->cp15.c2_insn);
6544 qemu_put_be32(f, env->cp15.c3);
6545 qemu_put_be32(f, env->cp15.c5_insn);
6546 qemu_put_be32(f, env->cp15.c5_data);
6547 for (i = 0; i < 8; i++) {
6548 qemu_put_be32(f, env->cp15.c6_region[i]);
6550 qemu_put_be32(f, env->cp15.c6_insn);
6551 qemu_put_be32(f, env->cp15.c6_data);
6552 qemu_put_be32(f, env->cp15.c9_insn);
6553 qemu_put_be32(f, env->cp15.c9_data);
6554 qemu_put_be32(f, env->cp15.c13_fcse);
6555 qemu_put_be32(f, env->cp15.c13_context);
6556 qemu_put_be32(f, env->cp15.c13_tls1);
6557 qemu_put_be32(f, env->cp15.c13_tls2);
6558 qemu_put_be32(f, env->cp15.c13_tls3);
6559 qemu_put_be32(f, env->cp15.c15_cpar);
6561 qemu_put_be32(f, env->features);
6563 if (arm_feature(env, ARM_FEATURE_VFP)) {
6564 for (i = 0; i < 16; i++) {
6566 u.d = env->vfp.regs[i];
6567 qemu_put_be32(f, u.l.upper);
6568 qemu_put_be32(f, u.l.lower);
6570 for (i = 0; i < 16; i++) {
6571 qemu_put_be32(f, env->vfp.xregs[i]);
6574 /* TODO: Should use proper FPSCR access functions. */
6575 qemu_put_be32(f, env->vfp.vec_len);
6576 qemu_put_be32(f, env->vfp.vec_stride);
6578 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6579 for (i = 16; i < 32; i++) {
6581 u.d = env->vfp.regs[i];
6582 qemu_put_be32(f, u.l.upper);
6583 qemu_put_be32(f, u.l.lower);
6588 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6589 for (i = 0; i < 16; i++) {
6590 qemu_put_be64(f, env->iwmmxt.regs[i]);
6592 for (i = 0; i < 16; i++) {
6593 qemu_put_be32(f, env->iwmmxt.cregs[i]);
6597 if (arm_feature(env, ARM_FEATURE_M)) {
6598 qemu_put_be32(f, env->v7m.other_sp);
6599 qemu_put_be32(f, env->v7m.vecbase);
6600 qemu_put_be32(f, env->v7m.basepri);
6601 qemu_put_be32(f, env->v7m.control);
6602 qemu_put_be32(f, env->v7m.current_sp);
6603 qemu_put_be32(f, env->v7m.exception);
6607 int cpu_load(QEMUFile *f, void *opaque, int version_id)
6609 CPUARMState *env = (CPUARMState *)opaque;
6612 if (version_id != ARM_CPU_SAVE_VERSION)
6615 for (i = 0; i < 16; i++) {
6616 env->regs[i] = qemu_get_be32(f);
6618 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6619 env->spsr = qemu_get_be32(f);
6620 for (i = 0; i < 6; i++) {
6621 env->banked_spsr[i] = qemu_get_be32(f);
6622 env->banked_r13[i] = qemu_get_be32(f);
6623 env->banked_r14[i] = qemu_get_be32(f);
6625 for (i = 0; i < 5; i++) {
6626 env->usr_regs[i] = qemu_get_be32(f);
6627 env->fiq_regs[i] = qemu_get_be32(f);
6629 env->cp15.c0_cpuid = qemu_get_be32(f);
6630 env->cp15.c0_cachetype = qemu_get_be32(f);
6631 env->cp15.c1_sys = qemu_get_be32(f);
6632 env->cp15.c1_coproc = qemu_get_be32(f);
6633 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6634 env->cp15.c2_base0 = qemu_get_be32(f);
6635 env->cp15.c2_base1 = qemu_get_be32(f);
6636 env->cp15.c2_mask = qemu_get_be32(f);
6637 env->cp15.c2_data = qemu_get_be32(f);
6638 env->cp15.c2_insn = qemu_get_be32(f);
6639 env->cp15.c3 = qemu_get_be32(f);
6640 env->cp15.c5_insn = qemu_get_be32(f);
6641 env->cp15.c5_data = qemu_get_be32(f);
6642 for (i = 0; i < 8; i++) {
6643 env->cp15.c6_region[i] = qemu_get_be32(f);
6645 env->cp15.c6_insn = qemu_get_be32(f);
6646 env->cp15.c6_data = qemu_get_be32(f);
6647 env->cp15.c9_insn = qemu_get_be32(f);
6648 env->cp15.c9_data = qemu_get_be32(f);
6649 env->cp15.c13_fcse = qemu_get_be32(f);
6650 env->cp15.c13_context = qemu_get_be32(f);
6651 env->cp15.c13_tls1 = qemu_get_be32(f);
6652 env->cp15.c13_tls2 = qemu_get_be32(f);
6653 env->cp15.c13_tls3 = qemu_get_be32(f);
6654 env->cp15.c15_cpar = qemu_get_be32(f);
6656 env->features = qemu_get_be32(f);
6658 if (arm_feature(env, ARM_FEATURE_VFP)) {
6659 for (i = 0; i < 16; i++) {
6661 u.l.upper = qemu_get_be32(f);
6662 u.l.lower = qemu_get_be32(f);
6663 env->vfp.regs[i] = u.d;
6665 for (i = 0; i < 16; i++) {
6666 env->vfp.xregs[i] = qemu_get_be32(f);
6669 /* TODO: Should use proper FPSCR access functions. */
6670 env->vfp.vec_len = qemu_get_be32(f);
6671 env->vfp.vec_stride = qemu_get_be32(f);
6673 if (arm_feature(env, ARM_FEATURE_VFP3)) {
6674 for (i = 0; i < 16; i++) {
6676 u.l.upper = qemu_get_be32(f);
6677 u.l.lower = qemu_get_be32(f);
6678 env->vfp.regs[i] = u.d;
6683 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6684 for (i = 0; i < 16; i++) {
6685 env->iwmmxt.regs[i] = qemu_get_be64(f);
6687 for (i = 0; i < 16; i++) {
6688 env->iwmmxt.cregs[i] = qemu_get_be32(f);
6692 if (arm_feature(env, ARM_FEATURE_M)) {
6693 env->v7m.other_sp = qemu_get_be32(f);
6694 env->v7m.vecbase = qemu_get_be32(f);
6695 env->v7m.basepri = qemu_get_be32(f);
6696 env->v7m.control = qemu_get_be32(f);
6697 env->v7m.current_sp = qemu_get_be32(f);
6698 env->v7m.exception = qemu_get_be32(f);
6706 //#warning No CPU save/restore functions
6710 /***********************************************************/
6711 /* ram save/restore */
6713 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6717 v = qemu_get_byte(f);
6720 if (qemu_get_buffer(f, buf, len) != len)
6724 v = qemu_get_byte(f);
6725 memset(buf, v, len);
6733 static int ram_load_v1(QEMUFile *f, void *opaque)
6737 if (qemu_get_be32(f) != phys_ram_size)
6739 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6740 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6747 #define BDRV_HASH_BLOCK_SIZE 1024
6748 #define IOBUF_SIZE 4096
6749 #define RAM_CBLOCK_MAGIC 0xfabe
6751 typedef struct RamCompressState {
6754 uint8_t buf[IOBUF_SIZE];
6757 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6760 memset(s, 0, sizeof(*s));
6762 ret = deflateInit2(&s->zstream, 1,
6764 9, Z_DEFAULT_STRATEGY);
6767 s->zstream.avail_out = IOBUF_SIZE;
6768 s->zstream.next_out = s->buf;
6772 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6774 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6775 qemu_put_be16(s->f, len);
6776 qemu_put_buffer(s->f, buf, len);
6779 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6783 s->zstream.avail_in = len;
6784 s->zstream.next_in = (uint8_t *)buf;
6785 while (s->zstream.avail_in > 0) {
6786 ret = deflate(&s->zstream, Z_NO_FLUSH);
6789 if (s->zstream.avail_out == 0) {
6790 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6791 s->zstream.avail_out = IOBUF_SIZE;
6792 s->zstream.next_out = s->buf;
6798 static void ram_compress_close(RamCompressState *s)
6802 /* compress last bytes */
6804 ret = deflate(&s->zstream, Z_FINISH);
6805 if (ret == Z_OK || ret == Z_STREAM_END) {
6806 len = IOBUF_SIZE - s->zstream.avail_out;
6808 ram_put_cblock(s, s->buf, len);
6810 s->zstream.avail_out = IOBUF_SIZE;
6811 s->zstream.next_out = s->buf;
6812 if (ret == Z_STREAM_END)
6819 deflateEnd(&s->zstream);
6822 typedef struct RamDecompressState {
6825 uint8_t buf[IOBUF_SIZE];
6826 } RamDecompressState;
6828 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6831 memset(s, 0, sizeof(*s));
6833 ret = inflateInit(&s->zstream);
6839 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6843 s->zstream.avail_out = len;
6844 s->zstream.next_out = buf;
6845 while (s->zstream.avail_out > 0) {
6846 if (s->zstream.avail_in == 0) {
6847 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6849 clen = qemu_get_be16(s->f);
6850 if (clen > IOBUF_SIZE)
6852 qemu_get_buffer(s->f, s->buf, clen);
6853 s->zstream.avail_in = clen;
6854 s->zstream.next_in = s->buf;
6856 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6857 if (ret != Z_OK && ret != Z_STREAM_END) {
6864 static void ram_decompress_close(RamDecompressState *s)
6866 inflateEnd(&s->zstream);
6869 static void ram_save(QEMUFile *f, void *opaque)
6872 RamCompressState s1, *s = &s1;
6875 qemu_put_be32(f, phys_ram_size);
6876 if (ram_compress_open(s, f) < 0)
6878 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6880 if (tight_savevm_enabled) {
6884 /* find if the memory block is available on a virtual
6887 for(j = 0; j < nb_drives; j++) {
6888 sector_num = bdrv_hash_find(drives_table[j].bdrv,
6890 BDRV_HASH_BLOCK_SIZE);
6891 if (sector_num >= 0)
6895 goto normal_compress;
6898 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6899 ram_compress_buf(s, buf, 10);
6905 ram_compress_buf(s, buf, 1);
6906 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6909 ram_compress_close(s);
6912 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6914 RamDecompressState s1, *s = &s1;
6918 if (version_id == 1)
6919 return ram_load_v1(f, opaque);
6920 if (version_id != 2)
6922 if (qemu_get_be32(f) != phys_ram_size)
6924 if (ram_decompress_open(s, f) < 0)
6926 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6927 if (ram_decompress_buf(s, buf, 1) < 0) {
6928 fprintf(stderr, "Error while reading ram block header\n");
6932 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6933 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6942 ram_decompress_buf(s, buf + 1, 9);
6944 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6945 if (bs_index >= nb_drives) {
6946 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6949 if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6951 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6952 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6953 bs_index, sector_num);
6960 printf("Error block header\n");
6964 ram_decompress_close(s);
6968 /***********************************************************/
6969 /* bottom halves (can be seen as timers which expire ASAP) */
6978 static QEMUBH *first_bh = NULL;
6980 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6983 bh = qemu_mallocz(sizeof(QEMUBH));
6987 bh->opaque = opaque;
6991 int qemu_bh_poll(void)
7010 void qemu_bh_schedule(QEMUBH *bh)
7012 CPUState *env = cpu_single_env;
7016 bh->next = first_bh;
7019 /* stop the currently executing CPU to execute the BH ASAP */
7021 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7025 void qemu_bh_cancel(QEMUBH *bh)
7028 if (bh->scheduled) {
7031 pbh = &(*pbh)->next;
7037 void qemu_bh_delete(QEMUBH *bh)
7043 /***********************************************************/
7044 /* machine registration */
7046 QEMUMachine *first_machine = NULL;
7048 int qemu_register_machine(QEMUMachine *m)
7051 pm = &first_machine;
7059 static QEMUMachine *find_machine(const char *name)
7063 for(m = first_machine; m != NULL; m = m->next) {
7064 if (!strcmp(m->name, name))
7070 /***********************************************************/
7071 /* main execution loop */
7073 static void gui_update(void *opaque)
7075 DisplayState *ds = opaque;
7076 ds->dpy_refresh(ds);
7077 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
7080 struct vm_change_state_entry {
7081 VMChangeStateHandler *cb;
7083 LIST_ENTRY (vm_change_state_entry) entries;
7086 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7088 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7091 VMChangeStateEntry *e;
7093 e = qemu_mallocz(sizeof (*e));
7099 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7103 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7105 LIST_REMOVE (e, entries);
7109 static void vm_state_notify(int running)
7111 VMChangeStateEntry *e;
7113 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7114 e->cb(e->opaque, running);
7118 /* XXX: support several handlers */
7119 static VMStopHandler *vm_stop_cb;
7120 static void *vm_stop_opaque;
7122 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7125 vm_stop_opaque = opaque;
7129 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7140 qemu_rearm_alarm_timer(alarm_timer);
7144 void vm_stop(int reason)
7147 cpu_disable_ticks();
7151 vm_stop_cb(vm_stop_opaque, reason);
7158 /* reset/shutdown handler */
7160 typedef struct QEMUResetEntry {
7161 QEMUResetHandler *func;
7163 struct QEMUResetEntry *next;
7166 static QEMUResetEntry *first_reset_entry;
7167 static int reset_requested;
7168 static int shutdown_requested;
7169 static int powerdown_requested;
7171 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7173 QEMUResetEntry **pre, *re;
7175 pre = &first_reset_entry;
7176 while (*pre != NULL)
7177 pre = &(*pre)->next;
7178 re = qemu_mallocz(sizeof(QEMUResetEntry));
7180 re->opaque = opaque;
7185 static void qemu_system_reset(void)
7189 /* reset all devices */
7190 for(re = first_reset_entry; re != NULL; re = re->next) {
7191 re->func(re->opaque);
7195 void qemu_system_reset_request(void)
7198 shutdown_requested = 1;
7200 reset_requested = 1;
7203 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7206 void qemu_system_shutdown_request(void)
7208 shutdown_requested = 1;
7210 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7213 void qemu_system_powerdown_request(void)
7215 powerdown_requested = 1;
7217 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7220 void main_loop_wait(int timeout)
7222 IOHandlerRecord *ioh;
7223 fd_set rfds, wfds, xfds;
7232 /* XXX: need to suppress polling by better using win32 events */
7234 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7235 ret |= pe->func(pe->opaque);
7240 WaitObjects *w = &wait_objects;
7242 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7243 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7244 if (w->func[ret - WAIT_OBJECT_0])
7245 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7247 /* Check for additional signaled events */
7248 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7250 /* Check if event is signaled */
7251 ret2 = WaitForSingleObject(w->events[i], 0);
7252 if(ret2 == WAIT_OBJECT_0) {
7254 w->func[i](w->opaque[i]);
7255 } else if (ret2 == WAIT_TIMEOUT) {
7257 err = GetLastError();
7258 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7261 } else if (ret == WAIT_TIMEOUT) {
7263 err = GetLastError();
7264 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7268 /* poll any events */
7269 /* XXX: separate device handlers from system ones */
7274 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7278 (!ioh->fd_read_poll ||
7279 ioh->fd_read_poll(ioh->opaque) != 0)) {
7280 FD_SET(ioh->fd, &rfds);
7284 if (ioh->fd_write) {
7285 FD_SET(ioh->fd, &wfds);
7295 tv.tv_usec = timeout * 1000;
7297 #if defined(CONFIG_SLIRP)
7299 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7302 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7304 IOHandlerRecord **pioh;
7306 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7307 if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7308 ioh->fd_read(ioh->opaque);
7310 if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7311 ioh->fd_write(ioh->opaque);
7315 /* remove deleted IO handlers */
7316 pioh = &first_io_handler;
7326 #if defined(CONFIG_SLIRP)
7333 slirp_select_poll(&rfds, &wfds, &xfds);
7339 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7340 qemu_get_clock(vm_clock));
7341 /* run dma transfers, if any */
7345 /* real time timers */
7346 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7347 qemu_get_clock(rt_clock));
7349 /* Check bottom-halves last in case any of the earlier events triggered
7355 static int main_loop(void)
7358 #ifdef CONFIG_PROFILER
7363 cur_cpu = first_cpu;
7364 next_cpu = cur_cpu->next_cpu ?: first_cpu;
7371 #ifdef CONFIG_PROFILER
7372 ti = profile_getclock();
7374 ret = cpu_exec(env);
7375 #ifdef CONFIG_PROFILER
7376 qemu_time += profile_getclock() - ti;
7378 next_cpu = env->next_cpu ?: first_cpu;
7379 if (event_pending) {
7380 ret = EXCP_INTERRUPT;
7384 if (ret == EXCP_HLT) {
7385 /* Give the next CPU a chance to run. */
7389 if (ret != EXCP_HALTED)
7391 /* all CPUs are halted ? */
7397 if (shutdown_requested) {
7398 ret = EXCP_INTERRUPT;
7401 if (reset_requested) {
7402 reset_requested = 0;
7403 qemu_system_reset();
7404 ret = EXCP_INTERRUPT;
7406 if (powerdown_requested) {
7407 powerdown_requested = 0;
7408 qemu_system_powerdown();
7409 ret = EXCP_INTERRUPT;
7411 if (ret == EXCP_DEBUG) {
7412 vm_stop(EXCP_DEBUG);
7414 /* If all cpus are halted then wait until the next IRQ */
7415 /* XXX: use timeout computed from timers */
7416 if (ret == EXCP_HALTED)
7423 #ifdef CONFIG_PROFILER
7424 ti = profile_getclock();
7426 main_loop_wait(timeout);
7427 #ifdef CONFIG_PROFILER
7428 dev_time += profile_getclock() - ti;
7431 cpu_disable_ticks();
7435 static void help(int exitcode)
7437 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7438 "usage: %s [options] [disk_image]\n"
7440 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7442 "Standard options:\n"
7443 "-M machine select emulated machine (-M ? for list)\n"
7444 "-cpu cpu select CPU (-cpu ? for list)\n"
7445 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
7446 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
7447 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
7448 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7449 "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][index=i]\n"
7450 " [,cyls=c,heads=h,secs=s[,trans=t]][snapshot=on|off]\n"
7451 " use 'file' as a drive image\n"
7452 "-mtdblock file use 'file' as on-board Flash memory image\n"
7453 "-sd file use 'file' as SecureDigital card image\n"
7454 "-pflash file use 'file' as a parallel flash image\n"
7455 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7456 "-snapshot write to temporary files instead of disk image files\n"
7458 "-no-frame open SDL window without a frame and window decorations\n"
7459 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7460 "-no-quit disable SDL window close capability\n"
7463 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
7465 "-m megs set virtual RAM size to megs MB [default=%d]\n"
7466 "-smp n set the number of CPUs to 'n' [default=1]\n"
7467 "-nographic disable graphical output and redirect serial I/Os to console\n"
7468 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
7470 "-k language use keyboard layout (for example \"fr\" for French)\n"
7473 "-audio-help print list of audio drivers and their options\n"
7474 "-soundhw c1,... enable audio support\n"
7475 " and only specified sound cards (comma separated list)\n"
7476 " use -soundhw ? to get the list of supported cards\n"
7477 " use -soundhw all to enable all of them\n"
7479 "-localtime set the real time clock to local time [default=utc]\n"
7480 "-full-screen start in full screen\n"
7482 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
7484 "-usb enable the USB driver (will be the default soon)\n"
7485 "-usbdevice name add the host or guest USB device 'name'\n"
7486 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7487 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
7489 "-name string set the name of the guest\n"
7491 "Network options:\n"
7492 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7493 " create a new Network Interface Card and connect it to VLAN 'n'\n"
7495 "-net user[,vlan=n][,hostname=host]\n"
7496 " connect the user mode network stack to VLAN 'n' and send\n"
7497 " hostname 'host' to DHCP clients\n"
7500 "-net tap[,vlan=n],ifname=name\n"
7501 " connect the host TAP network interface to VLAN 'n'\n"
7503 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7504 " connect the host TAP network interface to VLAN 'n' and use the\n"
7505 " network scripts 'file' (default=%s)\n"
7506 " and 'dfile' (default=%s);\n"
7507 " use '[down]script=no' to disable script execution;\n"
7508 " use 'fd=h' to connect to an already opened TAP interface\n"
7510 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7511 " connect the vlan 'n' to another VLAN using a socket connection\n"
7512 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7513 " connect the vlan 'n' to multicast maddr and port\n"
7514 "-net none use it alone to have zero network devices; if no -net option\n"
7515 " is provided, the default is '-net nic -net user'\n"
7518 "-tftp dir allow tftp access to files in dir [-net user]\n"
7519 "-bootp file advertise file in BOOTP replies\n"
7521 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
7523 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7524 " redirect TCP or UDP connections from host to guest [-net user]\n"
7527 "Linux boot specific:\n"
7528 "-kernel bzImage use 'bzImage' as kernel image\n"
7529 "-append cmdline use 'cmdline' as kernel command line\n"
7530 "-initrd file use 'file' as initial ram disk\n"
7532 "Debug/Expert options:\n"
7533 "-monitor dev redirect the monitor to char device 'dev'\n"
7534 "-serial dev redirect the serial port to char device 'dev'\n"
7535 "-parallel dev redirect the parallel port to char device 'dev'\n"
7536 "-pidfile file Write PID to 'file'\n"
7537 "-S freeze CPU at startup (use 'c' to start execution)\n"
7538 "-s wait gdb connection to port\n"
7539 "-p port set gdb connection port [default=%s]\n"
7540 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
7541 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
7542 " translation (t=none or lba) (usually qemu can guess them)\n"
7543 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
7545 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
7546 "-no-kqemu disable KQEMU kernel module usage\n"
7549 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
7550 " (default is CL-GD5446 PCI VGA)\n"
7551 "-no-acpi disable ACPI\n"
7553 "-no-reboot exit instead of rebooting\n"
7554 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
7555 "-vnc display start a VNC server on display\n"
7557 "-daemonize daemonize QEMU after initializing\n"
7559 "-option-rom rom load a file, rom, into the option ROM space\n"
7561 "-prom-env variable=value set OpenBIOS nvram variables\n"
7563 "-clock force the use of the given methods for timer alarm.\n"
7564 " To see what timers are available use -clock help\n"
7566 "During emulation, the following keys are useful:\n"
7567 "ctrl-alt-f toggle full screen\n"
7568 "ctrl-alt-n switch to virtual console 'n'\n"
7569 "ctrl-alt toggle mouse and keyboard grab\n"
7571 "When using -nographic, press 'ctrl-a h' to get some help.\n"
7576 DEFAULT_NETWORK_SCRIPT,
7577 DEFAULT_NETWORK_DOWN_SCRIPT,
7579 DEFAULT_GDBSTUB_PORT,
7584 #define HAS_ARG 0x0001
7599 QEMU_OPTION_mtdblock,
7603 QEMU_OPTION_snapshot,
7605 QEMU_OPTION_no_fd_bootchk,
7608 QEMU_OPTION_nographic,
7609 QEMU_OPTION_portrait,
7611 QEMU_OPTION_audio_help,
7612 QEMU_OPTION_soundhw,
7632 QEMU_OPTION_no_code_copy,
7634 QEMU_OPTION_localtime,
7635 QEMU_OPTION_cirrusvga,
7638 QEMU_OPTION_std_vga,
7640 QEMU_OPTION_monitor,
7642 QEMU_OPTION_parallel,
7644 QEMU_OPTION_full_screen,
7645 QEMU_OPTION_no_frame,
7646 QEMU_OPTION_alt_grab,
7647 QEMU_OPTION_no_quit,
7648 QEMU_OPTION_pidfile,
7649 QEMU_OPTION_no_kqemu,
7650 QEMU_OPTION_kernel_kqemu,
7651 QEMU_OPTION_win2k_hack,
7653 QEMU_OPTION_usbdevice,
7656 QEMU_OPTION_no_acpi,
7657 QEMU_OPTION_no_reboot,
7658 QEMU_OPTION_show_cursor,
7659 QEMU_OPTION_daemonize,
7660 QEMU_OPTION_option_rom,
7661 QEMU_OPTION_semihosting,
7663 QEMU_OPTION_prom_env,
7664 QEMU_OPTION_old_param,
7666 QEMU_OPTION_startdate,
7669 typedef struct QEMUOption {
7675 const QEMUOption qemu_options[] = {
7676 { "h", 0, QEMU_OPTION_h },
7677 { "help", 0, QEMU_OPTION_h },
7679 { "M", HAS_ARG, QEMU_OPTION_M },
7680 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7681 { "fda", HAS_ARG, QEMU_OPTION_fda },
7682 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7683 { "hda", HAS_ARG, QEMU_OPTION_hda },
7684 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7685 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7686 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7687 { "drive", HAS_ARG, QEMU_OPTION_drive },
7688 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7689 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7690 { "sd", HAS_ARG, QEMU_OPTION_sd },
7691 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7692 { "boot", HAS_ARG, QEMU_OPTION_boot },
7693 { "snapshot", 0, QEMU_OPTION_snapshot },
7695 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7697 { "m", HAS_ARG, QEMU_OPTION_m },
7698 { "nographic", 0, QEMU_OPTION_nographic },
7699 { "portrait", 0, QEMU_OPTION_portrait },
7700 { "k", HAS_ARG, QEMU_OPTION_k },
7702 { "audio-help", 0, QEMU_OPTION_audio_help },
7703 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7706 { "net", HAS_ARG, QEMU_OPTION_net},
7708 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7709 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7711 { "smb", HAS_ARG, QEMU_OPTION_smb },
7713 { "redir", HAS_ARG, QEMU_OPTION_redir },
7716 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7717 { "append", HAS_ARG, QEMU_OPTION_append },
7718 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7720 { "S", 0, QEMU_OPTION_S },
7721 { "s", 0, QEMU_OPTION_s },
7722 { "p", HAS_ARG, QEMU_OPTION_p },
7723 { "d", HAS_ARG, QEMU_OPTION_d },
7724 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7725 { "L", HAS_ARG, QEMU_OPTION_L },
7726 { "bios", HAS_ARG, QEMU_OPTION_bios },
7727 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7729 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7730 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7732 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7733 { "g", 1, QEMU_OPTION_g },
7735 { "localtime", 0, QEMU_OPTION_localtime },
7736 { "std-vga", 0, QEMU_OPTION_std_vga },
7737 { "echr", HAS_ARG, QEMU_OPTION_echr },
7738 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7739 { "serial", HAS_ARG, QEMU_OPTION_serial },
7740 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7741 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7742 { "full-screen", 0, QEMU_OPTION_full_screen },
7744 { "no-frame", 0, QEMU_OPTION_no_frame },
7745 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7746 { "no-quit", 0, QEMU_OPTION_no_quit },
7748 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7749 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7750 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7751 { "smp", HAS_ARG, QEMU_OPTION_smp },
7752 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7754 /* temporary options */
7755 { "usb", 0, QEMU_OPTION_usb },
7756 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7757 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7758 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7759 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7760 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7761 { "daemonize", 0, QEMU_OPTION_daemonize },
7762 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7763 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7764 { "semihosting", 0, QEMU_OPTION_semihosting },
7766 { "name", HAS_ARG, QEMU_OPTION_name },
7767 #if defined(TARGET_SPARC)
7768 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7770 #if defined(TARGET_ARM)
7771 { "old-param", 0, QEMU_OPTION_old_param },
7773 { "clock", HAS_ARG, QEMU_OPTION_clock },
7774 { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7778 /* password input */
7780 int qemu_key_check(BlockDriverState *bs, const char *name)
7785 if (!bdrv_is_encrypted(bs))
7788 term_printf("%s is encrypted.\n", name);
7789 for(i = 0; i < 3; i++) {
7790 monitor_readline("Password: ", 1, password, sizeof(password));
7791 if (bdrv_set_key(bs, password) == 0)
7793 term_printf("invalid password\n");
7798 static BlockDriverState *get_bdrv(int index)
7800 if (index > nb_drives)
7802 return drives_table[index].bdrv;
7805 static void read_passwords(void)
7807 BlockDriverState *bs;
7810 for(i = 0; i < 6; i++) {
7813 qemu_key_check(bs, bdrv_get_device_name(bs));
7817 /* XXX: currently we cannot use simultaneously different CPUs */
7818 static void register_machines(void)
7820 #if defined(TARGET_I386)
7821 qemu_register_machine(&pc_machine);
7822 qemu_register_machine(&isapc_machine);
7823 #elif defined(TARGET_PPC)
7824 qemu_register_machine(&heathrow_machine);
7825 qemu_register_machine(&core99_machine);
7826 qemu_register_machine(&prep_machine);
7827 qemu_register_machine(&ref405ep_machine);
7828 qemu_register_machine(&taihu_machine);
7829 #elif defined(TARGET_MIPS)
7830 qemu_register_machine(&mips_machine);
7831 qemu_register_machine(&mips_malta_machine);
7832 qemu_register_machine(&mips_pica61_machine);
7833 qemu_register_machine(&mips_mipssim_machine);
7834 #elif defined(TARGET_SPARC)
7835 #ifdef TARGET_SPARC64
7836 qemu_register_machine(&sun4u_machine);
7838 qemu_register_machine(&ss5_machine);
7839 qemu_register_machine(&ss10_machine);
7840 qemu_register_machine(&ss600mp_machine);
7842 #elif defined(TARGET_ARM)
7843 qemu_register_machine(&integratorcp_machine);
7844 qemu_register_machine(&versatilepb_machine);
7845 qemu_register_machine(&versatileab_machine);
7846 qemu_register_machine(&realview_machine);
7847 qemu_register_machine(&akitapda_machine);
7848 qemu_register_machine(&spitzpda_machine);
7849 qemu_register_machine(&borzoipda_machine);
7850 qemu_register_machine(&terrierpda_machine);
7851 qemu_register_machine(&palmte_machine);
7852 qemu_register_machine(&lm3s811evb_machine);
7853 qemu_register_machine(&lm3s6965evb_machine);
7854 qemu_register_machine(&connex_machine);
7855 qemu_register_machine(&verdex_machine);
7856 qemu_register_machine(&mainstone2_machine);
7857 #elif defined(TARGET_SH4)
7858 qemu_register_machine(&shix_machine);
7859 qemu_register_machine(&r2d_machine);
7860 #elif defined(TARGET_ALPHA)
7862 #elif defined(TARGET_M68K)
7863 qemu_register_machine(&mcf5208evb_machine);
7864 qemu_register_machine(&an5206_machine);
7865 qemu_register_machine(&dummy_m68k_machine);
7866 #elif defined(TARGET_CRIS)
7867 qemu_register_machine(&bareetraxfs_machine);
7869 #error unsupported CPU
7874 struct soundhw soundhw[] = {
7875 #ifdef HAS_AUDIO_CHOICE
7882 { .init_isa = pcspk_audio_init }
7887 "Creative Sound Blaster 16",
7890 { .init_isa = SB16_init }
7897 "Yamaha YMF262 (OPL3)",
7899 "Yamaha YM3812 (OPL2)",
7903 { .init_isa = Adlib_init }
7910 "Gravis Ultrasound GF1",
7913 { .init_isa = GUS_init }
7919 "ENSONIQ AudioPCI ES1370",
7922 { .init_pci = es1370_init }
7926 { NULL, NULL, 0, 0, { NULL } }
7929 static void select_soundhw (const char *optarg)
7933 if (*optarg == '?') {
7936 printf ("Valid sound card names (comma separated):\n");
7937 for (c = soundhw; c->name; ++c) {
7938 printf ("%-11s %s\n", c->name, c->descr);
7940 printf ("\n-soundhw all will enable all of the above\n");
7941 exit (*optarg != '?');
7949 if (!strcmp (optarg, "all")) {
7950 for (c = soundhw; c->name; ++c) {
7958 e = strchr (p, ',');
7959 l = !e ? strlen (p) : (size_t) (e - p);
7961 for (c = soundhw; c->name; ++c) {
7962 if (!strncmp (c->name, p, l)) {
7971 "Unknown sound card name (too big to show)\n");
7974 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7979 p += l + (e != NULL);
7983 goto show_valid_cards;
7989 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7991 exit(STATUS_CONTROL_C_EXIT);
7996 #define MAX_NET_CLIENTS 32
7998 int main(int argc, char **argv)
8000 #ifdef CONFIG_GDBSTUB
8002 const char *gdbstub_port;
8004 uint32_t boot_devices_bitmap = 0;
8006 int snapshot, linux_boot, net_boot;
8007 const char *initrd_filename;
8008 const char *kernel_filename, *kernel_cmdline;
8009 const char *boot_devices = "";
8010 DisplayState *ds = &display_state;
8011 int cyls, heads, secs, translation;
8012 char net_clients[MAX_NET_CLIENTS][256];
8016 const char *r, *optarg;
8017 CharDriverState *monitor_hd;
8018 char monitor_device[128];
8019 char serial_devices[MAX_SERIAL_PORTS][128];
8020 int serial_device_index;
8021 char parallel_devices[MAX_PARALLEL_PORTS][128];
8022 int parallel_device_index;
8023 const char *loadvm = NULL;
8024 QEMUMachine *machine;
8025 const char *cpu_model;
8026 char usb_devices[MAX_USB_CMDLINE][128];
8027 int usb_devices_index;
8029 const char *pid_file = NULL;
8032 LIST_INIT (&vm_change_state_head);
8035 struct sigaction act;
8036 sigfillset(&act.sa_mask);
8038 act.sa_handler = SIG_IGN;
8039 sigaction(SIGPIPE, &act, NULL);
8042 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8043 /* Note: cpu_interrupt() is currently not SMP safe, so we force
8044 QEMU to run on a single CPU */
8049 h = GetCurrentProcess();
8050 if (GetProcessAffinityMask(h, &mask, &smask)) {
8051 for(i = 0; i < 32; i++) {
8052 if (mask & (1 << i))
8057 SetProcessAffinityMask(h, mask);
8063 register_machines();
8064 machine = first_machine;
8066 initrd_filename = NULL;
8067 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8068 vga_ram_size = VGA_RAM_SIZE;
8069 #ifdef CONFIG_GDBSTUB
8071 gdbstub_port = DEFAULT_GDBSTUB_PORT;
8075 kernel_filename = NULL;
8076 kernel_cmdline = "";
8077 cyls = heads = secs = 0;
8078 translation = BIOS_ATA_TRANSLATION_AUTO;
8079 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
8081 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
8082 for(i = 1; i < MAX_SERIAL_PORTS; i++)
8083 serial_devices[i][0] = '\0';
8084 serial_device_index = 0;
8086 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
8087 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8088 parallel_devices[i][0] = '\0';
8089 parallel_device_index = 0;
8091 usb_devices_index = 0;
8099 /* default mac address of the first network interface */
8107 hda_index = drive_add(HD_ALIAS, argv[optind++], 0);
8109 const QEMUOption *popt;
8112 /* Treat --foo the same as -foo. */
8115 popt = qemu_options;
8118 fprintf(stderr, "%s: invalid option -- '%s'\n",
8122 if (!strcmp(popt->name, r + 1))
8126 if (popt->flags & HAS_ARG) {
8127 if (optind >= argc) {
8128 fprintf(stderr, "%s: option '%s' requires an argument\n",
8132 optarg = argv[optind++];
8137 switch(popt->index) {
8139 machine = find_machine(optarg);
8142 printf("Supported machines are:\n");
8143 for(m = first_machine; m != NULL; m = m->next) {
8144 printf("%-10s %s%s\n",
8146 m == first_machine ? " (default)" : "");
8148 exit(*optarg != '?');
8151 case QEMU_OPTION_cpu:
8152 /* hw initialization will check this */
8153 if (*optarg == '?') {
8154 /* XXX: implement xxx_cpu_list for targets that still miss it */
8155 #if defined(cpu_list)
8156 cpu_list(stdout, &fprintf);
8163 case QEMU_OPTION_initrd:
8164 initrd_filename = optarg;
8166 case QEMU_OPTION_hda:
8168 hda_index = drive_add(HD_ALIAS, optarg, 0);
8170 hda_index = drive_add(HD_ALIAS
8171 ",cyls=%d,heads=%d,secs=%d%s",
8172 optarg, 0, cyls, heads, secs,
8173 translation == BIOS_ATA_TRANSLATION_LBA ?
8175 translation == BIOS_ATA_TRANSLATION_NONE ?
8176 ",trans=none" : "");
8178 case QEMU_OPTION_hdb:
8179 case QEMU_OPTION_hdc:
8180 case QEMU_OPTION_hdd:
8181 drive_add(HD_ALIAS, optarg, popt->index - QEMU_OPTION_hda);
8183 case QEMU_OPTION_drive:
8184 drive_add("%s", optarg);
8186 case QEMU_OPTION_mtdblock:
8187 drive_add(MTD_ALIAS, optarg);
8189 case QEMU_OPTION_sd:
8190 drive_add("file=\"%s\"," SD_ALIAS, optarg);
8192 case QEMU_OPTION_pflash:
8193 drive_add(PFLASH_ALIAS, optarg);
8195 case QEMU_OPTION_snapshot:
8198 case QEMU_OPTION_hdachs:
8202 cyls = strtol(p, (char **)&p, 0);
8203 if (cyls < 1 || cyls > 16383)
8208 heads = strtol(p, (char **)&p, 0);
8209 if (heads < 1 || heads > 16)
8214 secs = strtol(p, (char **)&p, 0);
8215 if (secs < 1 || secs > 63)
8219 if (!strcmp(p, "none"))
8220 translation = BIOS_ATA_TRANSLATION_NONE;
8221 else if (!strcmp(p, "lba"))
8222 translation = BIOS_ATA_TRANSLATION_LBA;
8223 else if (!strcmp(p, "auto"))
8224 translation = BIOS_ATA_TRANSLATION_AUTO;
8227 } else if (*p != '\0') {
8229 fprintf(stderr, "qemu: invalid physical CHS format\n");
8232 if (hda_index != -1)
8233 snprintf(drives_opt[hda_index] +
8234 strlen(drives_opt[hda_index]),
8235 sizeof(drives_opt[0]) -
8236 strlen(drives_opt[hda_index]),
8237 ",cyls=%d,heads=%d,secs=%d%s",
8239 translation == BIOS_ATA_TRANSLATION_LBA ?
8241 translation == BIOS_ATA_TRANSLATION_NONE ?
8242 ",trans=none" : "");
8245 case QEMU_OPTION_nographic:
8246 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
8247 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
8248 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
8251 case QEMU_OPTION_portrait:
8254 case QEMU_OPTION_kernel:
8255 kernel_filename = optarg;
8257 case QEMU_OPTION_append:
8258 kernel_cmdline = optarg;
8260 case QEMU_OPTION_cdrom:
8261 drive_add("file=\"%s\"," CDROM_ALIAS, optarg);
8263 case QEMU_OPTION_boot:
8264 boot_devices = optarg;
8265 /* We just do some generic consistency checks */
8267 /* Could easily be extended to 64 devices if needed */
8268 const unsigned char *p;
8270 boot_devices_bitmap = 0;
8271 for (p = boot_devices; *p != '\0'; p++) {
8272 /* Allowed boot devices are:
8273 * a b : floppy disk drives
8274 * c ... f : IDE disk drives
8275 * g ... m : machine implementation dependant drives
8276 * n ... p : network devices
8277 * It's up to each machine implementation to check
8278 * if the given boot devices match the actual hardware
8279 * implementation and firmware features.
8281 if (*p < 'a' || *p > 'q') {
8282 fprintf(stderr, "Invalid boot device '%c'\n", *p);
8285 if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8287 "Boot device '%c' was given twice\n",*p);
8290 boot_devices_bitmap |= 1 << (*p - 'a');
8294 case QEMU_OPTION_fda:
8295 case QEMU_OPTION_fdb:
8296 drive_add("file=\"%s\"," FD_ALIAS, optarg,
8297 popt->index - QEMU_OPTION_fda);
8300 case QEMU_OPTION_no_fd_bootchk:
8304 case QEMU_OPTION_no_code_copy:
8305 code_copy_enabled = 0;
8307 case QEMU_OPTION_net:
8308 if (nb_net_clients >= MAX_NET_CLIENTS) {
8309 fprintf(stderr, "qemu: too many network clients\n");
8312 pstrcpy(net_clients[nb_net_clients],
8313 sizeof(net_clients[0]),
8318 case QEMU_OPTION_tftp:
8319 tftp_prefix = optarg;
8321 case QEMU_OPTION_bootp:
8322 bootp_filename = optarg;
8325 case QEMU_OPTION_smb:
8326 net_slirp_smb(optarg);
8329 case QEMU_OPTION_redir:
8330 net_slirp_redir(optarg);
8334 case QEMU_OPTION_audio_help:
8338 case QEMU_OPTION_soundhw:
8339 select_soundhw (optarg);
8346 ram_size = atoi(optarg) * 1024 * 1024;
8349 if (ram_size > PHYS_RAM_MAX_SIZE) {
8350 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
8351 PHYS_RAM_MAX_SIZE / (1024 * 1024));
8360 mask = cpu_str_to_log_mask(optarg);
8362 printf("Log items (comma separated):\n");
8363 for(item = cpu_log_items; item->mask != 0; item++) {
8364 printf("%-10s %s\n", item->name, item->help);
8371 #ifdef CONFIG_GDBSTUB
8376 gdbstub_port = optarg;
8382 case QEMU_OPTION_bios:
8389 keyboard_layout = optarg;
8391 case QEMU_OPTION_localtime:
8394 case QEMU_OPTION_cirrusvga:
8395 cirrus_vga_enabled = 1;
8398 case QEMU_OPTION_vmsvga:
8399 cirrus_vga_enabled = 0;
8402 case QEMU_OPTION_std_vga:
8403 cirrus_vga_enabled = 0;
8411 w = strtol(p, (char **)&p, 10);
8414 fprintf(stderr, "qemu: invalid resolution or depth\n");
8420 h = strtol(p, (char **)&p, 10);
8425 depth = strtol(p, (char **)&p, 10);
8426 if (depth != 8 && depth != 15 && depth != 16 &&
8427 depth != 24 && depth != 32)
8429 } else if (*p == '\0') {
8430 depth = graphic_depth;
8437 graphic_depth = depth;
8440 case QEMU_OPTION_echr:
8443 term_escape_char = strtol(optarg, &r, 0);
8445 printf("Bad argument to echr\n");
8448 case QEMU_OPTION_monitor:
8449 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8451 case QEMU_OPTION_serial:
8452 if (serial_device_index >= MAX_SERIAL_PORTS) {
8453 fprintf(stderr, "qemu: too many serial ports\n");
8456 pstrcpy(serial_devices[serial_device_index],
8457 sizeof(serial_devices[0]), optarg);
8458 serial_device_index++;
8460 case QEMU_OPTION_parallel:
8461 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8462 fprintf(stderr, "qemu: too many parallel ports\n");
8465 pstrcpy(parallel_devices[parallel_device_index],
8466 sizeof(parallel_devices[0]), optarg);
8467 parallel_device_index++;
8469 case QEMU_OPTION_loadvm:
8472 case QEMU_OPTION_full_screen:
8476 case QEMU_OPTION_no_frame:
8479 case QEMU_OPTION_alt_grab:
8482 case QEMU_OPTION_no_quit:
8486 case QEMU_OPTION_pidfile:
8490 case QEMU_OPTION_win2k_hack:
8491 win2k_install_hack = 1;
8495 case QEMU_OPTION_no_kqemu:
8498 case QEMU_OPTION_kernel_kqemu:
8502 case QEMU_OPTION_usb:
8505 case QEMU_OPTION_usbdevice:
8507 if (usb_devices_index >= MAX_USB_CMDLINE) {
8508 fprintf(stderr, "Too many USB devices\n");
8511 pstrcpy(usb_devices[usb_devices_index],
8512 sizeof(usb_devices[usb_devices_index]),
8514 usb_devices_index++;
8516 case QEMU_OPTION_smp:
8517 smp_cpus = atoi(optarg);
8518 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8519 fprintf(stderr, "Invalid number of CPUs\n");
8523 case QEMU_OPTION_vnc:
8524 vnc_display = optarg;
8526 case QEMU_OPTION_no_acpi:
8529 case QEMU_OPTION_no_reboot:
8532 case QEMU_OPTION_show_cursor:
8535 case QEMU_OPTION_daemonize:
8538 case QEMU_OPTION_option_rom:
8539 if (nb_option_roms >= MAX_OPTION_ROMS) {
8540 fprintf(stderr, "Too many option ROMs\n");
8543 option_rom[nb_option_roms] = optarg;
8546 case QEMU_OPTION_semihosting:
8547 semihosting_enabled = 1;
8549 case QEMU_OPTION_name:
8553 case QEMU_OPTION_prom_env:
8554 if (nb_prom_envs >= MAX_PROM_ENVS) {
8555 fprintf(stderr, "Too many prom variables\n");
8558 prom_envs[nb_prom_envs] = optarg;
8563 case QEMU_OPTION_old_param:
8566 case QEMU_OPTION_clock:
8567 configure_alarms(optarg);
8569 case QEMU_OPTION_startdate:
8572 if (!strcmp(optarg, "now")) {
8573 rtc_start_date = -1;
8575 if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8583 } else if (sscanf(optarg, "%d-%d-%d",
8586 &tm.tm_mday) == 3) {
8595 rtc_start_date = mktimegm(&tm);
8596 if (rtc_start_date == -1) {
8598 fprintf(stderr, "Invalid date format. Valid format are:\n"
8599 "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8610 if (daemonize && !nographic && vnc_display == NULL) {
8611 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8618 if (pipe(fds) == -1)
8629 len = read(fds[0], &status, 1);
8630 if (len == -1 && (errno == EINTR))
8635 else if (status == 1) {
8636 fprintf(stderr, "Could not acquire pidfile\n");
8654 signal(SIGTSTP, SIG_IGN);
8655 signal(SIGTTOU, SIG_IGN);
8656 signal(SIGTTIN, SIG_IGN);
8660 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8663 write(fds[1], &status, 1);
8665 fprintf(stderr, "Could not acquire pid file\n");
8673 linux_boot = (kernel_filename != NULL);
8674 net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8676 /* XXX: this should not be: some embedded targets just have flash */
8677 if (!linux_boot && net_boot == 0 &&
8681 /* boot to floppy or the default cd if no hard disk defined yet */
8682 if (!boot_devices[0]) {
8683 boot_devices = "cad";
8685 setvbuf(stdout, NULL, _IOLBF, 0);
8695 /* init network clients */
8696 if (nb_net_clients == 0) {
8697 /* if no clients, we use a default config */
8698 pstrcpy(net_clients[0], sizeof(net_clients[0]),
8700 pstrcpy(net_clients[1], sizeof(net_clients[0]),
8705 for(i = 0;i < nb_net_clients; i++) {
8706 if (net_client_init(net_clients[i]) < 0)
8709 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8710 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8712 if (vlan->nb_guest_devs == 0) {
8713 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8716 if (vlan->nb_host_devs == 0)
8718 "Warning: vlan %d is not connected to host network\n",
8723 /* XXX: this should be moved in the PC machine instanciation code */
8724 if (net_boot != 0) {
8726 for (i = 0; i < nb_nics && i < 4; i++) {
8727 const char *model = nd_table[i].model;
8729 if (net_boot & (1 << i)) {
8732 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8733 if (get_image_size(buf) > 0) {
8734 if (nb_option_roms >= MAX_OPTION_ROMS) {
8735 fprintf(stderr, "Too many option ROMs\n");
8738 option_rom[nb_option_roms] = strdup(buf);
8745 fprintf(stderr, "No valid PXE rom found for network device\n");
8751 /* init the memory */
8752 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8754 phys_ram_base = qemu_vmalloc(phys_ram_size);
8755 if (!phys_ram_base) {
8756 fprintf(stderr, "Could not allocate physical memory\n");
8762 /* we always create the cdrom drive, even if no disk is there */
8764 if (nb_drives_opt < MAX_DRIVES)
8765 drive_add(CDROM_ALIAS);
8767 /* we always create at least one floppy */
8769 if (nb_drives_opt < MAX_DRIVES)
8770 drive_add(FD_ALIAS, 0);
8772 /* we always create one sd slot, even if no card is in it */
8774 if (nb_drives_opt < MAX_DRIVES)
8775 drive_add(SD_ALIAS);
8777 /* open the virtual block devices */
8779 for(i = 0; i < nb_drives_opt; i++)
8780 if (drive_init(drives_opt[i], snapshot, machine) == -1)
8783 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8784 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8789 memset(&display_state, 0, sizeof(display_state));
8791 /* nearly nothing to do */
8792 dumb_display_init(ds);
8793 } else if (vnc_display != NULL) {
8794 vnc_display_init(ds);
8795 if (vnc_display_open(ds, vnc_display) < 0)
8798 #if defined(CONFIG_SDL)
8799 sdl_display_init(ds, full_screen, no_frame);
8800 #elif defined(CONFIG_COCOA)
8801 cocoa_display_init(ds, full_screen);
8803 dumb_display_init(ds);
8807 /* Maintain compatibility with multiple stdio monitors */
8808 if (!strcmp(monitor_device,"stdio")) {
8809 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8810 if (!strcmp(serial_devices[i],"mon:stdio")) {
8811 monitor_device[0] = '\0';
8813 } else if (!strcmp(serial_devices[i],"stdio")) {
8814 monitor_device[0] = '\0';
8815 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8820 if (monitor_device[0] != '\0') {
8821 monitor_hd = qemu_chr_open(monitor_device);
8823 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8826 monitor_init(monitor_hd, !nographic);
8829 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8830 const char *devname = serial_devices[i];
8831 if (devname[0] != '\0' && strcmp(devname, "none")) {
8832 serial_hds[i] = qemu_chr_open(devname);
8833 if (!serial_hds[i]) {
8834 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8838 if (strstart(devname, "vc", 0))
8839 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8843 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8844 const char *devname = parallel_devices[i];
8845 if (devname[0] != '\0' && strcmp(devname, "none")) {
8846 parallel_hds[i] = qemu_chr_open(devname);
8847 if (!parallel_hds[i]) {
8848 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8852 if (strstart(devname, "vc", 0))
8853 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8857 machine->init(ram_size, vga_ram_size, boot_devices, ds,
8858 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8860 /* init USB devices */
8862 for(i = 0; i < usb_devices_index; i++) {
8863 if (usb_device_add(usb_devices[i]) < 0) {
8864 fprintf(stderr, "Warning: could not add USB device %s\n",
8870 if (display_state.dpy_refresh) {
8871 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8872 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8875 #ifdef CONFIG_GDBSTUB
8877 /* XXX: use standard host:port notation and modify options
8879 if (gdbserver_start(gdbstub_port) < 0) {
8880 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8891 /* XXX: simplify init */
8904 len = write(fds[1], &status, 1);
8905 if (len == -1 && (errno == EINTR))
8911 TFR(fd = open("/dev/null", O_RDWR));
8925 #if !defined(_WIN32)
8926 /* close network clients */
8927 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8928 VLANClientState *vc;
8930 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8931 if (vc->fd_read == tap_receive) {
8933 TAPState *s = vc->opaque;
8935 if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8937 launch_script(s->down_script, ifname, s->fd);