mouse API change
[qemu/mini2440.git] / vl.c
blob8fba6e76eeef53951d40fef41818ce29902c928c
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 #include <linux/if.h>
51 #include <linux/if_tun.h>
52 #include <pty.h>
53 #include <malloc.h>
54 #include <linux/rtc.h>
55 #include <linux/ppdev.h>
56 #endif
57 #endif
59 #if defined(CONFIG_SLIRP)
60 #include "libslirp.h"
61 #endif
63 #ifdef _WIN32
64 #include <malloc.h>
65 #include <sys/timeb.h>
66 #include <windows.h>
67 #include <winsock2.h>
68 #include <ws2tcpip.h>
69 #define getopt_long_only getopt_long
70 #define memalign(align, size) malloc(size)
71 #endif
73 #ifdef CONFIG_SDL
74 #ifdef __APPLE__
75 #include <SDL/SDL.h>
76 #endif
77 #endif /* CONFIG_SDL */
79 #ifdef CONFIG_COCOA
80 #undef main
81 #define main qemu_main
82 #endif /* CONFIG_COCOA */
84 #include "disas.h"
86 #include "exec-all.h"
88 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
90 //#define DEBUG_UNUSED_IOPORT
91 //#define DEBUG_IOPORT
93 #if !defined(CONFIG_SOFTMMU)
94 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
95 #else
96 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
97 #endif
99 #ifdef TARGET_PPC
100 #define DEFAULT_RAM_SIZE 144
101 #else
102 #define DEFAULT_RAM_SIZE 128
103 #endif
104 /* in ms */
105 #define GUI_REFRESH_INTERVAL 30
107 /* XXX: use a two level table to limit memory usage */
108 #define MAX_IOPORTS 65536
110 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
111 char phys_ram_file[1024];
112 void *ioport_opaque[MAX_IOPORTS];
113 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
114 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
115 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
116 int vga_ram_size;
117 int bios_size;
118 static DisplayState display_state;
119 int nographic;
120 const char* keyboard_layout = NULL;
121 int64_t ticks_per_sec;
122 int boot_device = 'c';
123 int ram_size;
124 int pit_min_timer_count = 0;
125 int nb_nics;
126 NICInfo nd_table[MAX_NICS];
127 QEMUTimer *gui_timer;
128 int vm_running;
129 int rtc_utc = 1;
130 int cirrus_vga_enabled = 1;
131 #ifdef TARGET_SPARC
132 int graphic_width = 1024;
133 int graphic_height = 768;
134 #else
135 int graphic_width = 800;
136 int graphic_height = 600;
137 #endif
138 int graphic_depth = 15;
139 int full_screen = 0;
140 CharDriverState *serial_hds[MAX_SERIAL_PORTS];
141 CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
142 #ifdef TARGET_I386
143 int win2k_install_hack = 0;
144 #endif
145 int usb_enabled = 0;
146 USBPort *vm_usb_ports[MAX_VM_USB_PORTS];
147 USBDevice *vm_usb_hub;
148 static VLANState *first_vlan;
149 int smp_cpus = 1;
150 #if defined(TARGET_SPARC)
151 #define MAX_CPUS 16
152 #elif defined(TARGET_I386)
153 #define MAX_CPUS 255
154 #else
155 #define MAX_CPUS 1
156 #endif
158 /***********************************************************/
159 /* x86 ISA bus support */
161 target_phys_addr_t isa_mem_base = 0;
162 PicState2 *isa_pic;
164 uint32_t default_ioport_readb(void *opaque, uint32_t address)
166 #ifdef DEBUG_UNUSED_IOPORT
167 fprintf(stderr, "inb: port=0x%04x\n", address);
168 #endif
169 return 0xff;
172 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
174 #ifdef DEBUG_UNUSED_IOPORT
175 fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
176 #endif
179 /* default is to make two byte accesses */
180 uint32_t default_ioport_readw(void *opaque, uint32_t address)
182 uint32_t data;
183 data = ioport_read_table[0][address](ioport_opaque[address], address);
184 address = (address + 1) & (MAX_IOPORTS - 1);
185 data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
186 return data;
189 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
191 ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
192 address = (address + 1) & (MAX_IOPORTS - 1);
193 ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
196 uint32_t default_ioport_readl(void *opaque, uint32_t address)
198 #ifdef DEBUG_UNUSED_IOPORT
199 fprintf(stderr, "inl: port=0x%04x\n", address);
200 #endif
201 return 0xffffffff;
204 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
206 #ifdef DEBUG_UNUSED_IOPORT
207 fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
208 #endif
211 void init_ioports(void)
213 int i;
215 for(i = 0; i < MAX_IOPORTS; i++) {
216 ioport_read_table[0][i] = default_ioport_readb;
217 ioport_write_table[0][i] = default_ioport_writeb;
218 ioport_read_table[1][i] = default_ioport_readw;
219 ioport_write_table[1][i] = default_ioport_writew;
220 ioport_read_table[2][i] = default_ioport_readl;
221 ioport_write_table[2][i] = default_ioport_writel;
225 /* size is the word size in byte */
226 int register_ioport_read(int start, int length, int size,
227 IOPortReadFunc *func, void *opaque)
229 int i, bsize;
231 if (size == 1) {
232 bsize = 0;
233 } else if (size == 2) {
234 bsize = 1;
235 } else if (size == 4) {
236 bsize = 2;
237 } else {
238 hw_error("register_ioport_read: invalid size");
239 return -1;
241 for(i = start; i < start + length; i += size) {
242 ioport_read_table[bsize][i] = func;
243 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
244 hw_error("register_ioport_read: invalid opaque");
245 ioport_opaque[i] = opaque;
247 return 0;
250 /* size is the word size in byte */
251 int register_ioport_write(int start, int length, int size,
252 IOPortWriteFunc *func, void *opaque)
254 int i, bsize;
256 if (size == 1) {
257 bsize = 0;
258 } else if (size == 2) {
259 bsize = 1;
260 } else if (size == 4) {
261 bsize = 2;
262 } else {
263 hw_error("register_ioport_write: invalid size");
264 return -1;
266 for(i = start; i < start + length; i += size) {
267 ioport_write_table[bsize][i] = func;
268 if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
269 hw_error("register_ioport_read: invalid opaque");
270 ioport_opaque[i] = opaque;
272 return 0;
275 void isa_unassign_ioport(int start, int length)
277 int i;
279 for(i = start; i < start + length; i++) {
280 ioport_read_table[0][i] = default_ioport_readb;
281 ioport_read_table[1][i] = default_ioport_readw;
282 ioport_read_table[2][i] = default_ioport_readl;
284 ioport_write_table[0][i] = default_ioport_writeb;
285 ioport_write_table[1][i] = default_ioport_writew;
286 ioport_write_table[2][i] = default_ioport_writel;
290 /***********************************************************/
292 void pstrcpy(char *buf, int buf_size, const char *str)
294 int c;
295 char *q = buf;
297 if (buf_size <= 0)
298 return;
300 for(;;) {
301 c = *str++;
302 if (c == 0 || q >= buf + buf_size - 1)
303 break;
304 *q++ = c;
306 *q = '\0';
309 /* strcat and truncate. */
310 char *pstrcat(char *buf, int buf_size, const char *s)
312 int len;
313 len = strlen(buf);
314 if (len < buf_size)
315 pstrcpy(buf + len, buf_size - len, s);
316 return buf;
319 int strstart(const char *str, const char *val, const char **ptr)
321 const char *p, *q;
322 p = str;
323 q = val;
324 while (*q != '\0') {
325 if (*p != *q)
326 return 0;
327 p++;
328 q++;
330 if (ptr)
331 *ptr = p;
332 return 1;
335 /* return the size or -1 if error */
336 int get_image_size(const char *filename)
338 int fd, size;
339 fd = open(filename, O_RDONLY | O_BINARY);
340 if (fd < 0)
341 return -1;
342 size = lseek(fd, 0, SEEK_END);
343 close(fd);
344 return size;
347 /* return the size or -1 if error */
348 int load_image(const char *filename, uint8_t *addr)
350 int fd, size;
351 fd = open(filename, O_RDONLY | O_BINARY);
352 if (fd < 0)
353 return -1;
354 size = lseek(fd, 0, SEEK_END);
355 lseek(fd, 0, SEEK_SET);
356 if (read(fd, addr, size) != size) {
357 close(fd);
358 return -1;
360 close(fd);
361 return size;
364 void cpu_outb(CPUState *env, int addr, int val)
366 #ifdef DEBUG_IOPORT
367 if (loglevel & CPU_LOG_IOPORT)
368 fprintf(logfile, "outb: %04x %02x\n", addr, val);
369 #endif
370 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
371 #ifdef USE_KQEMU
372 if (env)
373 env->last_io_time = cpu_get_time_fast();
374 #endif
377 void cpu_outw(CPUState *env, int addr, int val)
379 #ifdef DEBUG_IOPORT
380 if (loglevel & CPU_LOG_IOPORT)
381 fprintf(logfile, "outw: %04x %04x\n", addr, val);
382 #endif
383 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
384 #ifdef USE_KQEMU
385 if (env)
386 env->last_io_time = cpu_get_time_fast();
387 #endif
390 void cpu_outl(CPUState *env, int addr, int val)
392 #ifdef DEBUG_IOPORT
393 if (loglevel & CPU_LOG_IOPORT)
394 fprintf(logfile, "outl: %04x %08x\n", addr, val);
395 #endif
396 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
403 int cpu_inb(CPUState *env, int addr)
405 int val;
406 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
407 #ifdef DEBUG_IOPORT
408 if (loglevel & CPU_LOG_IOPORT)
409 fprintf(logfile, "inb : %04x %02x\n", addr, val);
410 #endif
411 #ifdef USE_KQEMU
412 if (env)
413 env->last_io_time = cpu_get_time_fast();
414 #endif
415 return val;
418 int cpu_inw(CPUState *env, int addr)
420 int val;
421 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
422 #ifdef DEBUG_IOPORT
423 if (loglevel & CPU_LOG_IOPORT)
424 fprintf(logfile, "inw : %04x %04x\n", addr, val);
425 #endif
426 #ifdef USE_KQEMU
427 if (env)
428 env->last_io_time = cpu_get_time_fast();
429 #endif
430 return val;
433 int cpu_inl(CPUState *env, int addr)
435 int val;
436 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
437 #ifdef DEBUG_IOPORT
438 if (loglevel & CPU_LOG_IOPORT)
439 fprintf(logfile, "inl : %04x %08x\n", addr, val);
440 #endif
441 #ifdef USE_KQEMU
442 if (env)
443 env->last_io_time = cpu_get_time_fast();
444 #endif
445 return val;
448 /***********************************************************/
449 void hw_error(const char *fmt, ...)
451 va_list ap;
452 CPUState *env;
454 va_start(ap, fmt);
455 fprintf(stderr, "qemu: hardware error: ");
456 vfprintf(stderr, fmt, ap);
457 fprintf(stderr, "\n");
458 for(env = first_cpu; env != NULL; env = env->next_cpu) {
459 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
460 #ifdef TARGET_I386
461 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
462 #else
463 cpu_dump_state(env, stderr, fprintf, 0);
464 #endif
466 va_end(ap);
467 abort();
470 /***********************************************************/
471 /* keyboard/mouse */
473 static QEMUPutKBDEvent *qemu_put_kbd_event;
474 static void *qemu_put_kbd_event_opaque;
475 static QEMUPutMouseEvent *qemu_put_mouse_event;
476 static void *qemu_put_mouse_event_opaque;
477 static int qemu_put_mouse_event_absolute;
479 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
481 qemu_put_kbd_event_opaque = opaque;
482 qemu_put_kbd_event = func;
485 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
487 qemu_put_mouse_event_opaque = opaque;
488 qemu_put_mouse_event = func;
489 qemu_put_mouse_event_absolute = absolute;
492 void kbd_put_keycode(int keycode)
494 if (qemu_put_kbd_event) {
495 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
499 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
501 if (qemu_put_mouse_event) {
502 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
503 dx, dy, dz, buttons_state);
507 int kbd_mouse_is_absolute(void)
509 return qemu_put_mouse_event_absolute;
512 /***********************************************************/
513 /* timers */
515 #if defined(__powerpc__)
517 static inline uint32_t get_tbl(void)
519 uint32_t tbl;
520 asm volatile("mftb %0" : "=r" (tbl));
521 return tbl;
524 static inline uint32_t get_tbu(void)
526 uint32_t tbl;
527 asm volatile("mftbu %0" : "=r" (tbl));
528 return tbl;
531 int64_t cpu_get_real_ticks(void)
533 uint32_t l, h, h1;
534 /* NOTE: we test if wrapping has occurred */
535 do {
536 h = get_tbu();
537 l = get_tbl();
538 h1 = get_tbu();
539 } while (h != h1);
540 return ((int64_t)h << 32) | l;
543 #elif defined(__i386__)
545 int64_t cpu_get_real_ticks(void)
547 int64_t val;
548 asm volatile ("rdtsc" : "=A" (val));
549 return val;
552 #elif defined(__x86_64__)
554 int64_t cpu_get_real_ticks(void)
556 uint32_t low,high;
557 int64_t val;
558 asm volatile("rdtsc" : "=a" (low), "=d" (high));
559 val = high;
560 val <<= 32;
561 val |= low;
562 return val;
565 #elif defined(__ia64)
567 int64_t cpu_get_real_ticks(void)
569 int64_t val;
570 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
571 return val;
574 #elif defined(__s390__)
576 int64_t cpu_get_real_ticks(void)
578 int64_t val;
579 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
580 return val;
583 #else
584 #error unsupported CPU
585 #endif
587 static int64_t cpu_ticks_offset;
588 static int cpu_ticks_enabled;
590 static inline int64_t cpu_get_ticks(void)
592 if (!cpu_ticks_enabled) {
593 return cpu_ticks_offset;
594 } else {
595 return cpu_get_real_ticks() + cpu_ticks_offset;
599 /* enable cpu_get_ticks() */
600 void cpu_enable_ticks(void)
602 if (!cpu_ticks_enabled) {
603 cpu_ticks_offset -= cpu_get_real_ticks();
604 cpu_ticks_enabled = 1;
608 /* disable cpu_get_ticks() : the clock is stopped. You must not call
609 cpu_get_ticks() after that. */
610 void cpu_disable_ticks(void)
612 if (cpu_ticks_enabled) {
613 cpu_ticks_offset = cpu_get_ticks();
614 cpu_ticks_enabled = 0;
618 static int64_t get_clock(void)
620 #ifdef _WIN32
621 struct _timeb tb;
622 _ftime(&tb);
623 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
624 #else
625 struct timeval tv;
626 gettimeofday(&tv, NULL);
627 return tv.tv_sec * 1000000LL + tv.tv_usec;
628 #endif
631 void cpu_calibrate_ticks(void)
633 int64_t usec, ticks;
635 usec = get_clock();
636 ticks = cpu_get_real_ticks();
637 #ifdef _WIN32
638 Sleep(50);
639 #else
640 usleep(50 * 1000);
641 #endif
642 usec = get_clock() - usec;
643 ticks = cpu_get_real_ticks() - ticks;
644 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
647 /* compute with 96 bit intermediate result: (a*b)/c */
648 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
650 union {
651 uint64_t ll;
652 struct {
653 #ifdef WORDS_BIGENDIAN
654 uint32_t high, low;
655 #else
656 uint32_t low, high;
657 #endif
658 } l;
659 } u, res;
660 uint64_t rl, rh;
662 u.ll = a;
663 rl = (uint64_t)u.l.low * (uint64_t)b;
664 rh = (uint64_t)u.l.high * (uint64_t)b;
665 rh += (rl >> 32);
666 res.l.high = rh / c;
667 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
668 return res.ll;
671 #define QEMU_TIMER_REALTIME 0
672 #define QEMU_TIMER_VIRTUAL 1
674 struct QEMUClock {
675 int type;
676 /* XXX: add frequency */
679 struct QEMUTimer {
680 QEMUClock *clock;
681 int64_t expire_time;
682 QEMUTimerCB *cb;
683 void *opaque;
684 struct QEMUTimer *next;
687 QEMUClock *rt_clock;
688 QEMUClock *vm_clock;
690 static QEMUTimer *active_timers[2];
691 #ifdef _WIN32
692 static MMRESULT timerID;
693 #else
694 /* frequency of the times() clock tick */
695 static int timer_freq;
696 #endif
698 QEMUClock *qemu_new_clock(int type)
700 QEMUClock *clock;
701 clock = qemu_mallocz(sizeof(QEMUClock));
702 if (!clock)
703 return NULL;
704 clock->type = type;
705 return clock;
708 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
710 QEMUTimer *ts;
712 ts = qemu_mallocz(sizeof(QEMUTimer));
713 ts->clock = clock;
714 ts->cb = cb;
715 ts->opaque = opaque;
716 return ts;
719 void qemu_free_timer(QEMUTimer *ts)
721 qemu_free(ts);
724 /* stop a timer, but do not dealloc it */
725 void qemu_del_timer(QEMUTimer *ts)
727 QEMUTimer **pt, *t;
729 /* NOTE: this code must be signal safe because
730 qemu_timer_expired() can be called from a signal. */
731 pt = &active_timers[ts->clock->type];
732 for(;;) {
733 t = *pt;
734 if (!t)
735 break;
736 if (t == ts) {
737 *pt = t->next;
738 break;
740 pt = &t->next;
744 /* modify the current timer so that it will be fired when current_time
745 >= expire_time. The corresponding callback will be called. */
746 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
748 QEMUTimer **pt, *t;
750 qemu_del_timer(ts);
752 /* add the timer in the sorted list */
753 /* NOTE: this code must be signal safe because
754 qemu_timer_expired() can be called from a signal. */
755 pt = &active_timers[ts->clock->type];
756 for(;;) {
757 t = *pt;
758 if (!t)
759 break;
760 if (t->expire_time > expire_time)
761 break;
762 pt = &t->next;
764 ts->expire_time = expire_time;
765 ts->next = *pt;
766 *pt = ts;
769 int qemu_timer_pending(QEMUTimer *ts)
771 QEMUTimer *t;
772 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
773 if (t == ts)
774 return 1;
776 return 0;
779 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
781 if (!timer_head)
782 return 0;
783 return (timer_head->expire_time <= current_time);
786 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
788 QEMUTimer *ts;
790 for(;;) {
791 ts = *ptimer_head;
792 if (!ts || ts->expire_time > current_time)
793 break;
794 /* remove timer from the list before calling the callback */
795 *ptimer_head = ts->next;
796 ts->next = NULL;
798 /* run the callback (the timer list can be modified) */
799 ts->cb(ts->opaque);
803 int64_t qemu_get_clock(QEMUClock *clock)
805 switch(clock->type) {
806 case QEMU_TIMER_REALTIME:
807 #ifdef _WIN32
808 return GetTickCount();
809 #else
811 struct tms tp;
813 /* Note that using gettimeofday() is not a good solution
814 for timers because its value change when the date is
815 modified. */
816 if (timer_freq == 100) {
817 return times(&tp) * 10;
818 } else {
819 return ((int64_t)times(&tp) * 1000) / timer_freq;
822 #endif
823 default:
824 case QEMU_TIMER_VIRTUAL:
825 return cpu_get_ticks();
829 /* save a timer */
830 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
832 uint64_t expire_time;
834 if (qemu_timer_pending(ts)) {
835 expire_time = ts->expire_time;
836 } else {
837 expire_time = -1;
839 qemu_put_be64(f, expire_time);
842 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
844 uint64_t expire_time;
846 expire_time = qemu_get_be64(f);
847 if (expire_time != -1) {
848 qemu_mod_timer(ts, expire_time);
849 } else {
850 qemu_del_timer(ts);
854 static void timer_save(QEMUFile *f, void *opaque)
856 if (cpu_ticks_enabled) {
857 hw_error("cannot save state if virtual timers are running");
859 qemu_put_be64s(f, &cpu_ticks_offset);
860 qemu_put_be64s(f, &ticks_per_sec);
863 static int timer_load(QEMUFile *f, void *opaque, int version_id)
865 if (version_id != 1)
866 return -EINVAL;
867 if (cpu_ticks_enabled) {
868 return -EINVAL;
870 qemu_get_be64s(f, &cpu_ticks_offset);
871 qemu_get_be64s(f, &ticks_per_sec);
872 return 0;
875 #ifdef _WIN32
876 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
877 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
878 #else
879 static void host_alarm_handler(int host_signum)
880 #endif
882 #if 0
883 #define DISP_FREQ 1000
885 static int64_t delta_min = INT64_MAX;
886 static int64_t delta_max, delta_cum, last_clock, delta, ti;
887 static int count;
888 ti = qemu_get_clock(vm_clock);
889 if (last_clock != 0) {
890 delta = ti - last_clock;
891 if (delta < delta_min)
892 delta_min = delta;
893 if (delta > delta_max)
894 delta_max = delta;
895 delta_cum += delta;
896 if (++count == DISP_FREQ) {
897 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
898 muldiv64(delta_min, 1000000, ticks_per_sec),
899 muldiv64(delta_max, 1000000, ticks_per_sec),
900 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
901 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
902 count = 0;
903 delta_min = INT64_MAX;
904 delta_max = 0;
905 delta_cum = 0;
908 last_clock = ti;
910 #endif
911 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
912 qemu_get_clock(vm_clock)) ||
913 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
914 qemu_get_clock(rt_clock))) {
915 CPUState *env = cpu_single_env;
916 if (env) {
917 /* stop the currently executing cpu because a timer occured */
918 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
919 #ifdef USE_KQEMU
920 if (env->kqemu_enabled) {
921 kqemu_cpu_interrupt(env);
923 #endif
928 #ifndef _WIN32
930 #if defined(__linux__)
932 #define RTC_FREQ 1024
934 static int rtc_fd;
936 static int start_rtc_timer(void)
938 rtc_fd = open("/dev/rtc", O_RDONLY);
939 if (rtc_fd < 0)
940 return -1;
941 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
942 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
943 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
944 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
945 goto fail;
947 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
948 fail:
949 close(rtc_fd);
950 return -1;
952 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
953 return 0;
956 #else
958 static int start_rtc_timer(void)
960 return -1;
963 #endif /* !defined(__linux__) */
965 #endif /* !defined(_WIN32) */
967 static void init_timers(void)
969 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
970 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
972 #ifdef _WIN32
974 int count=0;
975 timerID = timeSetEvent(1, // interval (ms)
976 0, // resolution
977 host_alarm_handler, // function
978 (DWORD)&count, // user parameter
979 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
980 if( !timerID ) {
981 perror("failed timer alarm");
982 exit(1);
985 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
986 #else
988 struct sigaction act;
989 struct itimerval itv;
991 /* get times() syscall frequency */
992 timer_freq = sysconf(_SC_CLK_TCK);
994 /* timer signal */
995 sigfillset(&act.sa_mask);
996 act.sa_flags = 0;
997 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
998 act.sa_flags |= SA_ONSTACK;
999 #endif
1000 act.sa_handler = host_alarm_handler;
1001 sigaction(SIGALRM, &act, NULL);
1003 itv.it_interval.tv_sec = 0;
1004 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1005 itv.it_value.tv_sec = 0;
1006 itv.it_value.tv_usec = 10 * 1000;
1007 setitimer(ITIMER_REAL, &itv, NULL);
1008 /* we probe the tick duration of the kernel to inform the user if
1009 the emulated kernel requested a too high timer frequency */
1010 getitimer(ITIMER_REAL, &itv);
1012 #if defined(__linux__)
1013 if (itv.it_interval.tv_usec > 1000) {
1014 /* try to use /dev/rtc to have a faster timer */
1015 if (start_rtc_timer() < 0)
1016 goto use_itimer;
1017 /* disable itimer */
1018 itv.it_interval.tv_sec = 0;
1019 itv.it_interval.tv_usec = 0;
1020 itv.it_value.tv_sec = 0;
1021 itv.it_value.tv_usec = 0;
1022 setitimer(ITIMER_REAL, &itv, NULL);
1024 /* use the RTC */
1025 sigaction(SIGIO, &act, NULL);
1026 fcntl(rtc_fd, F_SETFL, O_ASYNC);
1027 fcntl(rtc_fd, F_SETOWN, getpid());
1028 } else
1029 #endif /* defined(__linux__) */
1031 use_itimer:
1032 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1033 PIT_FREQ) / 1000000;
1036 #endif
1039 void quit_timers(void)
1041 #ifdef _WIN32
1042 timeKillEvent(timerID);
1043 #endif
1046 /***********************************************************/
1047 /* character device */
1049 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1051 return s->chr_write(s, buf, len);
1054 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1056 if (!s->chr_ioctl)
1057 return -ENOTSUP;
1058 return s->chr_ioctl(s, cmd, arg);
1061 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1063 char buf[4096];
1064 va_list ap;
1065 va_start(ap, fmt);
1066 vsnprintf(buf, sizeof(buf), fmt, ap);
1067 qemu_chr_write(s, buf, strlen(buf));
1068 va_end(ap);
1071 void qemu_chr_send_event(CharDriverState *s, int event)
1073 if (s->chr_send_event)
1074 s->chr_send_event(s, event);
1077 void qemu_chr_add_read_handler(CharDriverState *s,
1078 IOCanRWHandler *fd_can_read,
1079 IOReadHandler *fd_read, void *opaque)
1081 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1084 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1086 s->chr_event = chr_event;
1089 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1091 return len;
1094 static void null_chr_add_read_handler(CharDriverState *chr,
1095 IOCanRWHandler *fd_can_read,
1096 IOReadHandler *fd_read, void *opaque)
1100 CharDriverState *qemu_chr_open_null(void)
1102 CharDriverState *chr;
1104 chr = qemu_mallocz(sizeof(CharDriverState));
1105 if (!chr)
1106 return NULL;
1107 chr->chr_write = null_chr_write;
1108 chr->chr_add_read_handler = null_chr_add_read_handler;
1109 return chr;
1112 #ifdef _WIN32
1114 #define socket_error() WSAGetLastError()
1115 #undef EINTR
1116 #define EWOULDBLOCK WSAEWOULDBLOCK
1117 #define EINTR WSAEINTR
1118 #define EINPROGRESS WSAEINPROGRESS
1120 static void socket_cleanup(void)
1122 WSACleanup();
1125 static int socket_init(void)
1127 WSADATA Data;
1128 int ret, err;
1130 ret = WSAStartup(MAKEWORD(2,2), &Data);
1131 if (ret != 0) {
1132 err = WSAGetLastError();
1133 fprintf(stderr, "WSAStartup: %d\n", err);
1134 return -1;
1136 atexit(socket_cleanup);
1137 return 0;
1140 static int send_all(int fd, const uint8_t *buf, int len1)
1142 int ret, len;
1144 len = len1;
1145 while (len > 0) {
1146 ret = send(fd, buf, len, 0);
1147 if (ret < 0) {
1148 int errno;
1149 errno = WSAGetLastError();
1150 if (errno != WSAEWOULDBLOCK) {
1151 return -1;
1153 } else if (ret == 0) {
1154 break;
1155 } else {
1156 buf += ret;
1157 len -= ret;
1160 return len1 - len;
1163 void socket_set_nonblock(int fd)
1165 unsigned long opt = 1;
1166 ioctlsocket(fd, FIONBIO, &opt);
1169 #else
1171 #define socket_error() errno
1172 #define closesocket(s) close(s)
1174 static int unix_write(int fd, const uint8_t *buf, int len1)
1176 int ret, len;
1178 len = len1;
1179 while (len > 0) {
1180 ret = write(fd, buf, len);
1181 if (ret < 0) {
1182 if (errno != EINTR && errno != EAGAIN)
1183 return -1;
1184 } else if (ret == 0) {
1185 break;
1186 } else {
1187 buf += ret;
1188 len -= ret;
1191 return len1 - len;
1194 static inline int send_all(int fd, const uint8_t *buf, int len1)
1196 return unix_write(fd, buf, len1);
1199 void socket_set_nonblock(int fd)
1201 fcntl(fd, F_SETFL, O_NONBLOCK);
1203 #endif /* !_WIN32 */
1205 #ifndef _WIN32
1207 typedef struct {
1208 int fd_in, fd_out;
1209 IOCanRWHandler *fd_can_read;
1210 IOReadHandler *fd_read;
1211 void *fd_opaque;
1212 int max_size;
1213 } FDCharDriver;
1215 #define STDIO_MAX_CLIENTS 2
1217 static int stdio_nb_clients;
1218 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1220 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1222 FDCharDriver *s = chr->opaque;
1223 return unix_write(s->fd_out, buf, len);
1226 static int fd_chr_read_poll(void *opaque)
1228 CharDriverState *chr = opaque;
1229 FDCharDriver *s = chr->opaque;
1231 s->max_size = s->fd_can_read(s->fd_opaque);
1232 return s->max_size;
1235 static void fd_chr_read(void *opaque)
1237 CharDriverState *chr = opaque;
1238 FDCharDriver *s = chr->opaque;
1239 int size, len;
1240 uint8_t buf[1024];
1242 len = sizeof(buf);
1243 if (len > s->max_size)
1244 len = s->max_size;
1245 if (len == 0)
1246 return;
1247 size = read(s->fd_in, buf, len);
1248 if (size > 0) {
1249 s->fd_read(s->fd_opaque, buf, size);
1253 static void fd_chr_add_read_handler(CharDriverState *chr,
1254 IOCanRWHandler *fd_can_read,
1255 IOReadHandler *fd_read, void *opaque)
1257 FDCharDriver *s = chr->opaque;
1259 if (s->fd_in >= 0) {
1260 s->fd_can_read = fd_can_read;
1261 s->fd_read = fd_read;
1262 s->fd_opaque = opaque;
1263 if (nographic && s->fd_in == 0) {
1264 } else {
1265 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1266 fd_chr_read, NULL, chr);
1271 /* open a character device to a unix fd */
1272 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1274 CharDriverState *chr;
1275 FDCharDriver *s;
1277 chr = qemu_mallocz(sizeof(CharDriverState));
1278 if (!chr)
1279 return NULL;
1280 s = qemu_mallocz(sizeof(FDCharDriver));
1281 if (!s) {
1282 free(chr);
1283 return NULL;
1285 s->fd_in = fd_in;
1286 s->fd_out = fd_out;
1287 chr->opaque = s;
1288 chr->chr_write = fd_chr_write;
1289 chr->chr_add_read_handler = fd_chr_add_read_handler;
1290 return chr;
1293 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1295 int fd_out;
1297 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1298 if (fd_out < 0)
1299 return NULL;
1300 return qemu_chr_open_fd(-1, fd_out);
1303 CharDriverState *qemu_chr_open_pipe(const char *filename)
1305 int fd;
1307 fd = open(filename, O_RDWR | O_BINARY);
1308 if (fd < 0)
1309 return NULL;
1310 return qemu_chr_open_fd(fd, fd);
1314 /* for STDIO, we handle the case where several clients use it
1315 (nographic mode) */
1317 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1319 #define TERM_FIFO_MAX_SIZE 1
1321 static int term_got_escape, client_index;
1322 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1323 int term_fifo_size;
1325 void term_print_help(void)
1327 printf("\n"
1328 "C-a h print this help\n"
1329 "C-a x exit emulator\n"
1330 "C-a s save disk data back to file (if -snapshot)\n"
1331 "C-a b send break (magic sysrq)\n"
1332 "C-a c switch between console and monitor\n"
1333 "C-a C-a send C-a\n"
1337 /* called when a char is received */
1338 static void stdio_received_byte(int ch)
1340 if (term_got_escape) {
1341 term_got_escape = 0;
1342 switch(ch) {
1343 case 'h':
1344 term_print_help();
1345 break;
1346 case 'x':
1347 exit(0);
1348 break;
1349 case 's':
1351 int i;
1352 for (i = 0; i < MAX_DISKS; i++) {
1353 if (bs_table[i])
1354 bdrv_commit(bs_table[i]);
1357 break;
1358 case 'b':
1359 if (client_index < stdio_nb_clients) {
1360 CharDriverState *chr;
1361 FDCharDriver *s;
1363 chr = stdio_clients[client_index];
1364 s = chr->opaque;
1365 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1367 break;
1368 case 'c':
1369 client_index++;
1370 if (client_index >= stdio_nb_clients)
1371 client_index = 0;
1372 if (client_index == 0) {
1373 /* send a new line in the monitor to get the prompt */
1374 ch = '\r';
1375 goto send_char;
1377 break;
1378 case TERM_ESCAPE:
1379 goto send_char;
1381 } else if (ch == TERM_ESCAPE) {
1382 term_got_escape = 1;
1383 } else {
1384 send_char:
1385 if (client_index < stdio_nb_clients) {
1386 uint8_t buf[1];
1387 CharDriverState *chr;
1388 FDCharDriver *s;
1390 chr = stdio_clients[client_index];
1391 s = chr->opaque;
1392 if (s->fd_can_read(s->fd_opaque) > 0) {
1393 buf[0] = ch;
1394 s->fd_read(s->fd_opaque, buf, 1);
1395 } else if (term_fifo_size == 0) {
1396 term_fifo[term_fifo_size++] = ch;
1402 static int stdio_read_poll(void *opaque)
1404 CharDriverState *chr;
1405 FDCharDriver *s;
1407 if (client_index < stdio_nb_clients) {
1408 chr = stdio_clients[client_index];
1409 s = chr->opaque;
1410 /* try to flush the queue if needed */
1411 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1412 s->fd_read(s->fd_opaque, term_fifo, 1);
1413 term_fifo_size = 0;
1415 /* see if we can absorb more chars */
1416 if (term_fifo_size == 0)
1417 return 1;
1418 else
1419 return 0;
1420 } else {
1421 return 1;
1425 static void stdio_read(void *opaque)
1427 int size;
1428 uint8_t buf[1];
1430 size = read(0, buf, 1);
1431 if (size > 0)
1432 stdio_received_byte(buf[0]);
1435 /* init terminal so that we can grab keys */
1436 static struct termios oldtty;
1437 static int old_fd0_flags;
1439 static void term_exit(void)
1441 tcsetattr (0, TCSANOW, &oldtty);
1442 fcntl(0, F_SETFL, old_fd0_flags);
1445 static void term_init(void)
1447 struct termios tty;
1449 tcgetattr (0, &tty);
1450 oldtty = tty;
1451 old_fd0_flags = fcntl(0, F_GETFL);
1453 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1454 |INLCR|IGNCR|ICRNL|IXON);
1455 tty.c_oflag |= OPOST;
1456 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1457 /* if graphical mode, we allow Ctrl-C handling */
1458 if (nographic)
1459 tty.c_lflag &= ~ISIG;
1460 tty.c_cflag &= ~(CSIZE|PARENB);
1461 tty.c_cflag |= CS8;
1462 tty.c_cc[VMIN] = 1;
1463 tty.c_cc[VTIME] = 0;
1465 tcsetattr (0, TCSANOW, &tty);
1467 atexit(term_exit);
1469 fcntl(0, F_SETFL, O_NONBLOCK);
1472 CharDriverState *qemu_chr_open_stdio(void)
1474 CharDriverState *chr;
1476 if (nographic) {
1477 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1478 return NULL;
1479 chr = qemu_chr_open_fd(0, 1);
1480 if (stdio_nb_clients == 0)
1481 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1482 client_index = stdio_nb_clients;
1483 } else {
1484 if (stdio_nb_clients != 0)
1485 return NULL;
1486 chr = qemu_chr_open_fd(0, 1);
1488 stdio_clients[stdio_nb_clients++] = chr;
1489 if (stdio_nb_clients == 1) {
1490 /* set the terminal in raw mode */
1491 term_init();
1493 return chr;
1496 #if defined(__linux__)
1497 CharDriverState *qemu_chr_open_pty(void)
1499 struct termios tty;
1500 char slave_name[1024];
1501 int master_fd, slave_fd;
1503 /* Not satisfying */
1504 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1505 return NULL;
1508 /* Disabling local echo and line-buffered output */
1509 tcgetattr (master_fd, &tty);
1510 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1511 tty.c_cc[VMIN] = 1;
1512 tty.c_cc[VTIME] = 0;
1513 tcsetattr (master_fd, TCSAFLUSH, &tty);
1515 fprintf(stderr, "char device redirected to %s\n", slave_name);
1516 return qemu_chr_open_fd(master_fd, master_fd);
1519 static void tty_serial_init(int fd, int speed,
1520 int parity, int data_bits, int stop_bits)
1522 struct termios tty;
1523 speed_t spd;
1525 #if 0
1526 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1527 speed, parity, data_bits, stop_bits);
1528 #endif
1529 tcgetattr (fd, &tty);
1531 switch(speed) {
1532 case 50:
1533 spd = B50;
1534 break;
1535 case 75:
1536 spd = B75;
1537 break;
1538 case 300:
1539 spd = B300;
1540 break;
1541 case 600:
1542 spd = B600;
1543 break;
1544 case 1200:
1545 spd = B1200;
1546 break;
1547 case 2400:
1548 spd = B2400;
1549 break;
1550 case 4800:
1551 spd = B4800;
1552 break;
1553 case 9600:
1554 spd = B9600;
1555 break;
1556 case 19200:
1557 spd = B19200;
1558 break;
1559 case 38400:
1560 spd = B38400;
1561 break;
1562 case 57600:
1563 spd = B57600;
1564 break;
1565 default:
1566 case 115200:
1567 spd = B115200;
1568 break;
1571 cfsetispeed(&tty, spd);
1572 cfsetospeed(&tty, spd);
1574 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1575 |INLCR|IGNCR|ICRNL|IXON);
1576 tty.c_oflag |= OPOST;
1577 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1578 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1579 switch(data_bits) {
1580 default:
1581 case 8:
1582 tty.c_cflag |= CS8;
1583 break;
1584 case 7:
1585 tty.c_cflag |= CS7;
1586 break;
1587 case 6:
1588 tty.c_cflag |= CS6;
1589 break;
1590 case 5:
1591 tty.c_cflag |= CS5;
1592 break;
1594 switch(parity) {
1595 default:
1596 case 'N':
1597 break;
1598 case 'E':
1599 tty.c_cflag |= PARENB;
1600 break;
1601 case 'O':
1602 tty.c_cflag |= PARENB | PARODD;
1603 break;
1606 tcsetattr (fd, TCSANOW, &tty);
1609 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1611 FDCharDriver *s = chr->opaque;
1613 switch(cmd) {
1614 case CHR_IOCTL_SERIAL_SET_PARAMS:
1616 QEMUSerialSetParams *ssp = arg;
1617 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1618 ssp->data_bits, ssp->stop_bits);
1620 break;
1621 case CHR_IOCTL_SERIAL_SET_BREAK:
1623 int enable = *(int *)arg;
1624 if (enable)
1625 tcsendbreak(s->fd_in, 1);
1627 break;
1628 default:
1629 return -ENOTSUP;
1631 return 0;
1634 CharDriverState *qemu_chr_open_tty(const char *filename)
1636 CharDriverState *chr;
1637 int fd;
1639 fd = open(filename, O_RDWR | O_NONBLOCK);
1640 if (fd < 0)
1641 return NULL;
1642 fcntl(fd, F_SETFL, O_NONBLOCK);
1643 tty_serial_init(fd, 115200, 'N', 8, 1);
1644 chr = qemu_chr_open_fd(fd, fd);
1645 if (!chr)
1646 return NULL;
1647 chr->chr_ioctl = tty_serial_ioctl;
1648 return chr;
1651 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1653 int fd = (int)chr->opaque;
1654 uint8_t b;
1656 switch(cmd) {
1657 case CHR_IOCTL_PP_READ_DATA:
1658 if (ioctl(fd, PPRDATA, &b) < 0)
1659 return -ENOTSUP;
1660 *(uint8_t *)arg = b;
1661 break;
1662 case CHR_IOCTL_PP_WRITE_DATA:
1663 b = *(uint8_t *)arg;
1664 if (ioctl(fd, PPWDATA, &b) < 0)
1665 return -ENOTSUP;
1666 break;
1667 case CHR_IOCTL_PP_READ_CONTROL:
1668 if (ioctl(fd, PPRCONTROL, &b) < 0)
1669 return -ENOTSUP;
1670 *(uint8_t *)arg = b;
1671 break;
1672 case CHR_IOCTL_PP_WRITE_CONTROL:
1673 b = *(uint8_t *)arg;
1674 if (ioctl(fd, PPWCONTROL, &b) < 0)
1675 return -ENOTSUP;
1676 break;
1677 case CHR_IOCTL_PP_READ_STATUS:
1678 if (ioctl(fd, PPRSTATUS, &b) < 0)
1679 return -ENOTSUP;
1680 *(uint8_t *)arg = b;
1681 break;
1682 default:
1683 return -ENOTSUP;
1685 return 0;
1688 CharDriverState *qemu_chr_open_pp(const char *filename)
1690 CharDriverState *chr;
1691 int fd;
1693 fd = open(filename, O_RDWR);
1694 if (fd < 0)
1695 return NULL;
1697 if (ioctl(fd, PPCLAIM) < 0) {
1698 close(fd);
1699 return NULL;
1702 chr = qemu_mallocz(sizeof(CharDriverState));
1703 if (!chr) {
1704 close(fd);
1705 return NULL;
1707 chr->opaque = (void *)fd;
1708 chr->chr_write = null_chr_write;
1709 chr->chr_add_read_handler = null_chr_add_read_handler;
1710 chr->chr_ioctl = pp_ioctl;
1711 return chr;
1714 #else
1715 CharDriverState *qemu_chr_open_pty(void)
1717 return NULL;
1719 #endif
1721 #endif /* !defined(_WIN32) */
1723 #ifdef _WIN32
1724 typedef struct {
1725 IOCanRWHandler *fd_can_read;
1726 IOReadHandler *fd_read;
1727 void *win_opaque;
1728 int max_size;
1729 HANDLE hcom, hrecv, hsend;
1730 OVERLAPPED orecv, osend;
1731 BOOL fpipe;
1732 DWORD len;
1733 } WinCharState;
1735 #define NSENDBUF 2048
1736 #define NRECVBUF 2048
1737 #define MAXCONNECT 1
1738 #define NTIMEOUT 5000
1740 static int win_chr_poll(void *opaque);
1741 static int win_chr_pipe_poll(void *opaque);
1743 static void win_chr_close2(WinCharState *s)
1745 if (s->hsend) {
1746 CloseHandle(s->hsend);
1747 s->hsend = NULL;
1749 if (s->hrecv) {
1750 CloseHandle(s->hrecv);
1751 s->hrecv = NULL;
1753 if (s->hcom) {
1754 CloseHandle(s->hcom);
1755 s->hcom = NULL;
1757 if (s->fpipe)
1758 qemu_del_polling_cb(win_chr_pipe_poll, s);
1759 else
1760 qemu_del_polling_cb(win_chr_poll, s);
1763 static void win_chr_close(CharDriverState *chr)
1765 WinCharState *s = chr->opaque;
1766 win_chr_close2(s);
1769 static int win_chr_init(WinCharState *s, const char *filename)
1771 COMMCONFIG comcfg;
1772 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1773 COMSTAT comstat;
1774 DWORD size;
1775 DWORD err;
1777 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1778 if (!s->hsend) {
1779 fprintf(stderr, "Failed CreateEvent\n");
1780 goto fail;
1782 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1783 if (!s->hrecv) {
1784 fprintf(stderr, "Failed CreateEvent\n");
1785 goto fail;
1788 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1789 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1790 if (s->hcom == INVALID_HANDLE_VALUE) {
1791 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1792 s->hcom = NULL;
1793 goto fail;
1796 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1797 fprintf(stderr, "Failed SetupComm\n");
1798 goto fail;
1801 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1802 size = sizeof(COMMCONFIG);
1803 GetDefaultCommConfig(filename, &comcfg, &size);
1804 comcfg.dcb.DCBlength = sizeof(DCB);
1805 CommConfigDialog(filename, NULL, &comcfg);
1807 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1808 fprintf(stderr, "Failed SetCommState\n");
1809 goto fail;
1812 if (!SetCommMask(s->hcom, EV_ERR)) {
1813 fprintf(stderr, "Failed SetCommMask\n");
1814 goto fail;
1817 cto.ReadIntervalTimeout = MAXDWORD;
1818 if (!SetCommTimeouts(s->hcom, &cto)) {
1819 fprintf(stderr, "Failed SetCommTimeouts\n");
1820 goto fail;
1823 if (!ClearCommError(s->hcom, &err, &comstat)) {
1824 fprintf(stderr, "Failed ClearCommError\n");
1825 goto fail;
1827 qemu_add_polling_cb(win_chr_poll, s);
1828 return 0;
1830 fail:
1831 win_chr_close2(s);
1832 return -1;
1835 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1837 WinCharState *s = chr->opaque;
1838 DWORD len, ret, size, err;
1840 len = len1;
1841 ZeroMemory(&s->osend, sizeof(s->osend));
1842 s->osend.hEvent = s->hsend;
1843 while (len > 0) {
1844 if (s->hsend)
1845 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1846 else
1847 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1848 if (!ret) {
1849 err = GetLastError();
1850 if (err == ERROR_IO_PENDING) {
1851 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1852 if (ret) {
1853 buf += size;
1854 len -= size;
1855 } else {
1856 break;
1858 } else {
1859 break;
1861 } else {
1862 buf += size;
1863 len -= size;
1866 return len1 - len;
1869 static int win_chr_read_poll(WinCharState *s)
1871 s->max_size = s->fd_can_read(s->win_opaque);
1872 return s->max_size;
1875 static void win_chr_readfile(WinCharState *s)
1877 int ret, err;
1878 uint8_t buf[1024];
1879 DWORD size;
1881 ZeroMemory(&s->orecv, sizeof(s->orecv));
1882 s->orecv.hEvent = s->hrecv;
1883 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1884 if (!ret) {
1885 err = GetLastError();
1886 if (err == ERROR_IO_PENDING) {
1887 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1891 if (size > 0) {
1892 s->fd_read(s->win_opaque, buf, size);
1896 static void win_chr_read(WinCharState *s)
1898 if (s->len > s->max_size)
1899 s->len = s->max_size;
1900 if (s->len == 0)
1901 return;
1903 win_chr_readfile(s);
1906 static int win_chr_poll(void *opaque)
1908 WinCharState *s = opaque;
1909 COMSTAT status;
1910 DWORD comerr;
1912 ClearCommError(s->hcom, &comerr, &status);
1913 if (status.cbInQue > 0) {
1914 s->len = status.cbInQue;
1915 win_chr_read_poll(s);
1916 win_chr_read(s);
1917 return 1;
1919 return 0;
1922 static void win_chr_add_read_handler(CharDriverState *chr,
1923 IOCanRWHandler *fd_can_read,
1924 IOReadHandler *fd_read, void *opaque)
1926 WinCharState *s = chr->opaque;
1928 s->fd_can_read = fd_can_read;
1929 s->fd_read = fd_read;
1930 s->win_opaque = opaque;
1933 CharDriverState *qemu_chr_open_win(const char *filename)
1935 CharDriverState *chr;
1936 WinCharState *s;
1938 chr = qemu_mallocz(sizeof(CharDriverState));
1939 if (!chr)
1940 return NULL;
1941 s = qemu_mallocz(sizeof(WinCharState));
1942 if (!s) {
1943 free(chr);
1944 return NULL;
1946 chr->opaque = s;
1947 chr->chr_write = win_chr_write;
1948 chr->chr_add_read_handler = win_chr_add_read_handler;
1949 chr->chr_close = win_chr_close;
1951 if (win_chr_init(s, filename) < 0) {
1952 free(s);
1953 free(chr);
1954 return NULL;
1956 return chr;
1959 static int win_chr_pipe_poll(void *opaque)
1961 WinCharState *s = opaque;
1962 DWORD size;
1964 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1965 if (size > 0) {
1966 s->len = size;
1967 win_chr_read_poll(s);
1968 win_chr_read(s);
1969 return 1;
1971 return 0;
1974 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1976 OVERLAPPED ov;
1977 int ret;
1978 DWORD size;
1979 char openname[256];
1981 s->fpipe = TRUE;
1983 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1984 if (!s->hsend) {
1985 fprintf(stderr, "Failed CreateEvent\n");
1986 goto fail;
1988 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1989 if (!s->hrecv) {
1990 fprintf(stderr, "Failed CreateEvent\n");
1991 goto fail;
1994 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1995 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1996 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1997 PIPE_WAIT,
1998 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1999 if (s->hcom == INVALID_HANDLE_VALUE) {
2000 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2001 s->hcom = NULL;
2002 goto fail;
2005 ZeroMemory(&ov, sizeof(ov));
2006 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2007 ret = ConnectNamedPipe(s->hcom, &ov);
2008 if (ret) {
2009 fprintf(stderr, "Failed ConnectNamedPipe\n");
2010 goto fail;
2013 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2014 if (!ret) {
2015 fprintf(stderr, "Failed GetOverlappedResult\n");
2016 if (ov.hEvent) {
2017 CloseHandle(ov.hEvent);
2018 ov.hEvent = NULL;
2020 goto fail;
2023 if (ov.hEvent) {
2024 CloseHandle(ov.hEvent);
2025 ov.hEvent = NULL;
2027 qemu_add_polling_cb(win_chr_pipe_poll, s);
2028 return 0;
2030 fail:
2031 win_chr_close2(s);
2032 return -1;
2036 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2038 CharDriverState *chr;
2039 WinCharState *s;
2041 chr = qemu_mallocz(sizeof(CharDriverState));
2042 if (!chr)
2043 return NULL;
2044 s = qemu_mallocz(sizeof(WinCharState));
2045 if (!s) {
2046 free(chr);
2047 return NULL;
2049 chr->opaque = s;
2050 chr->chr_write = win_chr_write;
2051 chr->chr_add_read_handler = win_chr_add_read_handler;
2052 chr->chr_close = win_chr_close;
2054 if (win_chr_pipe_init(s, filename) < 0) {
2055 free(s);
2056 free(chr);
2057 return NULL;
2059 return chr;
2062 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2064 CharDriverState *chr;
2065 WinCharState *s;
2067 chr = qemu_mallocz(sizeof(CharDriverState));
2068 if (!chr)
2069 return NULL;
2070 s = qemu_mallocz(sizeof(WinCharState));
2071 if (!s) {
2072 free(chr);
2073 return NULL;
2075 s->hcom = fd_out;
2076 chr->opaque = s;
2077 chr->chr_write = win_chr_write;
2078 chr->chr_add_read_handler = win_chr_add_read_handler;
2079 return chr;
2082 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2084 HANDLE fd_out;
2086 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2087 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2088 if (fd_out == INVALID_HANDLE_VALUE)
2089 return NULL;
2091 return qemu_chr_open_win_file(fd_out);
2093 #endif
2095 CharDriverState *qemu_chr_open(const char *filename)
2097 const char *p;
2099 if (!strcmp(filename, "vc")) {
2100 return text_console_init(&display_state);
2101 } else if (!strcmp(filename, "null")) {
2102 return qemu_chr_open_null();
2103 } else
2104 #ifndef _WIN32
2105 if (strstart(filename, "file:", &p)) {
2106 return qemu_chr_open_file_out(p);
2107 } else if (strstart(filename, "pipe:", &p)) {
2108 return qemu_chr_open_pipe(p);
2109 } else if (!strcmp(filename, "pty")) {
2110 return qemu_chr_open_pty();
2111 } else if (!strcmp(filename, "stdio")) {
2112 return qemu_chr_open_stdio();
2113 } else
2114 #endif
2115 #if defined(__linux__)
2116 if (strstart(filename, "/dev/parport", NULL)) {
2117 return qemu_chr_open_pp(filename);
2118 } else
2119 if (strstart(filename, "/dev/", NULL)) {
2120 return qemu_chr_open_tty(filename);
2121 } else
2122 #endif
2123 #ifdef _WIN32
2124 if (strstart(filename, "COM", NULL)) {
2125 return qemu_chr_open_win(filename);
2126 } else
2127 if (strstart(filename, "pipe:", &p)) {
2128 return qemu_chr_open_win_pipe(p);
2129 } else
2130 if (strstart(filename, "file:", &p)) {
2131 return qemu_chr_open_win_file_out(p);
2133 #endif
2135 return NULL;
2139 void qemu_chr_close(CharDriverState *chr)
2141 if (chr->chr_close)
2142 chr->chr_close(chr);
2145 /***********************************************************/
2146 /* network device redirectors */
2148 void hex_dump(FILE *f, const uint8_t *buf, int size)
2150 int len, i, j, c;
2152 for(i=0;i<size;i+=16) {
2153 len = size - i;
2154 if (len > 16)
2155 len = 16;
2156 fprintf(f, "%08x ", i);
2157 for(j=0;j<16;j++) {
2158 if (j < len)
2159 fprintf(f, " %02x", buf[i+j]);
2160 else
2161 fprintf(f, " ");
2163 fprintf(f, " ");
2164 for(j=0;j<len;j++) {
2165 c = buf[i+j];
2166 if (c < ' ' || c > '~')
2167 c = '.';
2168 fprintf(f, "%c", c);
2170 fprintf(f, "\n");
2174 static int parse_macaddr(uint8_t *macaddr, const char *p)
2176 int i;
2177 for(i = 0; i < 6; i++) {
2178 macaddr[i] = strtol(p, (char **)&p, 16);
2179 if (i == 5) {
2180 if (*p != '\0')
2181 return -1;
2182 } else {
2183 if (*p != ':')
2184 return -1;
2185 p++;
2188 return 0;
2191 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2193 const char *p, *p1;
2194 int len;
2195 p = *pp;
2196 p1 = strchr(p, sep);
2197 if (!p1)
2198 return -1;
2199 len = p1 - p;
2200 p1++;
2201 if (buf_size > 0) {
2202 if (len > buf_size - 1)
2203 len = buf_size - 1;
2204 memcpy(buf, p, len);
2205 buf[len] = '\0';
2207 *pp = p1;
2208 return 0;
2211 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2213 char buf[512];
2214 struct hostent *he;
2215 const char *p, *r;
2216 int port;
2218 p = str;
2219 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2220 return -1;
2221 saddr->sin_family = AF_INET;
2222 if (buf[0] == '\0') {
2223 saddr->sin_addr.s_addr = 0;
2224 } else {
2225 if (isdigit(buf[0])) {
2226 if (!inet_aton(buf, &saddr->sin_addr))
2227 return -1;
2228 } else {
2229 if ((he = gethostbyname(buf)) == NULL)
2230 return - 1;
2231 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2234 port = strtol(p, (char **)&r, 0);
2235 if (r == p)
2236 return -1;
2237 saddr->sin_port = htons(port);
2238 return 0;
2241 /* find or alloc a new VLAN */
2242 VLANState *qemu_find_vlan(int id)
2244 VLANState **pvlan, *vlan;
2245 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2246 if (vlan->id == id)
2247 return vlan;
2249 vlan = qemu_mallocz(sizeof(VLANState));
2250 if (!vlan)
2251 return NULL;
2252 vlan->id = id;
2253 vlan->next = NULL;
2254 pvlan = &first_vlan;
2255 while (*pvlan != NULL)
2256 pvlan = &(*pvlan)->next;
2257 *pvlan = vlan;
2258 return vlan;
2261 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2262 IOReadHandler *fd_read,
2263 IOCanRWHandler *fd_can_read,
2264 void *opaque)
2266 VLANClientState *vc, **pvc;
2267 vc = qemu_mallocz(sizeof(VLANClientState));
2268 if (!vc)
2269 return NULL;
2270 vc->fd_read = fd_read;
2271 vc->fd_can_read = fd_can_read;
2272 vc->opaque = opaque;
2273 vc->vlan = vlan;
2275 vc->next = NULL;
2276 pvc = &vlan->first_client;
2277 while (*pvc != NULL)
2278 pvc = &(*pvc)->next;
2279 *pvc = vc;
2280 return vc;
2283 int qemu_can_send_packet(VLANClientState *vc1)
2285 VLANState *vlan = vc1->vlan;
2286 VLANClientState *vc;
2288 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2289 if (vc != vc1) {
2290 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2291 return 0;
2294 return 1;
2297 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2299 VLANState *vlan = vc1->vlan;
2300 VLANClientState *vc;
2302 #if 0
2303 printf("vlan %d send:\n", vlan->id);
2304 hex_dump(stdout, buf, size);
2305 #endif
2306 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2307 if (vc != vc1) {
2308 vc->fd_read(vc->opaque, buf, size);
2313 #if defined(CONFIG_SLIRP)
2315 /* slirp network adapter */
2317 static int slirp_inited;
2318 static VLANClientState *slirp_vc;
2320 int slirp_can_output(void)
2322 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2325 void slirp_output(const uint8_t *pkt, int pkt_len)
2327 #if 0
2328 printf("slirp output:\n");
2329 hex_dump(stdout, pkt, pkt_len);
2330 #endif
2331 if (!slirp_vc)
2332 return;
2333 qemu_send_packet(slirp_vc, pkt, pkt_len);
2336 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2338 #if 0
2339 printf("slirp input:\n");
2340 hex_dump(stdout, buf, size);
2341 #endif
2342 slirp_input(buf, size);
2345 static int net_slirp_init(VLANState *vlan)
2347 if (!slirp_inited) {
2348 slirp_inited = 1;
2349 slirp_init();
2351 slirp_vc = qemu_new_vlan_client(vlan,
2352 slirp_receive, NULL, NULL);
2353 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2354 return 0;
2357 static void net_slirp_redir(const char *redir_str)
2359 int is_udp;
2360 char buf[256], *r;
2361 const char *p;
2362 struct in_addr guest_addr;
2363 int host_port, guest_port;
2365 if (!slirp_inited) {
2366 slirp_inited = 1;
2367 slirp_init();
2370 p = redir_str;
2371 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2372 goto fail;
2373 if (!strcmp(buf, "tcp")) {
2374 is_udp = 0;
2375 } else if (!strcmp(buf, "udp")) {
2376 is_udp = 1;
2377 } else {
2378 goto fail;
2381 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2382 goto fail;
2383 host_port = strtol(buf, &r, 0);
2384 if (r == buf)
2385 goto fail;
2387 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2388 goto fail;
2389 if (buf[0] == '\0') {
2390 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2392 if (!inet_aton(buf, &guest_addr))
2393 goto fail;
2395 guest_port = strtol(p, &r, 0);
2396 if (r == p)
2397 goto fail;
2399 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2400 fprintf(stderr, "qemu: could not set up redirection\n");
2401 exit(1);
2403 return;
2404 fail:
2405 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2406 exit(1);
2409 #ifndef _WIN32
2411 char smb_dir[1024];
2413 static void smb_exit(void)
2415 DIR *d;
2416 struct dirent *de;
2417 char filename[1024];
2419 /* erase all the files in the directory */
2420 d = opendir(smb_dir);
2421 for(;;) {
2422 de = readdir(d);
2423 if (!de)
2424 break;
2425 if (strcmp(de->d_name, ".") != 0 &&
2426 strcmp(de->d_name, "..") != 0) {
2427 snprintf(filename, sizeof(filename), "%s/%s",
2428 smb_dir, de->d_name);
2429 unlink(filename);
2432 closedir(d);
2433 rmdir(smb_dir);
2436 /* automatic user mode samba server configuration */
2437 void net_slirp_smb(const char *exported_dir)
2439 char smb_conf[1024];
2440 char smb_cmdline[1024];
2441 FILE *f;
2443 if (!slirp_inited) {
2444 slirp_inited = 1;
2445 slirp_init();
2448 /* XXX: better tmp dir construction */
2449 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2450 if (mkdir(smb_dir, 0700) < 0) {
2451 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2452 exit(1);
2454 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2456 f = fopen(smb_conf, "w");
2457 if (!f) {
2458 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2459 exit(1);
2461 fprintf(f,
2462 "[global]\n"
2463 "private dir=%s\n"
2464 "smb ports=0\n"
2465 "socket address=127.0.0.1\n"
2466 "pid directory=%s\n"
2467 "lock directory=%s\n"
2468 "log file=%s/log.smbd\n"
2469 "smb passwd file=%s/smbpasswd\n"
2470 "security = share\n"
2471 "[qemu]\n"
2472 "path=%s\n"
2473 "read only=no\n"
2474 "guest ok=yes\n",
2475 smb_dir,
2476 smb_dir,
2477 smb_dir,
2478 smb_dir,
2479 smb_dir,
2480 exported_dir
2482 fclose(f);
2483 atexit(smb_exit);
2485 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2486 smb_conf);
2488 slirp_add_exec(0, smb_cmdline, 4, 139);
2491 #endif /* !defined(_WIN32) */
2493 #endif /* CONFIG_SLIRP */
2495 #if !defined(_WIN32)
2497 typedef struct TAPState {
2498 VLANClientState *vc;
2499 int fd;
2500 } TAPState;
2502 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2504 TAPState *s = opaque;
2505 int ret;
2506 for(;;) {
2507 ret = write(s->fd, buf, size);
2508 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2509 } else {
2510 break;
2515 static void tap_send(void *opaque)
2517 TAPState *s = opaque;
2518 uint8_t buf[4096];
2519 int size;
2521 size = read(s->fd, buf, sizeof(buf));
2522 if (size > 0) {
2523 qemu_send_packet(s->vc, buf, size);
2527 /* fd support */
2529 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2531 TAPState *s;
2533 s = qemu_mallocz(sizeof(TAPState));
2534 if (!s)
2535 return NULL;
2536 s->fd = fd;
2537 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2538 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2539 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2540 return s;
2543 #ifdef _BSD
2544 static int tap_open(char *ifname, int ifname_size)
2546 int fd;
2547 char *dev;
2548 struct stat s;
2550 fd = open("/dev/tap", O_RDWR);
2551 if (fd < 0) {
2552 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2553 return -1;
2556 fstat(fd, &s);
2557 dev = devname(s.st_rdev, S_IFCHR);
2558 pstrcpy(ifname, ifname_size, dev);
2560 fcntl(fd, F_SETFL, O_NONBLOCK);
2561 return fd;
2563 #else
2564 static int tap_open(char *ifname, int ifname_size)
2566 struct ifreq ifr;
2567 int fd, ret;
2569 fd = open("/dev/net/tun", O_RDWR);
2570 if (fd < 0) {
2571 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2572 return -1;
2574 memset(&ifr, 0, sizeof(ifr));
2575 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2576 if (ifname[0] != '\0')
2577 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2578 else
2579 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2580 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2581 if (ret != 0) {
2582 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2583 close(fd);
2584 return -1;
2586 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2587 fcntl(fd, F_SETFL, O_NONBLOCK);
2588 return fd;
2590 #endif
2592 static int net_tap_init(VLANState *vlan, const char *ifname1,
2593 const char *setup_script)
2595 TAPState *s;
2596 int pid, status, fd;
2597 char *args[3];
2598 char **parg;
2599 char ifname[128];
2601 if (ifname1 != NULL)
2602 pstrcpy(ifname, sizeof(ifname), ifname1);
2603 else
2604 ifname[0] = '\0';
2605 fd = tap_open(ifname, sizeof(ifname));
2606 if (fd < 0)
2607 return -1;
2609 if (!setup_script)
2610 setup_script = "";
2611 if (setup_script[0] != '\0') {
2612 /* try to launch network init script */
2613 pid = fork();
2614 if (pid >= 0) {
2615 if (pid == 0) {
2616 parg = args;
2617 *parg++ = (char *)setup_script;
2618 *parg++ = ifname;
2619 *parg++ = NULL;
2620 execv(setup_script, args);
2621 _exit(1);
2623 while (waitpid(pid, &status, 0) != pid);
2624 if (!WIFEXITED(status) ||
2625 WEXITSTATUS(status) != 0) {
2626 fprintf(stderr, "%s: could not launch network script\n",
2627 setup_script);
2628 return -1;
2632 s = net_tap_fd_init(vlan, fd);
2633 if (!s)
2634 return -1;
2635 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2636 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2637 return 0;
2640 #endif /* !_WIN32 */
2642 /* network connection */
2643 typedef struct NetSocketState {
2644 VLANClientState *vc;
2645 int fd;
2646 int state; /* 0 = getting length, 1 = getting data */
2647 int index;
2648 int packet_len;
2649 uint8_t buf[4096];
2650 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2651 } NetSocketState;
2653 typedef struct NetSocketListenState {
2654 VLANState *vlan;
2655 int fd;
2656 } NetSocketListenState;
2658 /* XXX: we consider we can send the whole packet without blocking */
2659 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2661 NetSocketState *s = opaque;
2662 uint32_t len;
2663 len = htonl(size);
2665 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2666 send_all(s->fd, buf, size);
2669 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2671 NetSocketState *s = opaque;
2672 sendto(s->fd, buf, size, 0,
2673 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2676 static void net_socket_send(void *opaque)
2678 NetSocketState *s = opaque;
2679 int l, size, err;
2680 uint8_t buf1[4096];
2681 const uint8_t *buf;
2683 size = recv(s->fd, buf1, sizeof(buf1), 0);
2684 if (size < 0) {
2685 err = socket_error();
2686 if (err != EWOULDBLOCK)
2687 goto eoc;
2688 } else if (size == 0) {
2689 /* end of connection */
2690 eoc:
2691 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2692 closesocket(s->fd);
2693 return;
2695 buf = buf1;
2696 while (size > 0) {
2697 /* reassemble a packet from the network */
2698 switch(s->state) {
2699 case 0:
2700 l = 4 - s->index;
2701 if (l > size)
2702 l = size;
2703 memcpy(s->buf + s->index, buf, l);
2704 buf += l;
2705 size -= l;
2706 s->index += l;
2707 if (s->index == 4) {
2708 /* got length */
2709 s->packet_len = ntohl(*(uint32_t *)s->buf);
2710 s->index = 0;
2711 s->state = 1;
2713 break;
2714 case 1:
2715 l = s->packet_len - s->index;
2716 if (l > size)
2717 l = size;
2718 memcpy(s->buf + s->index, buf, l);
2719 s->index += l;
2720 buf += l;
2721 size -= l;
2722 if (s->index >= s->packet_len) {
2723 qemu_send_packet(s->vc, s->buf, s->packet_len);
2724 s->index = 0;
2725 s->state = 0;
2727 break;
2732 static void net_socket_send_dgram(void *opaque)
2734 NetSocketState *s = opaque;
2735 int size;
2737 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2738 if (size < 0)
2739 return;
2740 if (size == 0) {
2741 /* end of connection */
2742 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2743 return;
2745 qemu_send_packet(s->vc, s->buf, size);
2748 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2750 struct ip_mreq imr;
2751 int fd;
2752 int val, ret;
2753 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2754 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2755 inet_ntoa(mcastaddr->sin_addr),
2756 (int)ntohl(mcastaddr->sin_addr.s_addr));
2757 return -1;
2760 fd = socket(PF_INET, SOCK_DGRAM, 0);
2761 if (fd < 0) {
2762 perror("socket(PF_INET, SOCK_DGRAM)");
2763 return -1;
2766 val = 1;
2767 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2768 (const char *)&val, sizeof(val));
2769 if (ret < 0) {
2770 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2771 goto fail;
2774 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2775 if (ret < 0) {
2776 perror("bind");
2777 goto fail;
2780 /* Add host to multicast group */
2781 imr.imr_multiaddr = mcastaddr->sin_addr;
2782 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2784 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2785 (const char *)&imr, sizeof(struct ip_mreq));
2786 if (ret < 0) {
2787 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2788 goto fail;
2791 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2792 val = 1;
2793 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2794 (const char *)&val, sizeof(val));
2795 if (ret < 0) {
2796 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2797 goto fail;
2800 socket_set_nonblock(fd);
2801 return fd;
2802 fail:
2803 if (fd>=0) close(fd);
2804 return -1;
2807 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2808 int is_connected)
2810 struct sockaddr_in saddr;
2811 int newfd;
2812 socklen_t saddr_len;
2813 NetSocketState *s;
2815 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2816 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2817 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2820 if (is_connected) {
2821 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2822 /* must be bound */
2823 if (saddr.sin_addr.s_addr==0) {
2824 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2825 fd);
2826 return NULL;
2828 /* clone dgram socket */
2829 newfd = net_socket_mcast_create(&saddr);
2830 if (newfd < 0) {
2831 /* error already reported by net_socket_mcast_create() */
2832 close(fd);
2833 return NULL;
2835 /* clone newfd to fd, close newfd */
2836 dup2(newfd, fd);
2837 close(newfd);
2839 } else {
2840 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2841 fd, strerror(errno));
2842 return NULL;
2846 s = qemu_mallocz(sizeof(NetSocketState));
2847 if (!s)
2848 return NULL;
2849 s->fd = fd;
2851 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2852 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2854 /* mcast: save bound address as dst */
2855 if (is_connected) s->dgram_dst=saddr;
2857 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2858 "socket: fd=%d (%s mcast=%s:%d)",
2859 fd, is_connected? "cloned" : "",
2860 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2861 return s;
2864 static void net_socket_connect(void *opaque)
2866 NetSocketState *s = opaque;
2867 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2870 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2871 int is_connected)
2873 NetSocketState *s;
2874 s = qemu_mallocz(sizeof(NetSocketState));
2875 if (!s)
2876 return NULL;
2877 s->fd = fd;
2878 s->vc = qemu_new_vlan_client(vlan,
2879 net_socket_receive, NULL, s);
2880 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2881 "socket: fd=%d", fd);
2882 if (is_connected) {
2883 net_socket_connect(s);
2884 } else {
2885 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2887 return s;
2890 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2891 int is_connected)
2893 int so_type=-1, optlen=sizeof(so_type);
2895 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2896 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2897 return NULL;
2899 switch(so_type) {
2900 case SOCK_DGRAM:
2901 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2902 case SOCK_STREAM:
2903 return net_socket_fd_init_stream(vlan, fd, is_connected);
2904 default:
2905 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2906 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2907 return net_socket_fd_init_stream(vlan, fd, is_connected);
2909 return NULL;
2912 static void net_socket_accept(void *opaque)
2914 NetSocketListenState *s = opaque;
2915 NetSocketState *s1;
2916 struct sockaddr_in saddr;
2917 socklen_t len;
2918 int fd;
2920 for(;;) {
2921 len = sizeof(saddr);
2922 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2923 if (fd < 0 && errno != EINTR) {
2924 return;
2925 } else if (fd >= 0) {
2926 break;
2929 s1 = net_socket_fd_init(s->vlan, fd, 1);
2930 if (!s1) {
2931 close(fd);
2932 } else {
2933 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2934 "socket: connection from %s:%d",
2935 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2939 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2941 NetSocketListenState *s;
2942 int fd, val, ret;
2943 struct sockaddr_in saddr;
2945 if (parse_host_port(&saddr, host_str) < 0)
2946 return -1;
2948 s = qemu_mallocz(sizeof(NetSocketListenState));
2949 if (!s)
2950 return -1;
2952 fd = socket(PF_INET, SOCK_STREAM, 0);
2953 if (fd < 0) {
2954 perror("socket");
2955 return -1;
2957 socket_set_nonblock(fd);
2959 /* allow fast reuse */
2960 val = 1;
2961 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2963 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2964 if (ret < 0) {
2965 perror("bind");
2966 return -1;
2968 ret = listen(fd, 0);
2969 if (ret < 0) {
2970 perror("listen");
2971 return -1;
2973 s->vlan = vlan;
2974 s->fd = fd;
2975 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2976 return 0;
2979 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2981 NetSocketState *s;
2982 int fd, connected, ret, err;
2983 struct sockaddr_in saddr;
2985 if (parse_host_port(&saddr, host_str) < 0)
2986 return -1;
2988 fd = socket(PF_INET, SOCK_STREAM, 0);
2989 if (fd < 0) {
2990 perror("socket");
2991 return -1;
2993 socket_set_nonblock(fd);
2995 connected = 0;
2996 for(;;) {
2997 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2998 if (ret < 0) {
2999 err = socket_error();
3000 if (err == EINTR || err == EWOULDBLOCK) {
3001 } else if (err == EINPROGRESS) {
3002 break;
3003 } else {
3004 perror("connect");
3005 closesocket(fd);
3006 return -1;
3008 } else {
3009 connected = 1;
3010 break;
3013 s = net_socket_fd_init(vlan, fd, connected);
3014 if (!s)
3015 return -1;
3016 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3017 "socket: connect to %s:%d",
3018 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3019 return 0;
3022 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
3024 NetSocketState *s;
3025 int fd;
3026 struct sockaddr_in saddr;
3028 if (parse_host_port(&saddr, host_str) < 0)
3029 return -1;
3032 fd = net_socket_mcast_create(&saddr);
3033 if (fd < 0)
3034 return -1;
3036 s = net_socket_fd_init(vlan, fd, 0);
3037 if (!s)
3038 return -1;
3040 s->dgram_dst = saddr;
3042 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3043 "socket: mcast=%s:%d",
3044 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3045 return 0;
3049 static int get_param_value(char *buf, int buf_size,
3050 const char *tag, const char *str)
3052 const char *p;
3053 char *q;
3054 char option[128];
3056 p = str;
3057 for(;;) {
3058 q = option;
3059 while (*p != '\0' && *p != '=') {
3060 if ((q - option) < sizeof(option) - 1)
3061 *q++ = *p;
3062 p++;
3064 *q = '\0';
3065 if (*p != '=')
3066 break;
3067 p++;
3068 if (!strcmp(tag, option)) {
3069 q = buf;
3070 while (*p != '\0' && *p != ',') {
3071 if ((q - buf) < buf_size - 1)
3072 *q++ = *p;
3073 p++;
3075 *q = '\0';
3076 return q - buf;
3077 } else {
3078 while (*p != '\0' && *p != ',') {
3079 p++;
3082 if (*p != ',')
3083 break;
3084 p++;
3086 return 0;
3089 int net_client_init(const char *str)
3091 const char *p;
3092 char *q;
3093 char device[64];
3094 char buf[1024];
3095 int vlan_id, ret;
3096 VLANState *vlan;
3098 p = str;
3099 q = device;
3100 while (*p != '\0' && *p != ',') {
3101 if ((q - device) < sizeof(device) - 1)
3102 *q++ = *p;
3103 p++;
3105 *q = '\0';
3106 if (*p == ',')
3107 p++;
3108 vlan_id = 0;
3109 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3110 vlan_id = strtol(buf, NULL, 0);
3112 vlan = qemu_find_vlan(vlan_id);
3113 if (!vlan) {
3114 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3115 return -1;
3117 if (!strcmp(device, "nic")) {
3118 NICInfo *nd;
3119 uint8_t *macaddr;
3121 if (nb_nics >= MAX_NICS) {
3122 fprintf(stderr, "Too Many NICs\n");
3123 return -1;
3125 nd = &nd_table[nb_nics];
3126 macaddr = nd->macaddr;
3127 macaddr[0] = 0x52;
3128 macaddr[1] = 0x54;
3129 macaddr[2] = 0x00;
3130 macaddr[3] = 0x12;
3131 macaddr[4] = 0x34;
3132 macaddr[5] = 0x56 + nb_nics;
3134 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3135 if (parse_macaddr(macaddr, buf) < 0) {
3136 fprintf(stderr, "invalid syntax for ethernet address\n");
3137 return -1;
3140 if (get_param_value(buf, sizeof(buf), "model", p)) {
3141 nd->model = strdup(buf);
3143 nd->vlan = vlan;
3144 nb_nics++;
3145 ret = 0;
3146 } else
3147 if (!strcmp(device, "none")) {
3148 /* does nothing. It is needed to signal that no network cards
3149 are wanted */
3150 ret = 0;
3151 } else
3152 #ifdef CONFIG_SLIRP
3153 if (!strcmp(device, "user")) {
3154 ret = net_slirp_init(vlan);
3155 } else
3156 #endif
3157 #ifdef _WIN32
3158 if (!strcmp(device, "tap")) {
3159 char ifname[64];
3160 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3161 fprintf(stderr, "tap: no interface name\n");
3162 return -1;
3164 ret = tap_win32_init(vlan, ifname);
3165 } else
3166 #else
3167 if (!strcmp(device, "tap")) {
3168 char ifname[64];
3169 char setup_script[1024];
3170 int fd;
3171 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3172 fd = strtol(buf, NULL, 0);
3173 ret = -1;
3174 if (net_tap_fd_init(vlan, fd))
3175 ret = 0;
3176 } else {
3177 get_param_value(ifname, sizeof(ifname), "ifname", p);
3178 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3179 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3181 ret = net_tap_init(vlan, ifname, setup_script);
3183 } else
3184 #endif
3185 if (!strcmp(device, "socket")) {
3186 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3187 int fd;
3188 fd = strtol(buf, NULL, 0);
3189 ret = -1;
3190 if (net_socket_fd_init(vlan, fd, 1))
3191 ret = 0;
3192 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3193 ret = net_socket_listen_init(vlan, buf);
3194 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3195 ret = net_socket_connect_init(vlan, buf);
3196 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3197 ret = net_socket_mcast_init(vlan, buf);
3198 } else {
3199 fprintf(stderr, "Unknown socket options: %s\n", p);
3200 return -1;
3202 } else
3204 fprintf(stderr, "Unknown network device: %s\n", device);
3205 return -1;
3207 if (ret < 0) {
3208 fprintf(stderr, "Could not initialize device '%s'\n", device);
3211 return ret;
3214 void do_info_network(void)
3216 VLANState *vlan;
3217 VLANClientState *vc;
3219 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3220 term_printf("VLAN %d devices:\n", vlan->id);
3221 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3222 term_printf(" %s\n", vc->info_str);
3226 /***********************************************************/
3227 /* USB devices */
3229 static int usb_device_add(const char *devname)
3231 const char *p;
3232 USBDevice *dev;
3233 int i;
3235 if (!vm_usb_hub)
3236 return -1;
3237 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3238 if (!vm_usb_ports[i]->dev)
3239 break;
3241 if (i == MAX_VM_USB_PORTS)
3242 return -1;
3244 if (strstart(devname, "host:", &p)) {
3245 dev = usb_host_device_open(p);
3246 if (!dev)
3247 return -1;
3248 } else if (!strcmp(devname, "mouse")) {
3249 dev = usb_mouse_init();
3250 if (!dev)
3251 return -1;
3252 } else if (!strcmp(devname, "tablet")) {
3253 dev = usb_tablet_init();
3254 if (!dev)
3255 return -1;
3256 } else {
3257 return -1;
3259 usb_attach(vm_usb_ports[i], dev);
3260 return 0;
3263 static int usb_device_del(const char *devname)
3265 USBDevice *dev;
3266 int bus_num, addr, i;
3267 const char *p;
3269 if (!vm_usb_hub)
3270 return -1;
3272 p = strchr(devname, '.');
3273 if (!p)
3274 return -1;
3275 bus_num = strtoul(devname, NULL, 0);
3276 addr = strtoul(p + 1, NULL, 0);
3277 if (bus_num != 0)
3278 return -1;
3279 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3280 dev = vm_usb_ports[i]->dev;
3281 if (dev && dev->addr == addr)
3282 break;
3284 if (i == MAX_VM_USB_PORTS)
3285 return -1;
3286 usb_attach(vm_usb_ports[i], NULL);
3287 return 0;
3290 void do_usb_add(const char *devname)
3292 int ret;
3293 ret = usb_device_add(devname);
3294 if (ret < 0)
3295 term_printf("Could not add USB device '%s'\n", devname);
3298 void do_usb_del(const char *devname)
3300 int ret;
3301 ret = usb_device_del(devname);
3302 if (ret < 0)
3303 term_printf("Could not remove USB device '%s'\n", devname);
3306 void usb_info(void)
3308 USBDevice *dev;
3309 int i;
3310 const char *speed_str;
3312 if (!vm_usb_hub) {
3313 term_printf("USB support not enabled\n");
3314 return;
3317 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3318 dev = vm_usb_ports[i]->dev;
3319 if (dev) {
3320 term_printf("Hub port %d:\n", i);
3321 switch(dev->speed) {
3322 case USB_SPEED_LOW:
3323 speed_str = "1.5";
3324 break;
3325 case USB_SPEED_FULL:
3326 speed_str = "12";
3327 break;
3328 case USB_SPEED_HIGH:
3329 speed_str = "480";
3330 break;
3331 default:
3332 speed_str = "?";
3333 break;
3335 term_printf(" Device %d.%d, speed %s Mb/s\n",
3336 0, dev->addr, speed_str);
3341 /***********************************************************/
3342 /* pid file */
3344 static char *pid_filename;
3346 /* Remove PID file. Called on normal exit */
3348 static void remove_pidfile(void)
3350 unlink (pid_filename);
3353 static void create_pidfile(const char *filename)
3355 struct stat pidstat;
3356 FILE *f;
3358 /* Try to write our PID to the named file */
3359 if (stat(filename, &pidstat) < 0) {
3360 if (errno == ENOENT) {
3361 if ((f = fopen (filename, "w")) == NULL) {
3362 perror("Opening pidfile");
3363 exit(1);
3365 fprintf(f, "%d\n", getpid());
3366 fclose(f);
3367 pid_filename = qemu_strdup(filename);
3368 if (!pid_filename) {
3369 fprintf(stderr, "Could not save PID filename");
3370 exit(1);
3372 atexit(remove_pidfile);
3374 } else {
3375 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3376 filename);
3377 exit(1);
3381 /***********************************************************/
3382 /* dumb display */
3384 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3388 static void dumb_resize(DisplayState *ds, int w, int h)
3392 static void dumb_refresh(DisplayState *ds)
3394 vga_hw_update();
3397 void dumb_display_init(DisplayState *ds)
3399 ds->data = NULL;
3400 ds->linesize = 0;
3401 ds->depth = 0;
3402 ds->dpy_update = dumb_update;
3403 ds->dpy_resize = dumb_resize;
3404 ds->dpy_refresh = dumb_refresh;
3407 #if !defined(CONFIG_SOFTMMU)
3408 /***********************************************************/
3409 /* cpu signal handler */
3410 static void host_segv_handler(int host_signum, siginfo_t *info,
3411 void *puc)
3413 if (cpu_signal_handler(host_signum, info, puc))
3414 return;
3415 if (stdio_nb_clients > 0)
3416 term_exit();
3417 abort();
3419 #endif
3421 /***********************************************************/
3422 /* I/O handling */
3424 #define MAX_IO_HANDLERS 64
3426 typedef struct IOHandlerRecord {
3427 int fd;
3428 IOCanRWHandler *fd_read_poll;
3429 IOHandler *fd_read;
3430 IOHandler *fd_write;
3431 void *opaque;
3432 /* temporary data */
3433 struct pollfd *ufd;
3434 struct IOHandlerRecord *next;
3435 } IOHandlerRecord;
3437 static IOHandlerRecord *first_io_handler;
3439 /* XXX: fd_read_poll should be suppressed, but an API change is
3440 necessary in the character devices to suppress fd_can_read(). */
3441 int qemu_set_fd_handler2(int fd,
3442 IOCanRWHandler *fd_read_poll,
3443 IOHandler *fd_read,
3444 IOHandler *fd_write,
3445 void *opaque)
3447 IOHandlerRecord **pioh, *ioh;
3449 if (!fd_read && !fd_write) {
3450 pioh = &first_io_handler;
3451 for(;;) {
3452 ioh = *pioh;
3453 if (ioh == NULL)
3454 break;
3455 if (ioh->fd == fd) {
3456 *pioh = ioh->next;
3457 qemu_free(ioh);
3458 break;
3460 pioh = &ioh->next;
3462 } else {
3463 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3464 if (ioh->fd == fd)
3465 goto found;
3467 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3468 if (!ioh)
3469 return -1;
3470 ioh->next = first_io_handler;
3471 first_io_handler = ioh;
3472 found:
3473 ioh->fd = fd;
3474 ioh->fd_read_poll = fd_read_poll;
3475 ioh->fd_read = fd_read;
3476 ioh->fd_write = fd_write;
3477 ioh->opaque = opaque;
3479 return 0;
3482 int qemu_set_fd_handler(int fd,
3483 IOHandler *fd_read,
3484 IOHandler *fd_write,
3485 void *opaque)
3487 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3490 /***********************************************************/
3491 /* Polling handling */
3493 typedef struct PollingEntry {
3494 PollingFunc *func;
3495 void *opaque;
3496 struct PollingEntry *next;
3497 } PollingEntry;
3499 static PollingEntry *first_polling_entry;
3501 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3503 PollingEntry **ppe, *pe;
3504 pe = qemu_mallocz(sizeof(PollingEntry));
3505 if (!pe)
3506 return -1;
3507 pe->func = func;
3508 pe->opaque = opaque;
3509 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3510 *ppe = pe;
3511 return 0;
3514 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3516 PollingEntry **ppe, *pe;
3517 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3518 pe = *ppe;
3519 if (pe->func == func && pe->opaque == opaque) {
3520 *ppe = pe->next;
3521 qemu_free(pe);
3522 break;
3527 /***********************************************************/
3528 /* savevm/loadvm support */
3530 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3532 fwrite(buf, 1, size, f);
3535 void qemu_put_byte(QEMUFile *f, int v)
3537 fputc(v, f);
3540 void qemu_put_be16(QEMUFile *f, unsigned int v)
3542 qemu_put_byte(f, v >> 8);
3543 qemu_put_byte(f, v);
3546 void qemu_put_be32(QEMUFile *f, unsigned int v)
3548 qemu_put_byte(f, v >> 24);
3549 qemu_put_byte(f, v >> 16);
3550 qemu_put_byte(f, v >> 8);
3551 qemu_put_byte(f, v);
3554 void qemu_put_be64(QEMUFile *f, uint64_t v)
3556 qemu_put_be32(f, v >> 32);
3557 qemu_put_be32(f, v);
3560 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3562 return fread(buf, 1, size, f);
3565 int qemu_get_byte(QEMUFile *f)
3567 int v;
3568 v = fgetc(f);
3569 if (v == EOF)
3570 return 0;
3571 else
3572 return v;
3575 unsigned int qemu_get_be16(QEMUFile *f)
3577 unsigned int v;
3578 v = qemu_get_byte(f) << 8;
3579 v |= qemu_get_byte(f);
3580 return v;
3583 unsigned int qemu_get_be32(QEMUFile *f)
3585 unsigned int v;
3586 v = qemu_get_byte(f) << 24;
3587 v |= qemu_get_byte(f) << 16;
3588 v |= qemu_get_byte(f) << 8;
3589 v |= qemu_get_byte(f);
3590 return v;
3593 uint64_t qemu_get_be64(QEMUFile *f)
3595 uint64_t v;
3596 v = (uint64_t)qemu_get_be32(f) << 32;
3597 v |= qemu_get_be32(f);
3598 return v;
3601 int64_t qemu_ftell(QEMUFile *f)
3603 return ftell(f);
3606 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3608 if (fseek(f, pos, whence) < 0)
3609 return -1;
3610 return ftell(f);
3613 typedef struct SaveStateEntry {
3614 char idstr[256];
3615 int instance_id;
3616 int version_id;
3617 SaveStateHandler *save_state;
3618 LoadStateHandler *load_state;
3619 void *opaque;
3620 struct SaveStateEntry *next;
3621 } SaveStateEntry;
3623 static SaveStateEntry *first_se;
3625 int register_savevm(const char *idstr,
3626 int instance_id,
3627 int version_id,
3628 SaveStateHandler *save_state,
3629 LoadStateHandler *load_state,
3630 void *opaque)
3632 SaveStateEntry *se, **pse;
3634 se = qemu_malloc(sizeof(SaveStateEntry));
3635 if (!se)
3636 return -1;
3637 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3638 se->instance_id = instance_id;
3639 se->version_id = version_id;
3640 se->save_state = save_state;
3641 se->load_state = load_state;
3642 se->opaque = opaque;
3643 se->next = NULL;
3645 /* add at the end of list */
3646 pse = &first_se;
3647 while (*pse != NULL)
3648 pse = &(*pse)->next;
3649 *pse = se;
3650 return 0;
3653 #define QEMU_VM_FILE_MAGIC 0x5145564d
3654 #define QEMU_VM_FILE_VERSION 0x00000001
3656 int qemu_savevm(const char *filename)
3658 SaveStateEntry *se;
3659 QEMUFile *f;
3660 int len, len_pos, cur_pos, saved_vm_running, ret;
3662 saved_vm_running = vm_running;
3663 vm_stop(0);
3665 f = fopen(filename, "wb");
3666 if (!f) {
3667 ret = -1;
3668 goto the_end;
3671 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3672 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3674 for(se = first_se; se != NULL; se = se->next) {
3675 /* ID string */
3676 len = strlen(se->idstr);
3677 qemu_put_byte(f, len);
3678 qemu_put_buffer(f, se->idstr, len);
3680 qemu_put_be32(f, se->instance_id);
3681 qemu_put_be32(f, se->version_id);
3683 /* record size: filled later */
3684 len_pos = ftell(f);
3685 qemu_put_be32(f, 0);
3687 se->save_state(f, se->opaque);
3689 /* fill record size */
3690 cur_pos = ftell(f);
3691 len = ftell(f) - len_pos - 4;
3692 fseek(f, len_pos, SEEK_SET);
3693 qemu_put_be32(f, len);
3694 fseek(f, cur_pos, SEEK_SET);
3697 fclose(f);
3698 ret = 0;
3699 the_end:
3700 if (saved_vm_running)
3701 vm_start();
3702 return ret;
3705 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3707 SaveStateEntry *se;
3709 for(se = first_se; se != NULL; se = se->next) {
3710 if (!strcmp(se->idstr, idstr) &&
3711 instance_id == se->instance_id)
3712 return se;
3714 return NULL;
3717 int qemu_loadvm(const char *filename)
3719 SaveStateEntry *se;
3720 QEMUFile *f;
3721 int len, cur_pos, ret, instance_id, record_len, version_id;
3722 int saved_vm_running;
3723 unsigned int v;
3724 char idstr[256];
3726 saved_vm_running = vm_running;
3727 vm_stop(0);
3729 f = fopen(filename, "rb");
3730 if (!f) {
3731 ret = -1;
3732 goto the_end;
3735 v = qemu_get_be32(f);
3736 if (v != QEMU_VM_FILE_MAGIC)
3737 goto fail;
3738 v = qemu_get_be32(f);
3739 if (v != QEMU_VM_FILE_VERSION) {
3740 fail:
3741 fclose(f);
3742 ret = -1;
3743 goto the_end;
3745 for(;;) {
3746 len = qemu_get_byte(f);
3747 if (feof(f))
3748 break;
3749 qemu_get_buffer(f, idstr, len);
3750 idstr[len] = '\0';
3751 instance_id = qemu_get_be32(f);
3752 version_id = qemu_get_be32(f);
3753 record_len = qemu_get_be32(f);
3754 #if 0
3755 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3756 idstr, instance_id, version_id, record_len);
3757 #endif
3758 cur_pos = ftell(f);
3759 se = find_se(idstr, instance_id);
3760 if (!se) {
3761 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3762 instance_id, idstr);
3763 } else {
3764 ret = se->load_state(f, se->opaque, version_id);
3765 if (ret < 0) {
3766 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3767 instance_id, idstr);
3770 /* always seek to exact end of record */
3771 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3773 fclose(f);
3774 ret = 0;
3775 the_end:
3776 if (saved_vm_running)
3777 vm_start();
3778 return ret;
3781 /***********************************************************/
3782 /* cpu save/restore */
3784 #if defined(TARGET_I386)
3786 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3788 qemu_put_be32(f, dt->selector);
3789 qemu_put_betl(f, dt->base);
3790 qemu_put_be32(f, dt->limit);
3791 qemu_put_be32(f, dt->flags);
3794 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3796 dt->selector = qemu_get_be32(f);
3797 dt->base = qemu_get_betl(f);
3798 dt->limit = qemu_get_be32(f);
3799 dt->flags = qemu_get_be32(f);
3802 void cpu_save(QEMUFile *f, void *opaque)
3804 CPUState *env = opaque;
3805 uint16_t fptag, fpus, fpuc, fpregs_format;
3806 uint32_t hflags;
3807 int i;
3809 for(i = 0; i < CPU_NB_REGS; i++)
3810 qemu_put_betls(f, &env->regs[i]);
3811 qemu_put_betls(f, &env->eip);
3812 qemu_put_betls(f, &env->eflags);
3813 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3814 qemu_put_be32s(f, &hflags);
3816 /* FPU */
3817 fpuc = env->fpuc;
3818 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3819 fptag = 0;
3820 for(i = 0; i < 8; i++) {
3821 fptag |= ((!env->fptags[i]) << i);
3824 qemu_put_be16s(f, &fpuc);
3825 qemu_put_be16s(f, &fpus);
3826 qemu_put_be16s(f, &fptag);
3828 #ifdef USE_X86LDOUBLE
3829 fpregs_format = 0;
3830 #else
3831 fpregs_format = 1;
3832 #endif
3833 qemu_put_be16s(f, &fpregs_format);
3835 for(i = 0; i < 8; i++) {
3836 #ifdef USE_X86LDOUBLE
3838 uint64_t mant;
3839 uint16_t exp;
3840 /* we save the real CPU data (in case of MMX usage only 'mant'
3841 contains the MMX register */
3842 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3843 qemu_put_be64(f, mant);
3844 qemu_put_be16(f, exp);
3846 #else
3847 /* if we use doubles for float emulation, we save the doubles to
3848 avoid losing information in case of MMX usage. It can give
3849 problems if the image is restored on a CPU where long
3850 doubles are used instead. */
3851 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3852 #endif
3855 for(i = 0; i < 6; i++)
3856 cpu_put_seg(f, &env->segs[i]);
3857 cpu_put_seg(f, &env->ldt);
3858 cpu_put_seg(f, &env->tr);
3859 cpu_put_seg(f, &env->gdt);
3860 cpu_put_seg(f, &env->idt);
3862 qemu_put_be32s(f, &env->sysenter_cs);
3863 qemu_put_be32s(f, &env->sysenter_esp);
3864 qemu_put_be32s(f, &env->sysenter_eip);
3866 qemu_put_betls(f, &env->cr[0]);
3867 qemu_put_betls(f, &env->cr[2]);
3868 qemu_put_betls(f, &env->cr[3]);
3869 qemu_put_betls(f, &env->cr[4]);
3871 for(i = 0; i < 8; i++)
3872 qemu_put_betls(f, &env->dr[i]);
3874 /* MMU */
3875 qemu_put_be32s(f, &env->a20_mask);
3877 /* XMM */
3878 qemu_put_be32s(f, &env->mxcsr);
3879 for(i = 0; i < CPU_NB_REGS; i++) {
3880 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3881 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3884 #ifdef TARGET_X86_64
3885 qemu_put_be64s(f, &env->efer);
3886 qemu_put_be64s(f, &env->star);
3887 qemu_put_be64s(f, &env->lstar);
3888 qemu_put_be64s(f, &env->cstar);
3889 qemu_put_be64s(f, &env->fmask);
3890 qemu_put_be64s(f, &env->kernelgsbase);
3891 #endif
3894 #ifdef USE_X86LDOUBLE
3895 /* XXX: add that in a FPU generic layer */
3896 union x86_longdouble {
3897 uint64_t mant;
3898 uint16_t exp;
3901 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3902 #define EXPBIAS1 1023
3903 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3904 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3906 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3908 int e;
3909 /* mantissa */
3910 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3911 /* exponent + sign */
3912 e = EXPD1(temp) - EXPBIAS1 + 16383;
3913 e |= SIGND1(temp) >> 16;
3914 p->exp = e;
3916 #endif
3918 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3920 CPUState *env = opaque;
3921 int i, guess_mmx;
3922 uint32_t hflags;
3923 uint16_t fpus, fpuc, fptag, fpregs_format;
3925 if (version_id != 3)
3926 return -EINVAL;
3927 for(i = 0; i < CPU_NB_REGS; i++)
3928 qemu_get_betls(f, &env->regs[i]);
3929 qemu_get_betls(f, &env->eip);
3930 qemu_get_betls(f, &env->eflags);
3931 qemu_get_be32s(f, &hflags);
3933 qemu_get_be16s(f, &fpuc);
3934 qemu_get_be16s(f, &fpus);
3935 qemu_get_be16s(f, &fptag);
3936 qemu_get_be16s(f, &fpregs_format);
3938 /* NOTE: we cannot always restore the FPU state if the image come
3939 from a host with a different 'USE_X86LDOUBLE' define. We guess
3940 if we are in an MMX state to restore correctly in that case. */
3941 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3942 for(i = 0; i < 8; i++) {
3943 uint64_t mant;
3944 uint16_t exp;
3946 switch(fpregs_format) {
3947 case 0:
3948 mant = qemu_get_be64(f);
3949 exp = qemu_get_be16(f);
3950 #ifdef USE_X86LDOUBLE
3951 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3952 #else
3953 /* difficult case */
3954 if (guess_mmx)
3955 env->fpregs[i].mmx.MMX_Q(0) = mant;
3956 else
3957 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3958 #endif
3959 break;
3960 case 1:
3961 mant = qemu_get_be64(f);
3962 #ifdef USE_X86LDOUBLE
3964 union x86_longdouble *p;
3965 /* difficult case */
3966 p = (void *)&env->fpregs[i];
3967 if (guess_mmx) {
3968 p->mant = mant;
3969 p->exp = 0xffff;
3970 } else {
3971 fp64_to_fp80(p, mant);
3974 #else
3975 env->fpregs[i].mmx.MMX_Q(0) = mant;
3976 #endif
3977 break;
3978 default:
3979 return -EINVAL;
3983 env->fpuc = fpuc;
3984 /* XXX: restore FPU round state */
3985 env->fpstt = (fpus >> 11) & 7;
3986 env->fpus = fpus & ~0x3800;
3987 fptag ^= 0xff;
3988 for(i = 0; i < 8; i++) {
3989 env->fptags[i] = (fptag >> i) & 1;
3992 for(i = 0; i < 6; i++)
3993 cpu_get_seg(f, &env->segs[i]);
3994 cpu_get_seg(f, &env->ldt);
3995 cpu_get_seg(f, &env->tr);
3996 cpu_get_seg(f, &env->gdt);
3997 cpu_get_seg(f, &env->idt);
3999 qemu_get_be32s(f, &env->sysenter_cs);
4000 qemu_get_be32s(f, &env->sysenter_esp);
4001 qemu_get_be32s(f, &env->sysenter_eip);
4003 qemu_get_betls(f, &env->cr[0]);
4004 qemu_get_betls(f, &env->cr[2]);
4005 qemu_get_betls(f, &env->cr[3]);
4006 qemu_get_betls(f, &env->cr[4]);
4008 for(i = 0; i < 8; i++)
4009 qemu_get_betls(f, &env->dr[i]);
4011 /* MMU */
4012 qemu_get_be32s(f, &env->a20_mask);
4014 qemu_get_be32s(f, &env->mxcsr);
4015 for(i = 0; i < CPU_NB_REGS; i++) {
4016 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
4017 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
4020 #ifdef TARGET_X86_64
4021 qemu_get_be64s(f, &env->efer);
4022 qemu_get_be64s(f, &env->star);
4023 qemu_get_be64s(f, &env->lstar);
4024 qemu_get_be64s(f, &env->cstar);
4025 qemu_get_be64s(f, &env->fmask);
4026 qemu_get_be64s(f, &env->kernelgsbase);
4027 #endif
4029 /* XXX: compute hflags from scratch, except for CPL and IIF */
4030 env->hflags = hflags;
4031 tlb_flush(env, 1);
4032 return 0;
4035 #elif defined(TARGET_PPC)
4036 void cpu_save(QEMUFile *f, void *opaque)
4040 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4042 return 0;
4045 #elif defined(TARGET_MIPS)
4046 void cpu_save(QEMUFile *f, void *opaque)
4050 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4052 return 0;
4055 #elif defined(TARGET_SPARC)
4056 void cpu_save(QEMUFile *f, void *opaque)
4058 CPUState *env = opaque;
4059 int i;
4060 uint32_t tmp;
4062 for(i = 0; i < 8; i++)
4063 qemu_put_betls(f, &env->gregs[i]);
4064 for(i = 0; i < NWINDOWS * 16; i++)
4065 qemu_put_betls(f, &env->regbase[i]);
4067 /* FPU */
4068 for(i = 0; i < TARGET_FPREGS; i++) {
4069 union {
4070 TARGET_FPREG_T f;
4071 target_ulong i;
4072 } u;
4073 u.f = env->fpr[i];
4074 qemu_put_betl(f, u.i);
4077 qemu_put_betls(f, &env->pc);
4078 qemu_put_betls(f, &env->npc);
4079 qemu_put_betls(f, &env->y);
4080 tmp = GET_PSR(env);
4081 qemu_put_be32(f, tmp);
4082 qemu_put_betls(f, &env->fsr);
4083 qemu_put_betls(f, &env->tbr);
4084 #ifndef TARGET_SPARC64
4085 qemu_put_be32s(f, &env->wim);
4086 /* MMU */
4087 for(i = 0; i < 16; i++)
4088 qemu_put_be32s(f, &env->mmuregs[i]);
4089 #endif
4092 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4094 CPUState *env = opaque;
4095 int i;
4096 uint32_t tmp;
4098 for(i = 0; i < 8; i++)
4099 qemu_get_betls(f, &env->gregs[i]);
4100 for(i = 0; i < NWINDOWS * 16; i++)
4101 qemu_get_betls(f, &env->regbase[i]);
4103 /* FPU */
4104 for(i = 0; i < TARGET_FPREGS; i++) {
4105 union {
4106 TARGET_FPREG_T f;
4107 target_ulong i;
4108 } u;
4109 u.i = qemu_get_betl(f);
4110 env->fpr[i] = u.f;
4113 qemu_get_betls(f, &env->pc);
4114 qemu_get_betls(f, &env->npc);
4115 qemu_get_betls(f, &env->y);
4116 tmp = qemu_get_be32(f);
4117 env->cwp = 0; /* needed to ensure that the wrapping registers are
4118 correctly updated */
4119 PUT_PSR(env, tmp);
4120 qemu_get_betls(f, &env->fsr);
4121 qemu_get_betls(f, &env->tbr);
4122 #ifndef TARGET_SPARC64
4123 qemu_get_be32s(f, &env->wim);
4124 /* MMU */
4125 for(i = 0; i < 16; i++)
4126 qemu_get_be32s(f, &env->mmuregs[i]);
4127 #endif
4128 tlb_flush(env, 1);
4129 return 0;
4132 #elif defined(TARGET_ARM)
4134 /* ??? Need to implement these. */
4135 void cpu_save(QEMUFile *f, void *opaque)
4139 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4141 return 0;
4144 #else
4146 #warning No CPU save/restore functions
4148 #endif
4150 /***********************************************************/
4151 /* ram save/restore */
4153 /* we just avoid storing empty pages */
4154 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4156 int i, v;
4158 v = buf[0];
4159 for(i = 1; i < len; i++) {
4160 if (buf[i] != v)
4161 goto normal_save;
4163 qemu_put_byte(f, 1);
4164 qemu_put_byte(f, v);
4165 return;
4166 normal_save:
4167 qemu_put_byte(f, 0);
4168 qemu_put_buffer(f, buf, len);
4171 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4173 int v;
4175 v = qemu_get_byte(f);
4176 switch(v) {
4177 case 0:
4178 if (qemu_get_buffer(f, buf, len) != len)
4179 return -EIO;
4180 break;
4181 case 1:
4182 v = qemu_get_byte(f);
4183 memset(buf, v, len);
4184 break;
4185 default:
4186 return -EINVAL;
4188 return 0;
4191 static void ram_save(QEMUFile *f, void *opaque)
4193 int i;
4194 qemu_put_be32(f, phys_ram_size);
4195 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4196 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4200 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4202 int i, ret;
4204 if (version_id != 1)
4205 return -EINVAL;
4206 if (qemu_get_be32(f) != phys_ram_size)
4207 return -EINVAL;
4208 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4209 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4210 if (ret)
4211 return ret;
4213 return 0;
4216 /***********************************************************/
4217 /* machine registration */
4219 QEMUMachine *first_machine = NULL;
4221 int qemu_register_machine(QEMUMachine *m)
4223 QEMUMachine **pm;
4224 pm = &first_machine;
4225 while (*pm != NULL)
4226 pm = &(*pm)->next;
4227 m->next = NULL;
4228 *pm = m;
4229 return 0;
4232 QEMUMachine *find_machine(const char *name)
4234 QEMUMachine *m;
4236 for(m = first_machine; m != NULL; m = m->next) {
4237 if (!strcmp(m->name, name))
4238 return m;
4240 return NULL;
4243 /***********************************************************/
4244 /* main execution loop */
4246 void gui_update(void *opaque)
4248 display_state.dpy_refresh(&display_state);
4249 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4252 struct vm_change_state_entry {
4253 VMChangeStateHandler *cb;
4254 void *opaque;
4255 LIST_ENTRY (vm_change_state_entry) entries;
4258 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4260 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4261 void *opaque)
4263 VMChangeStateEntry *e;
4265 e = qemu_mallocz(sizeof (*e));
4266 if (!e)
4267 return NULL;
4269 e->cb = cb;
4270 e->opaque = opaque;
4271 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4272 return e;
4275 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4277 LIST_REMOVE (e, entries);
4278 qemu_free (e);
4281 static void vm_state_notify(int running)
4283 VMChangeStateEntry *e;
4285 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4286 e->cb(e->opaque, running);
4290 /* XXX: support several handlers */
4291 static VMStopHandler *vm_stop_cb;
4292 static void *vm_stop_opaque;
4294 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4296 vm_stop_cb = cb;
4297 vm_stop_opaque = opaque;
4298 return 0;
4301 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4303 vm_stop_cb = NULL;
4306 void vm_start(void)
4308 if (!vm_running) {
4309 cpu_enable_ticks();
4310 vm_running = 1;
4311 vm_state_notify(1);
4315 void vm_stop(int reason)
4317 if (vm_running) {
4318 cpu_disable_ticks();
4319 vm_running = 0;
4320 if (reason != 0) {
4321 if (vm_stop_cb) {
4322 vm_stop_cb(vm_stop_opaque, reason);
4325 vm_state_notify(0);
4329 /* reset/shutdown handler */
4331 typedef struct QEMUResetEntry {
4332 QEMUResetHandler *func;
4333 void *opaque;
4334 struct QEMUResetEntry *next;
4335 } QEMUResetEntry;
4337 static QEMUResetEntry *first_reset_entry;
4338 static int reset_requested;
4339 static int shutdown_requested;
4340 static int powerdown_requested;
4342 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4344 QEMUResetEntry **pre, *re;
4346 pre = &first_reset_entry;
4347 while (*pre != NULL)
4348 pre = &(*pre)->next;
4349 re = qemu_mallocz(sizeof(QEMUResetEntry));
4350 re->func = func;
4351 re->opaque = opaque;
4352 re->next = NULL;
4353 *pre = re;
4356 void qemu_system_reset(void)
4358 QEMUResetEntry *re;
4360 /* reset all devices */
4361 for(re = first_reset_entry; re != NULL; re = re->next) {
4362 re->func(re->opaque);
4366 void qemu_system_reset_request(void)
4368 reset_requested = 1;
4369 if (cpu_single_env)
4370 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4373 void qemu_system_shutdown_request(void)
4375 shutdown_requested = 1;
4376 if (cpu_single_env)
4377 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4380 void qemu_system_powerdown_request(void)
4382 powerdown_requested = 1;
4383 if (cpu_single_env)
4384 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4387 void main_loop_wait(int timeout)
4389 IOHandlerRecord *ioh, *ioh_next;
4390 fd_set rfds, wfds;
4391 int ret, nfds;
4392 struct timeval tv;
4393 PollingEntry *pe;
4396 /* XXX: need to suppress polling by better using win32 events */
4397 ret = 0;
4398 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4399 ret |= pe->func(pe->opaque);
4401 #ifdef _WIN32
4402 if (ret == 0 && timeout > 0) {
4403 Sleep(timeout);
4405 #endif
4406 /* poll any events */
4407 /* XXX: separate device handlers from system ones */
4408 nfds = -1;
4409 FD_ZERO(&rfds);
4410 FD_ZERO(&wfds);
4411 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4412 if (ioh->fd_read &&
4413 (!ioh->fd_read_poll ||
4414 ioh->fd_read_poll(ioh->opaque) != 0)) {
4415 FD_SET(ioh->fd, &rfds);
4416 if (ioh->fd > nfds)
4417 nfds = ioh->fd;
4419 if (ioh->fd_write) {
4420 FD_SET(ioh->fd, &wfds);
4421 if (ioh->fd > nfds)
4422 nfds = ioh->fd;
4426 tv.tv_sec = 0;
4427 #ifdef _WIN32
4428 tv.tv_usec = 0;
4429 #else
4430 tv.tv_usec = timeout * 1000;
4431 #endif
4432 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4433 if (ret > 0) {
4434 /* XXX: better handling of removal */
4435 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4436 ioh_next = ioh->next;
4437 if (FD_ISSET(ioh->fd, &rfds)) {
4438 ioh->fd_read(ioh->opaque);
4440 if (FD_ISSET(ioh->fd, &wfds)) {
4441 ioh->fd_write(ioh->opaque);
4445 #ifdef _WIN32
4446 tap_win32_poll();
4447 #endif
4449 #if defined(CONFIG_SLIRP)
4450 /* XXX: merge with the previous select() */
4451 if (slirp_inited) {
4452 fd_set rfds, wfds, xfds;
4453 int nfds;
4454 struct timeval tv;
4456 nfds = -1;
4457 FD_ZERO(&rfds);
4458 FD_ZERO(&wfds);
4459 FD_ZERO(&xfds);
4460 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4461 tv.tv_sec = 0;
4462 tv.tv_usec = 0;
4463 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4464 if (ret >= 0) {
4465 slirp_select_poll(&rfds, &wfds, &xfds);
4468 #endif
4470 if (vm_running) {
4471 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4472 qemu_get_clock(vm_clock));
4473 /* run dma transfers, if any */
4474 DMA_run();
4477 /* real time timers */
4478 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4479 qemu_get_clock(rt_clock));
4482 static CPUState *cur_cpu;
4484 int main_loop(void)
4486 int ret, timeout;
4487 #ifdef CONFIG_PROFILER
4488 int64_t ti;
4489 #endif
4490 CPUState *env;
4492 cur_cpu = first_cpu;
4493 for(;;) {
4494 if (vm_running) {
4496 env = cur_cpu;
4497 for(;;) {
4498 /* get next cpu */
4499 env = env->next_cpu;
4500 if (!env)
4501 env = first_cpu;
4502 #ifdef CONFIG_PROFILER
4503 ti = profile_getclock();
4504 #endif
4505 ret = cpu_exec(env);
4506 #ifdef CONFIG_PROFILER
4507 qemu_time += profile_getclock() - ti;
4508 #endif
4509 if (ret != EXCP_HALTED)
4510 break;
4511 /* all CPUs are halted ? */
4512 if (env == cur_cpu) {
4513 ret = EXCP_HLT;
4514 break;
4517 cur_cpu = env;
4519 if (shutdown_requested) {
4520 ret = EXCP_INTERRUPT;
4521 break;
4523 if (reset_requested) {
4524 reset_requested = 0;
4525 qemu_system_reset();
4526 ret = EXCP_INTERRUPT;
4528 if (powerdown_requested) {
4529 powerdown_requested = 0;
4530 qemu_system_powerdown();
4531 ret = EXCP_INTERRUPT;
4533 if (ret == EXCP_DEBUG) {
4534 vm_stop(EXCP_DEBUG);
4536 /* if hlt instruction, we wait until the next IRQ */
4537 /* XXX: use timeout computed from timers */
4538 if (ret == EXCP_HLT)
4539 timeout = 10;
4540 else
4541 timeout = 0;
4542 } else {
4543 timeout = 10;
4545 #ifdef CONFIG_PROFILER
4546 ti = profile_getclock();
4547 #endif
4548 main_loop_wait(timeout);
4549 #ifdef CONFIG_PROFILER
4550 dev_time += profile_getclock() - ti;
4551 #endif
4553 cpu_disable_ticks();
4554 return ret;
4557 void help(void)
4559 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4560 "usage: %s [options] [disk_image]\n"
4561 "\n"
4562 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4563 "\n"
4564 "Standard options:\n"
4565 "-M machine select emulated machine (-M ? for list)\n"
4566 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4567 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4568 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4569 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4570 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4571 "-snapshot write to temporary files instead of disk image files\n"
4572 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4573 "-smp n set the number of CPUs to 'n' [default=1]\n"
4574 "-nographic disable graphical output and redirect serial I/Os to console\n"
4575 #ifndef _WIN32
4576 "-k language use keyboard layout (for example \"fr\" for French)\n"
4577 #endif
4578 #ifdef HAS_AUDIO
4579 "-audio-help print list of audio drivers and their options\n"
4580 "-soundhw c1,... enable audio support\n"
4581 " and only specified sound cards (comma separated list)\n"
4582 " use -soundhw ? to get the list of supported cards\n"
4583 " use -soundhw all to enable all of them\n"
4584 #endif
4585 "-localtime set the real time clock to local time [default=utc]\n"
4586 "-full-screen start in full screen\n"
4587 #ifdef TARGET_I386
4588 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4589 #endif
4590 "-usb enable the USB driver (will be the default soon)\n"
4591 "-usbdevice name add the host or guest USB device 'name'\n"
4592 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4593 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4594 #endif
4595 "\n"
4596 "Network options:\n"
4597 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4598 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4599 #ifdef CONFIG_SLIRP
4600 "-net user[,vlan=n]\n"
4601 " connect the user mode network stack to VLAN 'n'\n"
4602 #endif
4603 #ifdef _WIN32
4604 "-net tap[,vlan=n],ifname=name\n"
4605 " connect the host TAP network interface to VLAN 'n'\n"
4606 #else
4607 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4608 " connect the host TAP network interface to VLAN 'n' and use\n"
4609 " the network script 'file' (default=%s);\n"
4610 " use 'fd=h' to connect to an already opened TAP interface\n"
4611 #endif
4612 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4613 " connect the vlan 'n' to another VLAN using a socket connection\n"
4614 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4615 " connect the vlan 'n' to multicast maddr and port\n"
4616 "-net none use it alone to have zero network devices; if no -net option\n"
4617 " is provided, the default is '-net nic -net user'\n"
4618 "\n"
4619 #ifdef CONFIG_SLIRP
4620 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4621 #ifndef _WIN32
4622 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4623 #endif
4624 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4625 " redirect TCP or UDP connections from host to guest [-net user]\n"
4626 #endif
4627 "\n"
4628 "Linux boot specific:\n"
4629 "-kernel bzImage use 'bzImage' as kernel image\n"
4630 "-append cmdline use 'cmdline' as kernel command line\n"
4631 "-initrd file use 'file' as initial ram disk\n"
4632 "\n"
4633 "Debug/Expert options:\n"
4634 "-monitor dev redirect the monitor to char device 'dev'\n"
4635 "-serial dev redirect the serial port to char device 'dev'\n"
4636 "-parallel dev redirect the parallel port to char device 'dev'\n"
4637 "-pidfile file Write PID to 'file'\n"
4638 "-S freeze CPU at startup (use 'c' to start execution)\n"
4639 "-s wait gdb connection to port %d\n"
4640 "-p port change gdb connection port\n"
4641 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4642 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4643 " translation (t=none or lba) (usually qemu can guess them)\n"
4644 "-L path set the directory for the BIOS and VGA BIOS\n"
4645 #ifdef USE_KQEMU
4646 "-no-kqemu disable KQEMU kernel module usage\n"
4647 #endif
4648 #ifdef USE_CODE_COPY
4649 "-no-code-copy disable code copy acceleration\n"
4650 #endif
4651 #ifdef TARGET_I386
4652 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4653 " (default is CL-GD5446 PCI VGA)\n"
4654 #endif
4655 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4656 "\n"
4657 "During emulation, the following keys are useful:\n"
4658 "ctrl-alt-f toggle full screen\n"
4659 "ctrl-alt-n switch to virtual console 'n'\n"
4660 "ctrl-alt toggle mouse and keyboard grab\n"
4661 "\n"
4662 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4664 #ifdef CONFIG_SOFTMMU
4665 "qemu",
4666 #else
4667 "qemu-fast",
4668 #endif
4669 DEFAULT_RAM_SIZE,
4670 #ifndef _WIN32
4671 DEFAULT_NETWORK_SCRIPT,
4672 #endif
4673 DEFAULT_GDBSTUB_PORT,
4674 "/tmp/qemu.log");
4675 #ifndef CONFIG_SOFTMMU
4676 printf("\n"
4677 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4678 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4679 "PC emulation.\n");
4680 #endif
4681 exit(1);
4684 #define HAS_ARG 0x0001
4686 enum {
4687 QEMU_OPTION_h,
4689 QEMU_OPTION_M,
4690 QEMU_OPTION_fda,
4691 QEMU_OPTION_fdb,
4692 QEMU_OPTION_hda,
4693 QEMU_OPTION_hdb,
4694 QEMU_OPTION_hdc,
4695 QEMU_OPTION_hdd,
4696 QEMU_OPTION_cdrom,
4697 QEMU_OPTION_boot,
4698 QEMU_OPTION_snapshot,
4699 QEMU_OPTION_m,
4700 QEMU_OPTION_nographic,
4701 #ifdef HAS_AUDIO
4702 QEMU_OPTION_audio_help,
4703 QEMU_OPTION_soundhw,
4704 #endif
4706 QEMU_OPTION_net,
4707 QEMU_OPTION_tftp,
4708 QEMU_OPTION_smb,
4709 QEMU_OPTION_redir,
4711 QEMU_OPTION_kernel,
4712 QEMU_OPTION_append,
4713 QEMU_OPTION_initrd,
4715 QEMU_OPTION_S,
4716 QEMU_OPTION_s,
4717 QEMU_OPTION_p,
4718 QEMU_OPTION_d,
4719 QEMU_OPTION_hdachs,
4720 QEMU_OPTION_L,
4721 QEMU_OPTION_no_code_copy,
4722 QEMU_OPTION_k,
4723 QEMU_OPTION_localtime,
4724 QEMU_OPTION_cirrusvga,
4725 QEMU_OPTION_g,
4726 QEMU_OPTION_std_vga,
4727 QEMU_OPTION_monitor,
4728 QEMU_OPTION_serial,
4729 QEMU_OPTION_parallel,
4730 QEMU_OPTION_loadvm,
4731 QEMU_OPTION_full_screen,
4732 QEMU_OPTION_pidfile,
4733 QEMU_OPTION_no_kqemu,
4734 QEMU_OPTION_kernel_kqemu,
4735 QEMU_OPTION_win2k_hack,
4736 QEMU_OPTION_usb,
4737 QEMU_OPTION_usbdevice,
4738 QEMU_OPTION_smp,
4741 typedef struct QEMUOption {
4742 const char *name;
4743 int flags;
4744 int index;
4745 } QEMUOption;
4747 const QEMUOption qemu_options[] = {
4748 { "h", 0, QEMU_OPTION_h },
4750 { "M", HAS_ARG, QEMU_OPTION_M },
4751 { "fda", HAS_ARG, QEMU_OPTION_fda },
4752 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4753 { "hda", HAS_ARG, QEMU_OPTION_hda },
4754 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4755 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4756 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4757 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4758 { "boot", HAS_ARG, QEMU_OPTION_boot },
4759 { "snapshot", 0, QEMU_OPTION_snapshot },
4760 { "m", HAS_ARG, QEMU_OPTION_m },
4761 { "nographic", 0, QEMU_OPTION_nographic },
4762 { "k", HAS_ARG, QEMU_OPTION_k },
4763 #ifdef HAS_AUDIO
4764 { "audio-help", 0, QEMU_OPTION_audio_help },
4765 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4766 #endif
4768 { "net", HAS_ARG, QEMU_OPTION_net},
4769 #ifdef CONFIG_SLIRP
4770 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4771 #ifndef _WIN32
4772 { "smb", HAS_ARG, QEMU_OPTION_smb },
4773 #endif
4774 { "redir", HAS_ARG, QEMU_OPTION_redir },
4775 #endif
4777 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4778 { "append", HAS_ARG, QEMU_OPTION_append },
4779 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4781 { "S", 0, QEMU_OPTION_S },
4782 { "s", 0, QEMU_OPTION_s },
4783 { "p", HAS_ARG, QEMU_OPTION_p },
4784 { "d", HAS_ARG, QEMU_OPTION_d },
4785 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4786 { "L", HAS_ARG, QEMU_OPTION_L },
4787 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4788 #ifdef USE_KQEMU
4789 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4790 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4791 #endif
4792 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4793 { "g", 1, QEMU_OPTION_g },
4794 #endif
4795 { "localtime", 0, QEMU_OPTION_localtime },
4796 { "std-vga", 0, QEMU_OPTION_std_vga },
4797 { "monitor", 1, QEMU_OPTION_monitor },
4798 { "serial", 1, QEMU_OPTION_serial },
4799 { "parallel", 1, QEMU_OPTION_parallel },
4800 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4801 { "full-screen", 0, QEMU_OPTION_full_screen },
4802 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4803 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4804 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4805 { "smp", HAS_ARG, QEMU_OPTION_smp },
4807 /* temporary options */
4808 { "usb", 0, QEMU_OPTION_usb },
4809 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4810 { NULL },
4813 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4815 /* this stack is only used during signal handling */
4816 #define SIGNAL_STACK_SIZE 32768
4818 static uint8_t *signal_stack;
4820 #endif
4822 /* password input */
4824 static BlockDriverState *get_bdrv(int index)
4826 BlockDriverState *bs;
4828 if (index < 4) {
4829 bs = bs_table[index];
4830 } else if (index < 6) {
4831 bs = fd_table[index - 4];
4832 } else {
4833 bs = NULL;
4835 return bs;
4838 static void read_passwords(void)
4840 BlockDriverState *bs;
4841 int i, j;
4842 char password[256];
4844 for(i = 0; i < 6; i++) {
4845 bs = get_bdrv(i);
4846 if (bs && bdrv_is_encrypted(bs)) {
4847 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4848 for(j = 0; j < 3; j++) {
4849 monitor_readline("Password: ",
4850 1, password, sizeof(password));
4851 if (bdrv_set_key(bs, password) == 0)
4852 break;
4853 term_printf("invalid password\n");
4859 /* XXX: currently we cannot use simultaneously different CPUs */
4860 void register_machines(void)
4862 #if defined(TARGET_I386)
4863 qemu_register_machine(&pc_machine);
4864 qemu_register_machine(&isapc_machine);
4865 #elif defined(TARGET_PPC)
4866 qemu_register_machine(&heathrow_machine);
4867 qemu_register_machine(&core99_machine);
4868 qemu_register_machine(&prep_machine);
4869 #elif defined(TARGET_MIPS)
4870 qemu_register_machine(&mips_machine);
4871 #elif defined(TARGET_SPARC)
4872 #ifdef TARGET_SPARC64
4873 qemu_register_machine(&sun4u_machine);
4874 #else
4875 qemu_register_machine(&sun4m_machine);
4876 #endif
4877 #elif defined(TARGET_ARM)
4878 qemu_register_machine(&integratorcp926_machine);
4879 qemu_register_machine(&integratorcp1026_machine);
4880 qemu_register_machine(&versatilepb_machine);
4881 #else
4882 #error unsupported CPU
4883 #endif
4886 #ifdef HAS_AUDIO
4887 struct soundhw soundhw[] = {
4889 "sb16",
4890 "Creative Sound Blaster 16",
4893 { .init_isa = SB16_init }
4896 #ifdef CONFIG_ADLIB
4898 "adlib",
4899 #ifdef HAS_YMF262
4900 "Yamaha YMF262 (OPL3)",
4901 #else
4902 "Yamaha YM3812 (OPL2)",
4903 #endif
4906 { .init_isa = Adlib_init }
4908 #endif
4910 #ifdef CONFIG_GUS
4912 "gus",
4913 "Gravis Ultrasound GF1",
4916 { .init_isa = GUS_init }
4918 #endif
4921 "es1370",
4922 "ENSONIQ AudioPCI ES1370",
4925 { .init_pci = es1370_init }
4928 { NULL, NULL, 0, 0, { NULL } }
4931 static void select_soundhw (const char *optarg)
4933 struct soundhw *c;
4935 if (*optarg == '?') {
4936 show_valid_cards:
4938 printf ("Valid sound card names (comma separated):\n");
4939 for (c = soundhw; c->name; ++c) {
4940 printf ("%-11s %s\n", c->name, c->descr);
4942 printf ("\n-soundhw all will enable all of the above\n");
4943 exit (*optarg != '?');
4945 else {
4946 size_t l;
4947 const char *p;
4948 char *e;
4949 int bad_card = 0;
4951 if (!strcmp (optarg, "all")) {
4952 for (c = soundhw; c->name; ++c) {
4953 c->enabled = 1;
4955 return;
4958 p = optarg;
4959 while (*p) {
4960 e = strchr (p, ',');
4961 l = !e ? strlen (p) : (size_t) (e - p);
4963 for (c = soundhw; c->name; ++c) {
4964 if (!strncmp (c->name, p, l)) {
4965 c->enabled = 1;
4966 break;
4970 if (!c->name) {
4971 if (l > 80) {
4972 fprintf (stderr,
4973 "Unknown sound card name (too big to show)\n");
4975 else {
4976 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4977 (int) l, p);
4979 bad_card = 1;
4981 p += l + (e != NULL);
4984 if (bad_card)
4985 goto show_valid_cards;
4988 #endif
4990 #define MAX_NET_CLIENTS 32
4992 int main(int argc, char **argv)
4994 #ifdef CONFIG_GDBSTUB
4995 int use_gdbstub, gdbstub_port;
4996 #endif
4997 int i, cdrom_index;
4998 int snapshot, linux_boot;
4999 const char *initrd_filename;
5000 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
5001 const char *kernel_filename, *kernel_cmdline;
5002 DisplayState *ds = &display_state;
5003 int cyls, heads, secs, translation;
5004 int start_emulation = 1;
5005 char net_clients[MAX_NET_CLIENTS][256];
5006 int nb_net_clients;
5007 int optind;
5008 const char *r, *optarg;
5009 CharDriverState *monitor_hd;
5010 char monitor_device[128];
5011 char serial_devices[MAX_SERIAL_PORTS][128];
5012 int serial_device_index;
5013 char parallel_devices[MAX_PARALLEL_PORTS][128];
5014 int parallel_device_index;
5015 const char *loadvm = NULL;
5016 QEMUMachine *machine;
5017 char usb_devices[MAX_VM_USB_PORTS][128];
5018 int usb_devices_index;
5020 LIST_INIT (&vm_change_state_head);
5021 #if !defined(CONFIG_SOFTMMU)
5022 /* we never want that malloc() uses mmap() */
5023 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5024 #endif
5025 register_machines();
5026 machine = first_machine;
5027 initrd_filename = NULL;
5028 for(i = 0; i < MAX_FD; i++)
5029 fd_filename[i] = NULL;
5030 for(i = 0; i < MAX_DISKS; i++)
5031 hd_filename[i] = NULL;
5032 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5033 vga_ram_size = VGA_RAM_SIZE;
5034 bios_size = BIOS_SIZE;
5035 #ifdef CONFIG_GDBSTUB
5036 use_gdbstub = 0;
5037 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5038 #endif
5039 snapshot = 0;
5040 nographic = 0;
5041 kernel_filename = NULL;
5042 kernel_cmdline = "";
5043 #ifdef TARGET_PPC
5044 cdrom_index = 1;
5045 #else
5046 cdrom_index = 2;
5047 #endif
5048 cyls = heads = secs = 0;
5049 translation = BIOS_ATA_TRANSLATION_AUTO;
5050 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5052 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5053 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5054 serial_devices[i][0] = '\0';
5055 serial_device_index = 0;
5057 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5058 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5059 parallel_devices[i][0] = '\0';
5060 parallel_device_index = 0;
5062 usb_devices_index = 0;
5064 nb_net_clients = 0;
5066 nb_nics = 0;
5067 /* default mac address of the first network interface */
5069 optind = 1;
5070 for(;;) {
5071 if (optind >= argc)
5072 break;
5073 r = argv[optind];
5074 if (r[0] != '-') {
5075 hd_filename[0] = argv[optind++];
5076 } else {
5077 const QEMUOption *popt;
5079 optind++;
5080 popt = qemu_options;
5081 for(;;) {
5082 if (!popt->name) {
5083 fprintf(stderr, "%s: invalid option -- '%s'\n",
5084 argv[0], r);
5085 exit(1);
5087 if (!strcmp(popt->name, r + 1))
5088 break;
5089 popt++;
5091 if (popt->flags & HAS_ARG) {
5092 if (optind >= argc) {
5093 fprintf(stderr, "%s: option '%s' requires an argument\n",
5094 argv[0], r);
5095 exit(1);
5097 optarg = argv[optind++];
5098 } else {
5099 optarg = NULL;
5102 switch(popt->index) {
5103 case QEMU_OPTION_M:
5104 machine = find_machine(optarg);
5105 if (!machine) {
5106 QEMUMachine *m;
5107 printf("Supported machines are:\n");
5108 for(m = first_machine; m != NULL; m = m->next) {
5109 printf("%-10s %s%s\n",
5110 m->name, m->desc,
5111 m == first_machine ? " (default)" : "");
5113 exit(1);
5115 break;
5116 case QEMU_OPTION_initrd:
5117 initrd_filename = optarg;
5118 break;
5119 case QEMU_OPTION_hda:
5120 case QEMU_OPTION_hdb:
5121 case QEMU_OPTION_hdc:
5122 case QEMU_OPTION_hdd:
5124 int hd_index;
5125 hd_index = popt->index - QEMU_OPTION_hda;
5126 hd_filename[hd_index] = optarg;
5127 if (hd_index == cdrom_index)
5128 cdrom_index = -1;
5130 break;
5131 case QEMU_OPTION_snapshot:
5132 snapshot = 1;
5133 break;
5134 case QEMU_OPTION_hdachs:
5136 const char *p;
5137 p = optarg;
5138 cyls = strtol(p, (char **)&p, 0);
5139 if (cyls < 1 || cyls > 16383)
5140 goto chs_fail;
5141 if (*p != ',')
5142 goto chs_fail;
5143 p++;
5144 heads = strtol(p, (char **)&p, 0);
5145 if (heads < 1 || heads > 16)
5146 goto chs_fail;
5147 if (*p != ',')
5148 goto chs_fail;
5149 p++;
5150 secs = strtol(p, (char **)&p, 0);
5151 if (secs < 1 || secs > 63)
5152 goto chs_fail;
5153 if (*p == ',') {
5154 p++;
5155 if (!strcmp(p, "none"))
5156 translation = BIOS_ATA_TRANSLATION_NONE;
5157 else if (!strcmp(p, "lba"))
5158 translation = BIOS_ATA_TRANSLATION_LBA;
5159 else if (!strcmp(p, "auto"))
5160 translation = BIOS_ATA_TRANSLATION_AUTO;
5161 else
5162 goto chs_fail;
5163 } else if (*p != '\0') {
5164 chs_fail:
5165 fprintf(stderr, "qemu: invalid physical CHS format\n");
5166 exit(1);
5169 break;
5170 case QEMU_OPTION_nographic:
5171 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5172 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5173 nographic = 1;
5174 break;
5175 case QEMU_OPTION_kernel:
5176 kernel_filename = optarg;
5177 break;
5178 case QEMU_OPTION_append:
5179 kernel_cmdline = optarg;
5180 break;
5181 case QEMU_OPTION_cdrom:
5182 if (cdrom_index >= 0) {
5183 hd_filename[cdrom_index] = optarg;
5185 break;
5186 case QEMU_OPTION_boot:
5187 boot_device = optarg[0];
5188 if (boot_device != 'a' &&
5189 #ifdef TARGET_SPARC
5190 // Network boot
5191 boot_device != 'n' &&
5192 #endif
5193 boot_device != 'c' && boot_device != 'd') {
5194 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5195 exit(1);
5197 break;
5198 case QEMU_OPTION_fda:
5199 fd_filename[0] = optarg;
5200 break;
5201 case QEMU_OPTION_fdb:
5202 fd_filename[1] = optarg;
5203 break;
5204 case QEMU_OPTION_no_code_copy:
5205 code_copy_enabled = 0;
5206 break;
5207 case QEMU_OPTION_net:
5208 if (nb_net_clients >= MAX_NET_CLIENTS) {
5209 fprintf(stderr, "qemu: too many network clients\n");
5210 exit(1);
5212 pstrcpy(net_clients[nb_net_clients],
5213 sizeof(net_clients[0]),
5214 optarg);
5215 nb_net_clients++;
5216 break;
5217 #ifdef CONFIG_SLIRP
5218 case QEMU_OPTION_tftp:
5219 tftp_prefix = optarg;
5220 break;
5221 #ifndef _WIN32
5222 case QEMU_OPTION_smb:
5223 net_slirp_smb(optarg);
5224 break;
5225 #endif
5226 case QEMU_OPTION_redir:
5227 net_slirp_redir(optarg);
5228 break;
5229 #endif
5230 #ifdef HAS_AUDIO
5231 case QEMU_OPTION_audio_help:
5232 AUD_help ();
5233 exit (0);
5234 break;
5235 case QEMU_OPTION_soundhw:
5236 select_soundhw (optarg);
5237 break;
5238 #endif
5239 case QEMU_OPTION_h:
5240 help();
5241 break;
5242 case QEMU_OPTION_m:
5243 ram_size = atoi(optarg) * 1024 * 1024;
5244 if (ram_size <= 0)
5245 help();
5246 if (ram_size > PHYS_RAM_MAX_SIZE) {
5247 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5248 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5249 exit(1);
5251 break;
5252 case QEMU_OPTION_d:
5254 int mask;
5255 CPULogItem *item;
5257 mask = cpu_str_to_log_mask(optarg);
5258 if (!mask) {
5259 printf("Log items (comma separated):\n");
5260 for(item = cpu_log_items; item->mask != 0; item++) {
5261 printf("%-10s %s\n", item->name, item->help);
5263 exit(1);
5265 cpu_set_log(mask);
5267 break;
5268 #ifdef CONFIG_GDBSTUB
5269 case QEMU_OPTION_s:
5270 use_gdbstub = 1;
5271 break;
5272 case QEMU_OPTION_p:
5273 gdbstub_port = atoi(optarg);
5274 break;
5275 #endif
5276 case QEMU_OPTION_L:
5277 bios_dir = optarg;
5278 break;
5279 case QEMU_OPTION_S:
5280 start_emulation = 0;
5281 break;
5282 case QEMU_OPTION_k:
5283 keyboard_layout = optarg;
5284 break;
5285 case QEMU_OPTION_localtime:
5286 rtc_utc = 0;
5287 break;
5288 case QEMU_OPTION_cirrusvga:
5289 cirrus_vga_enabled = 1;
5290 break;
5291 case QEMU_OPTION_std_vga:
5292 cirrus_vga_enabled = 0;
5293 break;
5294 case QEMU_OPTION_g:
5296 const char *p;
5297 int w, h, depth;
5298 p = optarg;
5299 w = strtol(p, (char **)&p, 10);
5300 if (w <= 0) {
5301 graphic_error:
5302 fprintf(stderr, "qemu: invalid resolution or depth\n");
5303 exit(1);
5305 if (*p != 'x')
5306 goto graphic_error;
5307 p++;
5308 h = strtol(p, (char **)&p, 10);
5309 if (h <= 0)
5310 goto graphic_error;
5311 if (*p == 'x') {
5312 p++;
5313 depth = strtol(p, (char **)&p, 10);
5314 if (depth != 8 && depth != 15 && depth != 16 &&
5315 depth != 24 && depth != 32)
5316 goto graphic_error;
5317 } else if (*p == '\0') {
5318 depth = graphic_depth;
5319 } else {
5320 goto graphic_error;
5323 graphic_width = w;
5324 graphic_height = h;
5325 graphic_depth = depth;
5327 break;
5328 case QEMU_OPTION_monitor:
5329 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5330 break;
5331 case QEMU_OPTION_serial:
5332 if (serial_device_index >= MAX_SERIAL_PORTS) {
5333 fprintf(stderr, "qemu: too many serial ports\n");
5334 exit(1);
5336 pstrcpy(serial_devices[serial_device_index],
5337 sizeof(serial_devices[0]), optarg);
5338 serial_device_index++;
5339 break;
5340 case QEMU_OPTION_parallel:
5341 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5342 fprintf(stderr, "qemu: too many parallel ports\n");
5343 exit(1);
5345 pstrcpy(parallel_devices[parallel_device_index],
5346 sizeof(parallel_devices[0]), optarg);
5347 parallel_device_index++;
5348 break;
5349 case QEMU_OPTION_loadvm:
5350 loadvm = optarg;
5351 break;
5352 case QEMU_OPTION_full_screen:
5353 full_screen = 1;
5354 break;
5355 case QEMU_OPTION_pidfile:
5356 create_pidfile(optarg);
5357 break;
5358 #ifdef TARGET_I386
5359 case QEMU_OPTION_win2k_hack:
5360 win2k_install_hack = 1;
5361 break;
5362 #endif
5363 #ifdef USE_KQEMU
5364 case QEMU_OPTION_no_kqemu:
5365 kqemu_allowed = 0;
5366 break;
5367 case QEMU_OPTION_kernel_kqemu:
5368 kqemu_allowed = 2;
5369 break;
5370 #endif
5371 case QEMU_OPTION_usb:
5372 usb_enabled = 1;
5373 break;
5374 case QEMU_OPTION_usbdevice:
5375 usb_enabled = 1;
5376 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5377 fprintf(stderr, "Too many USB devices\n");
5378 exit(1);
5380 pstrcpy(usb_devices[usb_devices_index],
5381 sizeof(usb_devices[usb_devices_index]),
5382 optarg);
5383 usb_devices_index++;
5384 break;
5385 case QEMU_OPTION_smp:
5386 smp_cpus = atoi(optarg);
5387 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5388 fprintf(stderr, "Invalid number of CPUs\n");
5389 exit(1);
5391 break;
5396 #ifdef USE_KQEMU
5397 if (smp_cpus > 1)
5398 kqemu_allowed = 0;
5399 #endif
5400 linux_boot = (kernel_filename != NULL);
5402 if (!linux_boot &&
5403 hd_filename[0] == '\0' &&
5404 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5405 fd_filename[0] == '\0')
5406 help();
5408 /* boot to cd by default if no hard disk */
5409 if (hd_filename[0] == '\0' && boot_device == 'c') {
5410 if (fd_filename[0] != '\0')
5411 boot_device = 'a';
5412 else
5413 boot_device = 'd';
5416 #if !defined(CONFIG_SOFTMMU)
5417 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5419 static uint8_t stdout_buf[4096];
5420 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5422 #else
5423 setvbuf(stdout, NULL, _IOLBF, 0);
5424 #endif
5426 #ifdef _WIN32
5427 socket_init();
5428 #endif
5430 /* init network clients */
5431 if (nb_net_clients == 0) {
5432 /* if no clients, we use a default config */
5433 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5434 "nic");
5435 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5436 "user");
5437 nb_net_clients = 2;
5440 for(i = 0;i < nb_net_clients; i++) {
5441 if (net_client_init(net_clients[i]) < 0)
5442 exit(1);
5445 /* init the memory */
5446 phys_ram_size = ram_size + vga_ram_size + bios_size;
5448 #ifdef CONFIG_SOFTMMU
5449 phys_ram_base = qemu_vmalloc(phys_ram_size);
5450 if (!phys_ram_base) {
5451 fprintf(stderr, "Could not allocate physical memory\n");
5452 exit(1);
5454 #else
5455 /* as we must map the same page at several addresses, we must use
5456 a fd */
5458 const char *tmpdir;
5460 tmpdir = getenv("QEMU_TMPDIR");
5461 if (!tmpdir)
5462 tmpdir = "/tmp";
5463 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5464 if (mkstemp(phys_ram_file) < 0) {
5465 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5466 phys_ram_file);
5467 exit(1);
5469 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5470 if (phys_ram_fd < 0) {
5471 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5472 phys_ram_file);
5473 exit(1);
5475 ftruncate(phys_ram_fd, phys_ram_size);
5476 unlink(phys_ram_file);
5477 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5478 phys_ram_size,
5479 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5480 phys_ram_fd, 0);
5481 if (phys_ram_base == MAP_FAILED) {
5482 fprintf(stderr, "Could not map physical memory\n");
5483 exit(1);
5486 #endif
5488 /* we always create the cdrom drive, even if no disk is there */
5489 bdrv_init();
5490 if (cdrom_index >= 0) {
5491 bs_table[cdrom_index] = bdrv_new("cdrom");
5492 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5495 /* open the virtual block devices */
5496 for(i = 0; i < MAX_DISKS; i++) {
5497 if (hd_filename[i]) {
5498 if (!bs_table[i]) {
5499 char buf[64];
5500 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5501 bs_table[i] = bdrv_new(buf);
5503 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5504 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5505 hd_filename[i]);
5506 exit(1);
5508 if (i == 0 && cyls != 0) {
5509 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5510 bdrv_set_translation_hint(bs_table[i], translation);
5515 /* we always create at least one floppy disk */
5516 fd_table[0] = bdrv_new("fda");
5517 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5519 for(i = 0; i < MAX_FD; i++) {
5520 if (fd_filename[i]) {
5521 if (!fd_table[i]) {
5522 char buf[64];
5523 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5524 fd_table[i] = bdrv_new(buf);
5525 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5527 if (fd_filename[i] != '\0') {
5528 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5529 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5530 fd_filename[i]);
5531 exit(1);
5537 /* init USB devices */
5538 if (usb_enabled) {
5539 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5540 for(i = 0; i < usb_devices_index; i++) {
5541 if (usb_device_add(usb_devices[i]) < 0) {
5542 fprintf(stderr, "Warning: could not add USB device %s\n",
5543 usb_devices[i]);
5548 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5549 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5551 init_ioports();
5552 cpu_calibrate_ticks();
5554 /* terminal init */
5555 if (nographic) {
5556 dumb_display_init(ds);
5557 } else {
5558 #if defined(CONFIG_SDL)
5559 sdl_display_init(ds, full_screen);
5560 #elif defined(CONFIG_COCOA)
5561 cocoa_display_init(ds, full_screen);
5562 #else
5563 dumb_display_init(ds);
5564 #endif
5567 monitor_hd = qemu_chr_open(monitor_device);
5568 if (!monitor_hd) {
5569 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5570 exit(1);
5572 monitor_init(monitor_hd, !nographic);
5574 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5575 if (serial_devices[i][0] != '\0') {
5576 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5577 if (!serial_hds[i]) {
5578 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5579 serial_devices[i]);
5580 exit(1);
5582 if (!strcmp(serial_devices[i], "vc"))
5583 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5587 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5588 if (parallel_devices[i][0] != '\0') {
5589 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5590 if (!parallel_hds[i]) {
5591 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5592 parallel_devices[i]);
5593 exit(1);
5595 if (!strcmp(parallel_devices[i], "vc"))
5596 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5600 /* setup cpu signal handlers for MMU / self modifying code handling */
5601 #if !defined(CONFIG_SOFTMMU)
5603 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5605 stack_t stk;
5606 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5607 stk.ss_sp = signal_stack;
5608 stk.ss_size = SIGNAL_STACK_SIZE;
5609 stk.ss_flags = 0;
5611 if (sigaltstack(&stk, NULL) < 0) {
5612 perror("sigaltstack");
5613 exit(1);
5616 #endif
5618 struct sigaction act;
5620 sigfillset(&act.sa_mask);
5621 act.sa_flags = SA_SIGINFO;
5622 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5623 act.sa_flags |= SA_ONSTACK;
5624 #endif
5625 act.sa_sigaction = host_segv_handler;
5626 sigaction(SIGSEGV, &act, NULL);
5627 sigaction(SIGBUS, &act, NULL);
5628 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5629 sigaction(SIGFPE, &act, NULL);
5630 #endif
5632 #endif
5634 #ifndef _WIN32
5636 struct sigaction act;
5637 sigfillset(&act.sa_mask);
5638 act.sa_flags = 0;
5639 act.sa_handler = SIG_IGN;
5640 sigaction(SIGPIPE, &act, NULL);
5642 #endif
5643 init_timers();
5645 machine->init(ram_size, vga_ram_size, boot_device,
5646 ds, fd_filename, snapshot,
5647 kernel_filename, kernel_cmdline, initrd_filename);
5649 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5650 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5652 #ifdef CONFIG_GDBSTUB
5653 if (use_gdbstub) {
5654 if (gdbserver_start(gdbstub_port) < 0) {
5655 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5656 gdbstub_port);
5657 exit(1);
5658 } else {
5659 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5661 } else
5662 #endif
5663 if (loadvm)
5664 qemu_loadvm(loadvm);
5667 /* XXX: simplify init */
5668 read_passwords();
5669 if (start_emulation) {
5670 vm_start();
5673 main_loop();
5674 quit_timers();
5675 return 0;