4 * Copyright (c) 2003-2007 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
35 #include <sys/times.h>
40 #include <sys/ioctl.h>
41 #include <sys/socket.h>
42 #include <netinet/in.h>
50 #elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
51 #include <freebsd/stdlib.h>
55 #include <linux/if_tun.h>
58 #include <linux/rtc.h>
59 #include <linux/hpet.h>
60 #include <linux/ppdev.h>
61 #include <linux/parport.h>
64 #include <sys/ethernet.h>
65 #include <sys/sockio.h>
66 #include <arpa/inet.h>
67 #include <netinet/arp.h>
68 #include <netinet/in.h>
69 #include <netinet/in_systm.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_icmp.h> // must come after ip.h
72 #include <netinet/udp.h>
73 #include <netinet/tcp.h>
81 #if defined(CONFIG_SLIRP)
87 #include <sys/timeb.h>
89 #define getopt_long_only getopt_long
90 #define memalign(align, size) malloc(size)
93 #include "qemu_socket.h"
99 #endif /* CONFIG_SDL */
103 #define main qemu_main
104 #endif /* CONFIG_COCOA */
108 #include "exec-all.h"
110 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
112 #define SMBD_COMMAND "/usr/sfw/sbin/smbd"
114 #define SMBD_COMMAND "/usr/sbin/smbd"
117 //#define DEBUG_UNUSED_IOPORT
118 //#define DEBUG_IOPORT
120 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
123 #define DEFAULT_RAM_SIZE 144
125 #define DEFAULT_RAM_SIZE 128
128 #define GUI_REFRESH_INTERVAL 30
130 /* Max number of USB devices that can be specified on the commandline. */
131 #define MAX_USB_CMDLINE 8
133 /* XXX: use a two level table to limit memory usage */
134 #define MAX_IOPORTS 65536
136 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
137 char phys_ram_file[1024];
138 void *ioport_opaque[MAX_IOPORTS];
139 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
140 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
141 /* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
142 to store the VM snapshots */
143 BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
144 BlockDriverState *pflash_table[MAX_PFLASH];
145 BlockDriverState *sd_bdrv;
146 BlockDriverState *mtd_bdrv;
147 /* point to the block driver where the snapshots are managed */
148 BlockDriverState *bs_snapshots;
150 static DisplayState display_state;
152 const char* keyboard_layout = NULL;
153 int64_t ticks_per_sec;
154 int boot_device = 'c';
156 int pit_min_timer_count = 0;
158 NICInfo nd_table[MAX_NICS];
161 int cirrus_vga_enabled = 1;
162 int vmsvga_enabled = 0;
164 int graphic_width = 1024;
165 int graphic_height = 768;
166 int graphic_depth = 8;
168 int graphic_width = 800;
169 int graphic_height = 600;
170 int graphic_depth = 15;
175 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
176 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
178 int win2k_install_hack = 0;
181 static VLANState *first_vlan;
183 const char *vnc_display;
184 #if defined(TARGET_SPARC)
186 #elif defined(TARGET_I386)
191 int acpi_enabled = 1;
195 int graphic_rotate = 0;
197 const char *option_rom[MAX_OPTION_ROMS];
199 int semihosting_enabled = 0;
204 const char *qemu_name;
207 unsigned int nb_prom_envs = 0;
208 const char *prom_envs[MAX_PROM_ENVS];
211 #define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
213 /***********************************************************/
214 /* x86 ISA bus support */
216 target_phys_addr_t isa_mem_base = 0;
219 uint32_t default_ioport_readb(void *opaque, uint32_t address)
221 #ifdef DEBUG_UNUSED_IOPORT
222 fprintf(stderr, "unused inb: port=0x%04x\n", address);
227 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
229 #ifdef DEBUG_UNUSED_IOPORT
230 fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
234 /* default is to make two byte accesses */
235 uint32_t default_ioport_readw(void *opaque, uint32_t address)
238 data = ioport_read_table[0][address](ioport_opaque[address], address);
239 address = (address + 1) & (MAX_IOPORTS - 1);
240 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
244 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
246 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
247 address = (address + 1) & (MAX_IOPORTS - 1);
248 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
251 uint32_t default_ioport_readl(void *opaque, uint32_t address)
253 #ifdef DEBUG_UNUSED_IOPORT
254 fprintf(stderr, "unused inl: port=0x%04x\n", address);
259 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
261 #ifdef DEBUG_UNUSED_IOPORT
262 fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
266 void init_ioports(void)
270 for(i = 0; i < MAX_IOPORTS; i++) {
271 ioport_read_table[0][i] = default_ioport_readb;
272 ioport_write_table[0][i] = default_ioport_writeb;
273 ioport_read_table[1][i] = default_ioport_readw;
274 ioport_write_table[1][i] = default_ioport_writew;
275 ioport_read_table[2][i] = default_ioport_readl;
276 ioport_write_table[2][i] = default_ioport_writel;
280 /* size is the word size in byte */
281 int register_ioport_read(int start, int length, int size,
282 IOPortReadFunc *func, void *opaque)
288 } else if (size == 2) {
290 } else if (size == 4) {
293 hw_error("register_ioport_read: invalid size");
296 for(i = start; i < start + length; i += size) {
297 ioport_read_table[bsize][i] = func;
298 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
299 hw_error("register_ioport_read: invalid opaque");
300 ioport_opaque[i] = opaque;
305 /* size is the word size in byte */
306 int register_ioport_write(int start, int length, int size,
307 IOPortWriteFunc *func, void *opaque)
313 } else if (size == 2) {
315 } else if (size == 4) {
318 hw_error("register_ioport_write: invalid size");
321 for(i = start; i < start + length; i += size) {
322 ioport_write_table[bsize][i] = func;
323 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
324 hw_error("register_ioport_write: invalid opaque");
325 ioport_opaque[i] = opaque;
330 void isa_unassign_ioport(int start, int length)
334 for(i = start; i < start + length; i++) {
335 ioport_read_table[0][i] = default_ioport_readb;
336 ioport_read_table[1][i] = default_ioport_readw;
337 ioport_read_table[2][i] = default_ioport_readl;
339 ioport_write_table[0][i] = default_ioport_writeb;
340 ioport_write_table[1][i] = default_ioport_writew;
341 ioport_write_table[2][i] = default_ioport_writel;
345 /***********************************************************/
347 void cpu_outb(CPUState *env, int addr, int val)
350 if (loglevel & CPU_LOG_IOPORT)
351 fprintf(logfile, "outb: %04x %02x\n", addr, val);
353 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
356 env->last_io_time = cpu_get_time_fast();
360 void cpu_outw(CPUState *env, int addr, int val)
363 if (loglevel & CPU_LOG_IOPORT)
364 fprintf(logfile, "outw: %04x %04x\n", addr, val);
366 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
369 env->last_io_time = cpu_get_time_fast();
373 void cpu_outl(CPUState *env, int addr, int val)
376 if (loglevel & CPU_LOG_IOPORT)
377 fprintf(logfile, "outl: %04x %08x\n", addr, val);
379 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
382 env->last_io_time = cpu_get_time_fast();
386 int cpu_inb(CPUState *env, int addr)
389 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
391 if (loglevel & CPU_LOG_IOPORT)
392 fprintf(logfile, "inb : %04x %02x\n", addr, val);
396 env->last_io_time = cpu_get_time_fast();
401 int cpu_inw(CPUState *env, int addr)
404 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
406 if (loglevel & CPU_LOG_IOPORT)
407 fprintf(logfile, "inw : %04x %04x\n", addr, val);
411 env->last_io_time = cpu_get_time_fast();
416 int cpu_inl(CPUState *env, int addr)
419 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
421 if (loglevel & CPU_LOG_IOPORT)
422 fprintf(logfile, "inl : %04x %08x\n", addr, val);
426 env->last_io_time = cpu_get_time_fast();
431 /***********************************************************/
432 void hw_error(const char *fmt, ...)
438 fprintf(stderr, "qemu: hardware error: ");
439 vfprintf(stderr, fmt, ap);
440 fprintf(stderr, "\n");
441 for(env = first_cpu; env != NULL; env = env->next_cpu) {
442 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
444 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
446 cpu_dump_state(env, stderr, fprintf, 0);
453 /***********************************************************/
456 static QEMUPutKBDEvent *qemu_put_kbd_event;
457 static void *qemu_put_kbd_event_opaque;
458 static QEMUPutMouseEntry *qemu_put_mouse_event_head;
459 static QEMUPutMouseEntry *qemu_put_mouse_event_current;
461 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
463 qemu_put_kbd_event_opaque = opaque;
464 qemu_put_kbd_event = func;
467 QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
468 void *opaque, int absolute,
471 QEMUPutMouseEntry *s, *cursor;
473 s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
477 s->qemu_put_mouse_event = func;
478 s->qemu_put_mouse_event_opaque = opaque;
479 s->qemu_put_mouse_event_absolute = absolute;
480 s->qemu_put_mouse_event_name = qemu_strdup(name);
483 if (!qemu_put_mouse_event_head) {
484 qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
488 cursor = qemu_put_mouse_event_head;
489 while (cursor->next != NULL)
490 cursor = cursor->next;
493 qemu_put_mouse_event_current = s;
498 void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
500 QEMUPutMouseEntry *prev = NULL, *cursor;
502 if (!qemu_put_mouse_event_head || entry == NULL)
505 cursor = qemu_put_mouse_event_head;
506 while (cursor != NULL && cursor != entry) {
508 cursor = cursor->next;
511 if (cursor == NULL) // does not exist or list empty
513 else if (prev == NULL) { // entry is head
514 qemu_put_mouse_event_head = cursor->next;
515 if (qemu_put_mouse_event_current == entry)
516 qemu_put_mouse_event_current = cursor->next;
517 qemu_free(entry->qemu_put_mouse_event_name);
522 prev->next = entry->next;
524 if (qemu_put_mouse_event_current == entry)
525 qemu_put_mouse_event_current = prev;
527 qemu_free(entry->qemu_put_mouse_event_name);
531 void kbd_put_keycode(int keycode)
533 if (qemu_put_kbd_event) {
534 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
538 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
540 QEMUPutMouseEvent *mouse_event;
541 void *mouse_event_opaque;
544 if (!qemu_put_mouse_event_current) {
549 qemu_put_mouse_event_current->qemu_put_mouse_event;
551 qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
554 if (graphic_rotate) {
555 if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
558 width = graphic_width;
559 mouse_event(mouse_event_opaque,
560 width - dy, dx, dz, buttons_state);
562 mouse_event(mouse_event_opaque,
563 dx, dy, dz, buttons_state);
567 int kbd_mouse_is_absolute(void)
569 if (!qemu_put_mouse_event_current)
572 return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
575 void do_info_mice(void)
577 QEMUPutMouseEntry *cursor;
580 if (!qemu_put_mouse_event_head) {
581 term_printf("No mouse devices connected\n");
585 term_printf("Mouse devices available:\n");
586 cursor = qemu_put_mouse_event_head;
587 while (cursor != NULL) {
588 term_printf("%c Mouse #%d: %s\n",
589 (cursor == qemu_put_mouse_event_current ? '*' : ' '),
590 index, cursor->qemu_put_mouse_event_name);
592 cursor = cursor->next;
596 void do_mouse_set(int index)
598 QEMUPutMouseEntry *cursor;
601 if (!qemu_put_mouse_event_head) {
602 term_printf("No mouse devices connected\n");
606 cursor = qemu_put_mouse_event_head;
607 while (cursor != NULL && index != i) {
609 cursor = cursor->next;
613 qemu_put_mouse_event_current = cursor;
615 term_printf("Mouse at given index not found\n");
618 /* compute with 96 bit intermediate result: (a*b)/c */
619 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
624 #ifdef WORDS_BIGENDIAN
634 rl = (uint64_t)u.l.low * (uint64_t)b;
635 rh = (uint64_t)u.l.high * (uint64_t)b;
638 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
642 /***********************************************************/
643 /* real time host monotonic timer */
645 #define QEMU_TIMER_BASE 1000000000LL
649 static int64_t clock_freq;
651 static void init_get_clock(void)
655 ret = QueryPerformanceFrequency(&freq);
657 fprintf(stderr, "Could not calibrate ticks\n");
660 clock_freq = freq.QuadPart;
663 static int64_t get_clock(void)
666 QueryPerformanceCounter(&ti);
667 return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
672 static int use_rt_clock;
674 static void init_get_clock(void)
677 #if defined(__linux__)
680 if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
687 static int64_t get_clock(void)
689 #if defined(__linux__)
692 clock_gettime(CLOCK_MONOTONIC, &ts);
693 return ts.tv_sec * 1000000000LL + ts.tv_nsec;
697 /* XXX: using gettimeofday leads to problems if the date
698 changes, so it should be avoided. */
700 gettimeofday(&tv, NULL);
701 return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
707 /***********************************************************/
708 /* guest cycle counter */
710 static int64_t cpu_ticks_prev;
711 static int64_t cpu_ticks_offset;
712 static int64_t cpu_clock_offset;
713 static int cpu_ticks_enabled;
715 /* return the host CPU cycle counter and handle stop/restart */
716 int64_t cpu_get_ticks(void)
718 if (!cpu_ticks_enabled) {
719 return cpu_ticks_offset;
722 ticks = cpu_get_real_ticks();
723 if (cpu_ticks_prev > ticks) {
724 /* Note: non increasing ticks may happen if the host uses
726 cpu_ticks_offset += cpu_ticks_prev - ticks;
728 cpu_ticks_prev = ticks;
729 return ticks + cpu_ticks_offset;
733 /* return the host CPU monotonic timer and handle stop/restart */
734 static int64_t cpu_get_clock(void)
737 if (!cpu_ticks_enabled) {
738 return cpu_clock_offset;
741 return ti + cpu_clock_offset;
745 /* enable cpu_get_ticks() */
746 void cpu_enable_ticks(void)
748 if (!cpu_ticks_enabled) {
749 cpu_ticks_offset -= cpu_get_real_ticks();
750 cpu_clock_offset -= get_clock();
751 cpu_ticks_enabled = 1;
755 /* disable cpu_get_ticks() : the clock is stopped. You must not call
756 cpu_get_ticks() after that. */
757 void cpu_disable_ticks(void)
759 if (cpu_ticks_enabled) {
760 cpu_ticks_offset = cpu_get_ticks();
761 cpu_clock_offset = cpu_get_clock();
762 cpu_ticks_enabled = 0;
766 /***********************************************************/
769 #define QEMU_TIMER_REALTIME 0
770 #define QEMU_TIMER_VIRTUAL 1
774 /* XXX: add frequency */
782 struct QEMUTimer *next;
785 struct qemu_alarm_timer {
788 int (*start)(struct qemu_alarm_timer *t);
789 void (*stop)(struct qemu_alarm_timer *t);
793 static struct qemu_alarm_timer *alarm_timer;
797 struct qemu_alarm_win32 {
801 } alarm_win32_data = {0, NULL, -1};
803 static int win32_start_timer(struct qemu_alarm_timer *t);
804 static void win32_stop_timer(struct qemu_alarm_timer *t);
808 static int unix_start_timer(struct qemu_alarm_timer *t);
809 static void unix_stop_timer(struct qemu_alarm_timer *t);
813 static int hpet_start_timer(struct qemu_alarm_timer *t);
814 static void hpet_stop_timer(struct qemu_alarm_timer *t);
816 static int rtc_start_timer(struct qemu_alarm_timer *t);
817 static void rtc_stop_timer(struct qemu_alarm_timer *t);
823 static struct qemu_alarm_timer alarm_timers[] = {
825 /* HPET - if available - is preferred */
826 {"hpet", hpet_start_timer, hpet_stop_timer, NULL},
827 /* ...otherwise try RTC */
828 {"rtc", rtc_start_timer, rtc_stop_timer, NULL},
831 {"unix", unix_start_timer, unix_stop_timer, NULL},
833 {"win32", win32_start_timer, win32_stop_timer, &alarm_win32_data},
841 static QEMUTimer *active_timers[2];
843 QEMUClock *qemu_new_clock(int type)
846 clock = qemu_mallocz(sizeof(QEMUClock));
853 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
857 ts = qemu_mallocz(sizeof(QEMUTimer));
864 void qemu_free_timer(QEMUTimer *ts)
869 /* stop a timer, but do not dealloc it */
870 void qemu_del_timer(QEMUTimer *ts)
874 /* NOTE: this code must be signal safe because
875 qemu_timer_expired() can be called from a signal. */
876 pt = &active_timers[ts->clock->type];
889 /* modify the current timer so that it will be fired when current_time
890 >= expire_time. The corresponding callback will be called. */
891 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
897 /* add the timer in the sorted list */
898 /* NOTE: this code must be signal safe because
899 qemu_timer_expired() can be called from a signal. */
900 pt = &active_timers[ts->clock->type];
905 if (t->expire_time > expire_time)
909 ts->expire_time = expire_time;
914 int qemu_timer_pending(QEMUTimer *ts)
917 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
924 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
928 return (timer_head->expire_time <= current_time);
931 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
937 if (!ts || ts->expire_time > current_time)
939 /* remove timer from the list before calling the callback */
940 *ptimer_head = ts->next;
943 /* run the callback (the timer list can be modified) */
948 int64_t qemu_get_clock(QEMUClock *clock)
950 switch(clock->type) {
951 case QEMU_TIMER_REALTIME:
952 return get_clock() / 1000000;
954 case QEMU_TIMER_VIRTUAL:
955 return cpu_get_clock();
959 static void init_timers(void)
962 ticks_per_sec = QEMU_TIMER_BASE;
963 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
964 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
968 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
970 uint64_t expire_time;
972 if (qemu_timer_pending(ts)) {
973 expire_time = ts->expire_time;
977 qemu_put_be64(f, expire_time);
980 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
982 uint64_t expire_time;
984 expire_time = qemu_get_be64(f);
985 if (expire_time != -1) {
986 qemu_mod_timer(ts, expire_time);
992 static void timer_save(QEMUFile *f, void *opaque)
994 if (cpu_ticks_enabled) {
995 hw_error("cannot save state if virtual timers are running");
997 qemu_put_be64s(f, &cpu_ticks_offset);
998 qemu_put_be64s(f, &ticks_per_sec);
999 qemu_put_be64s(f, &cpu_clock_offset);
1002 static int timer_load(QEMUFile *f, void *opaque, int version_id)
1004 if (version_id != 1 && version_id != 2)
1006 if (cpu_ticks_enabled) {
1009 qemu_get_be64s(f, &cpu_ticks_offset);
1010 qemu_get_be64s(f, &ticks_per_sec);
1011 if (version_id == 2) {
1012 qemu_get_be64s(f, &cpu_clock_offset);
1018 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1019 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1021 static void host_alarm_handler(int host_signum)
1025 #define DISP_FREQ 1000
1027 static int64_t delta_min = INT64_MAX;
1028 static int64_t delta_max, delta_cum, last_clock, delta, ti;
1030 ti = qemu_get_clock(vm_clock);
1031 if (last_clock != 0) {
1032 delta = ti - last_clock;
1033 if (delta < delta_min)
1035 if (delta > delta_max)
1038 if (++count == DISP_FREQ) {
1039 printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1040 muldiv64(delta_min, 1000000, ticks_per_sec),
1041 muldiv64(delta_max, 1000000, ticks_per_sec),
1042 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1043 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1045 delta_min = INT64_MAX;
1053 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1054 qemu_get_clock(vm_clock)) ||
1055 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1056 qemu_get_clock(rt_clock))) {
1058 struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1059 SetEvent(data->host_alarm);
1061 CPUState *env = cpu_single_env;
1063 /* stop the currently executing cpu because a timer occured */
1064 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1066 if (env->kqemu_enabled) {
1067 kqemu_cpu_interrupt(env);
1076 #if defined(__linux__)
1078 #define RTC_FREQ 1024
1080 static void enable_sigio_timer(int fd)
1082 struct sigaction act;
1085 sigfillset(&act.sa_mask);
1087 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1088 act.sa_flags |= SA_ONSTACK;
1090 act.sa_handler = host_alarm_handler;
1092 sigaction(SIGIO, &act, NULL);
1093 fcntl(fd, F_SETFL, O_ASYNC);
1094 fcntl(fd, F_SETOWN, getpid());
1097 static int hpet_start_timer(struct qemu_alarm_timer *t)
1099 struct hpet_info info;
1102 fd = open("/dev/hpet", O_RDONLY);
1107 r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1109 fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1110 "error, but for better emulation accuracy type:\n"
1111 "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1115 /* Check capabilities */
1116 r = ioctl(fd, HPET_INFO, &info);
1120 /* Enable periodic mode */
1121 r = ioctl(fd, HPET_EPI, 0);
1122 if (info.hi_flags && (r < 0))
1125 /* Enable interrupt */
1126 r = ioctl(fd, HPET_IE_ON, 0);
1130 enable_sigio_timer(fd);
1131 t->priv = (void *)fd;
1139 static void hpet_stop_timer(struct qemu_alarm_timer *t)
1141 int fd = (int)t->priv;
1146 static int rtc_start_timer(struct qemu_alarm_timer *t)
1150 TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1153 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1154 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1155 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1156 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1159 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1165 enable_sigio_timer(rtc_fd);
1167 t->priv = (void *)rtc_fd;
1172 static void rtc_stop_timer(struct qemu_alarm_timer *t)
1174 int rtc_fd = (int)t->priv;
1179 #endif /* !defined(__linux__) */
1181 static int unix_start_timer(struct qemu_alarm_timer *t)
1183 struct sigaction act;
1184 struct itimerval itv;
1188 sigfillset(&act.sa_mask);
1190 #if defined(TARGET_I386) && defined(USE_CODE_COPY)
1191 act.sa_flags |= SA_ONSTACK;
1193 act.sa_handler = host_alarm_handler;
1195 sigaction(SIGALRM, &act, NULL);
1197 itv.it_interval.tv_sec = 0;
1198 /* for i386 kernel 2.6 to get 1 ms */
1199 itv.it_interval.tv_usec = 999;
1200 itv.it_value.tv_sec = 0;
1201 itv.it_value.tv_usec = 10 * 1000;
1203 err = setitimer(ITIMER_REAL, &itv, NULL);
1210 static void unix_stop_timer(struct qemu_alarm_timer *t)
1212 struct itimerval itv;
1214 memset(&itv, 0, sizeof(itv));
1215 setitimer(ITIMER_REAL, &itv, NULL);
1218 #endif /* !defined(_WIN32) */
1222 static int win32_start_timer(struct qemu_alarm_timer *t)
1225 struct qemu_alarm_win32 *data = t->priv;
1227 data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1228 if (!data->host_alarm) {
1229 perror("Failed CreateEvent");
1233 memset(&tc, 0, sizeof(tc));
1234 timeGetDevCaps(&tc, sizeof(tc));
1236 if (data->period < tc.wPeriodMin)
1237 data->period = tc.wPeriodMin;
1239 timeBeginPeriod(data->period);
1241 data->timerId = timeSetEvent(1, // interval (ms)
1242 data->period, // resolution
1243 host_alarm_handler, // function
1244 (DWORD)t, // parameter
1245 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1247 if (!data->timerId) {
1248 perror("Failed to initialize win32 alarm timer");
1250 timeEndPeriod(data->period);
1251 CloseHandle(data->host_alarm);
1255 qemu_add_wait_object(data->host_alarm, NULL, NULL);
1260 static void win32_stop_timer(struct qemu_alarm_timer *t)
1262 struct qemu_alarm_win32 *data = t->priv;
1264 timeKillEvent(data->timerId);
1265 timeEndPeriod(data->period);
1267 CloseHandle(data->host_alarm);
1272 static void init_timer_alarm(void)
1274 struct qemu_alarm_timer *t;
1277 for (i = 0; alarm_timers[i].name; i++) {
1278 t = &alarm_timers[i];
1280 printf("trying %s...\n", t->name);
1288 fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1289 fprintf(stderr, "Terminating\n");
1296 void quit_timers(void)
1298 alarm_timer->stop(alarm_timer);
1302 /***********************************************************/
1303 /* character device */
1305 static void qemu_chr_event(CharDriverState *s, int event)
1309 s->chr_event(s->handler_opaque, event);
1312 static void qemu_chr_reset_bh(void *opaque)
1314 CharDriverState *s = opaque;
1315 qemu_chr_event(s, CHR_EVENT_RESET);
1316 qemu_bh_delete(s->bh);
1320 void qemu_chr_reset(CharDriverState *s)
1322 if (s->bh == NULL) {
1323 s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1324 qemu_bh_schedule(s->bh);
1328 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1330 return s->chr_write(s, buf, len);
1333 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1337 return s->chr_ioctl(s, cmd, arg);
1340 int qemu_chr_can_read(CharDriverState *s)
1342 if (!s->chr_can_read)
1344 return s->chr_can_read(s->handler_opaque);
1347 void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1349 s->chr_read(s->handler_opaque, buf, len);
1353 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1358 vsnprintf(buf, sizeof(buf), fmt, ap);
1359 qemu_chr_write(s, buf, strlen(buf));
1363 void qemu_chr_send_event(CharDriverState *s, int event)
1365 if (s->chr_send_event)
1366 s->chr_send_event(s, event);
1369 void qemu_chr_add_handlers(CharDriverState *s,
1370 IOCanRWHandler *fd_can_read,
1371 IOReadHandler *fd_read,
1372 IOEventHandler *fd_event,
1375 s->chr_can_read = fd_can_read;
1376 s->chr_read = fd_read;
1377 s->chr_event = fd_event;
1378 s->handler_opaque = opaque;
1379 if (s->chr_update_read_handler)
1380 s->chr_update_read_handler(s);
1383 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1388 static CharDriverState *qemu_chr_open_null(void)
1390 CharDriverState *chr;
1392 chr = qemu_mallocz(sizeof(CharDriverState));
1395 chr->chr_write = null_chr_write;
1399 /* MUX driver for serial I/O splitting */
1400 static int term_timestamps;
1401 static int64_t term_timestamps_start;
1404 IOCanRWHandler *chr_can_read[MAX_MUX];
1405 IOReadHandler *chr_read[MAX_MUX];
1406 IOEventHandler *chr_event[MAX_MUX];
1407 void *ext_opaque[MAX_MUX];
1408 CharDriverState *drv;
1410 int term_got_escape;
1415 static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1417 MuxDriver *d = chr->opaque;
1419 if (!term_timestamps) {
1420 ret = d->drv->chr_write(d->drv, buf, len);
1425 for(i = 0; i < len; i++) {
1426 ret += d->drv->chr_write(d->drv, buf+i, 1);
1427 if (buf[i] == '\n') {
1433 if (term_timestamps_start == -1)
1434 term_timestamps_start = ti;
1435 ti -= term_timestamps_start;
1436 secs = ti / 1000000000;
1437 snprintf(buf1, sizeof(buf1),
1438 "[%02d:%02d:%02d.%03d] ",
1442 (int)((ti / 1000000) % 1000));
1443 d->drv->chr_write(d->drv, buf1, strlen(buf1));
1450 static char *mux_help[] = {
1451 "% h print this help\n\r",
1452 "% x exit emulator\n\r",
1453 "% s save disk data back to file (if -snapshot)\n\r",
1454 "% t toggle console timestamps\n\r"
1455 "% b send break (magic sysrq)\n\r",
1456 "% c switch between console and monitor\n\r",
1461 static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1462 static void mux_print_help(CharDriverState *chr)
1465 char ebuf[15] = "Escape-Char";
1466 char cbuf[50] = "\n\r";
1468 if (term_escape_char > 0 && term_escape_char < 26) {
1469 sprintf(cbuf,"\n\r");
1470 sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1472 sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1474 chr->chr_write(chr, cbuf, strlen(cbuf));
1475 for (i = 0; mux_help[i] != NULL; i++) {
1476 for (j=0; mux_help[i][j] != '\0'; j++) {
1477 if (mux_help[i][j] == '%')
1478 chr->chr_write(chr, ebuf, strlen(ebuf));
1480 chr->chr_write(chr, &mux_help[i][j], 1);
1485 static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1487 if (d->term_got_escape) {
1488 d->term_got_escape = 0;
1489 if (ch == term_escape_char)
1494 mux_print_help(chr);
1498 char *term = "QEMU: Terminated\n\r";
1499 chr->chr_write(chr,term,strlen(term));
1506 for (i = 0; i < MAX_DISKS; i++) {
1508 bdrv_commit(bs_table[i]);
1511 bdrv_commit(mtd_bdrv);
1515 qemu_chr_event(chr, CHR_EVENT_BREAK);
1518 /* Switch to the next registered device */
1520 if (chr->focus >= d->mux_cnt)
1524 term_timestamps = !term_timestamps;
1525 term_timestamps_start = -1;
1528 } else if (ch == term_escape_char) {
1529 d->term_got_escape = 1;
1537 static int mux_chr_can_read(void *opaque)
1539 CharDriverState *chr = opaque;
1540 MuxDriver *d = chr->opaque;
1541 if (d->chr_can_read[chr->focus])
1542 return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1546 static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1548 CharDriverState *chr = opaque;
1549 MuxDriver *d = chr->opaque;
1551 for(i = 0; i < size; i++)
1552 if (mux_proc_byte(chr, d, buf[i]))
1553 d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1556 static void mux_chr_event(void *opaque, int event)
1558 CharDriverState *chr = opaque;
1559 MuxDriver *d = chr->opaque;
1562 /* Send the event to all registered listeners */
1563 for (i = 0; i < d->mux_cnt; i++)
1564 if (d->chr_event[i])
1565 d->chr_event[i](d->ext_opaque[i], event);
1568 static void mux_chr_update_read_handler(CharDriverState *chr)
1570 MuxDriver *d = chr->opaque;
1572 if (d->mux_cnt >= MAX_MUX) {
1573 fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1576 d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1577 d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1578 d->chr_read[d->mux_cnt] = chr->chr_read;
1579 d->chr_event[d->mux_cnt] = chr->chr_event;
1580 /* Fix up the real driver with mux routines */
1581 if (d->mux_cnt == 0) {
1582 qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1583 mux_chr_event, chr);
1585 chr->focus = d->mux_cnt;
1589 CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1591 CharDriverState *chr;
1594 chr = qemu_mallocz(sizeof(CharDriverState));
1597 d = qemu_mallocz(sizeof(MuxDriver));
1606 chr->chr_write = mux_chr_write;
1607 chr->chr_update_read_handler = mux_chr_update_read_handler;
1614 static void socket_cleanup(void)
1619 static int socket_init(void)
1624 ret = WSAStartup(MAKEWORD(2,2), &Data);
1626 err = WSAGetLastError();
1627 fprintf(stderr, "WSAStartup: %d\n", err);
1630 atexit(socket_cleanup);
1634 static int send_all(int fd, const uint8_t *buf, int len1)
1640 ret = send(fd, buf, len, 0);
1643 errno = WSAGetLastError();
1644 if (errno != WSAEWOULDBLOCK) {
1647 } else if (ret == 0) {
1657 void socket_set_nonblock(int fd)
1659 unsigned long opt = 1;
1660 ioctlsocket(fd, FIONBIO, &opt);
1665 static int unix_write(int fd, const uint8_t *buf, int len1)
1671 ret = write(fd, buf, len);
1673 if (errno != EINTR && errno != EAGAIN)
1675 } else if (ret == 0) {
1685 static inline int send_all(int fd, const uint8_t *buf, int len1)
1687 return unix_write(fd, buf, len1);
1690 void socket_set_nonblock(int fd)
1692 fcntl(fd, F_SETFL, O_NONBLOCK);
1694 #endif /* !_WIN32 */
1703 #define STDIO_MAX_CLIENTS 1
1704 static int stdio_nb_clients = 0;
1706 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1708 FDCharDriver *s = chr->opaque;
1709 return unix_write(s->fd_out, buf, len);
1712 static int fd_chr_read_poll(void *opaque)
1714 CharDriverState *chr = opaque;
1715 FDCharDriver *s = chr->opaque;
1717 s->max_size = qemu_chr_can_read(chr);
1721 static void fd_chr_read(void *opaque)
1723 CharDriverState *chr = opaque;
1724 FDCharDriver *s = chr->opaque;
1729 if (len > s->max_size)
1733 size = read(s->fd_in, buf, len);
1735 /* FD has been closed. Remove it from the active list. */
1736 qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1740 qemu_chr_read(chr, buf, size);
1744 static void fd_chr_update_read_handler(CharDriverState *chr)
1746 FDCharDriver *s = chr->opaque;
1748 if (s->fd_in >= 0) {
1749 if (nographic && s->fd_in == 0) {
1751 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1752 fd_chr_read, NULL, chr);
1757 /* open a character device to a unix fd */
1758 static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1760 CharDriverState *chr;
1763 chr = qemu_mallocz(sizeof(CharDriverState));
1766 s = qemu_mallocz(sizeof(FDCharDriver));
1774 chr->chr_write = fd_chr_write;
1775 chr->chr_update_read_handler = fd_chr_update_read_handler;
1777 qemu_chr_reset(chr);
1782 static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1786 TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
1789 return qemu_chr_open_fd(-1, fd_out);
1792 static CharDriverState *qemu_chr_open_pipe(const char *filename)
1795 char filename_in[256], filename_out[256];
1797 snprintf(filename_in, 256, "%s.in", filename);
1798 snprintf(filename_out, 256, "%s.out", filename);
1799 TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
1800 TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
1801 if (fd_in < 0 || fd_out < 0) {
1806 TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
1810 return qemu_chr_open_fd(fd_in, fd_out);
1814 /* for STDIO, we handle the case where several clients use it
1817 #define TERM_FIFO_MAX_SIZE 1
1819 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1820 static int term_fifo_size;
1822 static int stdio_read_poll(void *opaque)
1824 CharDriverState *chr = opaque;
1826 /* try to flush the queue if needed */
1827 if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1828 qemu_chr_read(chr, term_fifo, 1);
1831 /* see if we can absorb more chars */
1832 if (term_fifo_size == 0)
1838 static void stdio_read(void *opaque)
1842 CharDriverState *chr = opaque;
1844 size = read(0, buf, 1);
1846 /* stdin has been closed. Remove it from the active list. */
1847 qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1851 if (qemu_chr_can_read(chr) > 0) {
1852 qemu_chr_read(chr, buf, 1);
1853 } else if (term_fifo_size == 0) {
1854 term_fifo[term_fifo_size++] = buf[0];
1859 /* init terminal so that we can grab keys */
1860 static struct termios oldtty;
1861 static int old_fd0_flags;
1863 static void term_exit(void)
1865 tcsetattr (0, TCSANOW, &oldtty);
1866 fcntl(0, F_SETFL, old_fd0_flags);
1869 static void term_init(void)
1873 tcgetattr (0, &tty);
1875 old_fd0_flags = fcntl(0, F_GETFL);
1877 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1878 |INLCR|IGNCR|ICRNL|IXON);
1879 tty.c_oflag |= OPOST;
1880 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1881 /* if graphical mode, we allow Ctrl-C handling */
1883 tty.c_lflag &= ~ISIG;
1884 tty.c_cflag &= ~(CSIZE|PARENB);
1887 tty.c_cc[VTIME] = 0;
1889 tcsetattr (0, TCSANOW, &tty);
1893 fcntl(0, F_SETFL, O_NONBLOCK);
1896 static CharDriverState *qemu_chr_open_stdio(void)
1898 CharDriverState *chr;
1900 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1902 chr = qemu_chr_open_fd(0, 1);
1903 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1910 #if defined(__linux__) || defined(__sun__)
1911 static CharDriverState *qemu_chr_open_pty(void)
1914 char slave_name[1024];
1915 int master_fd, slave_fd;
1917 #if defined(__linux__)
1918 /* Not satisfying */
1919 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1924 /* Disabling local echo and line-buffered output */
1925 tcgetattr (master_fd, &tty);
1926 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1928 tty.c_cc[VTIME] = 0;
1929 tcsetattr (master_fd, TCSAFLUSH, &tty);
1931 fprintf(stderr, "char device redirected to %s\n", slave_name);
1932 return qemu_chr_open_fd(master_fd, master_fd);
1935 static void tty_serial_init(int fd, int speed,
1936 int parity, int data_bits, int stop_bits)
1942 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1943 speed, parity, data_bits, stop_bits);
1945 tcgetattr (fd, &tty);
1987 cfsetispeed(&tty, spd);
1988 cfsetospeed(&tty, spd);
1990 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1991 |INLCR|IGNCR|ICRNL|IXON);
1992 tty.c_oflag |= OPOST;
1993 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1994 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2015 tty.c_cflag |= PARENB;
2018 tty.c_cflag |= PARENB | PARODD;
2022 tty.c_cflag |= CSTOPB;
2024 tcsetattr (fd, TCSANOW, &tty);
2027 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2029 FDCharDriver *s = chr->opaque;
2032 case CHR_IOCTL_SERIAL_SET_PARAMS:
2034 QEMUSerialSetParams *ssp = arg;
2035 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2036 ssp->data_bits, ssp->stop_bits);
2039 case CHR_IOCTL_SERIAL_SET_BREAK:
2041 int enable = *(int *)arg;
2043 tcsendbreak(s->fd_in, 1);
2052 static CharDriverState *qemu_chr_open_tty(const char *filename)
2054 CharDriverState *chr;
2057 TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2058 fcntl(fd, F_SETFL, O_NONBLOCK);
2059 tty_serial_init(fd, 115200, 'N', 8, 1);
2060 chr = qemu_chr_open_fd(fd, fd);
2065 chr->chr_ioctl = tty_serial_ioctl;
2066 qemu_chr_reset(chr);
2069 #else /* ! __linux__ && ! __sun__ */
2070 static CharDriverState *qemu_chr_open_pty(void)
2074 #endif /* __linux__ || __sun__ */
2076 #if defined(__linux__)
2080 } ParallelCharDriver;
2082 static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2084 if (s->mode != mode) {
2086 if (ioctl(s->fd, PPSETMODE, &m) < 0)
2093 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2095 ParallelCharDriver *drv = chr->opaque;
2100 case CHR_IOCTL_PP_READ_DATA:
2101 if (ioctl(fd, PPRDATA, &b) < 0)
2103 *(uint8_t *)arg = b;
2105 case CHR_IOCTL_PP_WRITE_DATA:
2106 b = *(uint8_t *)arg;
2107 if (ioctl(fd, PPWDATA, &b) < 0)
2110 case CHR_IOCTL_PP_READ_CONTROL:
2111 if (ioctl(fd, PPRCONTROL, &b) < 0)
2113 /* Linux gives only the lowest bits, and no way to know data
2114 direction! For better compatibility set the fixed upper
2116 *(uint8_t *)arg = b | 0xc0;
2118 case CHR_IOCTL_PP_WRITE_CONTROL:
2119 b = *(uint8_t *)arg;
2120 if (ioctl(fd, PPWCONTROL, &b) < 0)
2123 case CHR_IOCTL_PP_READ_STATUS:
2124 if (ioctl(fd, PPRSTATUS, &b) < 0)
2126 *(uint8_t *)arg = b;
2128 case CHR_IOCTL_PP_EPP_READ_ADDR:
2129 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2130 struct ParallelIOArg *parg = arg;
2131 int n = read(fd, parg->buffer, parg->count);
2132 if (n != parg->count) {
2137 case CHR_IOCTL_PP_EPP_READ:
2138 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2139 struct ParallelIOArg *parg = arg;
2140 int n = read(fd, parg->buffer, parg->count);
2141 if (n != parg->count) {
2146 case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2147 if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2148 struct ParallelIOArg *parg = arg;
2149 int n = write(fd, parg->buffer, parg->count);
2150 if (n != parg->count) {
2155 case CHR_IOCTL_PP_EPP_WRITE:
2156 if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2157 struct ParallelIOArg *parg = arg;
2158 int n = write(fd, parg->buffer, parg->count);
2159 if (n != parg->count) {
2170 static void pp_close(CharDriverState *chr)
2172 ParallelCharDriver *drv = chr->opaque;
2175 pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2176 ioctl(fd, PPRELEASE);
2181 static CharDriverState *qemu_chr_open_pp(const char *filename)
2183 CharDriverState *chr;
2184 ParallelCharDriver *drv;
2187 TFR(fd = open(filename, O_RDWR));
2191 if (ioctl(fd, PPCLAIM) < 0) {
2196 drv = qemu_mallocz(sizeof(ParallelCharDriver));
2202 drv->mode = IEEE1284_MODE_COMPAT;
2204 chr = qemu_mallocz(sizeof(CharDriverState));
2210 chr->chr_write = null_chr_write;
2211 chr->chr_ioctl = pp_ioctl;
2212 chr->chr_close = pp_close;
2215 qemu_chr_reset(chr);
2219 #endif /* __linux__ */
2225 HANDLE hcom, hrecv, hsend;
2226 OVERLAPPED orecv, osend;
2231 #define NSENDBUF 2048
2232 #define NRECVBUF 2048
2233 #define MAXCONNECT 1
2234 #define NTIMEOUT 5000
2236 static int win_chr_poll(void *opaque);
2237 static int win_chr_pipe_poll(void *opaque);
2239 static void win_chr_close(CharDriverState *chr)
2241 WinCharState *s = chr->opaque;
2244 CloseHandle(s->hsend);
2248 CloseHandle(s->hrecv);
2252 CloseHandle(s->hcom);
2256 qemu_del_polling_cb(win_chr_pipe_poll, chr);
2258 qemu_del_polling_cb(win_chr_poll, chr);
2261 static int win_chr_init(CharDriverState *chr, const char *filename)
2263 WinCharState *s = chr->opaque;
2265 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2270 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2272 fprintf(stderr, "Failed CreateEvent\n");
2275 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2277 fprintf(stderr, "Failed CreateEvent\n");
2281 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2282 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2283 if (s->hcom == INVALID_HANDLE_VALUE) {
2284 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2289 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2290 fprintf(stderr, "Failed SetupComm\n");
2294 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2295 size = sizeof(COMMCONFIG);
2296 GetDefaultCommConfig(filename, &comcfg, &size);
2297 comcfg.dcb.DCBlength = sizeof(DCB);
2298 CommConfigDialog(filename, NULL, &comcfg);
2300 if (!SetCommState(s->hcom, &comcfg.dcb)) {
2301 fprintf(stderr, "Failed SetCommState\n");
2305 if (!SetCommMask(s->hcom, EV_ERR)) {
2306 fprintf(stderr, "Failed SetCommMask\n");
2310 cto.ReadIntervalTimeout = MAXDWORD;
2311 if (!SetCommTimeouts(s->hcom, &cto)) {
2312 fprintf(stderr, "Failed SetCommTimeouts\n");
2316 if (!ClearCommError(s->hcom, &err, &comstat)) {
2317 fprintf(stderr, "Failed ClearCommError\n");
2320 qemu_add_polling_cb(win_chr_poll, chr);
2328 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2330 WinCharState *s = chr->opaque;
2331 DWORD len, ret, size, err;
2334 ZeroMemory(&s->osend, sizeof(s->osend));
2335 s->osend.hEvent = s->hsend;
2338 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2340 ret = WriteFile(s->hcom, buf, len, &size, NULL);
2342 err = GetLastError();
2343 if (err == ERROR_IO_PENDING) {
2344 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2362 static int win_chr_read_poll(CharDriverState *chr)
2364 WinCharState *s = chr->opaque;
2366 s->max_size = qemu_chr_can_read(chr);
2370 static void win_chr_readfile(CharDriverState *chr)
2372 WinCharState *s = chr->opaque;
2377 ZeroMemory(&s->orecv, sizeof(s->orecv));
2378 s->orecv.hEvent = s->hrecv;
2379 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2381 err = GetLastError();
2382 if (err == ERROR_IO_PENDING) {
2383 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2388 qemu_chr_read(chr, buf, size);
2392 static void win_chr_read(CharDriverState *chr)
2394 WinCharState *s = chr->opaque;
2396 if (s->len > s->max_size)
2397 s->len = s->max_size;
2401 win_chr_readfile(chr);
2404 static int win_chr_poll(void *opaque)
2406 CharDriverState *chr = opaque;
2407 WinCharState *s = chr->opaque;
2411 ClearCommError(s->hcom, &comerr, &status);
2412 if (status.cbInQue > 0) {
2413 s->len = status.cbInQue;
2414 win_chr_read_poll(chr);
2421 static CharDriverState *qemu_chr_open_win(const char *filename)
2423 CharDriverState *chr;
2426 chr = qemu_mallocz(sizeof(CharDriverState));
2429 s = qemu_mallocz(sizeof(WinCharState));
2435 chr->chr_write = win_chr_write;
2436 chr->chr_close = win_chr_close;
2438 if (win_chr_init(chr, filename) < 0) {
2443 qemu_chr_reset(chr);
2447 static int win_chr_pipe_poll(void *opaque)
2449 CharDriverState *chr = opaque;
2450 WinCharState *s = chr->opaque;
2453 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2456 win_chr_read_poll(chr);
2463 static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2465 WinCharState *s = chr->opaque;
2473 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2475 fprintf(stderr, "Failed CreateEvent\n");
2478 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2480 fprintf(stderr, "Failed CreateEvent\n");
2484 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2485 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2486 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2488 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2489 if (s->hcom == INVALID_HANDLE_VALUE) {
2490 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2495 ZeroMemory(&ov, sizeof(ov));
2496 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2497 ret = ConnectNamedPipe(s->hcom, &ov);
2499 fprintf(stderr, "Failed ConnectNamedPipe\n");
2503 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2505 fprintf(stderr, "Failed GetOverlappedResult\n");
2507 CloseHandle(ov.hEvent);
2514 CloseHandle(ov.hEvent);
2517 qemu_add_polling_cb(win_chr_pipe_poll, chr);
2526 static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2528 CharDriverState *chr;
2531 chr = qemu_mallocz(sizeof(CharDriverState));
2534 s = qemu_mallocz(sizeof(WinCharState));
2540 chr->chr_write = win_chr_write;
2541 chr->chr_close = win_chr_close;
2543 if (win_chr_pipe_init(chr, filename) < 0) {
2548 qemu_chr_reset(chr);
2552 static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2554 CharDriverState *chr;
2557 chr = qemu_mallocz(sizeof(CharDriverState));
2560 s = qemu_mallocz(sizeof(WinCharState));
2567 chr->chr_write = win_chr_write;
2568 qemu_chr_reset(chr);
2572 static CharDriverState *qemu_chr_open_win_con(const char *filename)
2574 return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2577 static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2581 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2582 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2583 if (fd_out == INVALID_HANDLE_VALUE)
2586 return qemu_chr_open_win_file(fd_out);
2588 #endif /* !_WIN32 */
2590 /***********************************************************/
2591 /* UDP Net console */
2595 struct sockaddr_in daddr;
2602 static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2604 NetCharDriver *s = chr->opaque;
2606 return sendto(s->fd, buf, len, 0,
2607 (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2610 static int udp_chr_read_poll(void *opaque)
2612 CharDriverState *chr = opaque;
2613 NetCharDriver *s = chr->opaque;
2615 s->max_size = qemu_chr_can_read(chr);
2617 /* If there were any stray characters in the queue process them
2620 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2621 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2623 s->max_size = qemu_chr_can_read(chr);
2628 static void udp_chr_read(void *opaque)
2630 CharDriverState *chr = opaque;
2631 NetCharDriver *s = chr->opaque;
2633 if (s->max_size == 0)
2635 s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2636 s->bufptr = s->bufcnt;
2641 while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2642 qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2644 s->max_size = qemu_chr_can_read(chr);
2648 static void udp_chr_update_read_handler(CharDriverState *chr)
2650 NetCharDriver *s = chr->opaque;
2653 qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2654 udp_chr_read, NULL, chr);
2658 int parse_host_port(struct sockaddr_in *saddr, const char *str);
2660 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2662 int parse_host_src_port(struct sockaddr_in *haddr,
2663 struct sockaddr_in *saddr,
2666 static CharDriverState *qemu_chr_open_udp(const char *def)
2668 CharDriverState *chr = NULL;
2669 NetCharDriver *s = NULL;
2671 struct sockaddr_in saddr;
2673 chr = qemu_mallocz(sizeof(CharDriverState));
2676 s = qemu_mallocz(sizeof(NetCharDriver));
2680 fd = socket(PF_INET, SOCK_DGRAM, 0);
2682 perror("socket(PF_INET, SOCK_DGRAM)");
2686 if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2687 printf("Could not parse: %s\n", def);
2691 if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2701 chr->chr_write = udp_chr_write;
2702 chr->chr_update_read_handler = udp_chr_update_read_handler;
2715 /***********************************************************/
2716 /* TCP Net console */
2727 static void tcp_chr_accept(void *opaque);
2729 static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2731 TCPCharDriver *s = chr->opaque;
2733 return send_all(s->fd, buf, len);
2735 /* XXX: indicate an error ? */
2740 static int tcp_chr_read_poll(void *opaque)
2742 CharDriverState *chr = opaque;
2743 TCPCharDriver *s = chr->opaque;
2746 s->max_size = qemu_chr_can_read(chr);
2751 #define IAC_BREAK 243
2752 static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2754 char *buf, int *size)
2756 /* Handle any telnet client's basic IAC options to satisfy char by
2757 * char mode with no echo. All IAC options will be removed from
2758 * the buf and the do_telnetopt variable will be used to track the
2759 * state of the width of the IAC information.
2761 * IAC commands come in sets of 3 bytes with the exception of the
2762 * "IAC BREAK" command and the double IAC.
2768 for (i = 0; i < *size; i++) {
2769 if (s->do_telnetopt > 1) {
2770 if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2771 /* Double IAC means send an IAC */
2775 s->do_telnetopt = 1;
2777 if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2778 /* Handle IAC break commands by sending a serial break */
2779 qemu_chr_event(chr, CHR_EVENT_BREAK);
2784 if (s->do_telnetopt >= 4) {
2785 s->do_telnetopt = 1;
2788 if ((unsigned char)buf[i] == IAC) {
2789 s->do_telnetopt = 2;
2800 static void tcp_chr_read(void *opaque)
2802 CharDriverState *chr = opaque;
2803 TCPCharDriver *s = chr->opaque;
2807 if (!s->connected || s->max_size <= 0)
2810 if (len > s->max_size)
2812 size = recv(s->fd, buf, len, 0);
2814 /* connection closed */
2816 if (s->listen_fd >= 0) {
2817 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2819 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2822 } else if (size > 0) {
2823 if (s->do_telnetopt)
2824 tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2826 qemu_chr_read(chr, buf, size);
2830 static void tcp_chr_connect(void *opaque)
2832 CharDriverState *chr = opaque;
2833 TCPCharDriver *s = chr->opaque;
2836 qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2837 tcp_chr_read, NULL, chr);
2838 qemu_chr_reset(chr);
2841 #define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2842 static void tcp_chr_telnet_init(int fd)
2845 /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2846 IACSET(buf, 0xff, 0xfb, 0x01); /* IAC WILL ECHO */
2847 send(fd, (char *)buf, 3, 0);
2848 IACSET(buf, 0xff, 0xfb, 0x03); /* IAC WILL Suppress go ahead */
2849 send(fd, (char *)buf, 3, 0);
2850 IACSET(buf, 0xff, 0xfb, 0x00); /* IAC WILL Binary */
2851 send(fd, (char *)buf, 3, 0);
2852 IACSET(buf, 0xff, 0xfd, 0x00); /* IAC DO Binary */
2853 send(fd, (char *)buf, 3, 0);
2856 static void socket_set_nodelay(int fd)
2859 setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2862 static void tcp_chr_accept(void *opaque)
2864 CharDriverState *chr = opaque;
2865 TCPCharDriver *s = chr->opaque;
2866 struct sockaddr_in saddr;
2868 struct sockaddr_un uaddr;
2870 struct sockaddr *addr;
2877 len = sizeof(uaddr);
2878 addr = (struct sockaddr *)&uaddr;
2882 len = sizeof(saddr);
2883 addr = (struct sockaddr *)&saddr;
2885 fd = accept(s->listen_fd, addr, &len);
2886 if (fd < 0 && errno != EINTR) {
2888 } else if (fd >= 0) {
2889 if (s->do_telnetopt)
2890 tcp_chr_telnet_init(fd);
2894 socket_set_nonblock(fd);
2896 socket_set_nodelay(fd);
2898 qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2899 tcp_chr_connect(chr);
2902 static void tcp_chr_close(CharDriverState *chr)
2904 TCPCharDriver *s = chr->opaque;
2907 if (s->listen_fd >= 0)
2908 closesocket(s->listen_fd);
2912 static CharDriverState *qemu_chr_open_tcp(const char *host_str,
2916 CharDriverState *chr = NULL;
2917 TCPCharDriver *s = NULL;
2918 int fd = -1, ret, err, val;
2920 int is_waitconnect = 1;
2923 struct sockaddr_in saddr;
2925 struct sockaddr_un uaddr;
2927 struct sockaddr *addr;
2932 addr = (struct sockaddr *)&uaddr;
2933 addrlen = sizeof(uaddr);
2934 if (parse_unix_path(&uaddr, host_str) < 0)
2939 addr = (struct sockaddr *)&saddr;
2940 addrlen = sizeof(saddr);
2941 if (parse_host_port(&saddr, host_str) < 0)
2946 while((ptr = strchr(ptr,','))) {
2948 if (!strncmp(ptr,"server",6)) {
2950 } else if (!strncmp(ptr,"nowait",6)) {
2952 } else if (!strncmp(ptr,"nodelay",6)) {
2955 printf("Unknown option: %s\n", ptr);
2962 chr = qemu_mallocz(sizeof(CharDriverState));
2965 s = qemu_mallocz(sizeof(TCPCharDriver));
2971 fd = socket(PF_UNIX, SOCK_STREAM, 0);
2974 fd = socket(PF_INET, SOCK_STREAM, 0);
2979 if (!is_waitconnect)
2980 socket_set_nonblock(fd);
2985 s->is_unix = is_unix;
2986 s->do_nodelay = do_nodelay && !is_unix;
2989 chr->chr_write = tcp_chr_write;
2990 chr->chr_close = tcp_chr_close;
2993 /* allow fast reuse */
2997 strncpy(path, uaddr.sun_path, 108);
3004 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3007 ret = bind(fd, addr, addrlen);
3011 ret = listen(fd, 0);
3016 qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3018 s->do_telnetopt = 1;
3021 ret = connect(fd, addr, addrlen);
3023 err = socket_error();
3024 if (err == EINTR || err == EWOULDBLOCK) {
3025 } else if (err == EINPROGRESS) {
3028 } else if (err == WSAEALREADY) {
3040 socket_set_nodelay(fd);
3042 tcp_chr_connect(chr);
3044 qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3047 if (is_listen && is_waitconnect) {
3048 printf("QEMU waiting for connection on: %s\n", host_str);
3049 tcp_chr_accept(chr);
3050 socket_set_nonblock(s->listen_fd);
3062 CharDriverState *qemu_chr_open(const char *filename)
3066 if (!strcmp(filename, "vc")) {
3067 return text_console_init(&display_state, 0);
3068 } else if (strstart(filename, "vc:", &p)) {
3069 return text_console_init(&display_state, p);
3070 } else if (!strcmp(filename, "null")) {
3071 return qemu_chr_open_null();
3073 if (strstart(filename, "tcp:", &p)) {
3074 return qemu_chr_open_tcp(p, 0, 0);
3076 if (strstart(filename, "telnet:", &p)) {
3077 return qemu_chr_open_tcp(p, 1, 0);
3079 if (strstart(filename, "udp:", &p)) {
3080 return qemu_chr_open_udp(p);
3082 if (strstart(filename, "mon:", &p)) {
3083 CharDriverState *drv = qemu_chr_open(p);
3085 drv = qemu_chr_open_mux(drv);
3086 monitor_init(drv, !nographic);
3089 printf("Unable to open driver: %s\n", p);
3093 if (strstart(filename, "unix:", &p)) {
3094 return qemu_chr_open_tcp(p, 0, 1);
3095 } else if (strstart(filename, "file:", &p)) {
3096 return qemu_chr_open_file_out(p);
3097 } else if (strstart(filename, "pipe:", &p)) {
3098 return qemu_chr_open_pipe(p);
3099 } else if (!strcmp(filename, "pty")) {
3100 return qemu_chr_open_pty();
3101 } else if (!strcmp(filename, "stdio")) {
3102 return qemu_chr_open_stdio();
3104 #if defined(__linux__)
3105 if (strstart(filename, "/dev/parport", NULL)) {
3106 return qemu_chr_open_pp(filename);
3109 #if defined(__linux__) || defined(__sun__)
3110 if (strstart(filename, "/dev/", NULL)) {
3111 return qemu_chr_open_tty(filename);
3115 if (strstart(filename, "COM", NULL)) {
3116 return qemu_chr_open_win(filename);
3118 if (strstart(filename, "pipe:", &p)) {
3119 return qemu_chr_open_win_pipe(p);
3121 if (strstart(filename, "con:", NULL)) {
3122 return qemu_chr_open_win_con(filename);
3124 if (strstart(filename, "file:", &p)) {
3125 return qemu_chr_open_win_file_out(p);
3133 void qemu_chr_close(CharDriverState *chr)
3136 chr->chr_close(chr);
3139 /***********************************************************/
3140 /* network device redirectors */
3142 void hex_dump(FILE *f, const uint8_t *buf, int size)
3146 for(i=0;i<size;i+=16) {
3150 fprintf(f, "%08x ", i);
3153 fprintf(f, " %02x", buf[i+j]);
3158 for(j=0;j<len;j++) {
3160 if (c < ' ' || c > '~')
3162 fprintf(f, "%c", c);
3168 static int parse_macaddr(uint8_t *macaddr, const char *p)
3171 for(i = 0; i < 6; i++) {
3172 macaddr[i] = strtol(p, (char **)&p, 16);
3185 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3190 p1 = strchr(p, sep);
3196 if (len > buf_size - 1)
3198 memcpy(buf, p, len);
3205 int parse_host_src_port(struct sockaddr_in *haddr,
3206 struct sockaddr_in *saddr,
3207 const char *input_str)
3209 char *str = strdup(input_str);
3210 char *host_str = str;
3215 * Chop off any extra arguments at the end of the string which
3216 * would start with a comma, then fill in the src port information
3217 * if it was provided else use the "any address" and "any port".
3219 if ((ptr = strchr(str,',')))
3222 if ((src_str = strchr(input_str,'@'))) {
3227 if (parse_host_port(haddr, host_str) < 0)
3230 if (!src_str || *src_str == '\0')
3233 if (parse_host_port(saddr, src_str) < 0)
3244 int parse_host_port(struct sockaddr_in *saddr, const char *str)
3252 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3254 saddr->sin_family = AF_INET;
3255 if (buf[0] == '\0') {
3256 saddr->sin_addr.s_addr = 0;
3258 if (isdigit(buf[0])) {
3259 if (!inet_aton(buf, &saddr->sin_addr))
3262 if ((he = gethostbyname(buf)) == NULL)
3264 saddr->sin_addr = *(struct in_addr *)he->h_addr;
3267 port = strtol(p, (char **)&r, 0);
3270 saddr->sin_port = htons(port);
3275 static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3280 len = MIN(108, strlen(str));
3281 p = strchr(str, ',');
3283 len = MIN(len, p - str);
3285 memset(uaddr, 0, sizeof(*uaddr));
3287 uaddr->sun_family = AF_UNIX;
3288 memcpy(uaddr->sun_path, str, len);
3294 /* find or alloc a new VLAN */
3295 VLANState *qemu_find_vlan(int id)
3297 VLANState **pvlan, *vlan;
3298 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3302 vlan = qemu_mallocz(sizeof(VLANState));
3307 pvlan = &first_vlan;
3308 while (*pvlan != NULL)
3309 pvlan = &(*pvlan)->next;
3314 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3315 IOReadHandler *fd_read,
3316 IOCanRWHandler *fd_can_read,
3319 VLANClientState *vc, **pvc;
3320 vc = qemu_mallocz(sizeof(VLANClientState));
3323 vc->fd_read = fd_read;
3324 vc->fd_can_read = fd_can_read;
3325 vc->opaque = opaque;
3329 pvc = &vlan->first_client;
3330 while (*pvc != NULL)
3331 pvc = &(*pvc)->next;
3336 int qemu_can_send_packet(VLANClientState *vc1)
3338 VLANState *vlan = vc1->vlan;
3339 VLANClientState *vc;
3341 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3343 if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3350 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3352 VLANState *vlan = vc1->vlan;
3353 VLANClientState *vc;
3356 printf("vlan %d send:\n", vlan->id);
3357 hex_dump(stdout, buf, size);
3359 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3361 vc->fd_read(vc->opaque, buf, size);
3366 #if defined(CONFIG_SLIRP)
3368 /* slirp network adapter */
3370 static int slirp_inited;
3371 static VLANClientState *slirp_vc;
3373 int slirp_can_output(void)
3375 return !slirp_vc || qemu_can_send_packet(slirp_vc);
3378 void slirp_output(const uint8_t *pkt, int pkt_len)
3381 printf("slirp output:\n");
3382 hex_dump(stdout, pkt, pkt_len);
3386 qemu_send_packet(slirp_vc, pkt, pkt_len);
3389 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3392 printf("slirp input:\n");
3393 hex_dump(stdout, buf, size);
3395 slirp_input(buf, size);
3398 static int net_slirp_init(VLANState *vlan)
3400 if (!slirp_inited) {
3404 slirp_vc = qemu_new_vlan_client(vlan,
3405 slirp_receive, NULL, NULL);
3406 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3410 static void net_slirp_redir(const char *redir_str)
3415 struct in_addr guest_addr;
3416 int host_port, guest_port;
3418 if (!slirp_inited) {
3424 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3426 if (!strcmp(buf, "tcp")) {
3428 } else if (!strcmp(buf, "udp")) {
3434 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3436 host_port = strtol(buf, &r, 0);
3440 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3442 if (buf[0] == '\0') {
3443 pstrcpy(buf, sizeof(buf), "10.0.2.15");
3445 if (!inet_aton(buf, &guest_addr))
3448 guest_port = strtol(p, &r, 0);
3452 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3453 fprintf(stderr, "qemu: could not set up redirection\n");
3458 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3466 static void smb_exit(void)
3470 char filename[1024];
3472 /* erase all the files in the directory */
3473 d = opendir(smb_dir);
3478 if (strcmp(de->d_name, ".") != 0 &&
3479 strcmp(de->d_name, "..") != 0) {
3480 snprintf(filename, sizeof(filename), "%s/%s",
3481 smb_dir, de->d_name);
3489 /* automatic user mode samba server configuration */
3490 void net_slirp_smb(const char *exported_dir)
3492 char smb_conf[1024];
3493 char smb_cmdline[1024];
3496 if (!slirp_inited) {
3501 /* XXX: better tmp dir construction */
3502 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3503 if (mkdir(smb_dir, 0700) < 0) {
3504 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3507 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3509 f = fopen(smb_conf, "w");
3511 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3518 "socket address=127.0.0.1\n"
3519 "pid directory=%s\n"
3520 "lock directory=%s\n"
3521 "log file=%s/log.smbd\n"
3522 "smb passwd file=%s/smbpasswd\n"
3523 "security = share\n"
3538 snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3539 SMBD_COMMAND, smb_conf);
3541 slirp_add_exec(0, smb_cmdline, 4, 139);
3544 #endif /* !defined(_WIN32) */
3546 #endif /* CONFIG_SLIRP */
3548 #if !defined(_WIN32)
3550 typedef struct TAPState {
3551 VLANClientState *vc;
3555 static void tap_receive(void *opaque, const uint8_t *buf, int size)
3557 TAPState *s = opaque;
3560 ret = write(s->fd, buf, size);
3561 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3568 static void tap_send(void *opaque)
3570 TAPState *s = opaque;
3577 sbuf.maxlen = sizeof(buf);
3579 size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3581 size = read(s->fd, buf, sizeof(buf));
3584 qemu_send_packet(s->vc, buf, size);
3590 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3594 s = qemu_mallocz(sizeof(TAPState));
3598 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3599 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3600 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3604 #if defined (_BSD) || defined (__FreeBSD_kernel__)
3605 static int tap_open(char *ifname, int ifname_size)
3611 TFR(fd = open("/dev/tap", O_RDWR));
3613 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3618 dev = devname(s.st_rdev, S_IFCHR);
3619 pstrcpy(ifname, ifname_size, dev);
3621 fcntl(fd, F_SETFL, O_NONBLOCK);
3624 #elif defined(__sun__)
3625 #define TUNNEWPPA (('T'<<16) | 0x0001)
3627 * Allocate TAP device, returns opened fd.
3628 * Stores dev name in the first arg(must be large enough).
3630 int tap_alloc(char *dev)
3632 int tap_fd, if_fd, ppa = -1;
3633 static int ip_fd = 0;
3636 static int arp_fd = 0;
3637 int ip_muxid, arp_muxid;
3638 struct strioctl strioc_if, strioc_ppa;
3639 int link_type = I_PLINK;;
3641 char actual_name[32] = "";
3643 memset(&ifr, 0x0, sizeof(ifr));
3647 while( *ptr && !isdigit((int)*ptr) ) ptr++;
3651 /* Check if IP device was opened */
3655 TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3657 syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3661 TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3663 syslog(LOG_ERR, "Can't open /dev/tap");
3667 /* Assign a new PPA and get its unit number. */
3668 strioc_ppa.ic_cmd = TUNNEWPPA;
3669 strioc_ppa.ic_timout = 0;
3670 strioc_ppa.ic_len = sizeof(ppa);
3671 strioc_ppa.ic_dp = (char *)&ppa;
3672 if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3673 syslog (LOG_ERR, "Can't assign new interface");
3675 TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3677 syslog(LOG_ERR, "Can't open /dev/tap (2)");
3680 if(ioctl(if_fd, I_PUSH, "ip") < 0){
3681 syslog(LOG_ERR, "Can't push IP module");
3685 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3686 syslog(LOG_ERR, "Can't get flags\n");
3688 snprintf (actual_name, 32, "tap%d", ppa);
3689 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3692 /* Assign ppa according to the unit number returned by tun device */
3694 if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3695 syslog (LOG_ERR, "Can't set PPA %d", ppa);
3696 if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3697 syslog (LOG_ERR, "Can't get flags\n");
3698 /* Push arp module to if_fd */
3699 if (ioctl (if_fd, I_PUSH, "arp") < 0)
3700 syslog (LOG_ERR, "Can't push ARP module (2)");
3702 /* Push arp module to ip_fd */
3703 if (ioctl (ip_fd, I_POP, NULL) < 0)
3704 syslog (LOG_ERR, "I_POP failed\n");
3705 if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3706 syslog (LOG_ERR, "Can't push ARP module (3)\n");
3708 TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3710 syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3712 /* Set ifname to arp */
3713 strioc_if.ic_cmd = SIOCSLIFNAME;
3714 strioc_if.ic_timout = 0;
3715 strioc_if.ic_len = sizeof(ifr);
3716 strioc_if.ic_dp = (char *)𝔦
3717 if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3718 syslog (LOG_ERR, "Can't set ifname to arp\n");
3721 if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3722 syslog(LOG_ERR, "Can't link TAP device to IP");
3726 if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
3727 syslog (LOG_ERR, "Can't link TAP device to ARP");
3731 memset(&ifr, 0x0, sizeof(ifr));
3732 strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3733 ifr.lifr_ip_muxid = ip_muxid;
3734 ifr.lifr_arp_muxid = arp_muxid;
3736 if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3738 ioctl (ip_fd, I_PUNLINK , arp_muxid);
3739 ioctl (ip_fd, I_PUNLINK, ip_muxid);
3740 syslog (LOG_ERR, "Can't set multiplexor id");
3743 sprintf(dev, "tap%d", ppa);
3747 static int tap_open(char *ifname, int ifname_size)
3751 if( (fd = tap_alloc(dev)) < 0 ){
3752 fprintf(stderr, "Cannot allocate TAP device\n");
3755 pstrcpy(ifname, ifname_size, dev);
3756 fcntl(fd, F_SETFL, O_NONBLOCK);
3760 static int tap_open(char *ifname, int ifname_size)
3765 TFR(fd = open("/dev/net/tun", O_RDWR));
3767 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3770 memset(&ifr, 0, sizeof(ifr));
3771 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3772 if (ifname[0] != '\0')
3773 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3775 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3776 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3778 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3782 pstrcpy(ifname, ifname_size, ifr.ifr_name);
3783 fcntl(fd, F_SETFL, O_NONBLOCK);
3788 static int net_tap_init(VLANState *vlan, const char *ifname1,
3789 const char *setup_script)
3792 int pid, status, fd;
3797 if (ifname1 != NULL)
3798 pstrcpy(ifname, sizeof(ifname), ifname1);
3801 TFR(fd = tap_open(ifname, sizeof(ifname)));
3805 if (!setup_script || !strcmp(setup_script, "no"))
3807 if (setup_script[0] != '\0') {
3808 /* try to launch network init script */
3812 int open_max = sysconf (_SC_OPEN_MAX), i;
3813 for (i = 0; i < open_max; i++)
3814 if (i != STDIN_FILENO &&
3815 i != STDOUT_FILENO &&
3816 i != STDERR_FILENO &&
3821 *parg++ = (char *)setup_script;
3824 execv(setup_script, args);
3827 while (waitpid(pid, &status, 0) != pid);
3828 if (!WIFEXITED(status) ||
3829 WEXITSTATUS(status) != 0) {
3830 fprintf(stderr, "%s: could not launch network script\n",
3836 s = net_tap_fd_init(vlan, fd);
3839 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3840 "tap: ifname=%s setup_script=%s", ifname, setup_script);
3844 #endif /* !_WIN32 */
3846 /* network connection */
3847 typedef struct NetSocketState {
3848 VLANClientState *vc;
3850 int state; /* 0 = getting length, 1 = getting data */
3854 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3857 typedef struct NetSocketListenState {
3860 } NetSocketListenState;
3862 /* XXX: we consider we can send the whole packet without blocking */
3863 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3865 NetSocketState *s = opaque;
3869 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3870 send_all(s->fd, buf, size);
3873 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3875 NetSocketState *s = opaque;
3876 sendto(s->fd, buf, size, 0,
3877 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3880 static void net_socket_send(void *opaque)
3882 NetSocketState *s = opaque;
3887 size = recv(s->fd, buf1, sizeof(buf1), 0);
3889 err = socket_error();
3890 if (err != EWOULDBLOCK)
3892 } else if (size == 0) {
3893 /* end of connection */
3895 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3901 /* reassemble a packet from the network */
3907 memcpy(s->buf + s->index, buf, l);
3911 if (s->index == 4) {
3913 s->packet_len = ntohl(*(uint32_t *)s->buf);
3919 l = s->packet_len - s->index;
3922 memcpy(s->buf + s->index, buf, l);
3926 if (s->index >= s->packet_len) {
3927 qemu_send_packet(s->vc, s->buf, s->packet_len);
3936 static void net_socket_send_dgram(void *opaque)
3938 NetSocketState *s = opaque;
3941 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3945 /* end of connection */
3946 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3949 qemu_send_packet(s->vc, s->buf, size);
3952 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3957 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3958 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3959 inet_ntoa(mcastaddr->sin_addr),
3960 (int)ntohl(mcastaddr->sin_addr.s_addr));
3964 fd = socket(PF_INET, SOCK_DGRAM, 0);
3966 perror("socket(PF_INET, SOCK_DGRAM)");
3971 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
3972 (const char *)&val, sizeof(val));
3974 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3978 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3984 /* Add host to multicast group */
3985 imr.imr_multiaddr = mcastaddr->sin_addr;
3986 imr.imr_interface.s_addr = htonl(INADDR_ANY);
3988 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
3989 (const char *)&imr, sizeof(struct ip_mreq));
3991 perror("setsockopt(IP_ADD_MEMBERSHIP)");
3995 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3997 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
3998 (const char *)&val, sizeof(val));
4000 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4004 socket_set_nonblock(fd);
4012 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4015 struct sockaddr_in saddr;
4017 socklen_t saddr_len;
4020 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4021 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4022 * by ONLY ONE process: we must "clone" this dgram socket --jjo
4026 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4028 if (saddr.sin_addr.s_addr==0) {
4029 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4033 /* clone dgram socket */
4034 newfd = net_socket_mcast_create(&saddr);
4036 /* error already reported by net_socket_mcast_create() */
4040 /* clone newfd to fd, close newfd */
4045 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4046 fd, strerror(errno));
4051 s = qemu_mallocz(sizeof(NetSocketState));
4056 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4057 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4059 /* mcast: save bound address as dst */
4060 if (is_connected) s->dgram_dst=saddr;
4062 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4063 "socket: fd=%d (%s mcast=%s:%d)",
4064 fd, is_connected? "cloned" : "",
4065 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4069 static void net_socket_connect(void *opaque)
4071 NetSocketState *s = opaque;
4072 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4075 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4079 s = qemu_mallocz(sizeof(NetSocketState));
4083 s->vc = qemu_new_vlan_client(vlan,
4084 net_socket_receive, NULL, s);
4085 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4086 "socket: fd=%d", fd);
4088 net_socket_connect(s);
4090 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4095 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4098 int so_type=-1, optlen=sizeof(so_type);
4100 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4101 fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4106 return net_socket_fd_init_dgram(vlan, fd, is_connected);
4108 return net_socket_fd_init_stream(vlan, fd, is_connected);
4110 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4111 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4112 return net_socket_fd_init_stream(vlan, fd, is_connected);
4117 static void net_socket_accept(void *opaque)
4119 NetSocketListenState *s = opaque;
4121 struct sockaddr_in saddr;
4126 len = sizeof(saddr);
4127 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4128 if (fd < 0 && errno != EINTR) {
4130 } else if (fd >= 0) {
4134 s1 = net_socket_fd_init(s->vlan, fd, 1);
4138 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4139 "socket: connection from %s:%d",
4140 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4144 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4146 NetSocketListenState *s;
4148 struct sockaddr_in saddr;
4150 if (parse_host_port(&saddr, host_str) < 0)
4153 s = qemu_mallocz(sizeof(NetSocketListenState));
4157 fd = socket(PF_INET, SOCK_STREAM, 0);
4162 socket_set_nonblock(fd);
4164 /* allow fast reuse */
4166 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4168 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4173 ret = listen(fd, 0);
4180 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4184 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4187 int fd, connected, ret, err;
4188 struct sockaddr_in saddr;
4190 if (parse_host_port(&saddr, host_str) < 0)
4193 fd = socket(PF_INET, SOCK_STREAM, 0);
4198 socket_set_nonblock(fd);
4202 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4204 err = socket_error();
4205 if (err == EINTR || err == EWOULDBLOCK) {
4206 } else if (err == EINPROGRESS) {
4209 } else if (err == WSAEALREADY) {
4222 s = net_socket_fd_init(vlan, fd, connected);
4225 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4226 "socket: connect to %s:%d",
4227 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4231 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4235 struct sockaddr_in saddr;
4237 if (parse_host_port(&saddr, host_str) < 0)
4241 fd = net_socket_mcast_create(&saddr);
4245 s = net_socket_fd_init(vlan, fd, 0);
4249 s->dgram_dst = saddr;
4251 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4252 "socket: mcast=%s:%d",
4253 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4258 static int get_param_value(char *buf, int buf_size,
4259 const char *tag, const char *str)
4268 while (*p != '\0' && *p != '=') {
4269 if ((q - option) < sizeof(option) - 1)
4277 if (!strcmp(tag, option)) {
4279 while (*p != '\0' && *p != ',') {
4280 if ((q - buf) < buf_size - 1)
4287 while (*p != '\0' && *p != ',') {
4298 static int net_client_init(const char *str)
4309 while (*p != '\0' && *p != ',') {
4310 if ((q - device) < sizeof(device) - 1)
4318 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4319 vlan_id = strtol(buf, NULL, 0);
4321 vlan = qemu_find_vlan(vlan_id);
4323 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4326 if (!strcmp(device, "nic")) {
4330 if (nb_nics >= MAX_NICS) {
4331 fprintf(stderr, "Too Many NICs\n");
4334 nd = &nd_table[nb_nics];
4335 macaddr = nd->macaddr;
4341 macaddr[5] = 0x56 + nb_nics;
4343 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4344 if (parse_macaddr(macaddr, buf) < 0) {
4345 fprintf(stderr, "invalid syntax for ethernet address\n");
4349 if (get_param_value(buf, sizeof(buf), "model", p)) {
4350 nd->model = strdup(buf);
4354 vlan->nb_guest_devs++;
4357 if (!strcmp(device, "none")) {
4358 /* does nothing. It is needed to signal that no network cards
4363 if (!strcmp(device, "user")) {
4364 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4365 pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4367 vlan->nb_host_devs++;
4368 ret = net_slirp_init(vlan);
4372 if (!strcmp(device, "tap")) {
4374 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4375 fprintf(stderr, "tap: no interface name\n");
4378 vlan->nb_host_devs++;
4379 ret = tap_win32_init(vlan, ifname);
4382 if (!strcmp(device, "tap")) {
4384 char setup_script[1024];
4386 vlan->nb_host_devs++;
4387 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4388 fd = strtol(buf, NULL, 0);
4390 if (net_tap_fd_init(vlan, fd))
4393 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4396 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4397 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4399 ret = net_tap_init(vlan, ifname, setup_script);
4403 if (!strcmp(device, "socket")) {
4404 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4406 fd = strtol(buf, NULL, 0);
4408 if (net_socket_fd_init(vlan, fd, 1))
4410 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4411 ret = net_socket_listen_init(vlan, buf);
4412 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4413 ret = net_socket_connect_init(vlan, buf);
4414 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4415 ret = net_socket_mcast_init(vlan, buf);
4417 fprintf(stderr, "Unknown socket options: %s\n", p);
4420 vlan->nb_host_devs++;
4423 fprintf(stderr, "Unknown network device: %s\n", device);
4427 fprintf(stderr, "Could not initialize device '%s'\n", device);
4433 void do_info_network(void)
4436 VLANClientState *vc;
4438 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4439 term_printf("VLAN %d devices:\n", vlan->id);
4440 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4441 term_printf(" %s\n", vc->info_str);
4445 /***********************************************************/
4448 static USBPort *used_usb_ports;
4449 static USBPort *free_usb_ports;
4451 /* ??? Maybe change this to register a hub to keep track of the topology. */
4452 void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4453 usb_attachfn attach)
4455 port->opaque = opaque;
4456 port->index = index;
4457 port->attach = attach;
4458 port->next = free_usb_ports;
4459 free_usb_ports = port;
4462 static int usb_device_add(const char *devname)
4468 if (!free_usb_ports)
4471 if (strstart(devname, "host:", &p)) {
4472 dev = usb_host_device_open(p);
4473 } else if (!strcmp(devname, "mouse")) {
4474 dev = usb_mouse_init();
4475 } else if (!strcmp(devname, "tablet")) {
4476 dev = usb_tablet_init();
4477 } else if (!strcmp(devname, "keyboard")) {
4478 dev = usb_keyboard_init();
4479 } else if (strstart(devname, "disk:", &p)) {
4480 dev = usb_msd_init(p);
4481 } else if (!strcmp(devname, "wacom-tablet")) {
4482 dev = usb_wacom_init();
4489 /* Find a USB port to add the device to. */
4490 port = free_usb_ports;
4494 /* Create a new hub and chain it on. */
4495 free_usb_ports = NULL;
4496 port->next = used_usb_ports;
4497 used_usb_ports = port;
4499 hub = usb_hub_init(VM_USB_HUB_SIZE);
4500 usb_attach(port, hub);
4501 port = free_usb_ports;
4504 free_usb_ports = port->next;
4505 port->next = used_usb_ports;
4506 used_usb_ports = port;
4507 usb_attach(port, dev);
4511 static int usb_device_del(const char *devname)
4519 if (!used_usb_ports)
4522 p = strchr(devname, '.');
4525 bus_num = strtoul(devname, NULL, 0);
4526 addr = strtoul(p + 1, NULL, 0);
4530 lastp = &used_usb_ports;
4531 port = used_usb_ports;
4532 while (port && port->dev->addr != addr) {
4533 lastp = &port->next;
4541 *lastp = port->next;
4542 usb_attach(port, NULL);
4543 dev->handle_destroy(dev);
4544 port->next = free_usb_ports;
4545 free_usb_ports = port;
4549 void do_usb_add(const char *devname)
4552 ret = usb_device_add(devname);
4554 term_printf("Could not add USB device '%s'\n", devname);
4557 void do_usb_del(const char *devname)
4560 ret = usb_device_del(devname);
4562 term_printf("Could not remove USB device '%s'\n", devname);
4569 const char *speed_str;
4572 term_printf("USB support not enabled\n");
4576 for (port = used_usb_ports; port; port = port->next) {
4580 switch(dev->speed) {
4584 case USB_SPEED_FULL:
4587 case USB_SPEED_HIGH:
4594 term_printf(" Device %d.%d, Speed %s Mb/s, Product %s\n",
4595 0, dev->addr, speed_str, dev->devname);
4599 /***********************************************************/
4600 /* PCMCIA/Cardbus */
4602 static struct pcmcia_socket_entry_s {
4603 struct pcmcia_socket_s *socket;
4604 struct pcmcia_socket_entry_s *next;
4605 } *pcmcia_sockets = 0;
4607 void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4609 struct pcmcia_socket_entry_s *entry;
4611 entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4612 entry->socket = socket;
4613 entry->next = pcmcia_sockets;
4614 pcmcia_sockets = entry;
4617 void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4619 struct pcmcia_socket_entry_s *entry, **ptr;
4621 ptr = &pcmcia_sockets;
4622 for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4623 if (entry->socket == socket) {
4629 void pcmcia_info(void)
4631 struct pcmcia_socket_entry_s *iter;
4632 if (!pcmcia_sockets)
4633 term_printf("No PCMCIA sockets\n");
4635 for (iter = pcmcia_sockets; iter; iter = iter->next)
4636 term_printf("%s: %s\n", iter->socket->slot_string,
4637 iter->socket->attached ? iter->socket->card_string :
4641 /***********************************************************/
4644 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4648 static void dumb_resize(DisplayState *ds, int w, int h)
4652 static void dumb_refresh(DisplayState *ds)
4654 #if defined(CONFIG_SDL)
4659 static void dumb_display_init(DisplayState *ds)
4664 ds->dpy_update = dumb_update;
4665 ds->dpy_resize = dumb_resize;
4666 ds->dpy_refresh = dumb_refresh;
4669 /***********************************************************/
4672 #define MAX_IO_HANDLERS 64
4674 typedef struct IOHandlerRecord {
4676 IOCanRWHandler *fd_read_poll;
4678 IOHandler *fd_write;
4681 /* temporary data */
4683 struct IOHandlerRecord *next;
4686 static IOHandlerRecord *first_io_handler;
4688 /* XXX: fd_read_poll should be suppressed, but an API change is
4689 necessary in the character devices to suppress fd_can_read(). */
4690 int qemu_set_fd_handler2(int fd,
4691 IOCanRWHandler *fd_read_poll,
4693 IOHandler *fd_write,
4696 IOHandlerRecord **pioh, *ioh;
4698 if (!fd_read && !fd_write) {
4699 pioh = &first_io_handler;
4704 if (ioh->fd == fd) {
4711 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4715 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4718 ioh->next = first_io_handler;
4719 first_io_handler = ioh;
4722 ioh->fd_read_poll = fd_read_poll;
4723 ioh->fd_read = fd_read;
4724 ioh->fd_write = fd_write;
4725 ioh->opaque = opaque;
4731 int qemu_set_fd_handler(int fd,
4733 IOHandler *fd_write,
4736 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4739 /***********************************************************/
4740 /* Polling handling */
4742 typedef struct PollingEntry {
4745 struct PollingEntry *next;
4748 static PollingEntry *first_polling_entry;
4750 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4752 PollingEntry **ppe, *pe;
4753 pe = qemu_mallocz(sizeof(PollingEntry));
4757 pe->opaque = opaque;
4758 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4763 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4765 PollingEntry **ppe, *pe;
4766 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4768 if (pe->func == func && pe->opaque == opaque) {
4777 /***********************************************************/
4778 /* Wait objects support */
4779 typedef struct WaitObjects {
4781 HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4782 WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4783 void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4786 static WaitObjects wait_objects = {0};
4788 int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4790 WaitObjects *w = &wait_objects;
4792 if (w->num >= MAXIMUM_WAIT_OBJECTS)
4794 w->events[w->num] = handle;
4795 w->func[w->num] = func;
4796 w->opaque[w->num] = opaque;
4801 void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4804 WaitObjects *w = &wait_objects;
4807 for (i = 0; i < w->num; i++) {
4808 if (w->events[i] == handle)
4811 w->events[i] = w->events[i + 1];
4812 w->func[i] = w->func[i + 1];
4813 w->opaque[i] = w->opaque[i + 1];
4821 /***********************************************************/
4822 /* savevm/loadvm support */
4824 #define IO_BUF_SIZE 32768
4828 BlockDriverState *bs;
4831 int64_t base_offset;
4832 int64_t buf_offset; /* start of buffer when writing, end of buffer
4835 int buf_size; /* 0 when writing */
4836 uint8_t buf[IO_BUF_SIZE];
4839 QEMUFile *qemu_fopen(const char *filename, const char *mode)
4843 f = qemu_mallocz(sizeof(QEMUFile));
4846 if (!strcmp(mode, "wb")) {
4848 } else if (!strcmp(mode, "rb")) {
4853 f->outfile = fopen(filename, mode);
4865 QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4869 f = qemu_mallocz(sizeof(QEMUFile));
4874 f->is_writable = is_writable;
4875 f->base_offset = offset;
4879 void qemu_fflush(QEMUFile *f)
4881 if (!f->is_writable)
4883 if (f->buf_index > 0) {
4885 fseek(f->outfile, f->buf_offset, SEEK_SET);
4886 fwrite(f->buf, 1, f->buf_index, f->outfile);
4888 bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
4889 f->buf, f->buf_index);
4891 f->buf_offset += f->buf_index;
4896 static void qemu_fill_buffer(QEMUFile *f)
4903 fseek(f->outfile, f->buf_offset, SEEK_SET);
4904 len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4908 len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
4909 f->buf, IO_BUF_SIZE);
4915 f->buf_offset += len;
4918 void qemu_fclose(QEMUFile *f)
4928 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4932 l = IO_BUF_SIZE - f->buf_index;
4935 memcpy(f->buf + f->buf_index, buf, l);
4939 if (f->buf_index >= IO_BUF_SIZE)
4944 void qemu_put_byte(QEMUFile *f, int v)
4946 f->buf[f->buf_index++] = v;
4947 if (f->buf_index >= IO_BUF_SIZE)
4951 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4957 l = f->buf_size - f->buf_index;
4959 qemu_fill_buffer(f);
4960 l = f->buf_size - f->buf_index;
4966 memcpy(buf, f->buf + f->buf_index, l);
4971 return size1 - size;
4974 int qemu_get_byte(QEMUFile *f)
4976 if (f->buf_index >= f->buf_size) {
4977 qemu_fill_buffer(f);
4978 if (f->buf_index >= f->buf_size)
4981 return f->buf[f->buf_index++];
4984 int64_t qemu_ftell(QEMUFile *f)
4986 return f->buf_offset - f->buf_size + f->buf_index;
4989 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4991 if (whence == SEEK_SET) {
4993 } else if (whence == SEEK_CUR) {
4994 pos += qemu_ftell(f);
4996 /* SEEK_END not supported */
4999 if (f->is_writable) {
5001 f->buf_offset = pos;
5003 f->buf_offset = pos;
5010 void qemu_put_be16(QEMUFile *f, unsigned int v)
5012 qemu_put_byte(f, v >> 8);
5013 qemu_put_byte(f, v);
5016 void qemu_put_be32(QEMUFile *f, unsigned int v)
5018 qemu_put_byte(f, v >> 24);
5019 qemu_put_byte(f, v >> 16);
5020 qemu_put_byte(f, v >> 8);
5021 qemu_put_byte(f, v);
5024 void qemu_put_be64(QEMUFile *f, uint64_t v)
5026 qemu_put_be32(f, v >> 32);
5027 qemu_put_be32(f, v);
5030 unsigned int qemu_get_be16(QEMUFile *f)
5033 v = qemu_get_byte(f) << 8;
5034 v |= qemu_get_byte(f);
5038 unsigned int qemu_get_be32(QEMUFile *f)
5041 v = qemu_get_byte(f) << 24;
5042 v |= qemu_get_byte(f) << 16;
5043 v |= qemu_get_byte(f) << 8;
5044 v |= qemu_get_byte(f);
5048 uint64_t qemu_get_be64(QEMUFile *f)
5051 v = (uint64_t)qemu_get_be32(f) << 32;
5052 v |= qemu_get_be32(f);
5056 typedef struct SaveStateEntry {
5060 SaveStateHandler *save_state;
5061 LoadStateHandler *load_state;
5063 struct SaveStateEntry *next;
5066 static SaveStateEntry *first_se;
5068 int register_savevm(const char *idstr,
5071 SaveStateHandler *save_state,
5072 LoadStateHandler *load_state,
5075 SaveStateEntry *se, **pse;
5077 se = qemu_malloc(sizeof(SaveStateEntry));
5080 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5081 se->instance_id = instance_id;
5082 se->version_id = version_id;
5083 se->save_state = save_state;
5084 se->load_state = load_state;
5085 se->opaque = opaque;
5088 /* add at the end of list */
5090 while (*pse != NULL)
5091 pse = &(*pse)->next;
5096 #define QEMU_VM_FILE_MAGIC 0x5145564d
5097 #define QEMU_VM_FILE_VERSION 0x00000002
5099 int qemu_savevm_state(QEMUFile *f)
5103 int64_t cur_pos, len_pos, total_len_pos;
5105 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5106 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5107 total_len_pos = qemu_ftell(f);
5108 qemu_put_be64(f, 0); /* total size */
5110 for(se = first_se; se != NULL; se = se->next) {
5112 len = strlen(se->idstr);
5113 qemu_put_byte(f, len);
5114 qemu_put_buffer(f, se->idstr, len);
5116 qemu_put_be32(f, se->instance_id);
5117 qemu_put_be32(f, se->version_id);
5119 /* record size: filled later */
5120 len_pos = qemu_ftell(f);
5121 qemu_put_be32(f, 0);
5123 se->save_state(f, se->opaque);
5125 /* fill record size */
5126 cur_pos = qemu_ftell(f);
5127 len = cur_pos - len_pos - 4;
5128 qemu_fseek(f, len_pos, SEEK_SET);
5129 qemu_put_be32(f, len);
5130 qemu_fseek(f, cur_pos, SEEK_SET);
5132 cur_pos = qemu_ftell(f);
5133 qemu_fseek(f, total_len_pos, SEEK_SET);
5134 qemu_put_be64(f, cur_pos - total_len_pos - 8);
5135 qemu_fseek(f, cur_pos, SEEK_SET);
5141 static SaveStateEntry *find_se(const char *idstr, int instance_id)
5145 for(se = first_se; se != NULL; se = se->next) {
5146 if (!strcmp(se->idstr, idstr) &&
5147 instance_id == se->instance_id)
5153 int qemu_loadvm_state(QEMUFile *f)
5156 int len, ret, instance_id, record_len, version_id;
5157 int64_t total_len, end_pos, cur_pos;
5161 v = qemu_get_be32(f);
5162 if (v != QEMU_VM_FILE_MAGIC)
5164 v = qemu_get_be32(f);
5165 if (v != QEMU_VM_FILE_VERSION) {
5170 total_len = qemu_get_be64(f);
5171 end_pos = total_len + qemu_ftell(f);
5173 if (qemu_ftell(f) >= end_pos)
5175 len = qemu_get_byte(f);
5176 qemu_get_buffer(f, idstr, len);
5178 instance_id = qemu_get_be32(f);
5179 version_id = qemu_get_be32(f);
5180 record_len = qemu_get_be32(f);
5182 printf("idstr=%s instance=0x%x version=%d len=%d\n",
5183 idstr, instance_id, version_id, record_len);
5185 cur_pos = qemu_ftell(f);
5186 se = find_se(idstr, instance_id);
5188 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5189 instance_id, idstr);
5191 ret = se->load_state(f, se->opaque, version_id);
5193 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5194 instance_id, idstr);
5197 /* always seek to exact end of record */
5198 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5205 /* device can contain snapshots */
5206 static int bdrv_can_snapshot(BlockDriverState *bs)
5209 !bdrv_is_removable(bs) &&
5210 !bdrv_is_read_only(bs));
5213 /* device must be snapshots in order to have a reliable snapshot */
5214 static int bdrv_has_snapshot(BlockDriverState *bs)
5217 !bdrv_is_removable(bs) &&
5218 !bdrv_is_read_only(bs));
5221 static BlockDriverState *get_bs_snapshots(void)
5223 BlockDriverState *bs;
5227 return bs_snapshots;
5228 for(i = 0; i <= MAX_DISKS; i++) {
5230 if (bdrv_can_snapshot(bs))
5239 static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5242 QEMUSnapshotInfo *sn_tab, *sn;
5246 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5249 for(i = 0; i < nb_sns; i++) {
5251 if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5261 void do_savevm(const char *name)
5263 BlockDriverState *bs, *bs1;
5264 QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5265 int must_delete, ret, i;
5266 BlockDriverInfo bdi1, *bdi = &bdi1;
5268 int saved_vm_running;
5275 bs = get_bs_snapshots();
5277 term_printf("No block device can accept snapshots\n");
5281 /* ??? Should this occur after vm_stop? */
5284 saved_vm_running = vm_running;
5289 ret = bdrv_snapshot_find(bs, old_sn, name);
5294 memset(sn, 0, sizeof(*sn));
5296 pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5297 pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5300 pstrcpy(sn->name, sizeof(sn->name), name);
5303 /* fill auxiliary fields */
5306 sn->date_sec = tb.time;
5307 sn->date_nsec = tb.millitm * 1000000;
5309 gettimeofday(&tv, NULL);
5310 sn->date_sec = tv.tv_sec;
5311 sn->date_nsec = tv.tv_usec * 1000;
5313 sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5315 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5316 term_printf("Device %s does not support VM state snapshots\n",
5317 bdrv_get_device_name(bs));
5321 /* save the VM state */
5322 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5324 term_printf("Could not open VM state file\n");
5327 ret = qemu_savevm_state(f);
5328 sn->vm_state_size = qemu_ftell(f);
5331 term_printf("Error %d while writing VM\n", ret);
5335 /* create the snapshots */
5337 for(i = 0; i < MAX_DISKS; i++) {
5339 if (bdrv_has_snapshot(bs1)) {
5341 ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5343 term_printf("Error while deleting snapshot on '%s'\n",
5344 bdrv_get_device_name(bs1));
5347 ret = bdrv_snapshot_create(bs1, sn);
5349 term_printf("Error while creating snapshot on '%s'\n",
5350 bdrv_get_device_name(bs1));
5356 if (saved_vm_running)
5360 void do_loadvm(const char *name)
5362 BlockDriverState *bs, *bs1;
5363 BlockDriverInfo bdi1, *bdi = &bdi1;
5366 int saved_vm_running;
5368 bs = get_bs_snapshots();
5370 term_printf("No block device supports snapshots\n");
5374 /* Flush all IO requests so they don't interfere with the new state. */
5377 saved_vm_running = vm_running;
5380 for(i = 0; i <= MAX_DISKS; i++) {
5382 if (bdrv_has_snapshot(bs1)) {
5383 ret = bdrv_snapshot_goto(bs1, name);
5386 term_printf("Warning: ");
5389 term_printf("Snapshots not supported on device '%s'\n",
5390 bdrv_get_device_name(bs1));
5393 term_printf("Could not find snapshot '%s' on device '%s'\n",
5394 name, bdrv_get_device_name(bs1));
5397 term_printf("Error %d while activating snapshot on '%s'\n",
5398 ret, bdrv_get_device_name(bs1));
5401 /* fatal on snapshot block device */
5408 if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5409 term_printf("Device %s does not support VM state snapshots\n",
5410 bdrv_get_device_name(bs));
5414 /* restore the VM state */
5415 f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5417 term_printf("Could not open VM state file\n");
5420 ret = qemu_loadvm_state(f);
5423 term_printf("Error %d while loading VM state\n", ret);
5426 if (saved_vm_running)
5430 void do_delvm(const char *name)
5432 BlockDriverState *bs, *bs1;
5435 bs = get_bs_snapshots();
5437 term_printf("No block device supports snapshots\n");
5441 for(i = 0; i <= MAX_DISKS; i++) {
5443 if (bdrv_has_snapshot(bs1)) {
5444 ret = bdrv_snapshot_delete(bs1, name);
5446 if (ret == -ENOTSUP)
5447 term_printf("Snapshots not supported on device '%s'\n",
5448 bdrv_get_device_name(bs1));
5450 term_printf("Error %d while deleting snapshot on '%s'\n",
5451 ret, bdrv_get_device_name(bs1));
5457 void do_info_snapshots(void)
5459 BlockDriverState *bs, *bs1;
5460 QEMUSnapshotInfo *sn_tab, *sn;
5464 bs = get_bs_snapshots();
5466 term_printf("No available block device supports snapshots\n");
5469 term_printf("Snapshot devices:");
5470 for(i = 0; i <= MAX_DISKS; i++) {
5472 if (bdrv_has_snapshot(bs1)) {
5474 term_printf(" %s", bdrv_get_device_name(bs1));
5479 nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5481 term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5484 term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5485 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5486 for(i = 0; i < nb_sns; i++) {
5488 term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5493 /***********************************************************/
5494 /* cpu save/restore */
5496 #if defined(TARGET_I386)
5498 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5500 qemu_put_be32(f, dt->selector);
5501 qemu_put_betl(f, dt->base);
5502 qemu_put_be32(f, dt->limit);
5503 qemu_put_be32(f, dt->flags);
5506 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5508 dt->selector = qemu_get_be32(f);
5509 dt->base = qemu_get_betl(f);
5510 dt->limit = qemu_get_be32(f);
5511 dt->flags = qemu_get_be32(f);
5514 void cpu_save(QEMUFile *f, void *opaque)
5516 CPUState *env = opaque;
5517 uint16_t fptag, fpus, fpuc, fpregs_format;
5521 for(i = 0; i < CPU_NB_REGS; i++)
5522 qemu_put_betls(f, &env->regs[i]);
5523 qemu_put_betls(f, &env->eip);
5524 qemu_put_betls(f, &env->eflags);
5525 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5526 qemu_put_be32s(f, &hflags);
5530 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5532 for(i = 0; i < 8; i++) {
5533 fptag |= ((!env->fptags[i]) << i);
5536 qemu_put_be16s(f, &fpuc);
5537 qemu_put_be16s(f, &fpus);
5538 qemu_put_be16s(f, &fptag);
5540 #ifdef USE_X86LDOUBLE
5545 qemu_put_be16s(f, &fpregs_format);
5547 for(i = 0; i < 8; i++) {
5548 #ifdef USE_X86LDOUBLE
5552 /* we save the real CPU data (in case of MMX usage only 'mant'
5553 contains the MMX register */
5554 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5555 qemu_put_be64(f, mant);
5556 qemu_put_be16(f, exp);
5559 /* if we use doubles for float emulation, we save the doubles to
5560 avoid losing information in case of MMX usage. It can give
5561 problems if the image is restored on a CPU where long
5562 doubles are used instead. */
5563 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5567 for(i = 0; i < 6; i++)
5568 cpu_put_seg(f, &env->segs[i]);
5569 cpu_put_seg(f, &env->ldt);
5570 cpu_put_seg(f, &env->tr);
5571 cpu_put_seg(f, &env->gdt);
5572 cpu_put_seg(f, &env->idt);
5574 qemu_put_be32s(f, &env->sysenter_cs);
5575 qemu_put_be32s(f, &env->sysenter_esp);
5576 qemu_put_be32s(f, &env->sysenter_eip);
5578 qemu_put_betls(f, &env->cr[0]);
5579 qemu_put_betls(f, &env->cr[2]);
5580 qemu_put_betls(f, &env->cr[3]);
5581 qemu_put_betls(f, &env->cr[4]);
5583 for(i = 0; i < 8; i++)
5584 qemu_put_betls(f, &env->dr[i]);
5587 qemu_put_be32s(f, &env->a20_mask);
5590 qemu_put_be32s(f, &env->mxcsr);
5591 for(i = 0; i < CPU_NB_REGS; i++) {
5592 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5593 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5596 #ifdef TARGET_X86_64
5597 qemu_put_be64s(f, &env->efer);
5598 qemu_put_be64s(f, &env->star);
5599 qemu_put_be64s(f, &env->lstar);
5600 qemu_put_be64s(f, &env->cstar);
5601 qemu_put_be64s(f, &env->fmask);
5602 qemu_put_be64s(f, &env->kernelgsbase);
5604 qemu_put_be32s(f, &env->smbase);
5607 #ifdef USE_X86LDOUBLE
5608 /* XXX: add that in a FPU generic layer */
5609 union x86_longdouble {
5614 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
5615 #define EXPBIAS1 1023
5616 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
5617 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
5619 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5623 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5624 /* exponent + sign */
5625 e = EXPD1(temp) - EXPBIAS1 + 16383;
5626 e |= SIGND1(temp) >> 16;
5631 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5633 CPUState *env = opaque;
5636 uint16_t fpus, fpuc, fptag, fpregs_format;
5638 if (version_id != 3 && version_id != 4)
5640 for(i = 0; i < CPU_NB_REGS; i++)
5641 qemu_get_betls(f, &env->regs[i]);
5642 qemu_get_betls(f, &env->eip);
5643 qemu_get_betls(f, &env->eflags);
5644 qemu_get_be32s(f, &hflags);
5646 qemu_get_be16s(f, &fpuc);
5647 qemu_get_be16s(f, &fpus);
5648 qemu_get_be16s(f, &fptag);
5649 qemu_get_be16s(f, &fpregs_format);
5651 /* NOTE: we cannot always restore the FPU state if the image come
5652 from a host with a different 'USE_X86LDOUBLE' define. We guess
5653 if we are in an MMX state to restore correctly in that case. */
5654 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5655 for(i = 0; i < 8; i++) {
5659 switch(fpregs_format) {
5661 mant = qemu_get_be64(f);
5662 exp = qemu_get_be16(f);
5663 #ifdef USE_X86LDOUBLE
5664 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5666 /* difficult case */
5668 env->fpregs[i].mmx.MMX_Q(0) = mant;
5670 env->fpregs[i].d = cpu_set_fp80(mant, exp);
5674 mant = qemu_get_be64(f);
5675 #ifdef USE_X86LDOUBLE
5677 union x86_longdouble *p;
5678 /* difficult case */
5679 p = (void *)&env->fpregs[i];
5684 fp64_to_fp80(p, mant);
5688 env->fpregs[i].mmx.MMX_Q(0) = mant;
5697 /* XXX: restore FPU round state */
5698 env->fpstt = (fpus >> 11) & 7;
5699 env->fpus = fpus & ~0x3800;
5701 for(i = 0; i < 8; i++) {
5702 env->fptags[i] = (fptag >> i) & 1;
5705 for(i = 0; i < 6; i++)
5706 cpu_get_seg(f, &env->segs[i]);
5707 cpu_get_seg(f, &env->ldt);
5708 cpu_get_seg(f, &env->tr);
5709 cpu_get_seg(f, &env->gdt);
5710 cpu_get_seg(f, &env->idt);
5712 qemu_get_be32s(f, &env->sysenter_cs);
5713 qemu_get_be32s(f, &env->sysenter_esp);
5714 qemu_get_be32s(f, &env->sysenter_eip);
5716 qemu_get_betls(f, &env->cr[0]);
5717 qemu_get_betls(f, &env->cr[2]);
5718 qemu_get_betls(f, &env->cr[3]);
5719 qemu_get_betls(f, &env->cr[4]);
5721 for(i = 0; i < 8; i++)
5722 qemu_get_betls(f, &env->dr[i]);
5725 qemu_get_be32s(f, &env->a20_mask);
5727 qemu_get_be32s(f, &env->mxcsr);
5728 for(i = 0; i < CPU_NB_REGS; i++) {
5729 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5730 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5733 #ifdef TARGET_X86_64
5734 qemu_get_be64s(f, &env->efer);
5735 qemu_get_be64s(f, &env->star);
5736 qemu_get_be64s(f, &env->lstar);
5737 qemu_get_be64s(f, &env->cstar);
5738 qemu_get_be64s(f, &env->fmask);
5739 qemu_get_be64s(f, &env->kernelgsbase);
5741 if (version_id >= 4)
5742 qemu_get_be32s(f, &env->smbase);
5744 /* XXX: compute hflags from scratch, except for CPL and IIF */
5745 env->hflags = hflags;
5750 #elif defined(TARGET_PPC)
5751 void cpu_save(QEMUFile *f, void *opaque)
5755 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5760 #elif defined(TARGET_MIPS)
5761 void cpu_save(QEMUFile *f, void *opaque)
5765 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5770 #elif defined(TARGET_SPARC)
5771 void cpu_save(QEMUFile *f, void *opaque)
5773 CPUState *env = opaque;
5777 for(i = 0; i < 8; i++)
5778 qemu_put_betls(f, &env->gregs[i]);
5779 for(i = 0; i < NWINDOWS * 16; i++)
5780 qemu_put_betls(f, &env->regbase[i]);
5783 for(i = 0; i < TARGET_FPREGS; i++) {
5789 qemu_put_be32(f, u.i);
5792 qemu_put_betls(f, &env->pc);
5793 qemu_put_betls(f, &env->npc);
5794 qemu_put_betls(f, &env->y);
5796 qemu_put_be32(f, tmp);
5797 qemu_put_betls(f, &env->fsr);
5798 qemu_put_betls(f, &env->tbr);
5799 #ifndef TARGET_SPARC64
5800 qemu_put_be32s(f, &env->wim);
5802 for(i = 0; i < 16; i++)
5803 qemu_put_be32s(f, &env->mmuregs[i]);
5807 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5809 CPUState *env = opaque;
5813 for(i = 0; i < 8; i++)
5814 qemu_get_betls(f, &env->gregs[i]);
5815 for(i = 0; i < NWINDOWS * 16; i++)
5816 qemu_get_betls(f, &env->regbase[i]);
5819 for(i = 0; i < TARGET_FPREGS; i++) {
5824 u.i = qemu_get_be32(f);
5828 qemu_get_betls(f, &env->pc);
5829 qemu_get_betls(f, &env->npc);
5830 qemu_get_betls(f, &env->y);
5831 tmp = qemu_get_be32(f);
5832 env->cwp = 0; /* needed to ensure that the wrapping registers are
5833 correctly updated */
5835 qemu_get_betls(f, &env->fsr);
5836 qemu_get_betls(f, &env->tbr);
5837 #ifndef TARGET_SPARC64
5838 qemu_get_be32s(f, &env->wim);
5840 for(i = 0; i < 16; i++)
5841 qemu_get_be32s(f, &env->mmuregs[i]);
5847 #elif defined(TARGET_ARM)
5849 void cpu_save(QEMUFile *f, void *opaque)
5852 CPUARMState *env = (CPUARMState *)opaque;
5854 for (i = 0; i < 16; i++) {
5855 qemu_put_be32(f, env->regs[i]);
5857 qemu_put_be32(f, cpsr_read(env));
5858 qemu_put_be32(f, env->spsr);
5859 for (i = 0; i < 6; i++) {
5860 qemu_put_be32(f, env->banked_spsr[i]);
5861 qemu_put_be32(f, env->banked_r13[i]);
5862 qemu_put_be32(f, env->banked_r14[i]);
5864 for (i = 0; i < 5; i++) {
5865 qemu_put_be32(f, env->usr_regs[i]);
5866 qemu_put_be32(f, env->fiq_regs[i]);
5868 qemu_put_be32(f, env->cp15.c0_cpuid);
5869 qemu_put_be32(f, env->cp15.c0_cachetype);
5870 qemu_put_be32(f, env->cp15.c1_sys);
5871 qemu_put_be32(f, env->cp15.c1_coproc);
5872 qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
5873 qemu_put_be32(f, env->cp15.c2_base);
5874 qemu_put_be32(f, env->cp15.c2_data);
5875 qemu_put_be32(f, env->cp15.c2_insn);
5876 qemu_put_be32(f, env->cp15.c3);
5877 qemu_put_be32(f, env->cp15.c5_insn);
5878 qemu_put_be32(f, env->cp15.c5_data);
5879 for (i = 0; i < 8; i++) {
5880 qemu_put_be32(f, env->cp15.c6_region[i]);
5882 qemu_put_be32(f, env->cp15.c6_insn);
5883 qemu_put_be32(f, env->cp15.c6_data);
5884 qemu_put_be32(f, env->cp15.c9_insn);
5885 qemu_put_be32(f, env->cp15.c9_data);
5886 qemu_put_be32(f, env->cp15.c13_fcse);
5887 qemu_put_be32(f, env->cp15.c13_context);
5888 qemu_put_be32(f, env->cp15.c15_cpar);
5890 qemu_put_be32(f, env->features);
5892 if (arm_feature(env, ARM_FEATURE_VFP)) {
5893 for (i = 0; i < 16; i++) {
5895 u.d = env->vfp.regs[i];
5896 qemu_put_be32(f, u.l.upper);
5897 qemu_put_be32(f, u.l.lower);
5899 for (i = 0; i < 16; i++) {
5900 qemu_put_be32(f, env->vfp.xregs[i]);
5903 /* TODO: Should use proper FPSCR access functions. */
5904 qemu_put_be32(f, env->vfp.vec_len);
5905 qemu_put_be32(f, env->vfp.vec_stride);
5908 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5909 for (i = 0; i < 16; i++) {
5910 qemu_put_be64(f, env->iwmmxt.regs[i]);
5912 for (i = 0; i < 16; i++) {
5913 qemu_put_be32(f, env->iwmmxt.cregs[i]);
5918 int cpu_load(QEMUFile *f, void *opaque, int version_id)
5920 CPUARMState *env = (CPUARMState *)opaque;
5923 if (version_id != 0)
5926 for (i = 0; i < 16; i++) {
5927 env->regs[i] = qemu_get_be32(f);
5929 cpsr_write(env, qemu_get_be32(f), 0xffffffff);
5930 env->spsr = qemu_get_be32(f);
5931 for (i = 0; i < 6; i++) {
5932 env->banked_spsr[i] = qemu_get_be32(f);
5933 env->banked_r13[i] = qemu_get_be32(f);
5934 env->banked_r14[i] = qemu_get_be32(f);
5936 for (i = 0; i < 5; i++) {
5937 env->usr_regs[i] = qemu_get_be32(f);
5938 env->fiq_regs[i] = qemu_get_be32(f);
5940 env->cp15.c0_cpuid = qemu_get_be32(f);
5941 env->cp15.c0_cachetype = qemu_get_be32(f);
5942 env->cp15.c1_sys = qemu_get_be32(f);
5943 env->cp15.c1_coproc = qemu_get_be32(f);
5944 env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
5945 env->cp15.c2_base = qemu_get_be32(f);
5946 env->cp15.c2_data = qemu_get_be32(f);
5947 env->cp15.c2_insn = qemu_get_be32(f);
5948 env->cp15.c3 = qemu_get_be32(f);
5949 env->cp15.c5_insn = qemu_get_be32(f);
5950 env->cp15.c5_data = qemu_get_be32(f);
5951 for (i = 0; i < 8; i++) {
5952 env->cp15.c6_region[i] = qemu_get_be32(f);
5954 env->cp15.c6_insn = qemu_get_be32(f);
5955 env->cp15.c6_data = qemu_get_be32(f);
5956 env->cp15.c9_insn = qemu_get_be32(f);
5957 env->cp15.c9_data = qemu_get_be32(f);
5958 env->cp15.c13_fcse = qemu_get_be32(f);
5959 env->cp15.c13_context = qemu_get_be32(f);
5960 env->cp15.c15_cpar = qemu_get_be32(f);
5962 env->features = qemu_get_be32(f);
5964 if (arm_feature(env, ARM_FEATURE_VFP)) {
5965 for (i = 0; i < 16; i++) {
5967 u.l.upper = qemu_get_be32(f);
5968 u.l.lower = qemu_get_be32(f);
5969 env->vfp.regs[i] = u.d;
5971 for (i = 0; i < 16; i++) {
5972 env->vfp.xregs[i] = qemu_get_be32(f);
5975 /* TODO: Should use proper FPSCR access functions. */
5976 env->vfp.vec_len = qemu_get_be32(f);
5977 env->vfp.vec_stride = qemu_get_be32(f);
5980 if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
5981 for (i = 0; i < 16; i++) {
5982 env->iwmmxt.regs[i] = qemu_get_be64(f);
5984 for (i = 0; i < 16; i++) {
5985 env->iwmmxt.cregs[i] = qemu_get_be32(f);
5994 #warning No CPU save/restore functions
5998 /***********************************************************/
5999 /* ram save/restore */
6001 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6005 v = qemu_get_byte(f);
6008 if (qemu_get_buffer(f, buf, len) != len)
6012 v = qemu_get_byte(f);
6013 memset(buf, v, len);
6021 static int ram_load_v1(QEMUFile *f, void *opaque)
6025 if (qemu_get_be32(f) != phys_ram_size)
6027 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6028 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6035 #define BDRV_HASH_BLOCK_SIZE 1024
6036 #define IOBUF_SIZE 4096
6037 #define RAM_CBLOCK_MAGIC 0xfabe
6039 typedef struct RamCompressState {
6042 uint8_t buf[IOBUF_SIZE];
6045 static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6048 memset(s, 0, sizeof(*s));
6050 ret = deflateInit2(&s->zstream, 1,
6052 9, Z_DEFAULT_STRATEGY);
6055 s->zstream.avail_out = IOBUF_SIZE;
6056 s->zstream.next_out = s->buf;
6060 static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6062 qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6063 qemu_put_be16(s->f, len);
6064 qemu_put_buffer(s->f, buf, len);
6067 static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6071 s->zstream.avail_in = len;
6072 s->zstream.next_in = (uint8_t *)buf;
6073 while (s->zstream.avail_in > 0) {
6074 ret = deflate(&s->zstream, Z_NO_FLUSH);
6077 if (s->zstream.avail_out == 0) {
6078 ram_put_cblock(s, s->buf, IOBUF_SIZE);
6079 s->zstream.avail_out = IOBUF_SIZE;
6080 s->zstream.next_out = s->buf;
6086 static void ram_compress_close(RamCompressState *s)
6090 /* compress last bytes */
6092 ret = deflate(&s->zstream, Z_FINISH);
6093 if (ret == Z_OK || ret == Z_STREAM_END) {
6094 len = IOBUF_SIZE - s->zstream.avail_out;
6096 ram_put_cblock(s, s->buf, len);
6098 s->zstream.avail_out = IOBUF_SIZE;
6099 s->zstream.next_out = s->buf;
6100 if (ret == Z_STREAM_END)
6107 deflateEnd(&s->zstream);
6110 typedef struct RamDecompressState {
6113 uint8_t buf[IOBUF_SIZE];
6114 } RamDecompressState;
6116 static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6119 memset(s, 0, sizeof(*s));
6121 ret = inflateInit(&s->zstream);
6127 static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6131 s->zstream.avail_out = len;
6132 s->zstream.next_out = buf;
6133 while (s->zstream.avail_out > 0) {
6134 if (s->zstream.avail_in == 0) {
6135 if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6137 clen = qemu_get_be16(s->f);
6138 if (clen > IOBUF_SIZE)
6140 qemu_get_buffer(s->f, s->buf, clen);
6141 s->zstream.avail_in = clen;
6142 s->zstream.next_in = s->buf;
6144 ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6145 if (ret != Z_OK && ret != Z_STREAM_END) {
6152 static void ram_decompress_close(RamDecompressState *s)
6154 inflateEnd(&s->zstream);
6157 static void ram_save(QEMUFile *f, void *opaque)
6160 RamCompressState s1, *s = &s1;
6163 qemu_put_be32(f, phys_ram_size);
6164 if (ram_compress_open(s, f) < 0)
6166 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6168 if (tight_savevm_enabled) {
6172 /* find if the memory block is available on a virtual
6175 for(j = 0; j < MAX_DISKS; j++) {
6177 sector_num = bdrv_hash_find(bs_table[j],
6178 phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6179 if (sector_num >= 0)
6184 goto normal_compress;
6187 cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6188 ram_compress_buf(s, buf, 10);
6194 ram_compress_buf(s, buf, 1);
6195 ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6198 ram_compress_close(s);
6201 static int ram_load(QEMUFile *f, void *opaque, int version_id)
6203 RamDecompressState s1, *s = &s1;
6207 if (version_id == 1)
6208 return ram_load_v1(f, opaque);
6209 if (version_id != 2)
6211 if (qemu_get_be32(f) != phys_ram_size)
6213 if (ram_decompress_open(s, f) < 0)
6215 for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6216 if (ram_decompress_buf(s, buf, 1) < 0) {
6217 fprintf(stderr, "Error while reading ram block header\n");
6221 if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6222 fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6231 ram_decompress_buf(s, buf + 1, 9);
6233 sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6234 if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6235 fprintf(stderr, "Invalid block device index %d\n", bs_index);
6238 if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6239 BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6240 fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6241 bs_index, sector_num);
6248 printf("Error block header\n");
6252 ram_decompress_close(s);
6256 /***********************************************************/
6257 /* bottom halves (can be seen as timers which expire ASAP) */
6266 static QEMUBH *first_bh = NULL;
6268 QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6271 bh = qemu_mallocz(sizeof(QEMUBH));
6275 bh->opaque = opaque;
6279 int qemu_bh_poll(void)
6298 void qemu_bh_schedule(QEMUBH *bh)
6300 CPUState *env = cpu_single_env;
6304 bh->next = first_bh;
6307 /* stop the currently executing CPU to execute the BH ASAP */
6309 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6313 void qemu_bh_cancel(QEMUBH *bh)
6316 if (bh->scheduled) {
6319 pbh = &(*pbh)->next;
6325 void qemu_bh_delete(QEMUBH *bh)
6331 /***********************************************************/
6332 /* machine registration */
6334 QEMUMachine *first_machine = NULL;
6336 int qemu_register_machine(QEMUMachine *m)
6339 pm = &first_machine;
6347 QEMUMachine *find_machine(const char *name)
6351 for(m = first_machine; m != NULL; m = m->next) {
6352 if (!strcmp(m->name, name))
6358 /***********************************************************/
6359 /* main execution loop */
6361 void gui_update(void *opaque)
6363 DisplayState *ds = opaque;
6364 ds->dpy_refresh(ds);
6365 qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6368 struct vm_change_state_entry {
6369 VMChangeStateHandler *cb;
6371 LIST_ENTRY (vm_change_state_entry) entries;
6374 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6376 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6379 VMChangeStateEntry *e;
6381 e = qemu_mallocz(sizeof (*e));
6387 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6391 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6393 LIST_REMOVE (e, entries);
6397 static void vm_state_notify(int running)
6399 VMChangeStateEntry *e;
6401 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6402 e->cb(e->opaque, running);
6406 /* XXX: support several handlers */
6407 static VMStopHandler *vm_stop_cb;
6408 static void *vm_stop_opaque;
6410 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6413 vm_stop_opaque = opaque;
6417 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6431 void vm_stop(int reason)
6434 cpu_disable_ticks();
6438 vm_stop_cb(vm_stop_opaque, reason);
6445 /* reset/shutdown handler */
6447 typedef struct QEMUResetEntry {
6448 QEMUResetHandler *func;
6450 struct QEMUResetEntry *next;
6453 static QEMUResetEntry *first_reset_entry;
6454 static int reset_requested;
6455 static int shutdown_requested;
6456 static int powerdown_requested;
6458 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6460 QEMUResetEntry **pre, *re;
6462 pre = &first_reset_entry;
6463 while (*pre != NULL)
6464 pre = &(*pre)->next;
6465 re = qemu_mallocz(sizeof(QEMUResetEntry));
6467 re->opaque = opaque;
6472 static void qemu_system_reset(void)
6476 /* reset all devices */
6477 for(re = first_reset_entry; re != NULL; re = re->next) {
6478 re->func(re->opaque);
6482 void qemu_system_reset_request(void)
6485 shutdown_requested = 1;
6487 reset_requested = 1;
6490 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6493 void qemu_system_shutdown_request(void)
6495 shutdown_requested = 1;
6497 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6500 void qemu_system_powerdown_request(void)
6502 powerdown_requested = 1;
6504 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6507 void main_loop_wait(int timeout)
6509 IOHandlerRecord *ioh;
6510 fd_set rfds, wfds, xfds;
6519 /* XXX: need to suppress polling by better using win32 events */
6521 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6522 ret |= pe->func(pe->opaque);
6527 WaitObjects *w = &wait_objects;
6529 ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6530 if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6531 if (w->func[ret - WAIT_OBJECT_0])
6532 w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6534 /* Check for additional signaled events */
6535 for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6537 /* Check if event is signaled */
6538 ret2 = WaitForSingleObject(w->events[i], 0);
6539 if(ret2 == WAIT_OBJECT_0) {
6541 w->func[i](w->opaque[i]);
6542 } else if (ret2 == WAIT_TIMEOUT) {
6544 err = GetLastError();
6545 fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6548 } else if (ret == WAIT_TIMEOUT) {
6550 err = GetLastError();
6551 fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6555 /* poll any events */
6556 /* XXX: separate device handlers from system ones */
6561 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6565 (!ioh->fd_read_poll ||
6566 ioh->fd_read_poll(ioh->opaque) != 0)) {
6567 FD_SET(ioh->fd, &rfds);
6571 if (ioh->fd_write) {
6572 FD_SET(ioh->fd, &wfds);
6582 tv.tv_usec = timeout * 1000;
6584 #if defined(CONFIG_SLIRP)
6586 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6589 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6591 IOHandlerRecord **pioh;
6593 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6596 if (FD_ISSET(ioh->fd, &rfds)) {
6597 ioh->fd_read(ioh->opaque);
6599 if (FD_ISSET(ioh->fd, &wfds)) {
6600 ioh->fd_write(ioh->opaque);
6604 /* remove deleted IO handlers */
6605 pioh = &first_io_handler;
6615 #if defined(CONFIG_SLIRP)
6622 slirp_select_poll(&rfds, &wfds, &xfds);
6628 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6629 qemu_get_clock(vm_clock));
6630 /* run dma transfers, if any */
6634 /* real time timers */
6635 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6636 qemu_get_clock(rt_clock));
6638 /* Check bottom-halves last in case any of the earlier events triggered
6644 static CPUState *cur_cpu;
6649 #ifdef CONFIG_PROFILER
6654 cur_cpu = first_cpu;
6661 env = env->next_cpu;
6664 #ifdef CONFIG_PROFILER
6665 ti = profile_getclock();
6667 ret = cpu_exec(env);
6668 #ifdef CONFIG_PROFILER
6669 qemu_time += profile_getclock() - ti;
6671 if (ret == EXCP_HLT) {
6672 /* Give the next CPU a chance to run. */
6676 if (ret != EXCP_HALTED)
6678 /* all CPUs are halted ? */
6684 if (shutdown_requested) {
6685 ret = EXCP_INTERRUPT;
6688 if (reset_requested) {
6689 reset_requested = 0;
6690 qemu_system_reset();
6691 ret = EXCP_INTERRUPT;
6693 if (powerdown_requested) {
6694 powerdown_requested = 0;
6695 qemu_system_powerdown();
6696 ret = EXCP_INTERRUPT;
6698 if (ret == EXCP_DEBUG) {
6699 vm_stop(EXCP_DEBUG);
6701 /* If all cpus are halted then wait until the next IRQ */
6702 /* XXX: use timeout computed from timers */
6703 if (ret == EXCP_HALTED)
6710 #ifdef CONFIG_PROFILER
6711 ti = profile_getclock();
6713 main_loop_wait(timeout);
6714 #ifdef CONFIG_PROFILER
6715 dev_time += profile_getclock() - ti;
6718 cpu_disable_ticks();
6722 static void help(int exitcode)
6724 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6725 "usage: %s [options] [disk_image]\n"
6727 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6729 "Standard options:\n"
6730 "-M machine select emulated machine (-M ? for list)\n"
6731 "-cpu cpu select CPU (-cpu ? for list)\n"
6732 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
6733 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
6734 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
6735 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6736 "-mtdblock file use 'file' as on-board Flash memory image\n"
6737 "-sd file use 'file' as SecureDigital card image\n"
6738 "-pflash file use 'file' as a parallel flash image\n"
6739 "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6740 "-snapshot write to temporary files instead of disk image files\n"
6742 "-no-frame open SDL window without a frame and window decorations\n"
6743 "-alt-grab use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
6744 "-no-quit disable SDL window close capability\n"
6747 "-no-fd-bootchk disable boot signature checking for floppy disks\n"
6749 "-m megs set virtual RAM size to megs MB [default=%d]\n"
6750 "-smp n set the number of CPUs to 'n' [default=1]\n"
6751 "-nographic disable graphical output and redirect serial I/Os to console\n"
6752 "-portrait rotate graphical output 90 deg left (only PXA LCD)\n"
6754 "-k language use keyboard layout (for example \"fr\" for French)\n"
6757 "-audio-help print list of audio drivers and their options\n"
6758 "-soundhw c1,... enable audio support\n"
6759 " and only specified sound cards (comma separated list)\n"
6760 " use -soundhw ? to get the list of supported cards\n"
6761 " use -soundhw all to enable all of them\n"
6763 "-localtime set the real time clock to local time [default=utc]\n"
6764 "-full-screen start in full screen\n"
6766 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
6768 "-usb enable the USB driver (will be the default soon)\n"
6769 "-usbdevice name add the host or guest USB device 'name'\n"
6770 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
6771 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
6773 "-name string set the name of the guest\n"
6775 "Network options:\n"
6776 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6777 " create a new Network Interface Card and connect it to VLAN 'n'\n"
6779 "-net user[,vlan=n][,hostname=host]\n"
6780 " connect the user mode network stack to VLAN 'n' and send\n"
6781 " hostname 'host' to DHCP clients\n"
6784 "-net tap[,vlan=n],ifname=name\n"
6785 " connect the host TAP network interface to VLAN 'n'\n"
6787 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6788 " connect the host TAP network interface to VLAN 'n' and use\n"
6789 " the network script 'file' (default=%s);\n"
6790 " use 'script=no' to disable script execution;\n"
6791 " use 'fd=h' to connect to an already opened TAP interface\n"
6793 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6794 " connect the vlan 'n' to another VLAN using a socket connection\n"
6795 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6796 " connect the vlan 'n' to multicast maddr and port\n"
6797 "-net none use it alone to have zero network devices; if no -net option\n"
6798 " is provided, the default is '-net nic -net user'\n"
6801 "-tftp dir allow tftp access to files in dir [-net user]\n"
6802 "-bootp file advertise file in BOOTP replies\n"
6804 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
6806 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6807 " redirect TCP or UDP connections from host to guest [-net user]\n"
6810 "Linux boot specific:\n"
6811 "-kernel bzImage use 'bzImage' as kernel image\n"
6812 "-append cmdline use 'cmdline' as kernel command line\n"
6813 "-initrd file use 'file' as initial ram disk\n"
6815 "Debug/Expert options:\n"
6816 "-monitor dev redirect the monitor to char device 'dev'\n"
6817 "-serial dev redirect the serial port to char device 'dev'\n"
6818 "-parallel dev redirect the parallel port to char device 'dev'\n"
6819 "-pidfile file Write PID to 'file'\n"
6820 "-S freeze CPU at startup (use 'c' to start execution)\n"
6821 "-s wait gdb connection to port\n"
6822 "-p port set gdb connection port [default=%s]\n"
6823 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
6824 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
6825 " translation (t=none or lba) (usually qemu can guess them)\n"
6826 "-L path set the directory for the BIOS, VGA BIOS and keymaps\n"
6828 "-kernel-kqemu enable KQEMU full virtualization (default is user mode only)\n"
6829 "-no-kqemu disable KQEMU kernel module usage\n"
6831 #ifdef USE_CODE_COPY
6832 "-no-code-copy disable code copy acceleration\n"
6835 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
6836 " (default is CL-GD5446 PCI VGA)\n"
6837 "-no-acpi disable ACPI\n"
6839 "-no-reboot exit instead of rebooting\n"
6840 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
6841 "-vnc display start a VNC server on display\n"
6843 "-daemonize daemonize QEMU after initializing\n"
6845 "-option-rom rom load a file, rom, into the option ROM space\n"
6847 "-prom-env variable=value set OpenBIOS nvram variables\n"
6850 "During emulation, the following keys are useful:\n"
6851 "ctrl-alt-f toggle full screen\n"
6852 "ctrl-alt-n switch to virtual console 'n'\n"
6853 "ctrl-alt toggle mouse and keyboard grab\n"
6855 "When using -nographic, press 'ctrl-a h' to get some help.\n"
6860 DEFAULT_NETWORK_SCRIPT,
6862 DEFAULT_GDBSTUB_PORT,
6867 #define HAS_ARG 0x0001
6881 QEMU_OPTION_mtdblock,
6885 QEMU_OPTION_snapshot,
6887 QEMU_OPTION_no_fd_bootchk,
6890 QEMU_OPTION_nographic,
6891 QEMU_OPTION_portrait,
6893 QEMU_OPTION_audio_help,
6894 QEMU_OPTION_soundhw,
6913 QEMU_OPTION_no_code_copy,
6915 QEMU_OPTION_localtime,
6916 QEMU_OPTION_cirrusvga,
6919 QEMU_OPTION_std_vga,
6921 QEMU_OPTION_monitor,
6923 QEMU_OPTION_parallel,
6925 QEMU_OPTION_full_screen,
6926 QEMU_OPTION_no_frame,
6927 QEMU_OPTION_alt_grab,
6928 QEMU_OPTION_no_quit,
6929 QEMU_OPTION_pidfile,
6930 QEMU_OPTION_no_kqemu,
6931 QEMU_OPTION_kernel_kqemu,
6932 QEMU_OPTION_win2k_hack,
6934 QEMU_OPTION_usbdevice,
6937 QEMU_OPTION_no_acpi,
6938 QEMU_OPTION_no_reboot,
6939 QEMU_OPTION_show_cursor,
6940 QEMU_OPTION_daemonize,
6941 QEMU_OPTION_option_rom,
6942 QEMU_OPTION_semihosting,
6944 QEMU_OPTION_prom_env,
6945 QEMU_OPTION_old_param,
6948 typedef struct QEMUOption {
6954 const QEMUOption qemu_options[] = {
6955 { "h", 0, QEMU_OPTION_h },
6956 { "help", 0, QEMU_OPTION_h },
6958 { "M", HAS_ARG, QEMU_OPTION_M },
6959 { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6960 { "fda", HAS_ARG, QEMU_OPTION_fda },
6961 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6962 { "hda", HAS_ARG, QEMU_OPTION_hda },
6963 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6964 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6965 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6966 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6967 { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
6968 { "sd", HAS_ARG, QEMU_OPTION_sd },
6969 { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6970 { "boot", HAS_ARG, QEMU_OPTION_boot },
6971 { "snapshot", 0, QEMU_OPTION_snapshot },
6973 { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6975 { "m", HAS_ARG, QEMU_OPTION_m },
6976 { "nographic", 0, QEMU_OPTION_nographic },
6977 { "portrait", 0, QEMU_OPTION_portrait },
6978 { "k", HAS_ARG, QEMU_OPTION_k },
6980 { "audio-help", 0, QEMU_OPTION_audio_help },
6981 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6984 { "net", HAS_ARG, QEMU_OPTION_net},
6986 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6987 { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6989 { "smb", HAS_ARG, QEMU_OPTION_smb },
6991 { "redir", HAS_ARG, QEMU_OPTION_redir },
6994 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6995 { "append", HAS_ARG, QEMU_OPTION_append },
6996 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6998 { "S", 0, QEMU_OPTION_S },
6999 { "s", 0, QEMU_OPTION_s },
7000 { "p", HAS_ARG, QEMU_OPTION_p },
7001 { "d", HAS_ARG, QEMU_OPTION_d },
7002 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7003 { "L", HAS_ARG, QEMU_OPTION_L },
7004 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7006 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7007 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7009 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
7010 { "g", 1, QEMU_OPTION_g },
7012 { "localtime", 0, QEMU_OPTION_localtime },
7013 { "std-vga", 0, QEMU_OPTION_std_vga },
7014 { "echr", HAS_ARG, QEMU_OPTION_echr },
7015 { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7016 { "serial", HAS_ARG, QEMU_OPTION_serial },
7017 { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7018 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7019 { "full-screen", 0, QEMU_OPTION_full_screen },
7021 { "no-frame", 0, QEMU_OPTION_no_frame },
7022 { "alt-grab", 0, QEMU_OPTION_alt_grab },
7023 { "no-quit", 0, QEMU_OPTION_no_quit },
7025 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7026 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7027 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7028 { "smp", HAS_ARG, QEMU_OPTION_smp },
7029 { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7031 /* temporary options */
7032 { "usb", 0, QEMU_OPTION_usb },
7033 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7034 { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7035 { "no-acpi", 0, QEMU_OPTION_no_acpi },
7036 { "no-reboot", 0, QEMU_OPTION_no_reboot },
7037 { "show-cursor", 0, QEMU_OPTION_show_cursor },
7038 { "daemonize", 0, QEMU_OPTION_daemonize },
7039 { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7040 #if defined(TARGET_ARM) || defined(TARGET_M68K)
7041 { "semihosting", 0, QEMU_OPTION_semihosting },
7043 { "name", HAS_ARG, QEMU_OPTION_name },
7044 #if defined(TARGET_SPARC)
7045 { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7047 #if defined(TARGET_ARM)
7048 { "old-param", 0, QEMU_OPTION_old_param },
7053 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
7055 /* this stack is only used during signal handling */
7056 #define SIGNAL_STACK_SIZE 32768
7058 static uint8_t *signal_stack;
7062 /* password input */
7064 int qemu_key_check(BlockDriverState *bs, const char *name)
7069 if (!bdrv_is_encrypted(bs))
7072 term_printf("%s is encrypted.\n", name);
7073 for(i = 0; i < 3; i++) {
7074 monitor_readline("Password: ", 1, password, sizeof(password));
7075 if (bdrv_set_key(bs, password) == 0)
7077 term_printf("invalid password\n");
7082 static BlockDriverState *get_bdrv(int index)
7084 BlockDriverState *bs;
7087 bs = bs_table[index];
7088 } else if (index < 6) {
7089 bs = fd_table[index - 4];
7096 static void read_passwords(void)
7098 BlockDriverState *bs;
7101 for(i = 0; i < 6; i++) {
7104 qemu_key_check(bs, bdrv_get_device_name(bs));
7108 /* XXX: currently we cannot use simultaneously different CPUs */
7109 void register_machines(void)
7111 #if defined(TARGET_I386)
7112 qemu_register_machine(&pc_machine);
7113 qemu_register_machine(&isapc_machine);
7114 #elif defined(TARGET_PPC)
7115 qemu_register_machine(&heathrow_machine);
7116 qemu_register_machine(&core99_machine);
7117 qemu_register_machine(&prep_machine);
7118 qemu_register_machine(&ref405ep_machine);
7119 qemu_register_machine(&taihu_machine);
7120 #elif defined(TARGET_MIPS)
7121 qemu_register_machine(&mips_machine);
7122 qemu_register_machine(&mips_malta_machine);
7123 qemu_register_machine(&mips_pica61_machine);
7124 #elif defined(TARGET_SPARC)
7125 #ifdef TARGET_SPARC64
7126 qemu_register_machine(&sun4u_machine);
7128 qemu_register_machine(&ss5_machine);
7129 qemu_register_machine(&ss10_machine);
7131 #elif defined(TARGET_ARM)
7132 qemu_register_machine(&integratorcp_machine);
7133 qemu_register_machine(&versatilepb_machine);
7134 qemu_register_machine(&versatileab_machine);
7135 qemu_register_machine(&realview_machine);
7136 qemu_register_machine(&akitapda_machine);
7137 qemu_register_machine(&spitzpda_machine);
7138 qemu_register_machine(&borzoipda_machine);
7139 qemu_register_machine(&terrierpda_machine);
7140 qemu_register_machine(&palmte_machine);
7141 #elif defined(TARGET_SH4)
7142 qemu_register_machine(&shix_machine);
7143 #elif defined(TARGET_ALPHA)
7145 #elif defined(TARGET_M68K)
7146 qemu_register_machine(&mcf5208evb_machine);
7147 qemu_register_machine(&an5206_machine);
7149 #error unsupported CPU
7154 struct soundhw soundhw[] = {
7155 #ifdef HAS_AUDIO_CHOICE
7162 { .init_isa = pcspk_audio_init }
7167 "Creative Sound Blaster 16",
7170 { .init_isa = SB16_init }
7177 "Yamaha YMF262 (OPL3)",
7179 "Yamaha YM3812 (OPL2)",
7183 { .init_isa = Adlib_init }
7190 "Gravis Ultrasound GF1",
7193 { .init_isa = GUS_init }
7199 "ENSONIQ AudioPCI ES1370",
7202 { .init_pci = es1370_init }
7206 { NULL, NULL, 0, 0, { NULL } }
7209 static void select_soundhw (const char *optarg)
7213 if (*optarg == '?') {
7216 printf ("Valid sound card names (comma separated):\n");
7217 for (c = soundhw; c->name; ++c) {
7218 printf ("%-11s %s\n", c->name, c->descr);
7220 printf ("\n-soundhw all will enable all of the above\n");
7221 exit (*optarg != '?');
7229 if (!strcmp (optarg, "all")) {
7230 for (c = soundhw; c->name; ++c) {
7238 e = strchr (p, ',');
7239 l = !e ? strlen (p) : (size_t) (e - p);
7241 for (c = soundhw; c->name; ++c) {
7242 if (!strncmp (c->name, p, l)) {
7251 "Unknown sound card name (too big to show)\n");
7254 fprintf (stderr, "Unknown sound card name `%.*s'\n",
7259 p += l + (e != NULL);
7263 goto show_valid_cards;
7269 static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7271 exit(STATUS_CONTROL_C_EXIT);
7276 #define MAX_NET_CLIENTS 32
7278 int main(int argc, char **argv)
7280 #ifdef CONFIG_GDBSTUB
7282 const char *gdbstub_port;
7284 int i, cdrom_index, pflash_index;
7285 int snapshot, linux_boot;
7286 const char *initrd_filename;
7287 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7288 const char *pflash_filename[MAX_PFLASH];
7289 const char *sd_filename;
7290 const char *mtd_filename;
7291 const char *kernel_filename, *kernel_cmdline;
7292 DisplayState *ds = &display_state;
7293 int cyls, heads, secs, translation;
7294 char net_clients[MAX_NET_CLIENTS][256];
7297 const char *r, *optarg;
7298 CharDriverState *monitor_hd;
7299 char monitor_device[128];
7300 char serial_devices[MAX_SERIAL_PORTS][128];
7301 int serial_device_index;
7302 char parallel_devices[MAX_PARALLEL_PORTS][128];
7303 int parallel_device_index;
7304 const char *loadvm = NULL;
7305 QEMUMachine *machine;
7306 const char *cpu_model;
7307 char usb_devices[MAX_USB_CMDLINE][128];
7308 int usb_devices_index;
7310 const char *pid_file = NULL;
7313 LIST_INIT (&vm_change_state_head);
7316 struct sigaction act;
7317 sigfillset(&act.sa_mask);
7319 act.sa_handler = SIG_IGN;
7320 sigaction(SIGPIPE, &act, NULL);
7323 SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7324 /* Note: cpu_interrupt() is currently not SMP safe, so we force
7325 QEMU to run on a single CPU */
7330 h = GetCurrentProcess();
7331 if (GetProcessAffinityMask(h, &mask, &smask)) {
7332 for(i = 0; i < 32; i++) {
7333 if (mask & (1 << i))
7338 SetProcessAffinityMask(h, mask);
7344 register_machines();
7345 machine = first_machine;
7347 initrd_filename = NULL;
7348 for(i = 0; i < MAX_FD; i++)
7349 fd_filename[i] = NULL;
7350 for(i = 0; i < MAX_DISKS; i++)
7351 hd_filename[i] = NULL;
7352 for(i = 0; i < MAX_PFLASH; i++)
7353 pflash_filename[i] = NULL;
7356 mtd_filename = NULL;
7357 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7358 vga_ram_size = VGA_RAM_SIZE;
7359 #ifdef CONFIG_GDBSTUB
7361 gdbstub_port = DEFAULT_GDBSTUB_PORT;
7365 kernel_filename = NULL;
7366 kernel_cmdline = "";
7372 cyls = heads = secs = 0;
7373 translation = BIOS_ATA_TRANSLATION_AUTO;
7374 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7376 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7377 for(i = 1; i < MAX_SERIAL_PORTS; i++)
7378 serial_devices[i][0] = '\0';
7379 serial_device_index = 0;
7381 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7382 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7383 parallel_devices[i][0] = '\0';
7384 parallel_device_index = 0;
7386 usb_devices_index = 0;
7391 /* default mac address of the first network interface */
7399 hd_filename[0] = argv[optind++];
7401 const QEMUOption *popt;
7404 /* Treat --foo the same as -foo. */
7407 popt = qemu_options;
7410 fprintf(stderr, "%s: invalid option -- '%s'\n",
7414 if (!strcmp(popt->name, r + 1))
7418 if (popt->flags & HAS_ARG) {
7419 if (optind >= argc) {
7420 fprintf(stderr, "%s: option '%s' requires an argument\n",
7424 optarg = argv[optind++];
7429 switch(popt->index) {
7431 machine = find_machine(optarg);
7434 printf("Supported machines are:\n");
7435 for(m = first_machine; m != NULL; m = m->next) {
7436 printf("%-10s %s%s\n",
7438 m == first_machine ? " (default)" : "");
7440 exit(*optarg != '?');
7443 case QEMU_OPTION_cpu:
7444 /* hw initialization will check this */
7445 if (*optarg == '?') {
7446 #if defined(TARGET_PPC)
7447 ppc_cpu_list(stdout, &fprintf);
7448 #elif defined(TARGET_ARM)
7450 #elif defined(TARGET_MIPS)
7451 mips_cpu_list(stdout, &fprintf);
7452 #elif defined(TARGET_SPARC)
7453 sparc_cpu_list(stdout, &fprintf);
7460 case QEMU_OPTION_initrd:
7461 initrd_filename = optarg;
7463 case QEMU_OPTION_hda:
7464 case QEMU_OPTION_hdb:
7465 case QEMU_OPTION_hdc:
7466 case QEMU_OPTION_hdd:
7469 hd_index = popt->index - QEMU_OPTION_hda;
7470 hd_filename[hd_index] = optarg;
7471 if (hd_index == cdrom_index)
7475 case QEMU_OPTION_mtdblock:
7476 mtd_filename = optarg;
7478 case QEMU_OPTION_sd:
7479 sd_filename = optarg;
7481 case QEMU_OPTION_pflash:
7482 if (pflash_index >= MAX_PFLASH) {
7483 fprintf(stderr, "qemu: too many parallel flash images\n");
7486 pflash_filename[pflash_index++] = optarg;
7488 case QEMU_OPTION_snapshot:
7491 case QEMU_OPTION_hdachs:
7495 cyls = strtol(p, (char **)&p, 0);
7496 if (cyls < 1 || cyls > 16383)
7501 heads = strtol(p, (char **)&p, 0);
7502 if (heads < 1 || heads > 16)
7507 secs = strtol(p, (char **)&p, 0);
7508 if (secs < 1 || secs > 63)
7512 if (!strcmp(p, "none"))
7513 translation = BIOS_ATA_TRANSLATION_NONE;
7514 else if (!strcmp(p, "lba"))
7515 translation = BIOS_ATA_TRANSLATION_LBA;
7516 else if (!strcmp(p, "auto"))
7517 translation = BIOS_ATA_TRANSLATION_AUTO;
7520 } else if (*p != '\0') {
7522 fprintf(stderr, "qemu: invalid physical CHS format\n");
7527 case QEMU_OPTION_nographic:
7528 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7529 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7530 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7533 case QEMU_OPTION_portrait:
7536 case QEMU_OPTION_kernel:
7537 kernel_filename = optarg;
7539 case QEMU_OPTION_append:
7540 kernel_cmdline = optarg;
7542 case QEMU_OPTION_cdrom:
7543 if (cdrom_index >= 0) {
7544 hd_filename[cdrom_index] = optarg;
7547 case QEMU_OPTION_boot:
7548 boot_device = optarg[0];
7549 if (boot_device != 'a' &&
7550 #if defined(TARGET_SPARC) || defined(TARGET_I386)
7552 boot_device != 'n' &&
7554 boot_device != 'c' && boot_device != 'd') {
7555 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7559 case QEMU_OPTION_fda:
7560 fd_filename[0] = optarg;
7562 case QEMU_OPTION_fdb:
7563 fd_filename[1] = optarg;
7566 case QEMU_OPTION_no_fd_bootchk:
7570 case QEMU_OPTION_no_code_copy:
7571 code_copy_enabled = 0;
7573 case QEMU_OPTION_net:
7574 if (nb_net_clients >= MAX_NET_CLIENTS) {
7575 fprintf(stderr, "qemu: too many network clients\n");
7578 pstrcpy(net_clients[nb_net_clients],
7579 sizeof(net_clients[0]),
7584 case QEMU_OPTION_tftp:
7585 tftp_prefix = optarg;
7587 case QEMU_OPTION_bootp:
7588 bootp_filename = optarg;
7591 case QEMU_OPTION_smb:
7592 net_slirp_smb(optarg);
7595 case QEMU_OPTION_redir:
7596 net_slirp_redir(optarg);
7600 case QEMU_OPTION_audio_help:
7604 case QEMU_OPTION_soundhw:
7605 select_soundhw (optarg);
7612 ram_size = atoi(optarg) * 1024 * 1024;
7615 if (ram_size > PHYS_RAM_MAX_SIZE) {
7616 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7617 PHYS_RAM_MAX_SIZE / (1024 * 1024));
7626 mask = cpu_str_to_log_mask(optarg);
7628 printf("Log items (comma separated):\n");
7629 for(item = cpu_log_items; item->mask != 0; item++) {
7630 printf("%-10s %s\n", item->name, item->help);
7637 #ifdef CONFIG_GDBSTUB
7642 gdbstub_port = optarg;
7652 keyboard_layout = optarg;
7654 case QEMU_OPTION_localtime:
7657 case QEMU_OPTION_cirrusvga:
7658 cirrus_vga_enabled = 1;
7661 case QEMU_OPTION_vmsvga:
7662 cirrus_vga_enabled = 0;
7665 case QEMU_OPTION_std_vga:
7666 cirrus_vga_enabled = 0;
7674 w = strtol(p, (char **)&p, 10);
7677 fprintf(stderr, "qemu: invalid resolution or depth\n");
7683 h = strtol(p, (char **)&p, 10);
7688 depth = strtol(p, (char **)&p, 10);
7689 if (depth != 8 && depth != 15 && depth != 16 &&
7690 depth != 24 && depth != 32)
7692 } else if (*p == '\0') {
7693 depth = graphic_depth;
7700 graphic_depth = depth;
7703 case QEMU_OPTION_echr:
7706 term_escape_char = strtol(optarg, &r, 0);
7708 printf("Bad argument to echr\n");
7711 case QEMU_OPTION_monitor:
7712 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7714 case QEMU_OPTION_serial:
7715 if (serial_device_index >= MAX_SERIAL_PORTS) {
7716 fprintf(stderr, "qemu: too many serial ports\n");
7719 pstrcpy(serial_devices[serial_device_index],
7720 sizeof(serial_devices[0]), optarg);
7721 serial_device_index++;
7723 case QEMU_OPTION_parallel:
7724 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7725 fprintf(stderr, "qemu: too many parallel ports\n");
7728 pstrcpy(parallel_devices[parallel_device_index],
7729 sizeof(parallel_devices[0]), optarg);
7730 parallel_device_index++;
7732 case QEMU_OPTION_loadvm:
7735 case QEMU_OPTION_full_screen:
7739 case QEMU_OPTION_no_frame:
7742 case QEMU_OPTION_alt_grab:
7745 case QEMU_OPTION_no_quit:
7749 case QEMU_OPTION_pidfile:
7753 case QEMU_OPTION_win2k_hack:
7754 win2k_install_hack = 1;
7758 case QEMU_OPTION_no_kqemu:
7761 case QEMU_OPTION_kernel_kqemu:
7765 case QEMU_OPTION_usb:
7768 case QEMU_OPTION_usbdevice:
7770 if (usb_devices_index >= MAX_USB_CMDLINE) {
7771 fprintf(stderr, "Too many USB devices\n");
7774 pstrcpy(usb_devices[usb_devices_index],
7775 sizeof(usb_devices[usb_devices_index]),
7777 usb_devices_index++;
7779 case QEMU_OPTION_smp:
7780 smp_cpus = atoi(optarg);
7781 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7782 fprintf(stderr, "Invalid number of CPUs\n");
7786 case QEMU_OPTION_vnc:
7787 vnc_display = optarg;
7789 case QEMU_OPTION_no_acpi:
7792 case QEMU_OPTION_no_reboot:
7795 case QEMU_OPTION_show_cursor:
7798 case QEMU_OPTION_daemonize:
7801 case QEMU_OPTION_option_rom:
7802 if (nb_option_roms >= MAX_OPTION_ROMS) {
7803 fprintf(stderr, "Too many option ROMs\n");
7806 option_rom[nb_option_roms] = optarg;
7809 case QEMU_OPTION_semihosting:
7810 semihosting_enabled = 1;
7812 case QEMU_OPTION_name:
7816 case QEMU_OPTION_prom_env:
7817 if (nb_prom_envs >= MAX_PROM_ENVS) {
7818 fprintf(stderr, "Too many prom variables\n");
7821 prom_envs[nb_prom_envs] = optarg;
7826 case QEMU_OPTION_old_param:
7834 if (daemonize && !nographic && vnc_display == NULL) {
7835 fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7842 if (pipe(fds) == -1)
7853 len = read(fds[0], &status, 1);
7854 if (len == -1 && (errno == EINTR))
7859 else if (status == 1) {
7860 fprintf(stderr, "Could not acquire pidfile\n");
7878 signal(SIGTSTP, SIG_IGN);
7879 signal(SIGTTOU, SIG_IGN);
7880 signal(SIGTTIN, SIG_IGN);
7884 if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7887 write(fds[1], &status, 1);
7889 fprintf(stderr, "Could not acquire pid file\n");
7897 linux_boot = (kernel_filename != NULL);
7900 boot_device != 'n' &&
7901 hd_filename[0] == '\0' &&
7902 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7903 fd_filename[0] == '\0')
7906 /* boot to floppy or the default cd if no hard disk defined yet */
7907 if (hd_filename[0] == '\0' && boot_device == 'c') {
7908 if (fd_filename[0] != '\0')
7914 setvbuf(stdout, NULL, _IOLBF, 0);
7924 /* init network clients */
7925 if (nb_net_clients == 0) {
7926 /* if no clients, we use a default config */
7927 pstrcpy(net_clients[0], sizeof(net_clients[0]),
7929 pstrcpy(net_clients[1], sizeof(net_clients[0]),
7934 for(i = 0;i < nb_net_clients; i++) {
7935 if (net_client_init(net_clients[i]) < 0)
7938 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
7939 if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
7941 if (vlan->nb_guest_devs == 0) {
7942 fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
7945 if (vlan->nb_host_devs == 0)
7947 "Warning: vlan %d is not connected to host network\n",
7952 if (boot_device == 'n') {
7953 for (i = 0; i < nb_nics; i++) {
7954 const char *model = nd_table[i].model;
7958 snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7959 if (get_image_size(buf) > 0) {
7960 option_rom[nb_option_roms] = strdup(buf);
7966 fprintf(stderr, "No valid PXE rom found for network device\n");
7969 boot_device = 'c'; /* to prevent confusion by the BIOS */
7973 /* init the memory */
7974 phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7976 phys_ram_base = qemu_vmalloc(phys_ram_size);
7977 if (!phys_ram_base) {
7978 fprintf(stderr, "Could not allocate physical memory\n");
7982 /* we always create the cdrom drive, even if no disk is there */
7984 if (cdrom_index >= 0) {
7985 bs_table[cdrom_index] = bdrv_new("cdrom");
7986 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7989 /* open the virtual block devices */
7990 for(i = 0; i < MAX_DISKS; i++) {
7991 if (hd_filename[i]) {
7994 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7995 bs_table[i] = bdrv_new(buf);
7997 if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7998 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8002 if (i == 0 && cyls != 0) {
8003 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8004 bdrv_set_translation_hint(bs_table[i], translation);
8009 /* we always create at least one floppy disk */
8010 fd_table[0] = bdrv_new("fda");
8011 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8013 for(i = 0; i < MAX_FD; i++) {
8014 if (fd_filename[i]) {
8017 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8018 fd_table[i] = bdrv_new(buf);
8019 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8021 if (fd_filename[i][0] != '\0') {
8022 if (bdrv_open(fd_table[i], fd_filename[i],
8023 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8024 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8032 /* Open the virtual parallel flash block devices */
8033 for(i = 0; i < MAX_PFLASH; i++) {
8034 if (pflash_filename[i]) {
8035 if (!pflash_table[i]) {
8037 snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8038 pflash_table[i] = bdrv_new(buf);
8040 if (bdrv_open(pflash_table[i], pflash_filename[i],
8041 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8042 fprintf(stderr, "qemu: could not open flash image '%s'\n",
8043 pflash_filename[i]);
8049 sd_bdrv = bdrv_new ("sd");
8050 /* FIXME: This isn't really a floppy, but it's a reasonable
8052 bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8054 if (bdrv_open(sd_bdrv, sd_filename,
8055 snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8056 fprintf(stderr, "qemu: could not open SD card image %s\n",
8059 qemu_key_check(sd_bdrv, sd_filename);
8063 mtd_bdrv = bdrv_new ("mtd");
8064 if (bdrv_open(mtd_bdrv, mtd_filename,
8065 snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8066 qemu_key_check(mtd_bdrv, mtd_filename)) {
8067 fprintf(stderr, "qemu: could not open Flash image %s\n",
8069 bdrv_delete(mtd_bdrv);
8074 register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8075 register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8080 memset(&display_state, 0, sizeof(display_state));
8082 /* nearly nothing to do */
8083 dumb_display_init(ds);
8084 } else if (vnc_display != NULL) {
8085 vnc_display_init(ds, vnc_display);
8087 #if defined(CONFIG_SDL)
8088 sdl_display_init(ds, full_screen, no_frame);
8089 #elif defined(CONFIG_COCOA)
8090 cocoa_display_init(ds, full_screen);
8094 /* Maintain compatibility with multiple stdio monitors */
8095 if (!strcmp(monitor_device,"stdio")) {
8096 for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8097 if (!strcmp(serial_devices[i],"mon:stdio")) {
8098 monitor_device[0] = '\0';
8100 } else if (!strcmp(serial_devices[i],"stdio")) {
8101 monitor_device[0] = '\0';
8102 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8107 if (monitor_device[0] != '\0') {
8108 monitor_hd = qemu_chr_open(monitor_device);
8110 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8113 monitor_init(monitor_hd, !nographic);
8116 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8117 const char *devname = serial_devices[i];
8118 if (devname[0] != '\0' && strcmp(devname, "none")) {
8119 serial_hds[i] = qemu_chr_open(devname);
8120 if (!serial_hds[i]) {
8121 fprintf(stderr, "qemu: could not open serial device '%s'\n",
8125 if (strstart(devname, "vc", 0))
8126 qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8130 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8131 const char *devname = parallel_devices[i];
8132 if (devname[0] != '\0' && strcmp(devname, "none")) {
8133 parallel_hds[i] = qemu_chr_open(devname);
8134 if (!parallel_hds[i]) {
8135 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8139 if (strstart(devname, "vc", 0))
8140 qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8144 machine->init(ram_size, vga_ram_size, boot_device,
8145 ds, fd_filename, snapshot,
8146 kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8148 /* init USB devices */
8150 for(i = 0; i < usb_devices_index; i++) {
8151 if (usb_device_add(usb_devices[i]) < 0) {
8152 fprintf(stderr, "Warning: could not add USB device %s\n",
8158 if (display_state.dpy_refresh) {
8159 display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8160 qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8163 #ifdef CONFIG_GDBSTUB
8165 /* XXX: use standard host:port notation and modify options
8167 if (gdbserver_start(gdbstub_port) < 0) {
8168 fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8179 /* XXX: simplify init */
8192 len = write(fds[1], &status, 1);
8193 if (len == -1 && (errno == EINTR))
8199 TFR(fd = open("/dev/null", O_RDWR));