Fix typo in BSD FP rounding mode names.
[qemu/mini2440.git] / vl.c
blobef5bee56c2003e8d473df410b2534bafe744b5f2
1 /*
2 * QEMU System Emulator
3 *
4 * Copyright (c) 2003-2005 Fabrice Bellard
5 *
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
22 * THE SOFTWARE.
24 #include "vl.h"
26 #include <unistd.h>
27 #include <fcntl.h>
28 #include <signal.h>
29 #include <time.h>
30 #include <errno.h>
31 #include <sys/time.h>
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #include <netinet/in.h>
42 #include <dirent.h>
43 #include <netdb.h>
44 #ifdef _BSD
45 #include <sys/stat.h>
46 #ifndef __APPLE__
47 #include <libutil.h>
48 #endif
49 #else
50 #ifndef __sun__
51 #include <linux/if.h>
52 #include <linux/if_tun.h>
53 #include <pty.h>
54 #include <malloc.h>
55 #include <linux/rtc.h>
56 #include <linux/ppdev.h>
57 #endif
58 #endif
59 #endif
61 #if defined(CONFIG_SLIRP)
62 #include "libslirp.h"
63 #endif
65 #ifdef _WIN32
66 #include <malloc.h>
67 #include <sys/timeb.h>
68 #include <windows.h>
69 #include <winsock2.h>
70 #include <ws2tcpip.h>
71 #define getopt_long_only getopt_long
72 #define memalign(align, size) malloc(size)
73 #endif
75 #ifdef CONFIG_SDL
76 #ifdef __APPLE__
77 #include <SDL/SDL.h>
78 #endif
79 #endif /* CONFIG_SDL */
81 #ifdef CONFIG_COCOA
82 #undef main
83 #define main qemu_main
84 #endif /* CONFIG_COCOA */
86 #include "disas.h"
88 #include "exec-all.h"
90 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
92 //#define DEBUG_UNUSED_IOPORT
93 //#define DEBUG_IOPORT
95 #if !defined(CONFIG_SOFTMMU)
96 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
97 #else
98 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
99 #endif
101 #ifdef TARGET_PPC
102 #define DEFAULT_RAM_SIZE 144
103 #else
104 #define DEFAULT_RAM_SIZE 128
105 #endif
106 /* in ms */
107 #define GUI_REFRESH_INTERVAL 30
109 /* XXX: use a two level table to limit memory usage */
110 #define MAX_IOPORTS 65536
112 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
113 char phys_ram_file[1024];
114 void *ioport_opaque[MAX_IOPORTS];
115 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
116 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
117 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
118 int vga_ram_size;
119 int bios_size;
120 static DisplayState display_state;
121 int nographic;
122 const char* keyboard_layout = NULL;
123 int64_t ticks_per_sec;
124 int boot_device = 'c';
125 int ram_size;
126 int pit_min_timer_count = 0;
127 int nb_nics;
128 NICInfo nd_table[MAX_NICS];
129 QEMUTimer *gui_timer;
130 int vm_running;
131 int rtc_utc = 1;
132 int cirrus_vga_enabled = 1;
133 #ifdef TARGET_SPARC
134 int graphic_width = 1024;
135 int graphic_height = 768;
136 #else
137 int graphic_width = 800;
138 int graphic_height = 600;
139 #endif
140 int graphic_depth = 15;
141 int full_screen = 0;
142 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
143 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
144 #ifdef TARGET_I386
145 int win2k_install_hack = 0;
146 #endif
147 int usb_enabled = 0;
148 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
149 USBDevice *vm_usb_hub;
150 static VLANState *first_vlan;
151 int smp_cpus = 1;
152 #if defined(TARGET_SPARC)
153 #define MAX_CPUS 16
154 #elif defined(TARGET_I386)
155 #define MAX_CPUS 255
156 #else
157 #define MAX_CPUS 1
158 #endif
160 /***********************************************************/
161 /* x86 ISA bus support */
163 target_phys_addr_t isa_mem_base = 0;
164 PicState2 *isa_pic;
166 uint32_t default_ioport_readb(void *opaque, uint32_t address)
168 #ifdef DEBUG_UNUSED_IOPORT
169 fprintf(stderr, "inb: port=0x%04x\n", address);
170 #endif
171 return 0xff;
174 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
176 #ifdef DEBUG_UNUSED_IOPORT
177 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
178 #endif
181 /* default is to make two byte accesses */
182 uint32_t default_ioport_readw(void *opaque, uint32_t address)
184 uint32_t data;
185 data = ioport_read_table[0][address](ioport_opaque[address], address);
186 address = (address + 1) & (MAX_IOPORTS - 1);
187 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
188 return data;
191 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
193 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
194 address = (address + 1) & (MAX_IOPORTS - 1);
195 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
198 uint32_t default_ioport_readl(void *opaque, uint32_t address)
200 #ifdef DEBUG_UNUSED_IOPORT
201 fprintf(stderr, "inl: port=0x%04x\n", address);
202 #endif
203 return 0xffffffff;
206 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
208 #ifdef DEBUG_UNUSED_IOPORT
209 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
210 #endif
213 void init_ioports(void)
215 int i;
217 for(i = 0; i < MAX_IOPORTS; i++) {
218 ioport_read_table[0][i] = default_ioport_readb;
219 ioport_write_table[0][i] = default_ioport_writeb;
220 ioport_read_table[1][i] = default_ioport_readw;
221 ioport_write_table[1][i] = default_ioport_writew;
222 ioport_read_table[2][i] = default_ioport_readl;
223 ioport_write_table[2][i] = default_ioport_writel;
227 /* size is the word size in byte */
228 int register_ioport_read(int start, int length, int size,
229 IOPortReadFunc *func, void *opaque)
231 int i, bsize;
233 if (size == 1) {
234 bsize = 0;
235 } else if (size == 2) {
236 bsize = 1;
237 } else if (size == 4) {
238 bsize = 2;
239 } else {
240 hw_error("register_ioport_read: invalid size");
241 return -1;
243 for(i = start; i < start + length; i += size) {
244 ioport_read_table[bsize][i] = func;
245 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
246 hw_error("register_ioport_read: invalid opaque");
247 ioport_opaque[i] = opaque;
249 return 0;
252 /* size is the word size in byte */
253 int register_ioport_write(int start, int length, int size,
254 IOPortWriteFunc *func, void *opaque)
256 int i, bsize;
258 if (size == 1) {
259 bsize = 0;
260 } else if (size == 2) {
261 bsize = 1;
262 } else if (size == 4) {
263 bsize = 2;
264 } else {
265 hw_error("register_ioport_write: invalid size");
266 return -1;
268 for(i = start; i < start + length; i += size) {
269 ioport_write_table[bsize][i] = func;
270 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
271 hw_error("register_ioport_read: invalid opaque");
272 ioport_opaque[i] = opaque;
274 return 0;
277 void isa_unassign_ioport(int start, int length)
279 int i;
281 for(i = start; i < start + length; i++) {
282 ioport_read_table[0][i] = default_ioport_readb;
283 ioport_read_table[1][i] = default_ioport_readw;
284 ioport_read_table[2][i] = default_ioport_readl;
286 ioport_write_table[0][i] = default_ioport_writeb;
287 ioport_write_table[1][i] = default_ioport_writew;
288 ioport_write_table[2][i] = default_ioport_writel;
292 /***********************************************************/
294 void pstrcpy(char *buf, int buf_size, const char *str)
296 int c;
297 char *q = buf;
299 if (buf_size <= 0)
300 return;
302 for(;;) {
303 c = *str++;
304 if (c == 0 || q >= buf + buf_size - 1)
305 break;
306 *q++ = c;
308 *q = '\0';
311 /* strcat and truncate. */
312 char *pstrcat(char *buf, int buf_size, const char *s)
314 int len;
315 len = strlen(buf);
316 if (len < buf_size)
317 pstrcpy(buf + len, buf_size - len, s);
318 return buf;
321 int strstart(const char *str, const char *val, const char **ptr)
323 const char *p, *q;
324 p = str;
325 q = val;
326 while (*q != '\0') {
327 if (*p != *q)
328 return 0;
329 p++;
330 q++;
332 if (ptr)
333 *ptr = p;
334 return 1;
337 void cpu_outb(CPUState *env, int addr, int val)
339 #ifdef DEBUG_IOPORT
340 if (loglevel & CPU_LOG_IOPORT)
341 fprintf(logfile, "outb: %04x %02x\n", addr, val);
342 #endif
343 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
344 #ifdef USE_KQEMU
345 if (env)
346 env->last_io_time = cpu_get_time_fast();
347 #endif
350 void cpu_outw(CPUState *env, int addr, int val)
352 #ifdef DEBUG_IOPORT
353 if (loglevel & CPU_LOG_IOPORT)
354 fprintf(logfile, "outw: %04x %04x\n", addr, val);
355 #endif
356 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
357 #ifdef USE_KQEMU
358 if (env)
359 env->last_io_time = cpu_get_time_fast();
360 #endif
363 void cpu_outl(CPUState *env, int addr, int val)
365 #ifdef DEBUG_IOPORT
366 if (loglevel & CPU_LOG_IOPORT)
367 fprintf(logfile, "outl: %04x %08x\n", addr, val);
368 #endif
369 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
370 #ifdef USE_KQEMU
371 if (env)
372 env->last_io_time = cpu_get_time_fast();
373 #endif
376 int cpu_inb(CPUState *env, int addr)
378 int val;
379 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
380 #ifdef DEBUG_IOPORT
381 if (loglevel & CPU_LOG_IOPORT)
382 fprintf(logfile, "inb : %04x %02x\n", addr, val);
383 #endif
384 #ifdef USE_KQEMU
385 if (env)
386 env->last_io_time = cpu_get_time_fast();
387 #endif
388 return val;
391 int cpu_inw(CPUState *env, int addr)
393 int val;
394 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
395 #ifdef DEBUG_IOPORT
396 if (loglevel & CPU_LOG_IOPORT)
397 fprintf(logfile, "inw : %04x %04x\n", addr, val);
398 #endif
399 #ifdef USE_KQEMU
400 if (env)
401 env->last_io_time = cpu_get_time_fast();
402 #endif
403 return val;
406 int cpu_inl(CPUState *env, int addr)
408 int val;
409 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
410 #ifdef DEBUG_IOPORT
411 if (loglevel & CPU_LOG_IOPORT)
412 fprintf(logfile, "inl : %04x %08x\n", addr, val);
413 #endif
414 #ifdef USE_KQEMU
415 if (env)
416 env->last_io_time = cpu_get_time_fast();
417 #endif
418 return val;
421 /***********************************************************/
422 void hw_error(const char *fmt, ...)
424 va_list ap;
425 CPUState *env;
427 va_start(ap, fmt);
428 fprintf(stderr, "qemu: hardware error: ");
429 vfprintf(stderr, fmt, ap);
430 fprintf(stderr, "\n");
431 for(env = first_cpu; env != NULL; env = env->next_cpu) {
432 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
433 #ifdef TARGET_I386
434 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
435 #else
436 cpu_dump_state(env, stderr, fprintf, 0);
437 #endif
439 va_end(ap);
440 abort();
443 /***********************************************************/
444 /* keyboard/mouse */
446 static QEMUPutKBDEvent *qemu_put_kbd_event;
447 static void *qemu_put_kbd_event_opaque;
448 static QEMUPutMouseEvent *qemu_put_mouse_event;
449 static void *qemu_put_mouse_event_opaque;
450 static int qemu_put_mouse_event_absolute;
452 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
454 qemu_put_kbd_event_opaque = opaque;
455 qemu_put_kbd_event = func;
458 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
460 qemu_put_mouse_event_opaque = opaque;
461 qemu_put_mouse_event = func;
462 qemu_put_mouse_event_absolute = absolute;
465 void kbd_put_keycode(int keycode)
467 if (qemu_put_kbd_event) {
468 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
472 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
474 if (qemu_put_mouse_event) {
475 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
476 dx, dy, dz, buttons_state);
480 int kbd_mouse_is_absolute(void)
482 return qemu_put_mouse_event_absolute;
485 /***********************************************************/
486 /* timers */
488 #if defined(__powerpc__)
490 static inline uint32_t get_tbl(void)
492 uint32_t tbl;
493 asm volatile("mftb %0" : "=r" (tbl));
494 return tbl;
497 static inline uint32_t get_tbu(void)
499 uint32_t tbl;
500 asm volatile("mftbu %0" : "=r" (tbl));
501 return tbl;
504 int64_t cpu_get_real_ticks(void)
506 uint32_t l, h, h1;
507 /* NOTE: we test if wrapping has occurred */
508 do {
509 h = get_tbu();
510 l = get_tbl();
511 h1 = get_tbu();
512 } while (h != h1);
513 return ((int64_t)h << 32) | l;
516 #elif defined(__i386__)
518 int64_t cpu_get_real_ticks(void)
520 int64_t val;
521 asm volatile ("rdtsc" : "=A" (val));
522 return val;
525 #elif defined(__x86_64__)
527 int64_t cpu_get_real_ticks(void)
529 uint32_t low,high;
530 int64_t val;
531 asm volatile("rdtsc" : "=a" (low), "=d" (high));
532 val = high;
533 val <<= 32;
534 val |= low;
535 return val;
538 #elif defined(__ia64)
540 int64_t cpu_get_real_ticks(void)
542 int64_t val;
543 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
544 return val;
547 #elif defined(__s390__)
549 int64_t cpu_get_real_ticks(void)
551 int64_t val;
552 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
553 return val;
556 #else
557 #error unsupported CPU
558 #endif
560 static int64_t cpu_ticks_offset;
561 static int cpu_ticks_enabled;
563 static inline int64_t cpu_get_ticks(void)
565 if (!cpu_ticks_enabled) {
566 return cpu_ticks_offset;
567 } else {
568 return cpu_get_real_ticks() + cpu_ticks_offset;
572 /* enable cpu_get_ticks() */
573 void cpu_enable_ticks(void)
575 if (!cpu_ticks_enabled) {
576 cpu_ticks_offset -= cpu_get_real_ticks();
577 cpu_ticks_enabled = 1;
581 /* disable cpu_get_ticks() : the clock is stopped. You must not call
582 cpu_get_ticks() after that. */
583 void cpu_disable_ticks(void)
585 if (cpu_ticks_enabled) {
586 cpu_ticks_offset = cpu_get_ticks();
587 cpu_ticks_enabled = 0;
591 static int64_t get_clock(void)
593 #ifdef _WIN32
594 struct _timeb tb;
595 _ftime(&tb);
596 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
597 #else
598 struct timeval tv;
599 gettimeofday(&tv, NULL);
600 return tv.tv_sec * 1000000LL + tv.tv_usec;
601 #endif
604 void cpu_calibrate_ticks(void)
606 int64_t usec, ticks;
608 usec = get_clock();
609 ticks = cpu_get_real_ticks();
610 #ifdef _WIN32
611 Sleep(50);
612 #else
613 usleep(50 * 1000);
614 #endif
615 usec = get_clock() - usec;
616 ticks = cpu_get_real_ticks() - ticks;
617 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
620 /* compute with 96 bit intermediate result: (a*b)/c */
621 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
623 union {
624 uint64_t ll;
625 struct {
626 #ifdef WORDS_BIGENDIAN
627 uint32_t high, low;
628 #else
629 uint32_t low, high;
630 #endif
631 } l;
632 } u, res;
633 uint64_t rl, rh;
635 u.ll = a;
636 rl = (uint64_t)u.l.low * (uint64_t)b;
637 rh = (uint64_t)u.l.high * (uint64_t)b;
638 rh += (rl >> 32);
639 res.l.high = rh / c;
640 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
641 return res.ll;
644 #define QEMU_TIMER_REALTIME 0
645 #define QEMU_TIMER_VIRTUAL 1
647 struct QEMUClock {
648 int type;
649 /* XXX: add frequency */
652 struct QEMUTimer {
653 QEMUClock *clock;
654 int64_t expire_time;
655 QEMUTimerCB *cb;
656 void *opaque;
657 struct QEMUTimer *next;
660 QEMUClock *rt_clock;
661 QEMUClock *vm_clock;
663 static QEMUTimer *active_timers[2];
664 #ifdef _WIN32
665 static MMRESULT timerID;
666 #else
667 /* frequency of the times() clock tick */
668 static int timer_freq;
669 #endif
671 QEMUClock *qemu_new_clock(int type)
673 QEMUClock *clock;
674 clock = qemu_mallocz(sizeof(QEMUClock));
675 if (!clock)
676 return NULL;
677 clock->type = type;
678 return clock;
681 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
683 QEMUTimer *ts;
685 ts = qemu_mallocz(sizeof(QEMUTimer));
686 ts->clock = clock;
687 ts->cb = cb;
688 ts->opaque = opaque;
689 return ts;
692 void qemu_free_timer(QEMUTimer *ts)
694 qemu_free(ts);
697 /* stop a timer, but do not dealloc it */
698 void qemu_del_timer(QEMUTimer *ts)
700 QEMUTimer **pt, *t;
702 /* NOTE: this code must be signal safe because
703 qemu_timer_expired() can be called from a signal. */
704 pt = &active_timers[ts->clock->type];
705 for(;;) {
706 t = *pt;
707 if (!t)
708 break;
709 if (t == ts) {
710 *pt = t->next;
711 break;
713 pt = &t->next;
717 /* modify the current timer so that it will be fired when current_time
718 >= expire_time. The corresponding callback will be called. */
719 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
721 QEMUTimer **pt, *t;
723 qemu_del_timer(ts);
725 /* add the timer in the sorted list */
726 /* NOTE: this code must be signal safe because
727 qemu_timer_expired() can be called from a signal. */
728 pt = &active_timers[ts->clock->type];
729 for(;;) {
730 t = *pt;
731 if (!t)
732 break;
733 if (t->expire_time > expire_time)
734 break;
735 pt = &t->next;
737 ts->expire_time = expire_time;
738 ts->next = *pt;
739 *pt = ts;
742 int qemu_timer_pending(QEMUTimer *ts)
744 QEMUTimer *t;
745 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
746 if (t == ts)
747 return 1;
749 return 0;
752 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
754 if (!timer_head)
755 return 0;
756 return (timer_head->expire_time <= current_time);
759 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
761 QEMUTimer *ts;
763 for(;;) {
764 ts = *ptimer_head;
765 if (!ts || ts->expire_time > current_time)
766 break;
767 /* remove timer from the list before calling the callback */
768 *ptimer_head = ts->next;
769 ts->next = NULL;
771 /* run the callback (the timer list can be modified) */
772 ts->cb(ts->opaque);
776 int64_t qemu_get_clock(QEMUClock *clock)
778 switch(clock->type) {
779 case QEMU_TIMER_REALTIME:
780 #ifdef _WIN32
781 return GetTickCount();
782 #else
784 struct tms tp;
786 /* Note that using gettimeofday() is not a good solution
787 for timers because its value change when the date is
788 modified. */
789 if (timer_freq == 100) {
790 return times(&tp) * 10;
791 } else {
792 return ((int64_t)times(&tp) * 1000) / timer_freq;
795 #endif
796 default:
797 case QEMU_TIMER_VIRTUAL:
798 return cpu_get_ticks();
802 /* save a timer */
803 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
805 uint64_t expire_time;
807 if (qemu_timer_pending(ts)) {
808 expire_time = ts->expire_time;
809 } else {
810 expire_time = -1;
812 qemu_put_be64(f, expire_time);
815 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
817 uint64_t expire_time;
819 expire_time = qemu_get_be64(f);
820 if (expire_time != -1) {
821 qemu_mod_timer(ts, expire_time);
822 } else {
823 qemu_del_timer(ts);
827 static void timer_save(QEMUFile *f, void *opaque)
829 if (cpu_ticks_enabled) {
830 hw_error("cannot save state if virtual timers are running");
832 qemu_put_be64s(f, &cpu_ticks_offset);
833 qemu_put_be64s(f, &ticks_per_sec);
836 static int timer_load(QEMUFile *f, void *opaque, int version_id)
838 if (version_id != 1)
839 return -EINVAL;
840 if (cpu_ticks_enabled) {
841 return -EINVAL;
843 qemu_get_be64s(f, &cpu_ticks_offset);
844 qemu_get_be64s(f, &ticks_per_sec);
845 return 0;
848 #ifdef _WIN32
849 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
850 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
851 #else
852 static void host_alarm_handler(int host_signum)
853 #endif
855 #if 0
856 #define DISP_FREQ 1000
858 static int64_t delta_min = INT64_MAX;
859 static int64_t delta_max, delta_cum, last_clock, delta, ti;
860 static int count;
861 ti = qemu_get_clock(vm_clock);
862 if (last_clock != 0) {
863 delta = ti - last_clock;
864 if (delta < delta_min)
865 delta_min = delta;
866 if (delta > delta_max)
867 delta_max = delta;
868 delta_cum += delta;
869 if (++count == DISP_FREQ) {
870 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
871 muldiv64(delta_min, 1000000, ticks_per_sec),
872 muldiv64(delta_max, 1000000, ticks_per_sec),
873 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
874 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
875 count = 0;
876 delta_min = INT64_MAX;
877 delta_max = 0;
878 delta_cum = 0;
881 last_clock = ti;
883 #endif
884 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
885 qemu_get_clock(vm_clock)) ||
886 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
887 qemu_get_clock(rt_clock))) {
888 CPUState *env = cpu_single_env;
889 if (env) {
890 /* stop the currently executing cpu because a timer occured */
891 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
892 #ifdef USE_KQEMU
893 if (env->kqemu_enabled) {
894 kqemu_cpu_interrupt(env);
896 #endif
901 #ifndef _WIN32
903 #if defined(__linux__)
905 #define RTC_FREQ 1024
907 static int rtc_fd;
909 static int start_rtc_timer(void)
911 rtc_fd = open("/dev/rtc", O_RDONLY);
912 if (rtc_fd < 0)
913 return -1;
914 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
915 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
916 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
917 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
918 goto fail;
920 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
921 fail:
922 close(rtc_fd);
923 return -1;
925 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
926 return 0;
929 #else
931 static int start_rtc_timer(void)
933 return -1;
936 #endif /* !defined(__linux__) */
938 #endif /* !defined(_WIN32) */
940 static void init_timers(void)
942 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
943 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
945 #ifdef _WIN32
947 int count=0;
948 timerID = timeSetEvent(1, // interval (ms)
949 0, // resolution
950 host_alarm_handler, // function
951 (DWORD)&count, // user parameter
952 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
953 if( !timerID ) {
954 perror("failed timer alarm");
955 exit(1);
958 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
959 #else
961 struct sigaction act;
962 struct itimerval itv;
964 /* get times() syscall frequency */
965 timer_freq = sysconf(_SC_CLK_TCK);
967 /* timer signal */
968 sigfillset(&act.sa_mask);
969 act.sa_flags = 0;
970 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
971 act.sa_flags |= SA_ONSTACK;
972 #endif
973 act.sa_handler = host_alarm_handler;
974 sigaction(SIGALRM, &act, NULL);
976 itv.it_interval.tv_sec = 0;
977 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
978 itv.it_value.tv_sec = 0;
979 itv.it_value.tv_usec = 10 * 1000;
980 setitimer(ITIMER_REAL, &itv, NULL);
981 /* we probe the tick duration of the kernel to inform the user if
982 the emulated kernel requested a too high timer frequency */
983 getitimer(ITIMER_REAL, &itv);
985 #if defined(__linux__)
986 if (itv.it_interval.tv_usec > 1000) {
987 /* try to use /dev/rtc to have a faster timer */
988 if (start_rtc_timer() < 0)
989 goto use_itimer;
990 /* disable itimer */
991 itv.it_interval.tv_sec = 0;
992 itv.it_interval.tv_usec = 0;
993 itv.it_value.tv_sec = 0;
994 itv.it_value.tv_usec = 0;
995 setitimer(ITIMER_REAL, &itv, NULL);
997 /* use the RTC */
998 sigaction(SIGIO, &act, NULL);
999 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1000 fcntl(rtc_fd, F_SETOWN, getpid());
1001 } else
1002 #endif /* defined(__linux__) */
1004 use_itimer:
1005 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1006 PIT_FREQ) / 1000000;
1009 #endif
1012 void quit_timers(void)
1014 #ifdef _WIN32
1015 timeKillEvent(timerID);
1016 #endif
1019 /***********************************************************/
1020 /* character device */
1022 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1024 return s->chr_write(s, buf, len);
1027 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1029 if (!s->chr_ioctl)
1030 return -ENOTSUP;
1031 return s->chr_ioctl(s, cmd, arg);
1034 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1036 char buf[4096];
1037 va_list ap;
1038 va_start(ap, fmt);
1039 vsnprintf(buf, sizeof(buf), fmt, ap);
1040 qemu_chr_write(s, buf, strlen(buf));
1041 va_end(ap);
1044 void qemu_chr_send_event(CharDriverState *s, int event)
1046 if (s->chr_send_event)
1047 s->chr_send_event(s, event);
1050 void qemu_chr_add_read_handler(CharDriverState *s,
1051 IOCanRWHandler *fd_can_read,
1052 IOReadHandler *fd_read, void *opaque)
1054 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1057 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1059 s->chr_event = chr_event;
1062 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1064 return len;
1067 static void null_chr_add_read_handler(CharDriverState *chr,
1068 IOCanRWHandler *fd_can_read,
1069 IOReadHandler *fd_read, void *opaque)
1073 CharDriverState *qemu_chr_open_null(void)
1075 CharDriverState *chr;
1077 chr = qemu_mallocz(sizeof(CharDriverState));
1078 if (!chr)
1079 return NULL;
1080 chr->chr_write = null_chr_write;
1081 chr->chr_add_read_handler = null_chr_add_read_handler;
1082 return chr;
1085 #ifdef _WIN32
1087 #define socket_error() WSAGetLastError()
1088 #undef EINTR
1089 #define EWOULDBLOCK WSAEWOULDBLOCK
1090 #define EINTR WSAEINTR
1091 #define EINPROGRESS WSAEINPROGRESS
1093 static void socket_cleanup(void)
1095 WSACleanup();
1098 static int socket_init(void)
1100 WSADATA Data;
1101 int ret, err;
1103 ret = WSAStartup(MAKEWORD(2,2), &Data);
1104 if (ret != 0) {
1105 err = WSAGetLastError();
1106 fprintf(stderr, "WSAStartup: %d\n", err);
1107 return -1;
1109 atexit(socket_cleanup);
1110 return 0;
1113 static int send_all(int fd, const uint8_t *buf, int len1)
1115 int ret, len;
1117 len = len1;
1118 while (len > 0) {
1119 ret = send(fd, buf, len, 0);
1120 if (ret < 0) {
1121 int errno;
1122 errno = WSAGetLastError();
1123 if (errno != WSAEWOULDBLOCK) {
1124 return -1;
1126 } else if (ret == 0) {
1127 break;
1128 } else {
1129 buf += ret;
1130 len -= ret;
1133 return len1 - len;
1136 void socket_set_nonblock(int fd)
1138 unsigned long opt = 1;
1139 ioctlsocket(fd, FIONBIO, &opt);
1142 #else
1144 #define socket_error() errno
1145 #define closesocket(s) close(s)
1147 static int unix_write(int fd, const uint8_t *buf, int len1)
1149 int ret, len;
1151 len = len1;
1152 while (len > 0) {
1153 ret = write(fd, buf, len);
1154 if (ret < 0) {
1155 if (errno != EINTR && errno != EAGAIN)
1156 return -1;
1157 } else if (ret == 0) {
1158 break;
1159 } else {
1160 buf += ret;
1161 len -= ret;
1164 return len1 - len;
1167 static inline int send_all(int fd, const uint8_t *buf, int len1)
1169 return unix_write(fd, buf, len1);
1172 void socket_set_nonblock(int fd)
1174 fcntl(fd, F_SETFL, O_NONBLOCK);
1176 #endif /* !_WIN32 */
1178 #ifndef _WIN32
1180 typedef struct {
1181 int fd_in, fd_out;
1182 IOCanRWHandler *fd_can_read;
1183 IOReadHandler *fd_read;
1184 void *fd_opaque;
1185 int max_size;
1186 } FDCharDriver;
1188 #define STDIO_MAX_CLIENTS 2
1190 static int stdio_nb_clients;
1191 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1193 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1195 FDCharDriver *s = chr->opaque;
1196 return unix_write(s->fd_out, buf, len);
1199 static int fd_chr_read_poll(void *opaque)
1201 CharDriverState *chr = opaque;
1202 FDCharDriver *s = chr->opaque;
1204 s->max_size = s->fd_can_read(s->fd_opaque);
1205 return s->max_size;
1208 static void fd_chr_read(void *opaque)
1210 CharDriverState *chr = opaque;
1211 FDCharDriver *s = chr->opaque;
1212 int size, len;
1213 uint8_t buf[1024];
1215 len = sizeof(buf);
1216 if (len > s->max_size)
1217 len = s->max_size;
1218 if (len == 0)
1219 return;
1220 size = read(s->fd_in, buf, len);
1221 if (size > 0) {
1222 s->fd_read(s->fd_opaque, buf, size);
1226 static void fd_chr_add_read_handler(CharDriverState *chr,
1227 IOCanRWHandler *fd_can_read,
1228 IOReadHandler *fd_read, void *opaque)
1230 FDCharDriver *s = chr->opaque;
1232 if (s->fd_in >= 0) {
1233 s->fd_can_read = fd_can_read;
1234 s->fd_read = fd_read;
1235 s->fd_opaque = opaque;
1236 if (nographic && s->fd_in == 0) {
1237 } else {
1238 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1239 fd_chr_read, NULL, chr);
1244 /* open a character device to a unix fd */
1245 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1247 CharDriverState *chr;
1248 FDCharDriver *s;
1250 chr = qemu_mallocz(sizeof(CharDriverState));
1251 if (!chr)
1252 return NULL;
1253 s = qemu_mallocz(sizeof(FDCharDriver));
1254 if (!s) {
1255 free(chr);
1256 return NULL;
1258 s->fd_in = fd_in;
1259 s->fd_out = fd_out;
1260 chr->opaque = s;
1261 chr->chr_write = fd_chr_write;
1262 chr->chr_add_read_handler = fd_chr_add_read_handler;
1263 return chr;
1266 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1268 int fd_out;
1270 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1271 if (fd_out < 0)
1272 return NULL;
1273 return qemu_chr_open_fd(-1, fd_out);
1276 CharDriverState *qemu_chr_open_pipe(const char *filename)
1278 int fd;
1280 fd = open(filename, O_RDWR | O_BINARY);
1281 if (fd < 0)
1282 return NULL;
1283 return qemu_chr_open_fd(fd, fd);
1287 /* for STDIO, we handle the case where several clients use it
1288 (nographic mode) */
1290 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1292 #define TERM_FIFO_MAX_SIZE 1
1294 static int term_got_escape, client_index;
1295 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1296 int term_fifo_size;
1298 void term_print_help(void)
1300 printf("\n"
1301 "C-a h print this help\n"
1302 "C-a x exit emulator\n"
1303 "C-a s save disk data back to file (if -snapshot)\n"
1304 "C-a b send break (magic sysrq)\n"
1305 "C-a c switch between console and monitor\n"
1306 "C-a C-a send C-a\n"
1310 /* called when a char is received */
1311 static void stdio_received_byte(int ch)
1313 if (term_got_escape) {
1314 term_got_escape = 0;
1315 switch(ch) {
1316 case 'h':
1317 term_print_help();
1318 break;
1319 case 'x':
1320 exit(0);
1321 break;
1322 case 's':
1324 int i;
1325 for (i = 0; i < MAX_DISKS; i++) {
1326 if (bs_table[i])
1327 bdrv_commit(bs_table[i]);
1330 break;
1331 case 'b':
1332 if (client_index < stdio_nb_clients) {
1333 CharDriverState *chr;
1334 FDCharDriver *s;
1336 chr = stdio_clients[client_index];
1337 s = chr->opaque;
1338 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1340 break;
1341 case 'c':
1342 client_index++;
1343 if (client_index >= stdio_nb_clients)
1344 client_index = 0;
1345 if (client_index == 0) {
1346 /* send a new line in the monitor to get the prompt */
1347 ch = '\r';
1348 goto send_char;
1350 break;
1351 case TERM_ESCAPE:
1352 goto send_char;
1354 } else if (ch == TERM_ESCAPE) {
1355 term_got_escape = 1;
1356 } else {
1357 send_char:
1358 if (client_index < stdio_nb_clients) {
1359 uint8_t buf[1];
1360 CharDriverState *chr;
1361 FDCharDriver *s;
1363 chr = stdio_clients[client_index];
1364 s = chr->opaque;
1365 if (s->fd_can_read(s->fd_opaque) > 0) {
1366 buf[0] = ch;
1367 s->fd_read(s->fd_opaque, buf, 1);
1368 } else if (term_fifo_size == 0) {
1369 term_fifo[term_fifo_size++] = ch;
1375 static int stdio_read_poll(void *opaque)
1377 CharDriverState *chr;
1378 FDCharDriver *s;
1380 if (client_index < stdio_nb_clients) {
1381 chr = stdio_clients[client_index];
1382 s = chr->opaque;
1383 /* try to flush the queue if needed */
1384 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1385 s->fd_read(s->fd_opaque, term_fifo, 1);
1386 term_fifo_size = 0;
1388 /* see if we can absorb more chars */
1389 if (term_fifo_size == 0)
1390 return 1;
1391 else
1392 return 0;
1393 } else {
1394 return 1;
1398 static void stdio_read(void *opaque)
1400 int size;
1401 uint8_t buf[1];
1403 size = read(0, buf, 1);
1404 if (size > 0)
1405 stdio_received_byte(buf[0]);
1408 /* init terminal so that we can grab keys */
1409 static struct termios oldtty;
1410 static int old_fd0_flags;
1412 static void term_exit(void)
1414 tcsetattr (0, TCSANOW, &oldtty);
1415 fcntl(0, F_SETFL, old_fd0_flags);
1418 static void term_init(void)
1420 struct termios tty;
1422 tcgetattr (0, &tty);
1423 oldtty = tty;
1424 old_fd0_flags = fcntl(0, F_GETFL);
1426 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1427 |INLCR|IGNCR|ICRNL|IXON);
1428 tty.c_oflag |= OPOST;
1429 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1430 /* if graphical mode, we allow Ctrl-C handling */
1431 if (nographic)
1432 tty.c_lflag &= ~ISIG;
1433 tty.c_cflag &= ~(CSIZE|PARENB);
1434 tty.c_cflag |= CS8;
1435 tty.c_cc[VMIN] = 1;
1436 tty.c_cc[VTIME] = 0;
1438 tcsetattr (0, TCSANOW, &tty);
1440 atexit(term_exit);
1442 fcntl(0, F_SETFL, O_NONBLOCK);
1445 CharDriverState *qemu_chr_open_stdio(void)
1447 CharDriverState *chr;
1449 if (nographic) {
1450 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1451 return NULL;
1452 chr = qemu_chr_open_fd(0, 1);
1453 if (stdio_nb_clients == 0)
1454 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1455 client_index = stdio_nb_clients;
1456 } else {
1457 if (stdio_nb_clients != 0)
1458 return NULL;
1459 chr = qemu_chr_open_fd(0, 1);
1461 stdio_clients[stdio_nb_clients++] = chr;
1462 if (stdio_nb_clients == 1) {
1463 /* set the terminal in raw mode */
1464 term_init();
1466 return chr;
1469 #if defined(__linux__)
1470 CharDriverState *qemu_chr_open_pty(void)
1472 struct termios tty;
1473 char slave_name[1024];
1474 int master_fd, slave_fd;
1476 /* Not satisfying */
1477 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1478 return NULL;
1481 /* Disabling local echo and line-buffered output */
1482 tcgetattr (master_fd, &tty);
1483 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1484 tty.c_cc[VMIN] = 1;
1485 tty.c_cc[VTIME] = 0;
1486 tcsetattr (master_fd, TCSAFLUSH, &tty);
1488 fprintf(stderr, "char device redirected to %s\n", slave_name);
1489 return qemu_chr_open_fd(master_fd, master_fd);
1492 static void tty_serial_init(int fd, int speed,
1493 int parity, int data_bits, int stop_bits)
1495 struct termios tty;
1496 speed_t spd;
1498 #if 0
1499 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1500 speed, parity, data_bits, stop_bits);
1501 #endif
1502 tcgetattr (fd, &tty);
1504 switch(speed) {
1505 case 50:
1506 spd = B50;
1507 break;
1508 case 75:
1509 spd = B75;
1510 break;
1511 case 300:
1512 spd = B300;
1513 break;
1514 case 600:
1515 spd = B600;
1516 break;
1517 case 1200:
1518 spd = B1200;
1519 break;
1520 case 2400:
1521 spd = B2400;
1522 break;
1523 case 4800:
1524 spd = B4800;
1525 break;
1526 case 9600:
1527 spd = B9600;
1528 break;
1529 case 19200:
1530 spd = B19200;
1531 break;
1532 case 38400:
1533 spd = B38400;
1534 break;
1535 case 57600:
1536 spd = B57600;
1537 break;
1538 default:
1539 case 115200:
1540 spd = B115200;
1541 break;
1544 cfsetispeed(&tty, spd);
1545 cfsetospeed(&tty, spd);
1547 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1548 |INLCR|IGNCR|ICRNL|IXON);
1549 tty.c_oflag |= OPOST;
1550 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1551 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1552 switch(data_bits) {
1553 default:
1554 case 8:
1555 tty.c_cflag |= CS8;
1556 break;
1557 case 7:
1558 tty.c_cflag |= CS7;
1559 break;
1560 case 6:
1561 tty.c_cflag |= CS6;
1562 break;
1563 case 5:
1564 tty.c_cflag |= CS5;
1565 break;
1567 switch(parity) {
1568 default:
1569 case 'N':
1570 break;
1571 case 'E':
1572 tty.c_cflag |= PARENB;
1573 break;
1574 case 'O':
1575 tty.c_cflag |= PARENB | PARODD;
1576 break;
1579 tcsetattr (fd, TCSANOW, &tty);
1582 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1584 FDCharDriver *s = chr->opaque;
1586 switch(cmd) {
1587 case CHR_IOCTL_SERIAL_SET_PARAMS:
1589 QEMUSerialSetParams *ssp = arg;
1590 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1591 ssp->data_bits, ssp->stop_bits);
1593 break;
1594 case CHR_IOCTL_SERIAL_SET_BREAK:
1596 int enable = *(int *)arg;
1597 if (enable)
1598 tcsendbreak(s->fd_in, 1);
1600 break;
1601 default:
1602 return -ENOTSUP;
1604 return 0;
1607 CharDriverState *qemu_chr_open_tty(const char *filename)
1609 CharDriverState *chr;
1610 int fd;
1612 fd = open(filename, O_RDWR | O_NONBLOCK);
1613 if (fd < 0)
1614 return NULL;
1615 fcntl(fd, F_SETFL, O_NONBLOCK);
1616 tty_serial_init(fd, 115200, 'N', 8, 1);
1617 chr = qemu_chr_open_fd(fd, fd);
1618 if (!chr)
1619 return NULL;
1620 chr->chr_ioctl = tty_serial_ioctl;
1621 return chr;
1624 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1626 int fd = (int)chr->opaque;
1627 uint8_t b;
1629 switch(cmd) {
1630 case CHR_IOCTL_PP_READ_DATA:
1631 if (ioctl(fd, PPRDATA, &b) < 0)
1632 return -ENOTSUP;
1633 *(uint8_t *)arg = b;
1634 break;
1635 case CHR_IOCTL_PP_WRITE_DATA:
1636 b = *(uint8_t *)arg;
1637 if (ioctl(fd, PPWDATA, &b) < 0)
1638 return -ENOTSUP;
1639 break;
1640 case CHR_IOCTL_PP_READ_CONTROL:
1641 if (ioctl(fd, PPRCONTROL, &b) < 0)
1642 return -ENOTSUP;
1643 *(uint8_t *)arg = b;
1644 break;
1645 case CHR_IOCTL_PP_WRITE_CONTROL:
1646 b = *(uint8_t *)arg;
1647 if (ioctl(fd, PPWCONTROL, &b) < 0)
1648 return -ENOTSUP;
1649 break;
1650 case CHR_IOCTL_PP_READ_STATUS:
1651 if (ioctl(fd, PPRSTATUS, &b) < 0)
1652 return -ENOTSUP;
1653 *(uint8_t *)arg = b;
1654 break;
1655 default:
1656 return -ENOTSUP;
1658 return 0;
1661 CharDriverState *qemu_chr_open_pp(const char *filename)
1663 CharDriverState *chr;
1664 int fd;
1666 fd = open(filename, O_RDWR);
1667 if (fd < 0)
1668 return NULL;
1670 if (ioctl(fd, PPCLAIM) < 0) {
1671 close(fd);
1672 return NULL;
1675 chr = qemu_mallocz(sizeof(CharDriverState));
1676 if (!chr) {
1677 close(fd);
1678 return NULL;
1680 chr->opaque = (void *)fd;
1681 chr->chr_write = null_chr_write;
1682 chr->chr_add_read_handler = null_chr_add_read_handler;
1683 chr->chr_ioctl = pp_ioctl;
1684 return chr;
1687 #else
1688 CharDriverState *qemu_chr_open_pty(void)
1690 return NULL;
1692 #endif
1694 #endif /* !defined(_WIN32) */
1696 #ifdef _WIN32
1697 typedef struct {
1698 IOCanRWHandler *fd_can_read;
1699 IOReadHandler *fd_read;
1700 void *win_opaque;
1701 int max_size;
1702 HANDLE hcom, hrecv, hsend;
1703 OVERLAPPED orecv, osend;
1704 BOOL fpipe;
1705 DWORD len;
1706 } WinCharState;
1708 #define NSENDBUF 2048
1709 #define NRECVBUF 2048
1710 #define MAXCONNECT 1
1711 #define NTIMEOUT 5000
1713 static int win_chr_poll(void *opaque);
1714 static int win_chr_pipe_poll(void *opaque);
1716 static void win_chr_close2(WinCharState *s)
1718 if (s->hsend) {
1719 CloseHandle(s->hsend);
1720 s->hsend = NULL;
1722 if (s->hrecv) {
1723 CloseHandle(s->hrecv);
1724 s->hrecv = NULL;
1726 if (s->hcom) {
1727 CloseHandle(s->hcom);
1728 s->hcom = NULL;
1730 if (s->fpipe)
1731 qemu_del_polling_cb(win_chr_pipe_poll, s);
1732 else
1733 qemu_del_polling_cb(win_chr_poll, s);
1736 static void win_chr_close(CharDriverState *chr)
1738 WinCharState *s = chr->opaque;
1739 win_chr_close2(s);
1742 static int win_chr_init(WinCharState *s, const char *filename)
1744 COMMCONFIG comcfg;
1745 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1746 COMSTAT comstat;
1747 DWORD size;
1748 DWORD err;
1750 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1751 if (!s->hsend) {
1752 fprintf(stderr, "Failed CreateEvent\n");
1753 goto fail;
1755 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1756 if (!s->hrecv) {
1757 fprintf(stderr, "Failed CreateEvent\n");
1758 goto fail;
1761 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1762 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1763 if (s->hcom == INVALID_HANDLE_VALUE) {
1764 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1765 s->hcom = NULL;
1766 goto fail;
1769 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1770 fprintf(stderr, "Failed SetupComm\n");
1771 goto fail;
1774 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1775 size = sizeof(COMMCONFIG);
1776 GetDefaultCommConfig(filename, &comcfg, &size);
1777 comcfg.dcb.DCBlength = sizeof(DCB);
1778 CommConfigDialog(filename, NULL, &comcfg);
1780 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1781 fprintf(stderr, "Failed SetCommState\n");
1782 goto fail;
1785 if (!SetCommMask(s->hcom, EV_ERR)) {
1786 fprintf(stderr, "Failed SetCommMask\n");
1787 goto fail;
1790 cto.ReadIntervalTimeout = MAXDWORD;
1791 if (!SetCommTimeouts(s->hcom, &cto)) {
1792 fprintf(stderr, "Failed SetCommTimeouts\n");
1793 goto fail;
1796 if (!ClearCommError(s->hcom, &err, &comstat)) {
1797 fprintf(stderr, "Failed ClearCommError\n");
1798 goto fail;
1800 qemu_add_polling_cb(win_chr_poll, s);
1801 return 0;
1803 fail:
1804 win_chr_close2(s);
1805 return -1;
1808 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1810 WinCharState *s = chr->opaque;
1811 DWORD len, ret, size, err;
1813 len = len1;
1814 ZeroMemory(&s->osend, sizeof(s->osend));
1815 s->osend.hEvent = s->hsend;
1816 while (len > 0) {
1817 if (s->hsend)
1818 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1819 else
1820 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1821 if (!ret) {
1822 err = GetLastError();
1823 if (err == ERROR_IO_PENDING) {
1824 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1825 if (ret) {
1826 buf += size;
1827 len -= size;
1828 } else {
1829 break;
1831 } else {
1832 break;
1834 } else {
1835 buf += size;
1836 len -= size;
1839 return len1 - len;
1842 static int win_chr_read_poll(WinCharState *s)
1844 s->max_size = s->fd_can_read(s->win_opaque);
1845 return s->max_size;
1848 static void win_chr_readfile(WinCharState *s)
1850 int ret, err;
1851 uint8_t buf[1024];
1852 DWORD size;
1854 ZeroMemory(&s->orecv, sizeof(s->orecv));
1855 s->orecv.hEvent = s->hrecv;
1856 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1857 if (!ret) {
1858 err = GetLastError();
1859 if (err == ERROR_IO_PENDING) {
1860 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1864 if (size > 0) {
1865 s->fd_read(s->win_opaque, buf, size);
1869 static void win_chr_read(WinCharState *s)
1871 if (s->len > s->max_size)
1872 s->len = s->max_size;
1873 if (s->len == 0)
1874 return;
1876 win_chr_readfile(s);
1879 static int win_chr_poll(void *opaque)
1881 WinCharState *s = opaque;
1882 COMSTAT status;
1883 DWORD comerr;
1885 ClearCommError(s->hcom, &comerr, &status);
1886 if (status.cbInQue > 0) {
1887 s->len = status.cbInQue;
1888 win_chr_read_poll(s);
1889 win_chr_read(s);
1890 return 1;
1892 return 0;
1895 static void win_chr_add_read_handler(CharDriverState *chr,
1896 IOCanRWHandler *fd_can_read,
1897 IOReadHandler *fd_read, void *opaque)
1899 WinCharState *s = chr->opaque;
1901 s->fd_can_read = fd_can_read;
1902 s->fd_read = fd_read;
1903 s->win_opaque = opaque;
1906 CharDriverState *qemu_chr_open_win(const char *filename)
1908 CharDriverState *chr;
1909 WinCharState *s;
1911 chr = qemu_mallocz(sizeof(CharDriverState));
1912 if (!chr)
1913 return NULL;
1914 s = qemu_mallocz(sizeof(WinCharState));
1915 if (!s) {
1916 free(chr);
1917 return NULL;
1919 chr->opaque = s;
1920 chr->chr_write = win_chr_write;
1921 chr->chr_add_read_handler = win_chr_add_read_handler;
1922 chr->chr_close = win_chr_close;
1924 if (win_chr_init(s, filename) < 0) {
1925 free(s);
1926 free(chr);
1927 return NULL;
1929 return chr;
1932 static int win_chr_pipe_poll(void *opaque)
1934 WinCharState *s = opaque;
1935 DWORD size;
1937 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1938 if (size > 0) {
1939 s->len = size;
1940 win_chr_read_poll(s);
1941 win_chr_read(s);
1942 return 1;
1944 return 0;
1947 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1949 OVERLAPPED ov;
1950 int ret;
1951 DWORD size;
1952 char openname[256];
1954 s->fpipe = TRUE;
1956 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1957 if (!s->hsend) {
1958 fprintf(stderr, "Failed CreateEvent\n");
1959 goto fail;
1961 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1962 if (!s->hrecv) {
1963 fprintf(stderr, "Failed CreateEvent\n");
1964 goto fail;
1967 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1968 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1969 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1970 PIPE_WAIT,
1971 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1972 if (s->hcom == INVALID_HANDLE_VALUE) {
1973 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1974 s->hcom = NULL;
1975 goto fail;
1978 ZeroMemory(&ov, sizeof(ov));
1979 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1980 ret = ConnectNamedPipe(s->hcom, &ov);
1981 if (ret) {
1982 fprintf(stderr, "Failed ConnectNamedPipe\n");
1983 goto fail;
1986 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1987 if (!ret) {
1988 fprintf(stderr, "Failed GetOverlappedResult\n");
1989 if (ov.hEvent) {
1990 CloseHandle(ov.hEvent);
1991 ov.hEvent = NULL;
1993 goto fail;
1996 if (ov.hEvent) {
1997 CloseHandle(ov.hEvent);
1998 ov.hEvent = NULL;
2000 qemu_add_polling_cb(win_chr_pipe_poll, s);
2001 return 0;
2003 fail:
2004 win_chr_close2(s);
2005 return -1;
2009 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2011 CharDriverState *chr;
2012 WinCharState *s;
2014 chr = qemu_mallocz(sizeof(CharDriverState));
2015 if (!chr)
2016 return NULL;
2017 s = qemu_mallocz(sizeof(WinCharState));
2018 if (!s) {
2019 free(chr);
2020 return NULL;
2022 chr->opaque = s;
2023 chr->chr_write = win_chr_write;
2024 chr->chr_add_read_handler = win_chr_add_read_handler;
2025 chr->chr_close = win_chr_close;
2027 if (win_chr_pipe_init(s, filename) < 0) {
2028 free(s);
2029 free(chr);
2030 return NULL;
2032 return chr;
2035 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2037 CharDriverState *chr;
2038 WinCharState *s;
2040 chr = qemu_mallocz(sizeof(CharDriverState));
2041 if (!chr)
2042 return NULL;
2043 s = qemu_mallocz(sizeof(WinCharState));
2044 if (!s) {
2045 free(chr);
2046 return NULL;
2048 s->hcom = fd_out;
2049 chr->opaque = s;
2050 chr->chr_write = win_chr_write;
2051 chr->chr_add_read_handler = win_chr_add_read_handler;
2052 return chr;
2055 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2057 HANDLE fd_out;
2059 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2060 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2061 if (fd_out == INVALID_HANDLE_VALUE)
2062 return NULL;
2064 return qemu_chr_open_win_file(fd_out);
2066 #endif
2068 CharDriverState *qemu_chr_open(const char *filename)
2070 const char *p;
2072 if (!strcmp(filename, "vc")) {
2073 return text_console_init(&display_state);
2074 } else if (!strcmp(filename, "null")) {
2075 return qemu_chr_open_null();
2076 } else
2077 #ifndef _WIN32
2078 if (strstart(filename, "file:", &p)) {
2079 return qemu_chr_open_file_out(p);
2080 } else if (strstart(filename, "pipe:", &p)) {
2081 return qemu_chr_open_pipe(p);
2082 } else if (!strcmp(filename, "pty")) {
2083 return qemu_chr_open_pty();
2084 } else if (!strcmp(filename, "stdio")) {
2085 return qemu_chr_open_stdio();
2086 } else
2087 #endif
2088 #if defined(__linux__)
2089 if (strstart(filename, "/dev/parport", NULL)) {
2090 return qemu_chr_open_pp(filename);
2091 } else
2092 if (strstart(filename, "/dev/", NULL)) {
2093 return qemu_chr_open_tty(filename);
2094 } else
2095 #endif
2096 #ifdef _WIN32
2097 if (strstart(filename, "COM", NULL)) {
2098 return qemu_chr_open_win(filename);
2099 } else
2100 if (strstart(filename, "pipe:", &p)) {
2101 return qemu_chr_open_win_pipe(p);
2102 } else
2103 if (strstart(filename, "file:", &p)) {
2104 return qemu_chr_open_win_file_out(p);
2106 #endif
2108 return NULL;
2112 void qemu_chr_close(CharDriverState *chr)
2114 if (chr->chr_close)
2115 chr->chr_close(chr);
2118 /***********************************************************/
2119 /* network device redirectors */
2121 void hex_dump(FILE *f, const uint8_t *buf, int size)
2123 int len, i, j, c;
2125 for(i=0;i<size;i+=16) {
2126 len = size - i;
2127 if (len > 16)
2128 len = 16;
2129 fprintf(f, "%08x ", i);
2130 for(j=0;j<16;j++) {
2131 if (j < len)
2132 fprintf(f, " %02x", buf[i+j]);
2133 else
2134 fprintf(f, " ");
2136 fprintf(f, " ");
2137 for(j=0;j<len;j++) {
2138 c = buf[i+j];
2139 if (c < ' ' || c > '~')
2140 c = '.';
2141 fprintf(f, "%c", c);
2143 fprintf(f, "\n");
2147 static int parse_macaddr(uint8_t *macaddr, const char *p)
2149 int i;
2150 for(i = 0; i < 6; i++) {
2151 macaddr[i] = strtol(p, (char **)&p, 16);
2152 if (i == 5) {
2153 if (*p != '\0')
2154 return -1;
2155 } else {
2156 if (*p != ':')
2157 return -1;
2158 p++;
2161 return 0;
2164 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2166 const char *p, *p1;
2167 int len;
2168 p = *pp;
2169 p1 = strchr(p, sep);
2170 if (!p1)
2171 return -1;
2172 len = p1 - p;
2173 p1++;
2174 if (buf_size > 0) {
2175 if (len > buf_size - 1)
2176 len = buf_size - 1;
2177 memcpy(buf, p, len);
2178 buf[len] = '\0';
2180 *pp = p1;
2181 return 0;
2184 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2186 char buf[512];
2187 struct hostent *he;
2188 const char *p, *r;
2189 int port;
2191 p = str;
2192 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2193 return -1;
2194 saddr->sin_family = AF_INET;
2195 if (buf[0] == '\0') {
2196 saddr->sin_addr.s_addr = 0;
2197 } else {
2198 if (isdigit(buf[0])) {
2199 if (!inet_aton(buf, &saddr->sin_addr))
2200 return -1;
2201 } else {
2202 if ((he = gethostbyname(buf)) == NULL)
2203 return - 1;
2204 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2207 port = strtol(p, (char **)&r, 0);
2208 if (r == p)
2209 return -1;
2210 saddr->sin_port = htons(port);
2211 return 0;
2214 /* find or alloc a new VLAN */
2215 VLANState *qemu_find_vlan(int id)
2217 VLANState **pvlan, *vlan;
2218 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2219 if (vlan->id == id)
2220 return vlan;
2222 vlan = qemu_mallocz(sizeof(VLANState));
2223 if (!vlan)
2224 return NULL;
2225 vlan->id = id;
2226 vlan->next = NULL;
2227 pvlan = &first_vlan;
2228 while (*pvlan != NULL)
2229 pvlan = &(*pvlan)->next;
2230 *pvlan = vlan;
2231 return vlan;
2234 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2235 IOReadHandler *fd_read,
2236 IOCanRWHandler *fd_can_read,
2237 void *opaque)
2239 VLANClientState *vc, **pvc;
2240 vc = qemu_mallocz(sizeof(VLANClientState));
2241 if (!vc)
2242 return NULL;
2243 vc->fd_read = fd_read;
2244 vc->fd_can_read = fd_can_read;
2245 vc->opaque = opaque;
2246 vc->vlan = vlan;
2248 vc->next = NULL;
2249 pvc = &vlan->first_client;
2250 while (*pvc != NULL)
2251 pvc = &(*pvc)->next;
2252 *pvc = vc;
2253 return vc;
2256 int qemu_can_send_packet(VLANClientState *vc1)
2258 VLANState *vlan = vc1->vlan;
2259 VLANClientState *vc;
2261 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2262 if (vc != vc1) {
2263 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2264 return 0;
2267 return 1;
2270 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2272 VLANState *vlan = vc1->vlan;
2273 VLANClientState *vc;
2275 #if 0
2276 printf("vlan %d send:\n", vlan->id);
2277 hex_dump(stdout, buf, size);
2278 #endif
2279 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2280 if (vc != vc1) {
2281 vc->fd_read(vc->opaque, buf, size);
2286 #if defined(CONFIG_SLIRP)
2288 /* slirp network adapter */
2290 static int slirp_inited;
2291 static VLANClientState *slirp_vc;
2293 int slirp_can_output(void)
2295 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2298 void slirp_output(const uint8_t *pkt, int pkt_len)
2300 #if 0
2301 printf("slirp output:\n");
2302 hex_dump(stdout, pkt, pkt_len);
2303 #endif
2304 if (!slirp_vc)
2305 return;
2306 qemu_send_packet(slirp_vc, pkt, pkt_len);
2309 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2311 #if 0
2312 printf("slirp input:\n");
2313 hex_dump(stdout, buf, size);
2314 #endif
2315 slirp_input(buf, size);
2318 static int net_slirp_init(VLANState *vlan)
2320 if (!slirp_inited) {
2321 slirp_inited = 1;
2322 slirp_init();
2324 slirp_vc = qemu_new_vlan_client(vlan,
2325 slirp_receive, NULL, NULL);
2326 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2327 return 0;
2330 static void net_slirp_redir(const char *redir_str)
2332 int is_udp;
2333 char buf[256], *r;
2334 const char *p;
2335 struct in_addr guest_addr;
2336 int host_port, guest_port;
2338 if (!slirp_inited) {
2339 slirp_inited = 1;
2340 slirp_init();
2343 p = redir_str;
2344 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2345 goto fail;
2346 if (!strcmp(buf, "tcp")) {
2347 is_udp = 0;
2348 } else if (!strcmp(buf, "udp")) {
2349 is_udp = 1;
2350 } else {
2351 goto fail;
2354 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2355 goto fail;
2356 host_port = strtol(buf, &r, 0);
2357 if (r == buf)
2358 goto fail;
2360 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2361 goto fail;
2362 if (buf[0] == '\0') {
2363 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2365 if (!inet_aton(buf, &guest_addr))
2366 goto fail;
2368 guest_port = strtol(p, &r, 0);
2369 if (r == p)
2370 goto fail;
2372 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2373 fprintf(stderr, "qemu: could not set up redirection\n");
2374 exit(1);
2376 return;
2377 fail:
2378 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2379 exit(1);
2382 #ifndef _WIN32
2384 char smb_dir[1024];
2386 static void smb_exit(void)
2388 DIR *d;
2389 struct dirent *de;
2390 char filename[1024];
2392 /* erase all the files in the directory */
2393 d = opendir(smb_dir);
2394 for(;;) {
2395 de = readdir(d);
2396 if (!de)
2397 break;
2398 if (strcmp(de->d_name, ".") != 0 &&
2399 strcmp(de->d_name, "..") != 0) {
2400 snprintf(filename, sizeof(filename), "%s/%s",
2401 smb_dir, de->d_name);
2402 unlink(filename);
2405 closedir(d);
2406 rmdir(smb_dir);
2409 /* automatic user mode samba server configuration */
2410 void net_slirp_smb(const char *exported_dir)
2412 char smb_conf[1024];
2413 char smb_cmdline[1024];
2414 FILE *f;
2416 if (!slirp_inited) {
2417 slirp_inited = 1;
2418 slirp_init();
2421 /* XXX: better tmp dir construction */
2422 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2423 if (mkdir(smb_dir, 0700) < 0) {
2424 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2425 exit(1);
2427 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2429 f = fopen(smb_conf, "w");
2430 if (!f) {
2431 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2432 exit(1);
2434 fprintf(f,
2435 "[global]\n"
2436 "private dir=%s\n"
2437 "smb ports=0\n"
2438 "socket address=127.0.0.1\n"
2439 "pid directory=%s\n"
2440 "lock directory=%s\n"
2441 "log file=%s/log.smbd\n"
2442 "smb passwd file=%s/smbpasswd\n"
2443 "security = share\n"
2444 "[qemu]\n"
2445 "path=%s\n"
2446 "read only=no\n"
2447 "guest ok=yes\n",
2448 smb_dir,
2449 smb_dir,
2450 smb_dir,
2451 smb_dir,
2452 smb_dir,
2453 exported_dir
2455 fclose(f);
2456 atexit(smb_exit);
2458 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2459 smb_conf);
2461 slirp_add_exec(0, smb_cmdline, 4, 139);
2464 #endif /* !defined(_WIN32) */
2466 #endif /* CONFIG_SLIRP */
2468 #if !defined(_WIN32)
2470 typedef struct TAPState {
2471 VLANClientState *vc;
2472 int fd;
2473 } TAPState;
2475 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2477 TAPState *s = opaque;
2478 int ret;
2479 for(;;) {
2480 ret = write(s->fd, buf, size);
2481 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2482 } else {
2483 break;
2488 static void tap_send(void *opaque)
2490 TAPState *s = opaque;
2491 uint8_t buf[4096];
2492 int size;
2494 size = read(s->fd, buf, sizeof(buf));
2495 if (size > 0) {
2496 qemu_send_packet(s->vc, buf, size);
2500 /* fd support */
2502 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2504 TAPState *s;
2506 s = qemu_mallocz(sizeof(TAPState));
2507 if (!s)
2508 return NULL;
2509 s->fd = fd;
2510 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2511 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2512 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2513 return s;
2516 #ifdef _BSD
2517 static int tap_open(char *ifname, int ifname_size)
2519 int fd;
2520 char *dev;
2521 struct stat s;
2523 fd = open("/dev/tap", O_RDWR);
2524 if (fd < 0) {
2525 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2526 return -1;
2529 fstat(fd, &s);
2530 dev = devname(s.st_rdev, S_IFCHR);
2531 pstrcpy(ifname, ifname_size, dev);
2533 fcntl(fd, F_SETFL, O_NONBLOCK);
2534 return fd;
2536 #elif defined(__sun__)
2537 static int tap_open(char *ifname, int ifname_size)
2539 fprintf(stderr, "warning: tap_open not yet implemented\n");
2540 return -1;
2542 #else
2543 static int tap_open(char *ifname, int ifname_size)
2545 struct ifreq ifr;
2546 int fd, ret;
2548 fd = open("/dev/net/tun", O_RDWR);
2549 if (fd < 0) {
2550 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2551 return -1;
2553 memset(&ifr, 0, sizeof(ifr));
2554 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2555 if (ifname[0] != '\0')
2556 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2557 else
2558 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2559 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2560 if (ret != 0) {
2561 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2562 close(fd);
2563 return -1;
2565 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2566 fcntl(fd, F_SETFL, O_NONBLOCK);
2567 return fd;
2569 #endif
2571 static int net_tap_init(VLANState *vlan, const char *ifname1,
2572 const char *setup_script)
2574 TAPState *s;
2575 int pid, status, fd;
2576 char *args[3];
2577 char **parg;
2578 char ifname[128];
2580 if (ifname1 != NULL)
2581 pstrcpy(ifname, sizeof(ifname), ifname1);
2582 else
2583 ifname[0] = '\0';
2584 fd = tap_open(ifname, sizeof(ifname));
2585 if (fd < 0)
2586 return -1;
2588 if (!setup_script)
2589 setup_script = "";
2590 if (setup_script[0] != '\0') {
2591 /* try to launch network init script */
2592 pid = fork();
2593 if (pid >= 0) {
2594 if (pid == 0) {
2595 parg = args;
2596 *parg++ = (char *)setup_script;
2597 *parg++ = ifname;
2598 *parg++ = NULL;
2599 execv(setup_script, args);
2600 _exit(1);
2602 while (waitpid(pid, &status, 0) != pid);
2603 if (!WIFEXITED(status) ||
2604 WEXITSTATUS(status) != 0) {
2605 fprintf(stderr, "%s: could not launch network script\n",
2606 setup_script);
2607 return -1;
2611 s = net_tap_fd_init(vlan, fd);
2612 if (!s)
2613 return -1;
2614 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2615 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2616 return 0;
2619 #endif /* !_WIN32 */
2621 /* network connection */
2622 typedef struct NetSocketState {
2623 VLANClientState *vc;
2624 int fd;
2625 int state; /* 0 = getting length, 1 = getting data */
2626 int index;
2627 int packet_len;
2628 uint8_t buf[4096];
2629 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2630 } NetSocketState;
2632 typedef struct NetSocketListenState {
2633 VLANState *vlan;
2634 int fd;
2635 } NetSocketListenState;
2637 /* XXX: we consider we can send the whole packet without blocking */
2638 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2640 NetSocketState *s = opaque;
2641 uint32_t len;
2642 len = htonl(size);
2644 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2645 send_all(s->fd, buf, size);
2648 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2650 NetSocketState *s = opaque;
2651 sendto(s->fd, buf, size, 0,
2652 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2655 static void net_socket_send(void *opaque)
2657 NetSocketState *s = opaque;
2658 int l, size, err;
2659 uint8_t buf1[4096];
2660 const uint8_t *buf;
2662 size = recv(s->fd, buf1, sizeof(buf1), 0);
2663 if (size < 0) {
2664 err = socket_error();
2665 if (err != EWOULDBLOCK)
2666 goto eoc;
2667 } else if (size == 0) {
2668 /* end of connection */
2669 eoc:
2670 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2671 closesocket(s->fd);
2672 return;
2674 buf = buf1;
2675 while (size > 0) {
2676 /* reassemble a packet from the network */
2677 switch(s->state) {
2678 case 0:
2679 l = 4 - s->index;
2680 if (l > size)
2681 l = size;
2682 memcpy(s->buf + s->index, buf, l);
2683 buf += l;
2684 size -= l;
2685 s->index += l;
2686 if (s->index == 4) {
2687 /* got length */
2688 s->packet_len = ntohl(*(uint32_t *)s->buf);
2689 s->index = 0;
2690 s->state = 1;
2692 break;
2693 case 1:
2694 l = s->packet_len - s->index;
2695 if (l > size)
2696 l = size;
2697 memcpy(s->buf + s->index, buf, l);
2698 s->index += l;
2699 buf += l;
2700 size -= l;
2701 if (s->index >= s->packet_len) {
2702 qemu_send_packet(s->vc, s->buf, s->packet_len);
2703 s->index = 0;
2704 s->state = 0;
2706 break;
2711 static void net_socket_send_dgram(void *opaque)
2713 NetSocketState *s = opaque;
2714 int size;
2716 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2717 if (size < 0)
2718 return;
2719 if (size == 0) {
2720 /* end of connection */
2721 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2722 return;
2724 qemu_send_packet(s->vc, s->buf, size);
2727 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2729 struct ip_mreq imr;
2730 int fd;
2731 int val, ret;
2732 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2733 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2734 inet_ntoa(mcastaddr->sin_addr),
2735 (int)ntohl(mcastaddr->sin_addr.s_addr));
2736 return -1;
2739 fd = socket(PF_INET, SOCK_DGRAM, 0);
2740 if (fd < 0) {
2741 perror("socket(PF_INET, SOCK_DGRAM)");
2742 return -1;
2745 val = 1;
2746 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2747 (const char *)&val, sizeof(val));
2748 if (ret < 0) {
2749 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2750 goto fail;
2753 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2754 if (ret < 0) {
2755 perror("bind");
2756 goto fail;
2759 /* Add host to multicast group */
2760 imr.imr_multiaddr = mcastaddr->sin_addr;
2761 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2763 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2764 (const char *)&imr, sizeof(struct ip_mreq));
2765 if (ret < 0) {
2766 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2767 goto fail;
2770 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2771 val = 1;
2772 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2773 (const char *)&val, sizeof(val));
2774 if (ret < 0) {
2775 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2776 goto fail;
2779 socket_set_nonblock(fd);
2780 return fd;
2781 fail:
2782 if (fd>=0) close(fd);
2783 return -1;
2786 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2787 int is_connected)
2789 struct sockaddr_in saddr;
2790 int newfd;
2791 socklen_t saddr_len;
2792 NetSocketState *s;
2794 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2795 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2796 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2799 if (is_connected) {
2800 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2801 /* must be bound */
2802 if (saddr.sin_addr.s_addr==0) {
2803 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2804 fd);
2805 return NULL;
2807 /* clone dgram socket */
2808 newfd = net_socket_mcast_create(&saddr);
2809 if (newfd < 0) {
2810 /* error already reported by net_socket_mcast_create() */
2811 close(fd);
2812 return NULL;
2814 /* clone newfd to fd, close newfd */
2815 dup2(newfd, fd);
2816 close(newfd);
2818 } else {
2819 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2820 fd, strerror(errno));
2821 return NULL;
2825 s = qemu_mallocz(sizeof(NetSocketState));
2826 if (!s)
2827 return NULL;
2828 s->fd = fd;
2830 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2831 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2833 /* mcast: save bound address as dst */
2834 if (is_connected) s->dgram_dst=saddr;
2836 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2837 "socket: fd=%d (%s mcast=%s:%d)",
2838 fd, is_connected? "cloned" : "",
2839 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2840 return s;
2843 static void net_socket_connect(void *opaque)
2845 NetSocketState *s = opaque;
2846 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2849 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2850 int is_connected)
2852 NetSocketState *s;
2853 s = qemu_mallocz(sizeof(NetSocketState));
2854 if (!s)
2855 return NULL;
2856 s->fd = fd;
2857 s->vc = qemu_new_vlan_client(vlan,
2858 net_socket_receive, NULL, s);
2859 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2860 "socket: fd=%d", fd);
2861 if (is_connected) {
2862 net_socket_connect(s);
2863 } else {
2864 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2866 return s;
2869 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2870 int is_connected)
2872 int so_type=-1, optlen=sizeof(so_type);
2874 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2875 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2876 return NULL;
2878 switch(so_type) {
2879 case SOCK_DGRAM:
2880 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2881 case SOCK_STREAM:
2882 return net_socket_fd_init_stream(vlan, fd, is_connected);
2883 default:
2884 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2885 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2886 return net_socket_fd_init_stream(vlan, fd, is_connected);
2888 return NULL;
2891 static void net_socket_accept(void *opaque)
2893 NetSocketListenState *s = opaque;
2894 NetSocketState *s1;
2895 struct sockaddr_in saddr;
2896 socklen_t len;
2897 int fd;
2899 for(;;) {
2900 len = sizeof(saddr);
2901 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2902 if (fd < 0 && errno != EINTR) {
2903 return;
2904 } else if (fd >= 0) {
2905 break;
2908 s1 = net_socket_fd_init(s->vlan, fd, 1);
2909 if (!s1) {
2910 close(fd);
2911 } else {
2912 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2913 "socket: connection from %s:%d",
2914 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2918 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2920 NetSocketListenState *s;
2921 int fd, val, ret;
2922 struct sockaddr_in saddr;
2924 if (parse_host_port(&saddr, host_str) < 0)
2925 return -1;
2927 s = qemu_mallocz(sizeof(NetSocketListenState));
2928 if (!s)
2929 return -1;
2931 fd = socket(PF_INET, SOCK_STREAM, 0);
2932 if (fd < 0) {
2933 perror("socket");
2934 return -1;
2936 socket_set_nonblock(fd);
2938 /* allow fast reuse */
2939 val = 1;
2940 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2942 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2943 if (ret < 0) {
2944 perror("bind");
2945 return -1;
2947 ret = listen(fd, 0);
2948 if (ret < 0) {
2949 perror("listen");
2950 return -1;
2952 s->vlan = vlan;
2953 s->fd = fd;
2954 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2955 return 0;
2958 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2960 NetSocketState *s;
2961 int fd, connected, ret, err;
2962 struct sockaddr_in saddr;
2964 if (parse_host_port(&saddr, host_str) < 0)
2965 return -1;
2967 fd = socket(PF_INET, SOCK_STREAM, 0);
2968 if (fd < 0) {
2969 perror("socket");
2970 return -1;
2972 socket_set_nonblock(fd);
2974 connected = 0;
2975 for(;;) {
2976 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2977 if (ret < 0) {
2978 err = socket_error();
2979 if (err == EINTR || err == EWOULDBLOCK) {
2980 } else if (err == EINPROGRESS) {
2981 break;
2982 } else {
2983 perror("connect");
2984 closesocket(fd);
2985 return -1;
2987 } else {
2988 connected = 1;
2989 break;
2992 s = net_socket_fd_init(vlan, fd, connected);
2993 if (!s)
2994 return -1;
2995 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2996 "socket: connect to %s:%d",
2997 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2998 return 0;
3001 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3003 NetSocketState *s;
3004 int fd;
3005 struct sockaddr_in saddr;
3007 if (parse_host_port(&saddr, host_str) < 0)
3008 return -1;
3011 fd = net_socket_mcast_create(&saddr);
3012 if (fd < 0)
3013 return -1;
3015 s = net_socket_fd_init(vlan, fd, 0);
3016 if (!s)
3017 return -1;
3019 s->dgram_dst = saddr;
3021 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3022 "socket: mcast=%s:%d",
3023 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3024 return 0;
3028 static int get_param_value(char *buf, int buf_size,
3029 const char *tag, const char *str)
3031 const char *p;
3032 char *q;
3033 char option[128];
3035 p = str;
3036 for(;;) {
3037 q = option;
3038 while (*p != '\0' && *p != '=') {
3039 if ((q - option) < sizeof(option) - 1)
3040 *q++ = *p;
3041 p++;
3043 *q = '\0';
3044 if (*p != '=')
3045 break;
3046 p++;
3047 if (!strcmp(tag, option)) {
3048 q = buf;
3049 while (*p != '\0' && *p != ',') {
3050 if ((q - buf) < buf_size - 1)
3051 *q++ = *p;
3052 p++;
3054 *q = '\0';
3055 return q - buf;
3056 } else {
3057 while (*p != '\0' && *p != ',') {
3058 p++;
3061 if (*p != ',')
3062 break;
3063 p++;
3065 return 0;
3068 int net_client_init(const char *str)
3070 const char *p;
3071 char *q;
3072 char device[64];
3073 char buf[1024];
3074 int vlan_id, ret;
3075 VLANState *vlan;
3077 p = str;
3078 q = device;
3079 while (*p != '\0' && *p != ',') {
3080 if ((q - device) < sizeof(device) - 1)
3081 *q++ = *p;
3082 p++;
3084 *q = '\0';
3085 if (*p == ',')
3086 p++;
3087 vlan_id = 0;
3088 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3089 vlan_id = strtol(buf, NULL, 0);
3091 vlan = qemu_find_vlan(vlan_id);
3092 if (!vlan) {
3093 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3094 return -1;
3096 if (!strcmp(device, "nic")) {
3097 NICInfo *nd;
3098 uint8_t *macaddr;
3100 if (nb_nics >= MAX_NICS) {
3101 fprintf(stderr, "Too Many NICs\n");
3102 return -1;
3104 nd = &nd_table[nb_nics];
3105 macaddr = nd->macaddr;
3106 macaddr[0] = 0x52;
3107 macaddr[1] = 0x54;
3108 macaddr[2] = 0x00;
3109 macaddr[3] = 0x12;
3110 macaddr[4] = 0x34;
3111 macaddr[5] = 0x56 + nb_nics;
3113 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3114 if (parse_macaddr(macaddr, buf) < 0) {
3115 fprintf(stderr, "invalid syntax for ethernet address\n");
3116 return -1;
3119 if (get_param_value(buf, sizeof(buf), "model", p)) {
3120 nd->model = strdup(buf);
3122 nd->vlan = vlan;
3123 nb_nics++;
3124 ret = 0;
3125 } else
3126 if (!strcmp(device, "none")) {
3127 /* does nothing. It is needed to signal that no network cards
3128 are wanted */
3129 ret = 0;
3130 } else
3131 #ifdef CONFIG_SLIRP
3132 if (!strcmp(device, "user")) {
3133 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3134 if (strlen(buf) > 32)
3135 buf[32] = 0;
3136 strcpy(slirp_hostname, buf);
3138 ret = net_slirp_init(vlan);
3139 } else
3140 #endif
3141 #ifdef _WIN32
3142 if (!strcmp(device, "tap")) {
3143 char ifname[64];
3144 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3145 fprintf(stderr, "tap: no interface name\n");
3146 return -1;
3148 ret = tap_win32_init(vlan, ifname);
3149 } else
3150 #else
3151 if (!strcmp(device, "tap")) {
3152 char ifname[64];
3153 char setup_script[1024];
3154 int fd;
3155 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3156 fd = strtol(buf, NULL, 0);
3157 ret = -1;
3158 if (net_tap_fd_init(vlan, fd))
3159 ret = 0;
3160 } else {
3161 get_param_value(ifname, sizeof(ifname), "ifname", p);
3162 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3163 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3165 ret = net_tap_init(vlan, ifname, setup_script);
3167 } else
3168 #endif
3169 if (!strcmp(device, "socket")) {
3170 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3171 int fd;
3172 fd = strtol(buf, NULL, 0);
3173 ret = -1;
3174 if (net_socket_fd_init(vlan, fd, 1))
3175 ret = 0;
3176 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3177 ret = net_socket_listen_init(vlan, buf);
3178 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3179 ret = net_socket_connect_init(vlan, buf);
3180 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3181 ret = net_socket_mcast_init(vlan, buf);
3182 } else {
3183 fprintf(stderr, "Unknown socket options: %s\n", p);
3184 return -1;
3186 } else
3188 fprintf(stderr, "Unknown network device: %s\n", device);
3189 return -1;
3191 if (ret < 0) {
3192 fprintf(stderr, "Could not initialize device '%s'\n", device);
3195 return ret;
3198 void do_info_network(void)
3200 VLANState *vlan;
3201 VLANClientState *vc;
3203 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3204 term_printf("VLAN %d devices:\n", vlan->id);
3205 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3206 term_printf(" %s\n", vc->info_str);
3210 /***********************************************************/
3211 /* USB devices */
3213 static int usb_device_add(const char *devname)
3215 const char *p;
3216 USBDevice *dev;
3217 int i;
3219 if (!vm_usb_hub)
3220 return -1;
3221 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3222 if (!vm_usb_ports[i]->dev)
3223 break;
3225 if (i == MAX_VM_USB_PORTS)
3226 return -1;
3228 if (strstart(devname, "host:", &p)) {
3229 dev = usb_host_device_open(p);
3230 if (!dev)
3231 return -1;
3232 } else if (!strcmp(devname, "mouse")) {
3233 dev = usb_mouse_init();
3234 if (!dev)
3235 return -1;
3236 } else if (!strcmp(devname, "tablet")) {
3237 dev = usb_tablet_init();
3238 if (!dev)
3239 return -1;
3240 } else {
3241 return -1;
3243 usb_attach(vm_usb_ports[i], dev);
3244 return 0;
3247 static int usb_device_del(const char *devname)
3249 USBDevice *dev;
3250 int bus_num, addr, i;
3251 const char *p;
3253 if (!vm_usb_hub)
3254 return -1;
3256 p = strchr(devname, '.');
3257 if (!p)
3258 return -1;
3259 bus_num = strtoul(devname, NULL, 0);
3260 addr = strtoul(p + 1, NULL, 0);
3261 if (bus_num != 0)
3262 return -1;
3263 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3264 dev = vm_usb_ports[i]->dev;
3265 if (dev && dev->addr == addr)
3266 break;
3268 if (i == MAX_VM_USB_PORTS)
3269 return -1;
3270 usb_attach(vm_usb_ports[i], NULL);
3271 return 0;
3274 void do_usb_add(const char *devname)
3276 int ret;
3277 ret = usb_device_add(devname);
3278 if (ret < 0)
3279 term_printf("Could not add USB device '%s'\n", devname);
3282 void do_usb_del(const char *devname)
3284 int ret;
3285 ret = usb_device_del(devname);
3286 if (ret < 0)
3287 term_printf("Could not remove USB device '%s'\n", devname);
3290 void usb_info(void)
3292 USBDevice *dev;
3293 int i;
3294 const char *speed_str;
3296 if (!vm_usb_hub) {
3297 term_printf("USB support not enabled\n");
3298 return;
3301 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3302 dev = vm_usb_ports[i]->dev;
3303 if (dev) {
3304 term_printf("Hub port %d:\n", i);
3305 switch(dev->speed) {
3306 case USB_SPEED_LOW:
3307 speed_str = "1.5";
3308 break;
3309 case USB_SPEED_FULL:
3310 speed_str = "12";
3311 break;
3312 case USB_SPEED_HIGH:
3313 speed_str = "480";
3314 break;
3315 default:
3316 speed_str = "?";
3317 break;
3319 term_printf(" Device %d.%d, speed %s Mb/s\n",
3320 0, dev->addr, speed_str);
3325 /***********************************************************/
3326 /* pid file */
3328 static char *pid_filename;
3330 /* Remove PID file. Called on normal exit */
3332 static void remove_pidfile(void)
3334 unlink (pid_filename);
3337 static void create_pidfile(const char *filename)
3339 struct stat pidstat;
3340 FILE *f;
3342 /* Try to write our PID to the named file */
3343 if (stat(filename, &pidstat) < 0) {
3344 if (errno == ENOENT) {
3345 if ((f = fopen (filename, "w")) == NULL) {
3346 perror("Opening pidfile");
3347 exit(1);
3349 fprintf(f, "%d\n", getpid());
3350 fclose(f);
3351 pid_filename = qemu_strdup(filename);
3352 if (!pid_filename) {
3353 fprintf(stderr, "Could not save PID filename");
3354 exit(1);
3356 atexit(remove_pidfile);
3358 } else {
3359 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3360 filename);
3361 exit(1);
3365 /***********************************************************/
3366 /* dumb display */
3368 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3372 static void dumb_resize(DisplayState *ds, int w, int h)
3376 static void dumb_refresh(DisplayState *ds)
3378 vga_hw_update();
3381 void dumb_display_init(DisplayState *ds)
3383 ds->data = NULL;
3384 ds->linesize = 0;
3385 ds->depth = 0;
3386 ds->dpy_update = dumb_update;
3387 ds->dpy_resize = dumb_resize;
3388 ds->dpy_refresh = dumb_refresh;
3391 #if !defined(CONFIG_SOFTMMU)
3392 /***********************************************************/
3393 /* cpu signal handler */
3394 static void host_segv_handler(int host_signum, siginfo_t *info,
3395 void *puc)
3397 if (cpu_signal_handler(host_signum, info, puc))
3398 return;
3399 if (stdio_nb_clients > 0)
3400 term_exit();
3401 abort();
3403 #endif
3405 /***********************************************************/
3406 /* I/O handling */
3408 #define MAX_IO_HANDLERS 64
3410 typedef struct IOHandlerRecord {
3411 int fd;
3412 IOCanRWHandler *fd_read_poll;
3413 IOHandler *fd_read;
3414 IOHandler *fd_write;
3415 void *opaque;
3416 /* temporary data */
3417 struct pollfd *ufd;
3418 struct IOHandlerRecord *next;
3419 } IOHandlerRecord;
3421 static IOHandlerRecord *first_io_handler;
3423 /* XXX: fd_read_poll should be suppressed, but an API change is
3424 necessary in the character devices to suppress fd_can_read(). */
3425 int qemu_set_fd_handler2(int fd,
3426 IOCanRWHandler *fd_read_poll,
3427 IOHandler *fd_read,
3428 IOHandler *fd_write,
3429 void *opaque)
3431 IOHandlerRecord **pioh, *ioh;
3433 if (!fd_read && !fd_write) {
3434 pioh = &first_io_handler;
3435 for(;;) {
3436 ioh = *pioh;
3437 if (ioh == NULL)
3438 break;
3439 if (ioh->fd == fd) {
3440 *pioh = ioh->next;
3441 qemu_free(ioh);
3442 break;
3444 pioh = &ioh->next;
3446 } else {
3447 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3448 if (ioh->fd == fd)
3449 goto found;
3451 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3452 if (!ioh)
3453 return -1;
3454 ioh->next = first_io_handler;
3455 first_io_handler = ioh;
3456 found:
3457 ioh->fd = fd;
3458 ioh->fd_read_poll = fd_read_poll;
3459 ioh->fd_read = fd_read;
3460 ioh->fd_write = fd_write;
3461 ioh->opaque = opaque;
3463 return 0;
3466 int qemu_set_fd_handler(int fd,
3467 IOHandler *fd_read,
3468 IOHandler *fd_write,
3469 void *opaque)
3471 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3474 /***********************************************************/
3475 /* Polling handling */
3477 typedef struct PollingEntry {
3478 PollingFunc *func;
3479 void *opaque;
3480 struct PollingEntry *next;
3481 } PollingEntry;
3483 static PollingEntry *first_polling_entry;
3485 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3487 PollingEntry **ppe, *pe;
3488 pe = qemu_mallocz(sizeof(PollingEntry));
3489 if (!pe)
3490 return -1;
3491 pe->func = func;
3492 pe->opaque = opaque;
3493 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3494 *ppe = pe;
3495 return 0;
3498 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3500 PollingEntry **ppe, *pe;
3501 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3502 pe = *ppe;
3503 if (pe->func == func && pe->opaque == opaque) {
3504 *ppe = pe->next;
3505 qemu_free(pe);
3506 break;
3511 /***********************************************************/
3512 /* savevm/loadvm support */
3514 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3516 fwrite(buf, 1, size, f);
3519 void qemu_put_byte(QEMUFile *f, int v)
3521 fputc(v, f);
3524 void qemu_put_be16(QEMUFile *f, unsigned int v)
3526 qemu_put_byte(f, v >> 8);
3527 qemu_put_byte(f, v);
3530 void qemu_put_be32(QEMUFile *f, unsigned int v)
3532 qemu_put_byte(f, v >> 24);
3533 qemu_put_byte(f, v >> 16);
3534 qemu_put_byte(f, v >> 8);
3535 qemu_put_byte(f, v);
3538 void qemu_put_be64(QEMUFile *f, uint64_t v)
3540 qemu_put_be32(f, v >> 32);
3541 qemu_put_be32(f, v);
3544 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3546 return fread(buf, 1, size, f);
3549 int qemu_get_byte(QEMUFile *f)
3551 int v;
3552 v = fgetc(f);
3553 if (v == EOF)
3554 return 0;
3555 else
3556 return v;
3559 unsigned int qemu_get_be16(QEMUFile *f)
3561 unsigned int v;
3562 v = qemu_get_byte(f) << 8;
3563 v |= qemu_get_byte(f);
3564 return v;
3567 unsigned int qemu_get_be32(QEMUFile *f)
3569 unsigned int v;
3570 v = qemu_get_byte(f) << 24;
3571 v |= qemu_get_byte(f) << 16;
3572 v |= qemu_get_byte(f) << 8;
3573 v |= qemu_get_byte(f);
3574 return v;
3577 uint64_t qemu_get_be64(QEMUFile *f)
3579 uint64_t v;
3580 v = (uint64_t)qemu_get_be32(f) << 32;
3581 v |= qemu_get_be32(f);
3582 return v;
3585 int64_t qemu_ftell(QEMUFile *f)
3587 return ftell(f);
3590 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3592 if (fseek(f, pos, whence) < 0)
3593 return -1;
3594 return ftell(f);
3597 typedef struct SaveStateEntry {
3598 char idstr[256];
3599 int instance_id;
3600 int version_id;
3601 SaveStateHandler *save_state;
3602 LoadStateHandler *load_state;
3603 void *opaque;
3604 struct SaveStateEntry *next;
3605 } SaveStateEntry;
3607 static SaveStateEntry *first_se;
3609 int register_savevm(const char *idstr,
3610 int instance_id,
3611 int version_id,
3612 SaveStateHandler *save_state,
3613 LoadStateHandler *load_state,
3614 void *opaque)
3616 SaveStateEntry *se, **pse;
3618 se = qemu_malloc(sizeof(SaveStateEntry));
3619 if (!se)
3620 return -1;
3621 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3622 se->instance_id = instance_id;
3623 se->version_id = version_id;
3624 se->save_state = save_state;
3625 se->load_state = load_state;
3626 se->opaque = opaque;
3627 se->next = NULL;
3629 /* add at the end of list */
3630 pse = &first_se;
3631 while (*pse != NULL)
3632 pse = &(*pse)->next;
3633 *pse = se;
3634 return 0;
3637 #define QEMU_VM_FILE_MAGIC 0x5145564d
3638 #define QEMU_VM_FILE_VERSION 0x00000001
3640 int qemu_savevm(const char *filename)
3642 SaveStateEntry *se;
3643 QEMUFile *f;
3644 int len, len_pos, cur_pos, saved_vm_running, ret;
3646 saved_vm_running = vm_running;
3647 vm_stop(0);
3649 f = fopen(filename, "wb");
3650 if (!f) {
3651 ret = -1;
3652 goto the_end;
3655 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3656 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3658 for(se = first_se; se != NULL; se = se->next) {
3659 /* ID string */
3660 len = strlen(se->idstr);
3661 qemu_put_byte(f, len);
3662 qemu_put_buffer(f, se->idstr, len);
3664 qemu_put_be32(f, se->instance_id);
3665 qemu_put_be32(f, se->version_id);
3667 /* record size: filled later */
3668 len_pos = ftell(f);
3669 qemu_put_be32(f, 0);
3671 se->save_state(f, se->opaque);
3673 /* fill record size */
3674 cur_pos = ftell(f);
3675 len = ftell(f) - len_pos - 4;
3676 fseek(f, len_pos, SEEK_SET);
3677 qemu_put_be32(f, len);
3678 fseek(f, cur_pos, SEEK_SET);
3681 fclose(f);
3682 ret = 0;
3683 the_end:
3684 if (saved_vm_running)
3685 vm_start();
3686 return ret;
3689 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3691 SaveStateEntry *se;
3693 for(se = first_se; se != NULL; se = se->next) {
3694 if (!strcmp(se->idstr, idstr) &&
3695 instance_id == se->instance_id)
3696 return se;
3698 return NULL;
3701 int qemu_loadvm(const char *filename)
3703 SaveStateEntry *se;
3704 QEMUFile *f;
3705 int len, cur_pos, ret, instance_id, record_len, version_id;
3706 int saved_vm_running;
3707 unsigned int v;
3708 char idstr[256];
3710 saved_vm_running = vm_running;
3711 vm_stop(0);
3713 f = fopen(filename, "rb");
3714 if (!f) {
3715 ret = -1;
3716 goto the_end;
3719 v = qemu_get_be32(f);
3720 if (v != QEMU_VM_FILE_MAGIC)
3721 goto fail;
3722 v = qemu_get_be32(f);
3723 if (v != QEMU_VM_FILE_VERSION) {
3724 fail:
3725 fclose(f);
3726 ret = -1;
3727 goto the_end;
3729 for(;;) {
3730 len = qemu_get_byte(f);
3731 if (feof(f))
3732 break;
3733 qemu_get_buffer(f, idstr, len);
3734 idstr[len] = '\0';
3735 instance_id = qemu_get_be32(f);
3736 version_id = qemu_get_be32(f);
3737 record_len = qemu_get_be32(f);
3738 #if 0
3739 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3740 idstr, instance_id, version_id, record_len);
3741 #endif
3742 cur_pos = ftell(f);
3743 se = find_se(idstr, instance_id);
3744 if (!se) {
3745 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3746 instance_id, idstr);
3747 } else {
3748 ret = se->load_state(f, se->opaque, version_id);
3749 if (ret < 0) {
3750 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3751 instance_id, idstr);
3754 /* always seek to exact end of record */
3755 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3757 fclose(f);
3758 ret = 0;
3759 the_end:
3760 if (saved_vm_running)
3761 vm_start();
3762 return ret;
3765 /***********************************************************/
3766 /* cpu save/restore */
3768 #if defined(TARGET_I386)
3770 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3772 qemu_put_be32(f, dt->selector);
3773 qemu_put_betl(f, dt->base);
3774 qemu_put_be32(f, dt->limit);
3775 qemu_put_be32(f, dt->flags);
3778 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3780 dt->selector = qemu_get_be32(f);
3781 dt->base = qemu_get_betl(f);
3782 dt->limit = qemu_get_be32(f);
3783 dt->flags = qemu_get_be32(f);
3786 void cpu_save(QEMUFile *f, void *opaque)
3788 CPUState *env = opaque;
3789 uint16_t fptag, fpus, fpuc, fpregs_format;
3790 uint32_t hflags;
3791 int i;
3793 for(i = 0; i < CPU_NB_REGS; i++)
3794 qemu_put_betls(f, &env->regs[i]);
3795 qemu_put_betls(f, &env->eip);
3796 qemu_put_betls(f, &env->eflags);
3797 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3798 qemu_put_be32s(f, &hflags);
3800 /* FPU */
3801 fpuc = env->fpuc;
3802 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3803 fptag = 0;
3804 for(i = 0; i < 8; i++) {
3805 fptag |= ((!env->fptags[i]) << i);
3808 qemu_put_be16s(f, &fpuc);
3809 qemu_put_be16s(f, &fpus);
3810 qemu_put_be16s(f, &fptag);
3812 #ifdef USE_X86LDOUBLE
3813 fpregs_format = 0;
3814 #else
3815 fpregs_format = 1;
3816 #endif
3817 qemu_put_be16s(f, &fpregs_format);
3819 for(i = 0; i < 8; i++) {
3820 #ifdef USE_X86LDOUBLE
3822 uint64_t mant;
3823 uint16_t exp;
3824 /* we save the real CPU data (in case of MMX usage only 'mant'
3825 contains the MMX register */
3826 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3827 qemu_put_be64(f, mant);
3828 qemu_put_be16(f, exp);
3830 #else
3831 /* if we use doubles for float emulation, we save the doubles to
3832 avoid losing information in case of MMX usage. It can give
3833 problems if the image is restored on a CPU where long
3834 doubles are used instead. */
3835 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3836 #endif
3839 for(i = 0; i < 6; i++)
3840 cpu_put_seg(f, &env->segs[i]);
3841 cpu_put_seg(f, &env->ldt);
3842 cpu_put_seg(f, &env->tr);
3843 cpu_put_seg(f, &env->gdt);
3844 cpu_put_seg(f, &env->idt);
3846 qemu_put_be32s(f, &env->sysenter_cs);
3847 qemu_put_be32s(f, &env->sysenter_esp);
3848 qemu_put_be32s(f, &env->sysenter_eip);
3850 qemu_put_betls(f, &env->cr[0]);
3851 qemu_put_betls(f, &env->cr[2]);
3852 qemu_put_betls(f, &env->cr[3]);
3853 qemu_put_betls(f, &env->cr[4]);
3855 for(i = 0; i < 8; i++)
3856 qemu_put_betls(f, &env->dr[i]);
3858 /* MMU */
3859 qemu_put_be32s(f, &env->a20_mask);
3861 /* XMM */
3862 qemu_put_be32s(f, &env->mxcsr);
3863 for(i = 0; i < CPU_NB_REGS; i++) {
3864 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3865 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3868 #ifdef TARGET_X86_64
3869 qemu_put_be64s(f, &env->efer);
3870 qemu_put_be64s(f, &env->star);
3871 qemu_put_be64s(f, &env->lstar);
3872 qemu_put_be64s(f, &env->cstar);
3873 qemu_put_be64s(f, &env->fmask);
3874 qemu_put_be64s(f, &env->kernelgsbase);
3875 #endif
3878 #ifdef USE_X86LDOUBLE
3879 /* XXX: add that in a FPU generic layer */
3880 union x86_longdouble {
3881 uint64_t mant;
3882 uint16_t exp;
3885 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3886 #define EXPBIAS1 1023
3887 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3888 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3890 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3892 int e;
3893 /* mantissa */
3894 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3895 /* exponent + sign */
3896 e = EXPD1(temp) - EXPBIAS1 + 16383;
3897 e |= SIGND1(temp) >> 16;
3898 p->exp = e;
3900 #endif
3902 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3904 CPUState *env = opaque;
3905 int i, guess_mmx;
3906 uint32_t hflags;
3907 uint16_t fpus, fpuc, fptag, fpregs_format;
3909 if (version_id != 3)
3910 return -EINVAL;
3911 for(i = 0; i < CPU_NB_REGS; i++)
3912 qemu_get_betls(f, &env->regs[i]);
3913 qemu_get_betls(f, &env->eip);
3914 qemu_get_betls(f, &env->eflags);
3915 qemu_get_be32s(f, &hflags);
3917 qemu_get_be16s(f, &fpuc);
3918 qemu_get_be16s(f, &fpus);
3919 qemu_get_be16s(f, &fptag);
3920 qemu_get_be16s(f, &fpregs_format);
3922 /* NOTE: we cannot always restore the FPU state if the image come
3923 from a host with a different 'USE_X86LDOUBLE' define. We guess
3924 if we are in an MMX state to restore correctly in that case. */
3925 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3926 for(i = 0; i < 8; i++) {
3927 uint64_t mant;
3928 uint16_t exp;
3930 switch(fpregs_format) {
3931 case 0:
3932 mant = qemu_get_be64(f);
3933 exp = qemu_get_be16(f);
3934 #ifdef USE_X86LDOUBLE
3935 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3936 #else
3937 /* difficult case */
3938 if (guess_mmx)
3939 env->fpregs[i].mmx.MMX_Q(0) = mant;
3940 else
3941 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3942 #endif
3943 break;
3944 case 1:
3945 mant = qemu_get_be64(f);
3946 #ifdef USE_X86LDOUBLE
3948 union x86_longdouble *p;
3949 /* difficult case */
3950 p = (void *)&env->fpregs[i];
3951 if (guess_mmx) {
3952 p->mant = mant;
3953 p->exp = 0xffff;
3954 } else {
3955 fp64_to_fp80(p, mant);
3958 #else
3959 env->fpregs[i].mmx.MMX_Q(0) = mant;
3960 #endif
3961 break;
3962 default:
3963 return -EINVAL;
3967 env->fpuc = fpuc;
3968 /* XXX: restore FPU round state */
3969 env->fpstt = (fpus >> 11) & 7;
3970 env->fpus = fpus & ~0x3800;
3971 fptag ^= 0xff;
3972 for(i = 0; i < 8; i++) {
3973 env->fptags[i] = (fptag >> i) & 1;
3976 for(i = 0; i < 6; i++)
3977 cpu_get_seg(f, &env->segs[i]);
3978 cpu_get_seg(f, &env->ldt);
3979 cpu_get_seg(f, &env->tr);
3980 cpu_get_seg(f, &env->gdt);
3981 cpu_get_seg(f, &env->idt);
3983 qemu_get_be32s(f, &env->sysenter_cs);
3984 qemu_get_be32s(f, &env->sysenter_esp);
3985 qemu_get_be32s(f, &env->sysenter_eip);
3987 qemu_get_betls(f, &env->cr[0]);
3988 qemu_get_betls(f, &env->cr[2]);
3989 qemu_get_betls(f, &env->cr[3]);
3990 qemu_get_betls(f, &env->cr[4]);
3992 for(i = 0; i < 8; i++)
3993 qemu_get_betls(f, &env->dr[i]);
3995 /* MMU */
3996 qemu_get_be32s(f, &env->a20_mask);
3998 qemu_get_be32s(f, &env->mxcsr);
3999 for(i = 0; i < CPU_NB_REGS; i++) {
4000 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4001 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4004 #ifdef TARGET_X86_64
4005 qemu_get_be64s(f, &env->efer);
4006 qemu_get_be64s(f, &env->star);
4007 qemu_get_be64s(f, &env->lstar);
4008 qemu_get_be64s(f, &env->cstar);
4009 qemu_get_be64s(f, &env->fmask);
4010 qemu_get_be64s(f, &env->kernelgsbase);
4011 #endif
4013 /* XXX: compute hflags from scratch, except for CPL and IIF */
4014 env->hflags = hflags;
4015 tlb_flush(env, 1);
4016 return 0;
4019 #elif defined(TARGET_PPC)
4020 void cpu_save(QEMUFile *f, void *opaque)
4024 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4026 return 0;
4029 #elif defined(TARGET_MIPS)
4030 void cpu_save(QEMUFile *f, void *opaque)
4034 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4036 return 0;
4039 #elif defined(TARGET_SPARC)
4040 void cpu_save(QEMUFile *f, void *opaque)
4042 CPUState *env = opaque;
4043 int i;
4044 uint32_t tmp;
4046 for(i = 0; i < 8; i++)
4047 qemu_put_betls(f, &env->gregs[i]);
4048 for(i = 0; i < NWINDOWS * 16; i++)
4049 qemu_put_betls(f, &env->regbase[i]);
4051 /* FPU */
4052 for(i = 0; i < TARGET_FPREGS; i++) {
4053 union {
4054 TARGET_FPREG_T f;
4055 target_ulong i;
4056 } u;
4057 u.f = env->fpr[i];
4058 qemu_put_betl(f, u.i);
4061 qemu_put_betls(f, &env->pc);
4062 qemu_put_betls(f, &env->npc);
4063 qemu_put_betls(f, &env->y);
4064 tmp = GET_PSR(env);
4065 qemu_put_be32(f, tmp);
4066 qemu_put_betls(f, &env->fsr);
4067 qemu_put_betls(f, &env->tbr);
4068 #ifndef TARGET_SPARC64
4069 qemu_put_be32s(f, &env->wim);
4070 /* MMU */
4071 for(i = 0; i < 16; i++)
4072 qemu_put_be32s(f, &env->mmuregs[i]);
4073 #endif
4076 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4078 CPUState *env = opaque;
4079 int i;
4080 uint32_t tmp;
4082 for(i = 0; i < 8; i++)
4083 qemu_get_betls(f, &env->gregs[i]);
4084 for(i = 0; i < NWINDOWS * 16; i++)
4085 qemu_get_betls(f, &env->regbase[i]);
4087 /* FPU */
4088 for(i = 0; i < TARGET_FPREGS; i++) {
4089 union {
4090 TARGET_FPREG_T f;
4091 target_ulong i;
4092 } u;
4093 u.i = qemu_get_betl(f);
4094 env->fpr[i] = u.f;
4097 qemu_get_betls(f, &env->pc);
4098 qemu_get_betls(f, &env->npc);
4099 qemu_get_betls(f, &env->y);
4100 tmp = qemu_get_be32(f);
4101 env->cwp = 0; /* needed to ensure that the wrapping registers are
4102 correctly updated */
4103 PUT_PSR(env, tmp);
4104 qemu_get_betls(f, &env->fsr);
4105 qemu_get_betls(f, &env->tbr);
4106 #ifndef TARGET_SPARC64
4107 qemu_get_be32s(f, &env->wim);
4108 /* MMU */
4109 for(i = 0; i < 16; i++)
4110 qemu_get_be32s(f, &env->mmuregs[i]);
4111 #endif
4112 tlb_flush(env, 1);
4113 return 0;
4116 #elif defined(TARGET_ARM)
4118 /* ??? Need to implement these. */
4119 void cpu_save(QEMUFile *f, void *opaque)
4123 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4125 return 0;
4128 #else
4130 #warning No CPU save/restore functions
4132 #endif
4134 /***********************************************************/
4135 /* ram save/restore */
4137 /* we just avoid storing empty pages */
4138 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4140 int i, v;
4142 v = buf[0];
4143 for(i = 1; i < len; i++) {
4144 if (buf[i] != v)
4145 goto normal_save;
4147 qemu_put_byte(f, 1);
4148 qemu_put_byte(f, v);
4149 return;
4150 normal_save:
4151 qemu_put_byte(f, 0);
4152 qemu_put_buffer(f, buf, len);
4155 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4157 int v;
4159 v = qemu_get_byte(f);
4160 switch(v) {
4161 case 0:
4162 if (qemu_get_buffer(f, buf, len) != len)
4163 return -EIO;
4164 break;
4165 case 1:
4166 v = qemu_get_byte(f);
4167 memset(buf, v, len);
4168 break;
4169 default:
4170 return -EINVAL;
4172 return 0;
4175 static void ram_save(QEMUFile *f, void *opaque)
4177 int i;
4178 qemu_put_be32(f, phys_ram_size);
4179 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4180 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4184 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4186 int i, ret;
4188 if (version_id != 1)
4189 return -EINVAL;
4190 if (qemu_get_be32(f) != phys_ram_size)
4191 return -EINVAL;
4192 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4193 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4194 if (ret)
4195 return ret;
4197 return 0;
4200 /***********************************************************/
4201 /* machine registration */
4203 QEMUMachine *first_machine = NULL;
4205 int qemu_register_machine(QEMUMachine *m)
4207 QEMUMachine **pm;
4208 pm = &first_machine;
4209 while (*pm != NULL)
4210 pm = &(*pm)->next;
4211 m->next = NULL;
4212 *pm = m;
4213 return 0;
4216 QEMUMachine *find_machine(const char *name)
4218 QEMUMachine *m;
4220 for(m = first_machine; m != NULL; m = m->next) {
4221 if (!strcmp(m->name, name))
4222 return m;
4224 return NULL;
4227 /***********************************************************/
4228 /* main execution loop */
4230 void gui_update(void *opaque)
4232 display_state.dpy_refresh(&display_state);
4233 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4236 struct vm_change_state_entry {
4237 VMChangeStateHandler *cb;
4238 void *opaque;
4239 LIST_ENTRY (vm_change_state_entry) entries;
4242 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4244 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4245 void *opaque)
4247 VMChangeStateEntry *e;
4249 e = qemu_mallocz(sizeof (*e));
4250 if (!e)
4251 return NULL;
4253 e->cb = cb;
4254 e->opaque = opaque;
4255 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4256 return e;
4259 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4261 LIST_REMOVE (e, entries);
4262 qemu_free (e);
4265 static void vm_state_notify(int running)
4267 VMChangeStateEntry *e;
4269 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4270 e->cb(e->opaque, running);
4274 /* XXX: support several handlers */
4275 static VMStopHandler *vm_stop_cb;
4276 static void *vm_stop_opaque;
4278 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4280 vm_stop_cb = cb;
4281 vm_stop_opaque = opaque;
4282 return 0;
4285 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4287 vm_stop_cb = NULL;
4290 void vm_start(void)
4292 if (!vm_running) {
4293 cpu_enable_ticks();
4294 vm_running = 1;
4295 vm_state_notify(1);
4299 void vm_stop(int reason)
4301 if (vm_running) {
4302 cpu_disable_ticks();
4303 vm_running = 0;
4304 if (reason != 0) {
4305 if (vm_stop_cb) {
4306 vm_stop_cb(vm_stop_opaque, reason);
4309 vm_state_notify(0);
4313 /* reset/shutdown handler */
4315 typedef struct QEMUResetEntry {
4316 QEMUResetHandler *func;
4317 void *opaque;
4318 struct QEMUResetEntry *next;
4319 } QEMUResetEntry;
4321 static QEMUResetEntry *first_reset_entry;
4322 static int reset_requested;
4323 static int shutdown_requested;
4324 static int powerdown_requested;
4326 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4328 QEMUResetEntry **pre, *re;
4330 pre = &first_reset_entry;
4331 while (*pre != NULL)
4332 pre = &(*pre)->next;
4333 re = qemu_mallocz(sizeof(QEMUResetEntry));
4334 re->func = func;
4335 re->opaque = opaque;
4336 re->next = NULL;
4337 *pre = re;
4340 void qemu_system_reset(void)
4342 QEMUResetEntry *re;
4344 /* reset all devices */
4345 for(re = first_reset_entry; re != NULL; re = re->next) {
4346 re->func(re->opaque);
4350 void qemu_system_reset_request(void)
4352 reset_requested = 1;
4353 if (cpu_single_env)
4354 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4357 void qemu_system_shutdown_request(void)
4359 shutdown_requested = 1;
4360 if (cpu_single_env)
4361 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4364 void qemu_system_powerdown_request(void)
4366 powerdown_requested = 1;
4367 if (cpu_single_env)
4368 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4371 void main_loop_wait(int timeout)
4373 IOHandlerRecord *ioh, *ioh_next;
4374 fd_set rfds, wfds;
4375 int ret, nfds;
4376 struct timeval tv;
4377 PollingEntry *pe;
4380 /* XXX: need to suppress polling by better using win32 events */
4381 ret = 0;
4382 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4383 ret |= pe->func(pe->opaque);
4385 #ifdef _WIN32
4386 if (ret == 0 && timeout > 0) {
4387 Sleep(timeout);
4389 #endif
4390 /* poll any events */
4391 /* XXX: separate device handlers from system ones */
4392 nfds = -1;
4393 FD_ZERO(&rfds);
4394 FD_ZERO(&wfds);
4395 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4396 if (ioh->fd_read &&
4397 (!ioh->fd_read_poll ||
4398 ioh->fd_read_poll(ioh->opaque) != 0)) {
4399 FD_SET(ioh->fd, &rfds);
4400 if (ioh->fd > nfds)
4401 nfds = ioh->fd;
4403 if (ioh->fd_write) {
4404 FD_SET(ioh->fd, &wfds);
4405 if (ioh->fd > nfds)
4406 nfds = ioh->fd;
4410 tv.tv_sec = 0;
4411 #ifdef _WIN32
4412 tv.tv_usec = 0;
4413 #else
4414 tv.tv_usec = timeout * 1000;
4415 #endif
4416 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4417 if (ret > 0) {
4418 /* XXX: better handling of removal */
4419 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4420 ioh_next = ioh->next;
4421 if (FD_ISSET(ioh->fd, &rfds)) {
4422 ioh->fd_read(ioh->opaque);
4424 if (FD_ISSET(ioh->fd, &wfds)) {
4425 ioh->fd_write(ioh->opaque);
4429 #ifdef _WIN32
4430 tap_win32_poll();
4431 #endif
4433 #if defined(CONFIG_SLIRP)
4434 /* XXX: merge with the previous select() */
4435 if (slirp_inited) {
4436 fd_set rfds, wfds, xfds;
4437 int nfds;
4438 struct timeval tv;
4440 nfds = -1;
4441 FD_ZERO(&rfds);
4442 FD_ZERO(&wfds);
4443 FD_ZERO(&xfds);
4444 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4445 tv.tv_sec = 0;
4446 tv.tv_usec = 0;
4447 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4448 if (ret >= 0) {
4449 slirp_select_poll(&rfds, &wfds, &xfds);
4452 #endif
4454 if (vm_running) {
4455 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4456 qemu_get_clock(vm_clock));
4457 /* run dma transfers, if any */
4458 DMA_run();
4461 /* real time timers */
4462 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4463 qemu_get_clock(rt_clock));
4466 static CPUState *cur_cpu;
4468 int main_loop(void)
4470 int ret, timeout;
4471 #ifdef CONFIG_PROFILER
4472 int64_t ti;
4473 #endif
4474 CPUState *env;
4476 cur_cpu = first_cpu;
4477 for(;;) {
4478 if (vm_running) {
4480 env = cur_cpu;
4481 for(;;) {
4482 /* get next cpu */
4483 env = env->next_cpu;
4484 if (!env)
4485 env = first_cpu;
4486 #ifdef CONFIG_PROFILER
4487 ti = profile_getclock();
4488 #endif
4489 ret = cpu_exec(env);
4490 #ifdef CONFIG_PROFILER
4491 qemu_time += profile_getclock() - ti;
4492 #endif
4493 if (ret != EXCP_HALTED)
4494 break;
4495 /* all CPUs are halted ? */
4496 if (env == cur_cpu) {
4497 ret = EXCP_HLT;
4498 break;
4501 cur_cpu = env;
4503 if (shutdown_requested) {
4504 ret = EXCP_INTERRUPT;
4505 break;
4507 if (reset_requested) {
4508 reset_requested = 0;
4509 qemu_system_reset();
4510 ret = EXCP_INTERRUPT;
4512 if (powerdown_requested) {
4513 powerdown_requested = 0;
4514 qemu_system_powerdown();
4515 ret = EXCP_INTERRUPT;
4517 if (ret == EXCP_DEBUG) {
4518 vm_stop(EXCP_DEBUG);
4520 /* if hlt instruction, we wait until the next IRQ */
4521 /* XXX: use timeout computed from timers */
4522 if (ret == EXCP_HLT)
4523 timeout = 10;
4524 else
4525 timeout = 0;
4526 } else {
4527 timeout = 10;
4529 #ifdef CONFIG_PROFILER
4530 ti = profile_getclock();
4531 #endif
4532 main_loop_wait(timeout);
4533 #ifdef CONFIG_PROFILER
4534 dev_time += profile_getclock() - ti;
4535 #endif
4537 cpu_disable_ticks();
4538 return ret;
4541 void help(void)
4543 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4544 "usage: %s [options] [disk_image]\n"
4545 "\n"
4546 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4547 "\n"
4548 "Standard options:\n"
4549 "-M machine select emulated machine (-M ? for list)\n"
4550 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4551 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4552 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4553 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4554 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4555 "-snapshot write to temporary files instead of disk image files\n"
4556 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4557 "-smp n set the number of CPUs to 'n' [default=1]\n"
4558 "-nographic disable graphical output and redirect serial I/Os to console\n"
4559 #ifndef _WIN32
4560 "-k language use keyboard layout (for example \"fr\" for French)\n"
4561 #endif
4562 #ifdef HAS_AUDIO
4563 "-audio-help print list of audio drivers and their options\n"
4564 "-soundhw c1,... enable audio support\n"
4565 " and only specified sound cards (comma separated list)\n"
4566 " use -soundhw ? to get the list of supported cards\n"
4567 " use -soundhw all to enable all of them\n"
4568 #endif
4569 "-localtime set the real time clock to local time [default=utc]\n"
4570 "-full-screen start in full screen\n"
4571 #ifdef TARGET_I386
4572 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4573 #endif
4574 "-usb enable the USB driver (will be the default soon)\n"
4575 "-usbdevice name add the host or guest USB device 'name'\n"
4576 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4577 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4578 #endif
4579 "\n"
4580 "Network options:\n"
4581 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4582 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4583 #ifdef CONFIG_SLIRP
4584 "-net user[,vlan=n][,hostname=host]\n"
4585 " connect the user mode network stack to VLAN 'n' and send\n"
4586 " hostname 'host' to DHCP clients\n"
4587 #endif
4588 #ifdef _WIN32
4589 "-net tap[,vlan=n],ifname=name\n"
4590 " connect the host TAP network interface to VLAN 'n'\n"
4591 #else
4592 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4593 " connect the host TAP network interface to VLAN 'n' and use\n"
4594 " the network script 'file' (default=%s);\n"
4595 " use 'fd=h' to connect to an already opened TAP interface\n"
4596 #endif
4597 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4598 " connect the vlan 'n' to another VLAN using a socket connection\n"
4599 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4600 " connect the vlan 'n' to multicast maddr and port\n"
4601 "-net none use it alone to have zero network devices; if no -net option\n"
4602 " is provided, the default is '-net nic -net user'\n"
4603 "\n"
4604 #ifdef CONFIG_SLIRP
4605 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4606 #ifndef _WIN32
4607 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4608 #endif
4609 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4610 " redirect TCP or UDP connections from host to guest [-net user]\n"
4611 #endif
4612 "\n"
4613 "Linux boot specific:\n"
4614 "-kernel bzImage use 'bzImage' as kernel image\n"
4615 "-append cmdline use 'cmdline' as kernel command line\n"
4616 "-initrd file use 'file' as initial ram disk\n"
4617 "\n"
4618 "Debug/Expert options:\n"
4619 "-monitor dev redirect the monitor to char device 'dev'\n"
4620 "-serial dev redirect the serial port to char device 'dev'\n"
4621 "-parallel dev redirect the parallel port to char device 'dev'\n"
4622 "-pidfile file Write PID to 'file'\n"
4623 "-S freeze CPU at startup (use 'c' to start execution)\n"
4624 "-s wait gdb connection to port %d\n"
4625 "-p port change gdb connection port\n"
4626 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4627 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4628 " translation (t=none or lba) (usually qemu can guess them)\n"
4629 "-L path set the directory for the BIOS and VGA BIOS\n"
4630 #ifdef USE_KQEMU
4631 "-no-kqemu disable KQEMU kernel module usage\n"
4632 #endif
4633 #ifdef USE_CODE_COPY
4634 "-no-code-copy disable code copy acceleration\n"
4635 #endif
4636 #ifdef TARGET_I386
4637 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4638 " (default is CL-GD5446 PCI VGA)\n"
4639 #endif
4640 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4641 "\n"
4642 "During emulation, the following keys are useful:\n"
4643 "ctrl-alt-f toggle full screen\n"
4644 "ctrl-alt-n switch to virtual console 'n'\n"
4645 "ctrl-alt toggle mouse and keyboard grab\n"
4646 "\n"
4647 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4649 #ifdef CONFIG_SOFTMMU
4650 "qemu",
4651 #else
4652 "qemu-fast",
4653 #endif
4654 DEFAULT_RAM_SIZE,
4655 #ifndef _WIN32
4656 DEFAULT_NETWORK_SCRIPT,
4657 #endif
4658 DEFAULT_GDBSTUB_PORT,
4659 "/tmp/qemu.log");
4660 #ifndef CONFIG_SOFTMMU
4661 printf("\n"
4662 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4663 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4664 "PC emulation.\n");
4665 #endif
4666 exit(1);
4669 #define HAS_ARG 0x0001
4671 enum {
4672 QEMU_OPTION_h,
4674 QEMU_OPTION_M,
4675 QEMU_OPTION_fda,
4676 QEMU_OPTION_fdb,
4677 QEMU_OPTION_hda,
4678 QEMU_OPTION_hdb,
4679 QEMU_OPTION_hdc,
4680 QEMU_OPTION_hdd,
4681 QEMU_OPTION_cdrom,
4682 QEMU_OPTION_boot,
4683 QEMU_OPTION_snapshot,
4684 QEMU_OPTION_m,
4685 QEMU_OPTION_nographic,
4686 #ifdef HAS_AUDIO
4687 QEMU_OPTION_audio_help,
4688 QEMU_OPTION_soundhw,
4689 #endif
4691 QEMU_OPTION_net,
4692 QEMU_OPTION_tftp,
4693 QEMU_OPTION_smb,
4694 QEMU_OPTION_redir,
4696 QEMU_OPTION_kernel,
4697 QEMU_OPTION_append,
4698 QEMU_OPTION_initrd,
4700 QEMU_OPTION_S,
4701 QEMU_OPTION_s,
4702 QEMU_OPTION_p,
4703 QEMU_OPTION_d,
4704 QEMU_OPTION_hdachs,
4705 QEMU_OPTION_L,
4706 QEMU_OPTION_no_code_copy,
4707 QEMU_OPTION_k,
4708 QEMU_OPTION_localtime,
4709 QEMU_OPTION_cirrusvga,
4710 QEMU_OPTION_g,
4711 QEMU_OPTION_std_vga,
4712 QEMU_OPTION_monitor,
4713 QEMU_OPTION_serial,
4714 QEMU_OPTION_parallel,
4715 QEMU_OPTION_loadvm,
4716 QEMU_OPTION_full_screen,
4717 QEMU_OPTION_pidfile,
4718 QEMU_OPTION_no_kqemu,
4719 QEMU_OPTION_kernel_kqemu,
4720 QEMU_OPTION_win2k_hack,
4721 QEMU_OPTION_usb,
4722 QEMU_OPTION_usbdevice,
4723 QEMU_OPTION_smp,
4726 typedef struct QEMUOption {
4727 const char *name;
4728 int flags;
4729 int index;
4730 } QEMUOption;
4732 const QEMUOption qemu_options[] = {
4733 { "h", 0, QEMU_OPTION_h },
4735 { "M", HAS_ARG, QEMU_OPTION_M },
4736 { "fda", HAS_ARG, QEMU_OPTION_fda },
4737 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4738 { "hda", HAS_ARG, QEMU_OPTION_hda },
4739 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4740 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4741 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4742 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4743 { "boot", HAS_ARG, QEMU_OPTION_boot },
4744 { "snapshot", 0, QEMU_OPTION_snapshot },
4745 { "m", HAS_ARG, QEMU_OPTION_m },
4746 { "nographic", 0, QEMU_OPTION_nographic },
4747 { "k", HAS_ARG, QEMU_OPTION_k },
4748 #ifdef HAS_AUDIO
4749 { "audio-help", 0, QEMU_OPTION_audio_help },
4750 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4751 #endif
4753 { "net", HAS_ARG, QEMU_OPTION_net},
4754 #ifdef CONFIG_SLIRP
4755 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4756 #ifndef _WIN32
4757 { "smb", HAS_ARG, QEMU_OPTION_smb },
4758 #endif
4759 { "redir", HAS_ARG, QEMU_OPTION_redir },
4760 #endif
4762 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4763 { "append", HAS_ARG, QEMU_OPTION_append },
4764 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4766 { "S", 0, QEMU_OPTION_S },
4767 { "s", 0, QEMU_OPTION_s },
4768 { "p", HAS_ARG, QEMU_OPTION_p },
4769 { "d", HAS_ARG, QEMU_OPTION_d },
4770 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4771 { "L", HAS_ARG, QEMU_OPTION_L },
4772 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4773 #ifdef USE_KQEMU
4774 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4775 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4776 #endif
4777 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4778 { "g", 1, QEMU_OPTION_g },
4779 #endif
4780 { "localtime", 0, QEMU_OPTION_localtime },
4781 { "std-vga", 0, QEMU_OPTION_std_vga },
4782 { "monitor", 1, QEMU_OPTION_monitor },
4783 { "serial", 1, QEMU_OPTION_serial },
4784 { "parallel", 1, QEMU_OPTION_parallel },
4785 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4786 { "full-screen", 0, QEMU_OPTION_full_screen },
4787 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4788 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4789 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4790 { "smp", HAS_ARG, QEMU_OPTION_smp },
4792 /* temporary options */
4793 { "usb", 0, QEMU_OPTION_usb },
4794 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4795 { NULL },
4798 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4800 /* this stack is only used during signal handling */
4801 #define SIGNAL_STACK_SIZE 32768
4803 static uint8_t *signal_stack;
4805 #endif
4807 /* password input */
4809 static BlockDriverState *get_bdrv(int index)
4811 BlockDriverState *bs;
4813 if (index < 4) {
4814 bs = bs_table[index];
4815 } else if (index < 6) {
4816 bs = fd_table[index - 4];
4817 } else {
4818 bs = NULL;
4820 return bs;
4823 static void read_passwords(void)
4825 BlockDriverState *bs;
4826 int i, j;
4827 char password[256];
4829 for(i = 0; i < 6; i++) {
4830 bs = get_bdrv(i);
4831 if (bs && bdrv_is_encrypted(bs)) {
4832 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4833 for(j = 0; j < 3; j++) {
4834 monitor_readline("Password: ",
4835 1, password, sizeof(password));
4836 if (bdrv_set_key(bs, password) == 0)
4837 break;
4838 term_printf("invalid password\n");
4844 /* XXX: currently we cannot use simultaneously different CPUs */
4845 void register_machines(void)
4847 #if defined(TARGET_I386)
4848 qemu_register_machine(&pc_machine);
4849 qemu_register_machine(&isapc_machine);
4850 #elif defined(TARGET_PPC)
4851 qemu_register_machine(&heathrow_machine);
4852 qemu_register_machine(&core99_machine);
4853 qemu_register_machine(&prep_machine);
4854 #elif defined(TARGET_MIPS)
4855 qemu_register_machine(&mips_machine);
4856 #elif defined(TARGET_SPARC)
4857 #ifdef TARGET_SPARC64
4858 qemu_register_machine(&sun4u_machine);
4859 #else
4860 qemu_register_machine(&sun4m_machine);
4861 #endif
4862 #elif defined(TARGET_ARM)
4863 qemu_register_machine(&integratorcp926_machine);
4864 qemu_register_machine(&integratorcp1026_machine);
4865 qemu_register_machine(&versatilepb_machine);
4866 qemu_register_machine(&versatileab_machine);
4867 #elif defined(TARGET_SH4)
4868 qemu_register_machine(&shix_machine);
4869 #else
4870 #error unsupported CPU
4871 #endif
4874 #ifdef HAS_AUDIO
4875 struct soundhw soundhw[] = {
4876 #ifdef TARGET_I386
4878 "pcspk",
4879 "PC speaker",
4882 { .init_isa = pcspk_audio_init }
4884 #endif
4886 "sb16",
4887 "Creative Sound Blaster 16",
4890 { .init_isa = SB16_init }
4893 #ifdef CONFIG_ADLIB
4895 "adlib",
4896 #ifdef HAS_YMF262
4897 "Yamaha YMF262 (OPL3)",
4898 #else
4899 "Yamaha YM3812 (OPL2)",
4900 #endif
4903 { .init_isa = Adlib_init }
4905 #endif
4907 #ifdef CONFIG_GUS
4909 "gus",
4910 "Gravis Ultrasound GF1",
4913 { .init_isa = GUS_init }
4915 #endif
4918 "es1370",
4919 "ENSONIQ AudioPCI ES1370",
4922 { .init_pci = es1370_init }
4925 { NULL, NULL, 0, 0, { NULL } }
4928 static void select_soundhw (const char *optarg)
4930 struct soundhw *c;
4932 if (*optarg == '?') {
4933 show_valid_cards:
4935 printf ("Valid sound card names (comma separated):\n");
4936 for (c = soundhw; c->name; ++c) {
4937 printf ("%-11s %s\n", c->name, c->descr);
4939 printf ("\n-soundhw all will enable all of the above\n");
4940 exit (*optarg != '?');
4942 else {
4943 size_t l;
4944 const char *p;
4945 char *e;
4946 int bad_card = 0;
4948 if (!strcmp (optarg, "all")) {
4949 for (c = soundhw; c->name; ++c) {
4950 c->enabled = 1;
4952 return;
4955 p = optarg;
4956 while (*p) {
4957 e = strchr (p, ',');
4958 l = !e ? strlen (p) : (size_t) (e - p);
4960 for (c = soundhw; c->name; ++c) {
4961 if (!strncmp (c->name, p, l)) {
4962 c->enabled = 1;
4963 break;
4967 if (!c->name) {
4968 if (l > 80) {
4969 fprintf (stderr,
4970 "Unknown sound card name (too big to show)\n");
4972 else {
4973 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4974 (int) l, p);
4976 bad_card = 1;
4978 p += l + (e != NULL);
4981 if (bad_card)
4982 goto show_valid_cards;
4985 #endif
4987 #define MAX_NET_CLIENTS 32
4989 int main(int argc, char **argv)
4991 #ifdef CONFIG_GDBSTUB
4992 int use_gdbstub, gdbstub_port;
4993 #endif
4994 int i, cdrom_index;
4995 int snapshot, linux_boot;
4996 const char *initrd_filename;
4997 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4998 const char *kernel_filename, *kernel_cmdline;
4999 DisplayState *ds = &display_state;
5000 int cyls, heads, secs, translation;
5001 int start_emulation = 1;
5002 char net_clients[MAX_NET_CLIENTS][256];
5003 int nb_net_clients;
5004 int optind;
5005 const char *r, *optarg;
5006 CharDriverState *monitor_hd;
5007 char monitor_device[128];
5008 char serial_devices[MAX_SERIAL_PORTS][128];
5009 int serial_device_index;
5010 char parallel_devices[MAX_PARALLEL_PORTS][128];
5011 int parallel_device_index;
5012 const char *loadvm = NULL;
5013 QEMUMachine *machine;
5014 char usb_devices[MAX_VM_USB_PORTS][128];
5015 int usb_devices_index;
5017 LIST_INIT (&vm_change_state_head);
5018 #if !defined(CONFIG_SOFTMMU)
5019 /* we never want that malloc() uses mmap() */
5020 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5021 #endif
5022 register_machines();
5023 machine = first_machine;
5024 initrd_filename = NULL;
5025 for(i = 0; i < MAX_FD; i++)
5026 fd_filename[i] = NULL;
5027 for(i = 0; i < MAX_DISKS; i++)
5028 hd_filename[i] = NULL;
5029 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5030 vga_ram_size = VGA_RAM_SIZE;
5031 bios_size = BIOS_SIZE;
5032 #ifdef CONFIG_GDBSTUB
5033 use_gdbstub = 0;
5034 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5035 #endif
5036 snapshot = 0;
5037 nographic = 0;
5038 kernel_filename = NULL;
5039 kernel_cmdline = "";
5040 #ifdef TARGET_PPC
5041 cdrom_index = 1;
5042 #else
5043 cdrom_index = 2;
5044 #endif
5045 cyls = heads = secs = 0;
5046 translation = BIOS_ATA_TRANSLATION_AUTO;
5047 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5049 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5050 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5051 serial_devices[i][0] = '\0';
5052 serial_device_index = 0;
5054 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5055 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5056 parallel_devices[i][0] = '\0';
5057 parallel_device_index = 0;
5059 usb_devices_index = 0;
5061 nb_net_clients = 0;
5063 nb_nics = 0;
5064 /* default mac address of the first network interface */
5066 optind = 1;
5067 for(;;) {
5068 if (optind >= argc)
5069 break;
5070 r = argv[optind];
5071 if (r[0] != '-') {
5072 hd_filename[0] = argv[optind++];
5073 } else {
5074 const QEMUOption *popt;
5076 optind++;
5077 popt = qemu_options;
5078 for(;;) {
5079 if (!popt->name) {
5080 fprintf(stderr, "%s: invalid option -- '%s'\n",
5081 argv[0], r);
5082 exit(1);
5084 if (!strcmp(popt->name, r + 1))
5085 break;
5086 popt++;
5088 if (popt->flags & HAS_ARG) {
5089 if (optind >= argc) {
5090 fprintf(stderr, "%s: option '%s' requires an argument\n",
5091 argv[0], r);
5092 exit(1);
5094 optarg = argv[optind++];
5095 } else {
5096 optarg = NULL;
5099 switch(popt->index) {
5100 case QEMU_OPTION_M:
5101 machine = find_machine(optarg);
5102 if (!machine) {
5103 QEMUMachine *m;
5104 printf("Supported machines are:\n");
5105 for(m = first_machine; m != NULL; m = m->next) {
5106 printf("%-10s %s%s\n",
5107 m->name, m->desc,
5108 m == first_machine ? " (default)" : "");
5110 exit(1);
5112 break;
5113 case QEMU_OPTION_initrd:
5114 initrd_filename = optarg;
5115 break;
5116 case QEMU_OPTION_hda:
5117 case QEMU_OPTION_hdb:
5118 case QEMU_OPTION_hdc:
5119 case QEMU_OPTION_hdd:
5121 int hd_index;
5122 hd_index = popt->index - QEMU_OPTION_hda;
5123 hd_filename[hd_index] = optarg;
5124 if (hd_index == cdrom_index)
5125 cdrom_index = -1;
5127 break;
5128 case QEMU_OPTION_snapshot:
5129 snapshot = 1;
5130 break;
5131 case QEMU_OPTION_hdachs:
5133 const char *p;
5134 p = optarg;
5135 cyls = strtol(p, (char **)&p, 0);
5136 if (cyls < 1 || cyls > 16383)
5137 goto chs_fail;
5138 if (*p != ',')
5139 goto chs_fail;
5140 p++;
5141 heads = strtol(p, (char **)&p, 0);
5142 if (heads < 1 || heads > 16)
5143 goto chs_fail;
5144 if (*p != ',')
5145 goto chs_fail;
5146 p++;
5147 secs = strtol(p, (char **)&p, 0);
5148 if (secs < 1 || secs > 63)
5149 goto chs_fail;
5150 if (*p == ',') {
5151 p++;
5152 if (!strcmp(p, "none"))
5153 translation = BIOS_ATA_TRANSLATION_NONE;
5154 else if (!strcmp(p, "lba"))
5155 translation = BIOS_ATA_TRANSLATION_LBA;
5156 else if (!strcmp(p, "auto"))
5157 translation = BIOS_ATA_TRANSLATION_AUTO;
5158 else
5159 goto chs_fail;
5160 } else if (*p != '\0') {
5161 chs_fail:
5162 fprintf(stderr, "qemu: invalid physical CHS format\n");
5163 exit(1);
5166 break;
5167 case QEMU_OPTION_nographic:
5168 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5169 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5170 nographic = 1;
5171 break;
5172 case QEMU_OPTION_kernel:
5173 kernel_filename = optarg;
5174 break;
5175 case QEMU_OPTION_append:
5176 kernel_cmdline = optarg;
5177 break;
5178 case QEMU_OPTION_cdrom:
5179 if (cdrom_index >= 0) {
5180 hd_filename[cdrom_index] = optarg;
5182 break;
5183 case QEMU_OPTION_boot:
5184 boot_device = optarg[0];
5185 if (boot_device != 'a' &&
5186 #ifdef TARGET_SPARC
5187 // Network boot
5188 boot_device != 'n' &&
5189 #endif
5190 boot_device != 'c' && boot_device != 'd') {
5191 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5192 exit(1);
5194 break;
5195 case QEMU_OPTION_fda:
5196 fd_filename[0] = optarg;
5197 break;
5198 case QEMU_OPTION_fdb:
5199 fd_filename[1] = optarg;
5200 break;
5201 case QEMU_OPTION_no_code_copy:
5202 code_copy_enabled = 0;
5203 break;
5204 case QEMU_OPTION_net:
5205 if (nb_net_clients >= MAX_NET_CLIENTS) {
5206 fprintf(stderr, "qemu: too many network clients\n");
5207 exit(1);
5209 pstrcpy(net_clients[nb_net_clients],
5210 sizeof(net_clients[0]),
5211 optarg);
5212 nb_net_clients++;
5213 break;
5214 #ifdef CONFIG_SLIRP
5215 case QEMU_OPTION_tftp:
5216 tftp_prefix = optarg;
5217 break;
5218 #ifndef _WIN32
5219 case QEMU_OPTION_smb:
5220 net_slirp_smb(optarg);
5221 break;
5222 #endif
5223 case QEMU_OPTION_redir:
5224 net_slirp_redir(optarg);
5225 break;
5226 #endif
5227 #ifdef HAS_AUDIO
5228 case QEMU_OPTION_audio_help:
5229 AUD_help ();
5230 exit (0);
5231 break;
5232 case QEMU_OPTION_soundhw:
5233 select_soundhw (optarg);
5234 break;
5235 #endif
5236 case QEMU_OPTION_h:
5237 help();
5238 break;
5239 case QEMU_OPTION_m:
5240 ram_size = atoi(optarg) * 1024 * 1024;
5241 if (ram_size <= 0)
5242 help();
5243 if (ram_size > PHYS_RAM_MAX_SIZE) {
5244 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5245 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5246 exit(1);
5248 break;
5249 case QEMU_OPTION_d:
5251 int mask;
5252 CPULogItem *item;
5254 mask = cpu_str_to_log_mask(optarg);
5255 if (!mask) {
5256 printf("Log items (comma separated):\n");
5257 for(item = cpu_log_items; item->mask != 0; item++) {
5258 printf("%-10s %s\n", item->name, item->help);
5260 exit(1);
5262 cpu_set_log(mask);
5264 break;
5265 #ifdef CONFIG_GDBSTUB
5266 case QEMU_OPTION_s:
5267 use_gdbstub = 1;
5268 break;
5269 case QEMU_OPTION_p:
5270 gdbstub_port = atoi(optarg);
5271 break;
5272 #endif
5273 case QEMU_OPTION_L:
5274 bios_dir = optarg;
5275 break;
5276 case QEMU_OPTION_S:
5277 start_emulation = 0;
5278 break;
5279 case QEMU_OPTION_k:
5280 keyboard_layout = optarg;
5281 break;
5282 case QEMU_OPTION_localtime:
5283 rtc_utc = 0;
5284 break;
5285 case QEMU_OPTION_cirrusvga:
5286 cirrus_vga_enabled = 1;
5287 break;
5288 case QEMU_OPTION_std_vga:
5289 cirrus_vga_enabled = 0;
5290 break;
5291 case QEMU_OPTION_g:
5293 const char *p;
5294 int w, h, depth;
5295 p = optarg;
5296 w = strtol(p, (char **)&p, 10);
5297 if (w <= 0) {
5298 graphic_error:
5299 fprintf(stderr, "qemu: invalid resolution or depth\n");
5300 exit(1);
5302 if (*p != 'x')
5303 goto graphic_error;
5304 p++;
5305 h = strtol(p, (char **)&p, 10);
5306 if (h <= 0)
5307 goto graphic_error;
5308 if (*p == 'x') {
5309 p++;
5310 depth = strtol(p, (char **)&p, 10);
5311 if (depth != 8 && depth != 15 && depth != 16 &&
5312 depth != 24 && depth != 32)
5313 goto graphic_error;
5314 } else if (*p == '\0') {
5315 depth = graphic_depth;
5316 } else {
5317 goto graphic_error;
5320 graphic_width = w;
5321 graphic_height = h;
5322 graphic_depth = depth;
5324 break;
5325 case QEMU_OPTION_monitor:
5326 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5327 break;
5328 case QEMU_OPTION_serial:
5329 if (serial_device_index >= MAX_SERIAL_PORTS) {
5330 fprintf(stderr, "qemu: too many serial ports\n");
5331 exit(1);
5333 pstrcpy(serial_devices[serial_device_index],
5334 sizeof(serial_devices[0]), optarg);
5335 serial_device_index++;
5336 break;
5337 case QEMU_OPTION_parallel:
5338 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5339 fprintf(stderr, "qemu: too many parallel ports\n");
5340 exit(1);
5342 pstrcpy(parallel_devices[parallel_device_index],
5343 sizeof(parallel_devices[0]), optarg);
5344 parallel_device_index++;
5345 break;
5346 case QEMU_OPTION_loadvm:
5347 loadvm = optarg;
5348 break;
5349 case QEMU_OPTION_full_screen:
5350 full_screen = 1;
5351 break;
5352 case QEMU_OPTION_pidfile:
5353 create_pidfile(optarg);
5354 break;
5355 #ifdef TARGET_I386
5356 case QEMU_OPTION_win2k_hack:
5357 win2k_install_hack = 1;
5358 break;
5359 #endif
5360 #ifdef USE_KQEMU
5361 case QEMU_OPTION_no_kqemu:
5362 kqemu_allowed = 0;
5363 break;
5364 case QEMU_OPTION_kernel_kqemu:
5365 kqemu_allowed = 2;
5366 break;
5367 #endif
5368 case QEMU_OPTION_usb:
5369 usb_enabled = 1;
5370 break;
5371 case QEMU_OPTION_usbdevice:
5372 usb_enabled = 1;
5373 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5374 fprintf(stderr, "Too many USB devices\n");
5375 exit(1);
5377 pstrcpy(usb_devices[usb_devices_index],
5378 sizeof(usb_devices[usb_devices_index]),
5379 optarg);
5380 usb_devices_index++;
5381 break;
5382 case QEMU_OPTION_smp:
5383 smp_cpus = atoi(optarg);
5384 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5385 fprintf(stderr, "Invalid number of CPUs\n");
5386 exit(1);
5388 break;
5393 #ifdef USE_KQEMU
5394 if (smp_cpus > 1)
5395 kqemu_allowed = 0;
5396 #endif
5397 linux_boot = (kernel_filename != NULL);
5399 if (!linux_boot &&
5400 hd_filename[0] == '\0' &&
5401 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5402 fd_filename[0] == '\0')
5403 help();
5405 /* boot to cd by default if no hard disk */
5406 if (hd_filename[0] == '\0' && boot_device == 'c') {
5407 if (fd_filename[0] != '\0')
5408 boot_device = 'a';
5409 else
5410 boot_device = 'd';
5413 #if !defined(CONFIG_SOFTMMU)
5414 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5416 static uint8_t stdout_buf[4096];
5417 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5419 #else
5420 setvbuf(stdout, NULL, _IOLBF, 0);
5421 #endif
5423 #ifdef _WIN32
5424 socket_init();
5425 #endif
5427 /* init network clients */
5428 if (nb_net_clients == 0) {
5429 /* if no clients, we use a default config */
5430 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5431 "nic");
5432 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5433 "user");
5434 nb_net_clients = 2;
5437 for(i = 0;i < nb_net_clients; i++) {
5438 if (net_client_init(net_clients[i]) < 0)
5439 exit(1);
5442 /* init the memory */
5443 phys_ram_size = ram_size + vga_ram_size + bios_size;
5445 #ifdef CONFIG_SOFTMMU
5446 phys_ram_base = qemu_vmalloc(phys_ram_size);
5447 if (!phys_ram_base) {
5448 fprintf(stderr, "Could not allocate physical memory\n");
5449 exit(1);
5451 #else
5452 /* as we must map the same page at several addresses, we must use
5453 a fd */
5455 const char *tmpdir;
5457 tmpdir = getenv("QEMU_TMPDIR");
5458 if (!tmpdir)
5459 tmpdir = "/tmp";
5460 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5461 if (mkstemp(phys_ram_file) < 0) {
5462 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5463 phys_ram_file);
5464 exit(1);
5466 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5467 if (phys_ram_fd < 0) {
5468 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5469 phys_ram_file);
5470 exit(1);
5472 ftruncate(phys_ram_fd, phys_ram_size);
5473 unlink(phys_ram_file);
5474 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5475 phys_ram_size,
5476 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5477 phys_ram_fd, 0);
5478 if (phys_ram_base == MAP_FAILED) {
5479 fprintf(stderr, "Could not map physical memory\n");
5480 exit(1);
5483 #endif
5485 /* we always create the cdrom drive, even if no disk is there */
5486 bdrv_init();
5487 if (cdrom_index >= 0) {
5488 bs_table[cdrom_index] = bdrv_new("cdrom");
5489 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5492 /* open the virtual block devices */
5493 for(i = 0; i < MAX_DISKS; i++) {
5494 if (hd_filename[i]) {
5495 if (!bs_table[i]) {
5496 char buf[64];
5497 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5498 bs_table[i] = bdrv_new(buf);
5500 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5501 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5502 hd_filename[i]);
5503 exit(1);
5505 if (i == 0 && cyls != 0) {
5506 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5507 bdrv_set_translation_hint(bs_table[i], translation);
5512 /* we always create at least one floppy disk */
5513 fd_table[0] = bdrv_new("fda");
5514 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5516 for(i = 0; i < MAX_FD; i++) {
5517 if (fd_filename[i]) {
5518 if (!fd_table[i]) {
5519 char buf[64];
5520 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5521 fd_table[i] = bdrv_new(buf);
5522 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5524 if (fd_filename[i] != '\0') {
5525 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5526 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5527 fd_filename[i]);
5528 exit(1);
5534 /* init USB devices */
5535 if (usb_enabled) {
5536 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5537 for(i = 0; i < usb_devices_index; i++) {
5538 if (usb_device_add(usb_devices[i]) < 0) {
5539 fprintf(stderr, "Warning: could not add USB device %s\n",
5540 usb_devices[i]);
5545 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5546 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5548 init_ioports();
5549 cpu_calibrate_ticks();
5551 /* terminal init */
5552 if (nographic) {
5553 dumb_display_init(ds);
5554 } else {
5555 #if defined(CONFIG_SDL)
5556 sdl_display_init(ds, full_screen);
5557 #elif defined(CONFIG_COCOA)
5558 cocoa_display_init(ds, full_screen);
5559 #else
5560 dumb_display_init(ds);
5561 #endif
5564 monitor_hd = qemu_chr_open(monitor_device);
5565 if (!monitor_hd) {
5566 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5567 exit(1);
5569 monitor_init(monitor_hd, !nographic);
5571 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5572 if (serial_devices[i][0] != '\0') {
5573 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5574 if (!serial_hds[i]) {
5575 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5576 serial_devices[i]);
5577 exit(1);
5579 if (!strcmp(serial_devices[i], "vc"))
5580 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5584 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5585 if (parallel_devices[i][0] != '\0') {
5586 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5587 if (!parallel_hds[i]) {
5588 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5589 parallel_devices[i]);
5590 exit(1);
5592 if (!strcmp(parallel_devices[i], "vc"))
5593 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5597 /* setup cpu signal handlers for MMU / self modifying code handling */
5598 #if !defined(CONFIG_SOFTMMU)
5600 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5602 stack_t stk;
5603 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5604 stk.ss_sp = signal_stack;
5605 stk.ss_size = SIGNAL_STACK_SIZE;
5606 stk.ss_flags = 0;
5608 if (sigaltstack(&stk, NULL) < 0) {
5609 perror("sigaltstack");
5610 exit(1);
5613 #endif
5615 struct sigaction act;
5617 sigfillset(&act.sa_mask);
5618 act.sa_flags = SA_SIGINFO;
5619 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5620 act.sa_flags |= SA_ONSTACK;
5621 #endif
5622 act.sa_sigaction = host_segv_handler;
5623 sigaction(SIGSEGV, &act, NULL);
5624 sigaction(SIGBUS, &act, NULL);
5625 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5626 sigaction(SIGFPE, &act, NULL);
5627 #endif
5629 #endif
5631 #ifndef _WIN32
5633 struct sigaction act;
5634 sigfillset(&act.sa_mask);
5635 act.sa_flags = 0;
5636 act.sa_handler = SIG_IGN;
5637 sigaction(SIGPIPE, &act, NULL);
5639 #endif
5640 init_timers();
5642 machine->init(ram_size, vga_ram_size, boot_device,
5643 ds, fd_filename, snapshot,
5644 kernel_filename, kernel_cmdline, initrd_filename);
5646 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5647 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5649 #ifdef CONFIG_GDBSTUB
5650 if (use_gdbstub) {
5651 if (gdbserver_start(gdbstub_port) < 0) {
5652 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5653 gdbstub_port);
5654 exit(1);
5655 } else {
5656 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5658 } else
5659 #endif
5660 if (loadvm)
5661 qemu_loadvm(loadvm);
5664 /* XXX: simplify init */
5665 read_passwords();
5666 if (start_emulation) {
5667 vm_start();
5670 main_loop();
5671 quit_timers();
5672 return 0;