Autodetect tools neccessary for building documentation.
[qemu/mini2440.git] / vl.c
blob36b7e24fe31e641f7c0bd4e1298a3ab2663694da
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 void cpu_outb(CPUState *env, int addr, int val)
337 #ifdef DEBUG_IOPORT
338 if (loglevel & CPU_LOG_IOPORT)
339 fprintf(logfile, "outb: %04x %02x\n", addr, val);
340 #endif
341 ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
342 #ifdef USE_KQEMU
343 if (env)
344 env->last_io_time = cpu_get_time_fast();
345 #endif
348 void cpu_outw(CPUState *env, int addr, int val)
350 #ifdef DEBUG_IOPORT
351 if (loglevel & CPU_LOG_IOPORT)
352 fprintf(logfile, "outw: %04x %04x\n", addr, val);
353 #endif
354 ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
355 #ifdef USE_KQEMU
356 if (env)
357 env->last_io_time = cpu_get_time_fast();
358 #endif
361 void cpu_outl(CPUState *env, int addr, int val)
363 #ifdef DEBUG_IOPORT
364 if (loglevel & CPU_LOG_IOPORT)
365 fprintf(logfile, "outl: %04x %08x\n", addr, val);
366 #endif
367 ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
368 #ifdef USE_KQEMU
369 if (env)
370 env->last_io_time = cpu_get_time_fast();
371 #endif
374 int cpu_inb(CPUState *env, int addr)
376 int val;
377 val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
378 #ifdef DEBUG_IOPORT
379 if (loglevel & CPU_LOG_IOPORT)
380 fprintf(logfile, "inb : %04x %02x\n", addr, val);
381 #endif
382 #ifdef USE_KQEMU
383 if (env)
384 env->last_io_time = cpu_get_time_fast();
385 #endif
386 return val;
389 int cpu_inw(CPUState *env, int addr)
391 int val;
392 val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
393 #ifdef DEBUG_IOPORT
394 if (loglevel & CPU_LOG_IOPORT)
395 fprintf(logfile, "inw : %04x %04x\n", addr, val);
396 #endif
397 #ifdef USE_KQEMU
398 if (env)
399 env->last_io_time = cpu_get_time_fast();
400 #endif
401 return val;
404 int cpu_inl(CPUState *env, int addr)
406 int val;
407 val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
408 #ifdef DEBUG_IOPORT
409 if (loglevel & CPU_LOG_IOPORT)
410 fprintf(logfile, "inl : %04x %08x\n", addr, val);
411 #endif
412 #ifdef USE_KQEMU
413 if (env)
414 env->last_io_time = cpu_get_time_fast();
415 #endif
416 return val;
419 /***********************************************************/
420 void hw_error(const char *fmt, ...)
422 va_list ap;
423 CPUState *env;
425 va_start(ap, fmt);
426 fprintf(stderr, "qemu: hardware error: ");
427 vfprintf(stderr, fmt, ap);
428 fprintf(stderr, "\n");
429 for(env = first_cpu; env != NULL; env = env->next_cpu) {
430 fprintf(stderr, "CPU #%d:\n", env->cpu_index);
431 #ifdef TARGET_I386
432 cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
433 #else
434 cpu_dump_state(env, stderr, fprintf, 0);
435 #endif
437 va_end(ap);
438 abort();
441 /***********************************************************/
442 /* keyboard/mouse */
444 static QEMUPutKBDEvent *qemu_put_kbd_event;
445 static void *qemu_put_kbd_event_opaque;
446 static QEMUPutMouseEvent *qemu_put_mouse_event;
447 static void *qemu_put_mouse_event_opaque;
448 static int qemu_put_mouse_event_absolute;
450 void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
452 qemu_put_kbd_event_opaque = opaque;
453 qemu_put_kbd_event = func;
456 void qemu_add_mouse_event_handler(QEMUPutMouseEvent *func, void *opaque, int absolute)
458 qemu_put_mouse_event_opaque = opaque;
459 qemu_put_mouse_event = func;
460 qemu_put_mouse_event_absolute = absolute;
463 void kbd_put_keycode(int keycode)
465 if (qemu_put_kbd_event) {
466 qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
470 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
472 if (qemu_put_mouse_event) {
473 qemu_put_mouse_event(qemu_put_mouse_event_opaque,
474 dx, dy, dz, buttons_state);
478 int kbd_mouse_is_absolute(void)
480 return qemu_put_mouse_event_absolute;
483 /***********************************************************/
484 /* timers */
486 #if defined(__powerpc__)
488 static inline uint32_t get_tbl(void)
490 uint32_t tbl;
491 asm volatile("mftb %0" : "=r" (tbl));
492 return tbl;
495 static inline uint32_t get_tbu(void)
497 uint32_t tbl;
498 asm volatile("mftbu %0" : "=r" (tbl));
499 return tbl;
502 int64_t cpu_get_real_ticks(void)
504 uint32_t l, h, h1;
505 /* NOTE: we test if wrapping has occurred */
506 do {
507 h = get_tbu();
508 l = get_tbl();
509 h1 = get_tbu();
510 } while (h != h1);
511 return ((int64_t)h << 32) | l;
514 #elif defined(__i386__)
516 int64_t cpu_get_real_ticks(void)
518 int64_t val;
519 asm volatile ("rdtsc" : "=A" (val));
520 return val;
523 #elif defined(__x86_64__)
525 int64_t cpu_get_real_ticks(void)
527 uint32_t low,high;
528 int64_t val;
529 asm volatile("rdtsc" : "=a" (low), "=d" (high));
530 val = high;
531 val <<= 32;
532 val |= low;
533 return val;
536 #elif defined(__ia64)
538 int64_t cpu_get_real_ticks(void)
540 int64_t val;
541 asm volatile ("mov %0 = ar.itc" : "=r"(val) :: "memory");
542 return val;
545 #elif defined(__s390__)
547 int64_t cpu_get_real_ticks(void)
549 int64_t val;
550 asm volatile("stck 0(%1)" : "=m" (val) : "a" (&val) : "cc");
551 return val;
554 #else
555 #error unsupported CPU
556 #endif
558 static int64_t cpu_ticks_offset;
559 static int cpu_ticks_enabled;
561 static inline int64_t cpu_get_ticks(void)
563 if (!cpu_ticks_enabled) {
564 return cpu_ticks_offset;
565 } else {
566 return cpu_get_real_ticks() + cpu_ticks_offset;
570 /* enable cpu_get_ticks() */
571 void cpu_enable_ticks(void)
573 if (!cpu_ticks_enabled) {
574 cpu_ticks_offset -= cpu_get_real_ticks();
575 cpu_ticks_enabled = 1;
579 /* disable cpu_get_ticks() : the clock is stopped. You must not call
580 cpu_get_ticks() after that. */
581 void cpu_disable_ticks(void)
583 if (cpu_ticks_enabled) {
584 cpu_ticks_offset = cpu_get_ticks();
585 cpu_ticks_enabled = 0;
589 static int64_t get_clock(void)
591 #ifdef _WIN32
592 struct _timeb tb;
593 _ftime(&tb);
594 return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
595 #else
596 struct timeval tv;
597 gettimeofday(&tv, NULL);
598 return tv.tv_sec * 1000000LL + tv.tv_usec;
599 #endif
602 void cpu_calibrate_ticks(void)
604 int64_t usec, ticks;
606 usec = get_clock();
607 ticks = cpu_get_real_ticks();
608 #ifdef _WIN32
609 Sleep(50);
610 #else
611 usleep(50 * 1000);
612 #endif
613 usec = get_clock() - usec;
614 ticks = cpu_get_real_ticks() - ticks;
615 ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
618 /* compute with 96 bit intermediate result: (a*b)/c */
619 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
621 union {
622 uint64_t ll;
623 struct {
624 #ifdef WORDS_BIGENDIAN
625 uint32_t high, low;
626 #else
627 uint32_t low, high;
628 #endif
629 } l;
630 } u, res;
631 uint64_t rl, rh;
633 u.ll = a;
634 rl = (uint64_t)u.l.low * (uint64_t)b;
635 rh = (uint64_t)u.l.high * (uint64_t)b;
636 rh += (rl >> 32);
637 res.l.high = rh / c;
638 res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
639 return res.ll;
642 #define QEMU_TIMER_REALTIME 0
643 #define QEMU_TIMER_VIRTUAL 1
645 struct QEMUClock {
646 int type;
647 /* XXX: add frequency */
650 struct QEMUTimer {
651 QEMUClock *clock;
652 int64_t expire_time;
653 QEMUTimerCB *cb;
654 void *opaque;
655 struct QEMUTimer *next;
658 QEMUClock *rt_clock;
659 QEMUClock *vm_clock;
661 static QEMUTimer *active_timers[2];
662 #ifdef _WIN32
663 static MMRESULT timerID;
664 #else
665 /* frequency of the times() clock tick */
666 static int timer_freq;
667 #endif
669 QEMUClock *qemu_new_clock(int type)
671 QEMUClock *clock;
672 clock = qemu_mallocz(sizeof(QEMUClock));
673 if (!clock)
674 return NULL;
675 clock->type = type;
676 return clock;
679 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
681 QEMUTimer *ts;
683 ts = qemu_mallocz(sizeof(QEMUTimer));
684 ts->clock = clock;
685 ts->cb = cb;
686 ts->opaque = opaque;
687 return ts;
690 void qemu_free_timer(QEMUTimer *ts)
692 qemu_free(ts);
695 /* stop a timer, but do not dealloc it */
696 void qemu_del_timer(QEMUTimer *ts)
698 QEMUTimer **pt, *t;
700 /* NOTE: this code must be signal safe because
701 qemu_timer_expired() can be called from a signal. */
702 pt = &active_timers[ts->clock->type];
703 for(;;) {
704 t = *pt;
705 if (!t)
706 break;
707 if (t == ts) {
708 *pt = t->next;
709 break;
711 pt = &t->next;
715 /* modify the current timer so that it will be fired when current_time
716 >= expire_time. The corresponding callback will be called. */
717 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
719 QEMUTimer **pt, *t;
721 qemu_del_timer(ts);
723 /* add the timer in the sorted list */
724 /* NOTE: this code must be signal safe because
725 qemu_timer_expired() can be called from a signal. */
726 pt = &active_timers[ts->clock->type];
727 for(;;) {
728 t = *pt;
729 if (!t)
730 break;
731 if (t->expire_time > expire_time)
732 break;
733 pt = &t->next;
735 ts->expire_time = expire_time;
736 ts->next = *pt;
737 *pt = ts;
740 int qemu_timer_pending(QEMUTimer *ts)
742 QEMUTimer *t;
743 for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
744 if (t == ts)
745 return 1;
747 return 0;
750 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
752 if (!timer_head)
753 return 0;
754 return (timer_head->expire_time <= current_time);
757 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
759 QEMUTimer *ts;
761 for(;;) {
762 ts = *ptimer_head;
763 if (!ts || ts->expire_time > current_time)
764 break;
765 /* remove timer from the list before calling the callback */
766 *ptimer_head = ts->next;
767 ts->next = NULL;
769 /* run the callback (the timer list can be modified) */
770 ts->cb(ts->opaque);
774 int64_t qemu_get_clock(QEMUClock *clock)
776 switch(clock->type) {
777 case QEMU_TIMER_REALTIME:
778 #ifdef _WIN32
779 return GetTickCount();
780 #else
782 struct tms tp;
784 /* Note that using gettimeofday() is not a good solution
785 for timers because its value change when the date is
786 modified. */
787 if (timer_freq == 100) {
788 return times(&tp) * 10;
789 } else {
790 return ((int64_t)times(&tp) * 1000) / timer_freq;
793 #endif
794 default:
795 case QEMU_TIMER_VIRTUAL:
796 return cpu_get_ticks();
800 /* save a timer */
801 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
803 uint64_t expire_time;
805 if (qemu_timer_pending(ts)) {
806 expire_time = ts->expire_time;
807 } else {
808 expire_time = -1;
810 qemu_put_be64(f, expire_time);
813 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
815 uint64_t expire_time;
817 expire_time = qemu_get_be64(f);
818 if (expire_time != -1) {
819 qemu_mod_timer(ts, expire_time);
820 } else {
821 qemu_del_timer(ts);
825 static void timer_save(QEMUFile *f, void *opaque)
827 if (cpu_ticks_enabled) {
828 hw_error("cannot save state if virtual timers are running");
830 qemu_put_be64s(f, &cpu_ticks_offset);
831 qemu_put_be64s(f, &ticks_per_sec);
834 static int timer_load(QEMUFile *f, void *opaque, int version_id)
836 if (version_id != 1)
837 return -EINVAL;
838 if (cpu_ticks_enabled) {
839 return -EINVAL;
841 qemu_get_be64s(f, &cpu_ticks_offset);
842 qemu_get_be64s(f, &ticks_per_sec);
843 return 0;
846 #ifdef _WIN32
847 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
848 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
849 #else
850 static void host_alarm_handler(int host_signum)
851 #endif
853 #if 0
854 #define DISP_FREQ 1000
856 static int64_t delta_min = INT64_MAX;
857 static int64_t delta_max, delta_cum, last_clock, delta, ti;
858 static int count;
859 ti = qemu_get_clock(vm_clock);
860 if (last_clock != 0) {
861 delta = ti - last_clock;
862 if (delta < delta_min)
863 delta_min = delta;
864 if (delta > delta_max)
865 delta_max = delta;
866 delta_cum += delta;
867 if (++count == DISP_FREQ) {
868 printf("timer: min=%lld us max=%lld us avg=%lld us avg_freq=%0.3f Hz\n",
869 muldiv64(delta_min, 1000000, ticks_per_sec),
870 muldiv64(delta_max, 1000000, ticks_per_sec),
871 muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
872 (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
873 count = 0;
874 delta_min = INT64_MAX;
875 delta_max = 0;
876 delta_cum = 0;
879 last_clock = ti;
881 #endif
882 if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
883 qemu_get_clock(vm_clock)) ||
884 qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
885 qemu_get_clock(rt_clock))) {
886 CPUState *env = cpu_single_env;
887 if (env) {
888 /* stop the currently executing cpu because a timer occured */
889 cpu_interrupt(env, CPU_INTERRUPT_EXIT);
890 #ifdef USE_KQEMU
891 if (env->kqemu_enabled) {
892 kqemu_cpu_interrupt(env);
894 #endif
899 #ifndef _WIN32
901 #if defined(__linux__)
903 #define RTC_FREQ 1024
905 static int rtc_fd;
907 static int start_rtc_timer(void)
909 rtc_fd = open("/dev/rtc", O_RDONLY);
910 if (rtc_fd < 0)
911 return -1;
912 if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
913 fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
914 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
915 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
916 goto fail;
918 if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
919 fail:
920 close(rtc_fd);
921 return -1;
923 pit_min_timer_count = PIT_FREQ / RTC_FREQ;
924 return 0;
927 #else
929 static int start_rtc_timer(void)
931 return -1;
934 #endif /* !defined(__linux__) */
936 #endif /* !defined(_WIN32) */
938 static void init_timers(void)
940 rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
941 vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
943 #ifdef _WIN32
945 int count=0;
946 timerID = timeSetEvent(1, // interval (ms)
947 0, // resolution
948 host_alarm_handler, // function
949 (DWORD)&count, // user parameter
950 TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
951 if( !timerID ) {
952 perror("failed timer alarm");
953 exit(1);
956 pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
957 #else
959 struct sigaction act;
960 struct itimerval itv;
962 /* get times() syscall frequency */
963 timer_freq = sysconf(_SC_CLK_TCK);
965 /* timer signal */
966 sigfillset(&act.sa_mask);
967 act.sa_flags = 0;
968 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
969 act.sa_flags |= SA_ONSTACK;
970 #endif
971 act.sa_handler = host_alarm_handler;
972 sigaction(SIGALRM, &act, NULL);
974 itv.it_interval.tv_sec = 0;
975 itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
976 itv.it_value.tv_sec = 0;
977 itv.it_value.tv_usec = 10 * 1000;
978 setitimer(ITIMER_REAL, &itv, NULL);
979 /* we probe the tick duration of the kernel to inform the user if
980 the emulated kernel requested a too high timer frequency */
981 getitimer(ITIMER_REAL, &itv);
983 #if defined(__linux__)
984 if (itv.it_interval.tv_usec > 1000) {
985 /* try to use /dev/rtc to have a faster timer */
986 if (start_rtc_timer() < 0)
987 goto use_itimer;
988 /* disable itimer */
989 itv.it_interval.tv_sec = 0;
990 itv.it_interval.tv_usec = 0;
991 itv.it_value.tv_sec = 0;
992 itv.it_value.tv_usec = 0;
993 setitimer(ITIMER_REAL, &itv, NULL);
995 /* use the RTC */
996 sigaction(SIGIO, &act, NULL);
997 fcntl(rtc_fd, F_SETFL, O_ASYNC);
998 fcntl(rtc_fd, F_SETOWN, getpid());
999 } else
1000 #endif /* defined(__linux__) */
1002 use_itimer:
1003 pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec *
1004 PIT_FREQ) / 1000000;
1007 #endif
1010 void quit_timers(void)
1012 #ifdef _WIN32
1013 timeKillEvent(timerID);
1014 #endif
1017 /***********************************************************/
1018 /* character device */
1020 int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1022 return s->chr_write(s, buf, len);
1025 int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1027 if (!s->chr_ioctl)
1028 return -ENOTSUP;
1029 return s->chr_ioctl(s, cmd, arg);
1032 void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1034 char buf[4096];
1035 va_list ap;
1036 va_start(ap, fmt);
1037 vsnprintf(buf, sizeof(buf), fmt, ap);
1038 qemu_chr_write(s, buf, strlen(buf));
1039 va_end(ap);
1042 void qemu_chr_send_event(CharDriverState *s, int event)
1044 if (s->chr_send_event)
1045 s->chr_send_event(s, event);
1048 void qemu_chr_add_read_handler(CharDriverState *s,
1049 IOCanRWHandler *fd_can_read,
1050 IOReadHandler *fd_read, void *opaque)
1052 s->chr_add_read_handler(s, fd_can_read, fd_read, opaque);
1055 void qemu_chr_add_event_handler(CharDriverState *s, IOEventHandler *chr_event)
1057 s->chr_event = chr_event;
1060 static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1062 return len;
1065 static void null_chr_add_read_handler(CharDriverState *chr,
1066 IOCanRWHandler *fd_can_read,
1067 IOReadHandler *fd_read, void *opaque)
1071 CharDriverState *qemu_chr_open_null(void)
1073 CharDriverState *chr;
1075 chr = qemu_mallocz(sizeof(CharDriverState));
1076 if (!chr)
1077 return NULL;
1078 chr->chr_write = null_chr_write;
1079 chr->chr_add_read_handler = null_chr_add_read_handler;
1080 return chr;
1083 #ifdef _WIN32
1085 #define socket_error() WSAGetLastError()
1086 #undef EINTR
1087 #define EWOULDBLOCK WSAEWOULDBLOCK
1088 #define EINTR WSAEINTR
1089 #define EINPROGRESS WSAEINPROGRESS
1091 static void socket_cleanup(void)
1093 WSACleanup();
1096 static int socket_init(void)
1098 WSADATA Data;
1099 int ret, err;
1101 ret = WSAStartup(MAKEWORD(2,2), &Data);
1102 if (ret != 0) {
1103 err = WSAGetLastError();
1104 fprintf(stderr, "WSAStartup: %d\n", err);
1105 return -1;
1107 atexit(socket_cleanup);
1108 return 0;
1111 static int send_all(int fd, const uint8_t *buf, int len1)
1113 int ret, len;
1115 len = len1;
1116 while (len > 0) {
1117 ret = send(fd, buf, len, 0);
1118 if (ret < 0) {
1119 int errno;
1120 errno = WSAGetLastError();
1121 if (errno != WSAEWOULDBLOCK) {
1122 return -1;
1124 } else if (ret == 0) {
1125 break;
1126 } else {
1127 buf += ret;
1128 len -= ret;
1131 return len1 - len;
1134 void socket_set_nonblock(int fd)
1136 unsigned long opt = 1;
1137 ioctlsocket(fd, FIONBIO, &opt);
1140 #else
1142 #define socket_error() errno
1143 #define closesocket(s) close(s)
1145 static int unix_write(int fd, const uint8_t *buf, int len1)
1147 int ret, len;
1149 len = len1;
1150 while (len > 0) {
1151 ret = write(fd, buf, len);
1152 if (ret < 0) {
1153 if (errno != EINTR && errno != EAGAIN)
1154 return -1;
1155 } else if (ret == 0) {
1156 break;
1157 } else {
1158 buf += ret;
1159 len -= ret;
1162 return len1 - len;
1165 static inline int send_all(int fd, const uint8_t *buf, int len1)
1167 return unix_write(fd, buf, len1);
1170 void socket_set_nonblock(int fd)
1172 fcntl(fd, F_SETFL, O_NONBLOCK);
1174 #endif /* !_WIN32 */
1176 #ifndef _WIN32
1178 typedef struct {
1179 int fd_in, fd_out;
1180 IOCanRWHandler *fd_can_read;
1181 IOReadHandler *fd_read;
1182 void *fd_opaque;
1183 int max_size;
1184 } FDCharDriver;
1186 #define STDIO_MAX_CLIENTS 2
1188 static int stdio_nb_clients;
1189 static CharDriverState *stdio_clients[STDIO_MAX_CLIENTS];
1191 static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1193 FDCharDriver *s = chr->opaque;
1194 return unix_write(s->fd_out, buf, len);
1197 static int fd_chr_read_poll(void *opaque)
1199 CharDriverState *chr = opaque;
1200 FDCharDriver *s = chr->opaque;
1202 s->max_size = s->fd_can_read(s->fd_opaque);
1203 return s->max_size;
1206 static void fd_chr_read(void *opaque)
1208 CharDriverState *chr = opaque;
1209 FDCharDriver *s = chr->opaque;
1210 int size, len;
1211 uint8_t buf[1024];
1213 len = sizeof(buf);
1214 if (len > s->max_size)
1215 len = s->max_size;
1216 if (len == 0)
1217 return;
1218 size = read(s->fd_in, buf, len);
1219 if (size > 0) {
1220 s->fd_read(s->fd_opaque, buf, size);
1224 static void fd_chr_add_read_handler(CharDriverState *chr,
1225 IOCanRWHandler *fd_can_read,
1226 IOReadHandler *fd_read, void *opaque)
1228 FDCharDriver *s = chr->opaque;
1230 if (s->fd_in >= 0) {
1231 s->fd_can_read = fd_can_read;
1232 s->fd_read = fd_read;
1233 s->fd_opaque = opaque;
1234 if (nographic && s->fd_in == 0) {
1235 } else {
1236 qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
1237 fd_chr_read, NULL, chr);
1242 /* open a character device to a unix fd */
1243 CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1245 CharDriverState *chr;
1246 FDCharDriver *s;
1248 chr = qemu_mallocz(sizeof(CharDriverState));
1249 if (!chr)
1250 return NULL;
1251 s = qemu_mallocz(sizeof(FDCharDriver));
1252 if (!s) {
1253 free(chr);
1254 return NULL;
1256 s->fd_in = fd_in;
1257 s->fd_out = fd_out;
1258 chr->opaque = s;
1259 chr->chr_write = fd_chr_write;
1260 chr->chr_add_read_handler = fd_chr_add_read_handler;
1261 return chr;
1264 CharDriverState *qemu_chr_open_file_out(const char *file_out)
1266 int fd_out;
1268 fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1269 if (fd_out < 0)
1270 return NULL;
1271 return qemu_chr_open_fd(-1, fd_out);
1274 CharDriverState *qemu_chr_open_pipe(const char *filename)
1276 int fd;
1278 fd = open(filename, O_RDWR | O_BINARY);
1279 if (fd < 0)
1280 return NULL;
1281 return qemu_chr_open_fd(fd, fd);
1285 /* for STDIO, we handle the case where several clients use it
1286 (nographic mode) */
1288 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1290 #define TERM_FIFO_MAX_SIZE 1
1292 static int term_got_escape, client_index;
1293 static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1294 int term_fifo_size;
1296 void term_print_help(void)
1298 printf("\n"
1299 "C-a h print this help\n"
1300 "C-a x exit emulator\n"
1301 "C-a s save disk data back to file (if -snapshot)\n"
1302 "C-a b send break (magic sysrq)\n"
1303 "C-a c switch between console and monitor\n"
1304 "C-a C-a send C-a\n"
1308 /* called when a char is received */
1309 static void stdio_received_byte(int ch)
1311 if (term_got_escape) {
1312 term_got_escape = 0;
1313 switch(ch) {
1314 case 'h':
1315 term_print_help();
1316 break;
1317 case 'x':
1318 exit(0);
1319 break;
1320 case 's':
1322 int i;
1323 for (i = 0; i < MAX_DISKS; i++) {
1324 if (bs_table[i])
1325 bdrv_commit(bs_table[i]);
1328 break;
1329 case 'b':
1330 if (client_index < stdio_nb_clients) {
1331 CharDriverState *chr;
1332 FDCharDriver *s;
1334 chr = stdio_clients[client_index];
1335 s = chr->opaque;
1336 chr->chr_event(s->fd_opaque, CHR_EVENT_BREAK);
1338 break;
1339 case 'c':
1340 client_index++;
1341 if (client_index >= stdio_nb_clients)
1342 client_index = 0;
1343 if (client_index == 0) {
1344 /* send a new line in the monitor to get the prompt */
1345 ch = '\r';
1346 goto send_char;
1348 break;
1349 case TERM_ESCAPE:
1350 goto send_char;
1352 } else if (ch == TERM_ESCAPE) {
1353 term_got_escape = 1;
1354 } else {
1355 send_char:
1356 if (client_index < stdio_nb_clients) {
1357 uint8_t buf[1];
1358 CharDriverState *chr;
1359 FDCharDriver *s;
1361 chr = stdio_clients[client_index];
1362 s = chr->opaque;
1363 if (s->fd_can_read(s->fd_opaque) > 0) {
1364 buf[0] = ch;
1365 s->fd_read(s->fd_opaque, buf, 1);
1366 } else if (term_fifo_size == 0) {
1367 term_fifo[term_fifo_size++] = ch;
1373 static int stdio_read_poll(void *opaque)
1375 CharDriverState *chr;
1376 FDCharDriver *s;
1378 if (client_index < stdio_nb_clients) {
1379 chr = stdio_clients[client_index];
1380 s = chr->opaque;
1381 /* try to flush the queue if needed */
1382 if (term_fifo_size != 0 && s->fd_can_read(s->fd_opaque) > 0) {
1383 s->fd_read(s->fd_opaque, term_fifo, 1);
1384 term_fifo_size = 0;
1386 /* see if we can absorb more chars */
1387 if (term_fifo_size == 0)
1388 return 1;
1389 else
1390 return 0;
1391 } else {
1392 return 1;
1396 static void stdio_read(void *opaque)
1398 int size;
1399 uint8_t buf[1];
1401 size = read(0, buf, 1);
1402 if (size > 0)
1403 stdio_received_byte(buf[0]);
1406 /* init terminal so that we can grab keys */
1407 static struct termios oldtty;
1408 static int old_fd0_flags;
1410 static void term_exit(void)
1412 tcsetattr (0, TCSANOW, &oldtty);
1413 fcntl(0, F_SETFL, old_fd0_flags);
1416 static void term_init(void)
1418 struct termios tty;
1420 tcgetattr (0, &tty);
1421 oldtty = tty;
1422 old_fd0_flags = fcntl(0, F_GETFL);
1424 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1425 |INLCR|IGNCR|ICRNL|IXON);
1426 tty.c_oflag |= OPOST;
1427 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1428 /* if graphical mode, we allow Ctrl-C handling */
1429 if (nographic)
1430 tty.c_lflag &= ~ISIG;
1431 tty.c_cflag &= ~(CSIZE|PARENB);
1432 tty.c_cflag |= CS8;
1433 tty.c_cc[VMIN] = 1;
1434 tty.c_cc[VTIME] = 0;
1436 tcsetattr (0, TCSANOW, &tty);
1438 atexit(term_exit);
1440 fcntl(0, F_SETFL, O_NONBLOCK);
1443 CharDriverState *qemu_chr_open_stdio(void)
1445 CharDriverState *chr;
1447 if (nographic) {
1448 if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1449 return NULL;
1450 chr = qemu_chr_open_fd(0, 1);
1451 if (stdio_nb_clients == 0)
1452 qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, NULL);
1453 client_index = stdio_nb_clients;
1454 } else {
1455 if (stdio_nb_clients != 0)
1456 return NULL;
1457 chr = qemu_chr_open_fd(0, 1);
1459 stdio_clients[stdio_nb_clients++] = chr;
1460 if (stdio_nb_clients == 1) {
1461 /* set the terminal in raw mode */
1462 term_init();
1464 return chr;
1467 #if defined(__linux__)
1468 CharDriverState *qemu_chr_open_pty(void)
1470 struct termios tty;
1471 char slave_name[1024];
1472 int master_fd, slave_fd;
1474 /* Not satisfying */
1475 if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1476 return NULL;
1479 /* Disabling local echo and line-buffered output */
1480 tcgetattr (master_fd, &tty);
1481 tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1482 tty.c_cc[VMIN] = 1;
1483 tty.c_cc[VTIME] = 0;
1484 tcsetattr (master_fd, TCSAFLUSH, &tty);
1486 fprintf(stderr, "char device redirected to %s\n", slave_name);
1487 return qemu_chr_open_fd(master_fd, master_fd);
1490 static void tty_serial_init(int fd, int speed,
1491 int parity, int data_bits, int stop_bits)
1493 struct termios tty;
1494 speed_t spd;
1496 #if 0
1497 printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
1498 speed, parity, data_bits, stop_bits);
1499 #endif
1500 tcgetattr (fd, &tty);
1502 switch(speed) {
1503 case 50:
1504 spd = B50;
1505 break;
1506 case 75:
1507 spd = B75;
1508 break;
1509 case 300:
1510 spd = B300;
1511 break;
1512 case 600:
1513 spd = B600;
1514 break;
1515 case 1200:
1516 spd = B1200;
1517 break;
1518 case 2400:
1519 spd = B2400;
1520 break;
1521 case 4800:
1522 spd = B4800;
1523 break;
1524 case 9600:
1525 spd = B9600;
1526 break;
1527 case 19200:
1528 spd = B19200;
1529 break;
1530 case 38400:
1531 spd = B38400;
1532 break;
1533 case 57600:
1534 spd = B57600;
1535 break;
1536 default:
1537 case 115200:
1538 spd = B115200;
1539 break;
1542 cfsetispeed(&tty, spd);
1543 cfsetospeed(&tty, spd);
1545 tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1546 |INLCR|IGNCR|ICRNL|IXON);
1547 tty.c_oflag |= OPOST;
1548 tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1549 tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS);
1550 switch(data_bits) {
1551 default:
1552 case 8:
1553 tty.c_cflag |= CS8;
1554 break;
1555 case 7:
1556 tty.c_cflag |= CS7;
1557 break;
1558 case 6:
1559 tty.c_cflag |= CS6;
1560 break;
1561 case 5:
1562 tty.c_cflag |= CS5;
1563 break;
1565 switch(parity) {
1566 default:
1567 case 'N':
1568 break;
1569 case 'E':
1570 tty.c_cflag |= PARENB;
1571 break;
1572 case 'O':
1573 tty.c_cflag |= PARENB | PARODD;
1574 break;
1577 tcsetattr (fd, TCSANOW, &tty);
1580 static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1582 FDCharDriver *s = chr->opaque;
1584 switch(cmd) {
1585 case CHR_IOCTL_SERIAL_SET_PARAMS:
1587 QEMUSerialSetParams *ssp = arg;
1588 tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
1589 ssp->data_bits, ssp->stop_bits);
1591 break;
1592 case CHR_IOCTL_SERIAL_SET_BREAK:
1594 int enable = *(int *)arg;
1595 if (enable)
1596 tcsendbreak(s->fd_in, 1);
1598 break;
1599 default:
1600 return -ENOTSUP;
1602 return 0;
1605 CharDriverState *qemu_chr_open_tty(const char *filename)
1607 CharDriverState *chr;
1608 int fd;
1610 fd = open(filename, O_RDWR | O_NONBLOCK);
1611 if (fd < 0)
1612 return NULL;
1613 fcntl(fd, F_SETFL, O_NONBLOCK);
1614 tty_serial_init(fd, 115200, 'N', 8, 1);
1615 chr = qemu_chr_open_fd(fd, fd);
1616 if (!chr)
1617 return NULL;
1618 chr->chr_ioctl = tty_serial_ioctl;
1619 return chr;
1622 static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1624 int fd = (int)chr->opaque;
1625 uint8_t b;
1627 switch(cmd) {
1628 case CHR_IOCTL_PP_READ_DATA:
1629 if (ioctl(fd, PPRDATA, &b) < 0)
1630 return -ENOTSUP;
1631 *(uint8_t *)arg = b;
1632 break;
1633 case CHR_IOCTL_PP_WRITE_DATA:
1634 b = *(uint8_t *)arg;
1635 if (ioctl(fd, PPWDATA, &b) < 0)
1636 return -ENOTSUP;
1637 break;
1638 case CHR_IOCTL_PP_READ_CONTROL:
1639 if (ioctl(fd, PPRCONTROL, &b) < 0)
1640 return -ENOTSUP;
1641 *(uint8_t *)arg = b;
1642 break;
1643 case CHR_IOCTL_PP_WRITE_CONTROL:
1644 b = *(uint8_t *)arg;
1645 if (ioctl(fd, PPWCONTROL, &b) < 0)
1646 return -ENOTSUP;
1647 break;
1648 case CHR_IOCTL_PP_READ_STATUS:
1649 if (ioctl(fd, PPRSTATUS, &b) < 0)
1650 return -ENOTSUP;
1651 *(uint8_t *)arg = b;
1652 break;
1653 default:
1654 return -ENOTSUP;
1656 return 0;
1659 CharDriverState *qemu_chr_open_pp(const char *filename)
1661 CharDriverState *chr;
1662 int fd;
1664 fd = open(filename, O_RDWR);
1665 if (fd < 0)
1666 return NULL;
1668 if (ioctl(fd, PPCLAIM) < 0) {
1669 close(fd);
1670 return NULL;
1673 chr = qemu_mallocz(sizeof(CharDriverState));
1674 if (!chr) {
1675 close(fd);
1676 return NULL;
1678 chr->opaque = (void *)fd;
1679 chr->chr_write = null_chr_write;
1680 chr->chr_add_read_handler = null_chr_add_read_handler;
1681 chr->chr_ioctl = pp_ioctl;
1682 return chr;
1685 #else
1686 CharDriverState *qemu_chr_open_pty(void)
1688 return NULL;
1690 #endif
1692 #endif /* !defined(_WIN32) */
1694 #ifdef _WIN32
1695 typedef struct {
1696 IOCanRWHandler *fd_can_read;
1697 IOReadHandler *fd_read;
1698 void *win_opaque;
1699 int max_size;
1700 HANDLE hcom, hrecv, hsend;
1701 OVERLAPPED orecv, osend;
1702 BOOL fpipe;
1703 DWORD len;
1704 } WinCharState;
1706 #define NSENDBUF 2048
1707 #define NRECVBUF 2048
1708 #define MAXCONNECT 1
1709 #define NTIMEOUT 5000
1711 static int win_chr_poll(void *opaque);
1712 static int win_chr_pipe_poll(void *opaque);
1714 static void win_chr_close2(WinCharState *s)
1716 if (s->hsend) {
1717 CloseHandle(s->hsend);
1718 s->hsend = NULL;
1720 if (s->hrecv) {
1721 CloseHandle(s->hrecv);
1722 s->hrecv = NULL;
1724 if (s->hcom) {
1725 CloseHandle(s->hcom);
1726 s->hcom = NULL;
1728 if (s->fpipe)
1729 qemu_del_polling_cb(win_chr_pipe_poll, s);
1730 else
1731 qemu_del_polling_cb(win_chr_poll, s);
1734 static void win_chr_close(CharDriverState *chr)
1736 WinCharState *s = chr->opaque;
1737 win_chr_close2(s);
1740 static int win_chr_init(WinCharState *s, const char *filename)
1742 COMMCONFIG comcfg;
1743 COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
1744 COMSTAT comstat;
1745 DWORD size;
1746 DWORD err;
1748 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1749 if (!s->hsend) {
1750 fprintf(stderr, "Failed CreateEvent\n");
1751 goto fail;
1753 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1754 if (!s->hrecv) {
1755 fprintf(stderr, "Failed CreateEvent\n");
1756 goto fail;
1759 s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
1760 OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
1761 if (s->hcom == INVALID_HANDLE_VALUE) {
1762 fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
1763 s->hcom = NULL;
1764 goto fail;
1767 if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
1768 fprintf(stderr, "Failed SetupComm\n");
1769 goto fail;
1772 ZeroMemory(&comcfg, sizeof(COMMCONFIG));
1773 size = sizeof(COMMCONFIG);
1774 GetDefaultCommConfig(filename, &comcfg, &size);
1775 comcfg.dcb.DCBlength = sizeof(DCB);
1776 CommConfigDialog(filename, NULL, &comcfg);
1778 if (!SetCommState(s->hcom, &comcfg.dcb)) {
1779 fprintf(stderr, "Failed SetCommState\n");
1780 goto fail;
1783 if (!SetCommMask(s->hcom, EV_ERR)) {
1784 fprintf(stderr, "Failed SetCommMask\n");
1785 goto fail;
1788 cto.ReadIntervalTimeout = MAXDWORD;
1789 if (!SetCommTimeouts(s->hcom, &cto)) {
1790 fprintf(stderr, "Failed SetCommTimeouts\n");
1791 goto fail;
1794 if (!ClearCommError(s->hcom, &err, &comstat)) {
1795 fprintf(stderr, "Failed ClearCommError\n");
1796 goto fail;
1798 qemu_add_polling_cb(win_chr_poll, s);
1799 return 0;
1801 fail:
1802 win_chr_close2(s);
1803 return -1;
1806 static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
1808 WinCharState *s = chr->opaque;
1809 DWORD len, ret, size, err;
1811 len = len1;
1812 ZeroMemory(&s->osend, sizeof(s->osend));
1813 s->osend.hEvent = s->hsend;
1814 while (len > 0) {
1815 if (s->hsend)
1816 ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
1817 else
1818 ret = WriteFile(s->hcom, buf, len, &size, NULL);
1819 if (!ret) {
1820 err = GetLastError();
1821 if (err == ERROR_IO_PENDING) {
1822 ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
1823 if (ret) {
1824 buf += size;
1825 len -= size;
1826 } else {
1827 break;
1829 } else {
1830 break;
1832 } else {
1833 buf += size;
1834 len -= size;
1837 return len1 - len;
1840 static int win_chr_read_poll(WinCharState *s)
1842 s->max_size = s->fd_can_read(s->win_opaque);
1843 return s->max_size;
1846 static void win_chr_readfile(WinCharState *s)
1848 int ret, err;
1849 uint8_t buf[1024];
1850 DWORD size;
1852 ZeroMemory(&s->orecv, sizeof(s->orecv));
1853 s->orecv.hEvent = s->hrecv;
1854 ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
1855 if (!ret) {
1856 err = GetLastError();
1857 if (err == ERROR_IO_PENDING) {
1858 ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
1862 if (size > 0) {
1863 s->fd_read(s->win_opaque, buf, size);
1867 static void win_chr_read(WinCharState *s)
1869 if (s->len > s->max_size)
1870 s->len = s->max_size;
1871 if (s->len == 0)
1872 return;
1874 win_chr_readfile(s);
1877 static int win_chr_poll(void *opaque)
1879 WinCharState *s = opaque;
1880 COMSTAT status;
1881 DWORD comerr;
1883 ClearCommError(s->hcom, &comerr, &status);
1884 if (status.cbInQue > 0) {
1885 s->len = status.cbInQue;
1886 win_chr_read_poll(s);
1887 win_chr_read(s);
1888 return 1;
1890 return 0;
1893 static void win_chr_add_read_handler(CharDriverState *chr,
1894 IOCanRWHandler *fd_can_read,
1895 IOReadHandler *fd_read, void *opaque)
1897 WinCharState *s = chr->opaque;
1899 s->fd_can_read = fd_can_read;
1900 s->fd_read = fd_read;
1901 s->win_opaque = opaque;
1904 CharDriverState *qemu_chr_open_win(const char *filename)
1906 CharDriverState *chr;
1907 WinCharState *s;
1909 chr = qemu_mallocz(sizeof(CharDriverState));
1910 if (!chr)
1911 return NULL;
1912 s = qemu_mallocz(sizeof(WinCharState));
1913 if (!s) {
1914 free(chr);
1915 return NULL;
1917 chr->opaque = s;
1918 chr->chr_write = win_chr_write;
1919 chr->chr_add_read_handler = win_chr_add_read_handler;
1920 chr->chr_close = win_chr_close;
1922 if (win_chr_init(s, filename) < 0) {
1923 free(s);
1924 free(chr);
1925 return NULL;
1927 return chr;
1930 static int win_chr_pipe_poll(void *opaque)
1932 WinCharState *s = opaque;
1933 DWORD size;
1935 PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
1936 if (size > 0) {
1937 s->len = size;
1938 win_chr_read_poll(s);
1939 win_chr_read(s);
1940 return 1;
1942 return 0;
1945 static int win_chr_pipe_init(WinCharState *s, const char *filename)
1947 OVERLAPPED ov;
1948 int ret;
1949 DWORD size;
1950 char openname[256];
1952 s->fpipe = TRUE;
1954 s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
1955 if (!s->hsend) {
1956 fprintf(stderr, "Failed CreateEvent\n");
1957 goto fail;
1959 s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
1960 if (!s->hrecv) {
1961 fprintf(stderr, "Failed CreateEvent\n");
1962 goto fail;
1965 snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
1966 s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
1967 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
1968 PIPE_WAIT,
1969 MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
1970 if (s->hcom == INVALID_HANDLE_VALUE) {
1971 fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
1972 s->hcom = NULL;
1973 goto fail;
1976 ZeroMemory(&ov, sizeof(ov));
1977 ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
1978 ret = ConnectNamedPipe(s->hcom, &ov);
1979 if (ret) {
1980 fprintf(stderr, "Failed ConnectNamedPipe\n");
1981 goto fail;
1984 ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
1985 if (!ret) {
1986 fprintf(stderr, "Failed GetOverlappedResult\n");
1987 if (ov.hEvent) {
1988 CloseHandle(ov.hEvent);
1989 ov.hEvent = NULL;
1991 goto fail;
1994 if (ov.hEvent) {
1995 CloseHandle(ov.hEvent);
1996 ov.hEvent = NULL;
1998 qemu_add_polling_cb(win_chr_pipe_poll, s);
1999 return 0;
2001 fail:
2002 win_chr_close2(s);
2003 return -1;
2007 CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2009 CharDriverState *chr;
2010 WinCharState *s;
2012 chr = qemu_mallocz(sizeof(CharDriverState));
2013 if (!chr)
2014 return NULL;
2015 s = qemu_mallocz(sizeof(WinCharState));
2016 if (!s) {
2017 free(chr);
2018 return NULL;
2020 chr->opaque = s;
2021 chr->chr_write = win_chr_write;
2022 chr->chr_add_read_handler = win_chr_add_read_handler;
2023 chr->chr_close = win_chr_close;
2025 if (win_chr_pipe_init(s, filename) < 0) {
2026 free(s);
2027 free(chr);
2028 return NULL;
2030 return chr;
2033 CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2035 CharDriverState *chr;
2036 WinCharState *s;
2038 chr = qemu_mallocz(sizeof(CharDriverState));
2039 if (!chr)
2040 return NULL;
2041 s = qemu_mallocz(sizeof(WinCharState));
2042 if (!s) {
2043 free(chr);
2044 return NULL;
2046 s->hcom = fd_out;
2047 chr->opaque = s;
2048 chr->chr_write = win_chr_write;
2049 chr->chr_add_read_handler = win_chr_add_read_handler;
2050 return chr;
2053 CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2055 HANDLE fd_out;
2057 fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2058 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2059 if (fd_out == INVALID_HANDLE_VALUE)
2060 return NULL;
2062 return qemu_chr_open_win_file(fd_out);
2064 #endif
2066 CharDriverState *qemu_chr_open(const char *filename)
2068 const char *p;
2070 if (!strcmp(filename, "vc")) {
2071 return text_console_init(&display_state);
2072 } else if (!strcmp(filename, "null")) {
2073 return qemu_chr_open_null();
2074 } else
2075 #ifndef _WIN32
2076 if (strstart(filename, "file:", &p)) {
2077 return qemu_chr_open_file_out(p);
2078 } else if (strstart(filename, "pipe:", &p)) {
2079 return qemu_chr_open_pipe(p);
2080 } else if (!strcmp(filename, "pty")) {
2081 return qemu_chr_open_pty();
2082 } else if (!strcmp(filename, "stdio")) {
2083 return qemu_chr_open_stdio();
2084 } else
2085 #endif
2086 #if defined(__linux__)
2087 if (strstart(filename, "/dev/parport", NULL)) {
2088 return qemu_chr_open_pp(filename);
2089 } else
2090 if (strstart(filename, "/dev/", NULL)) {
2091 return qemu_chr_open_tty(filename);
2092 } else
2093 #endif
2094 #ifdef _WIN32
2095 if (strstart(filename, "COM", NULL)) {
2096 return qemu_chr_open_win(filename);
2097 } else
2098 if (strstart(filename, "pipe:", &p)) {
2099 return qemu_chr_open_win_pipe(p);
2100 } else
2101 if (strstart(filename, "file:", &p)) {
2102 return qemu_chr_open_win_file_out(p);
2104 #endif
2106 return NULL;
2110 void qemu_chr_close(CharDriverState *chr)
2112 if (chr->chr_close)
2113 chr->chr_close(chr);
2116 /***********************************************************/
2117 /* network device redirectors */
2119 void hex_dump(FILE *f, const uint8_t *buf, int size)
2121 int len, i, j, c;
2123 for(i=0;i<size;i+=16) {
2124 len = size - i;
2125 if (len > 16)
2126 len = 16;
2127 fprintf(f, "%08x ", i);
2128 for(j=0;j<16;j++) {
2129 if (j < len)
2130 fprintf(f, " %02x", buf[i+j]);
2131 else
2132 fprintf(f, " ");
2134 fprintf(f, " ");
2135 for(j=0;j<len;j++) {
2136 c = buf[i+j];
2137 if (c < ' ' || c > '~')
2138 c = '.';
2139 fprintf(f, "%c", c);
2141 fprintf(f, "\n");
2145 static int parse_macaddr(uint8_t *macaddr, const char *p)
2147 int i;
2148 for(i = 0; i < 6; i++) {
2149 macaddr[i] = strtol(p, (char **)&p, 16);
2150 if (i == 5) {
2151 if (*p != '\0')
2152 return -1;
2153 } else {
2154 if (*p != ':')
2155 return -1;
2156 p++;
2159 return 0;
2162 static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
2164 const char *p, *p1;
2165 int len;
2166 p = *pp;
2167 p1 = strchr(p, sep);
2168 if (!p1)
2169 return -1;
2170 len = p1 - p;
2171 p1++;
2172 if (buf_size > 0) {
2173 if (len > buf_size - 1)
2174 len = buf_size - 1;
2175 memcpy(buf, p, len);
2176 buf[len] = '\0';
2178 *pp = p1;
2179 return 0;
2182 int parse_host_port(struct sockaddr_in *saddr, const char *str)
2184 char buf[512];
2185 struct hostent *he;
2186 const char *p, *r;
2187 int port;
2189 p = str;
2190 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2191 return -1;
2192 saddr->sin_family = AF_INET;
2193 if (buf[0] == '\0') {
2194 saddr->sin_addr.s_addr = 0;
2195 } else {
2196 if (isdigit(buf[0])) {
2197 if (!inet_aton(buf, &saddr->sin_addr))
2198 return -1;
2199 } else {
2200 if ((he = gethostbyname(buf)) == NULL)
2201 return - 1;
2202 saddr->sin_addr = *(struct in_addr *)he->h_addr;
2205 port = strtol(p, (char **)&r, 0);
2206 if (r == p)
2207 return -1;
2208 saddr->sin_port = htons(port);
2209 return 0;
2212 /* find or alloc a new VLAN */
2213 VLANState *qemu_find_vlan(int id)
2215 VLANState **pvlan, *vlan;
2216 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
2217 if (vlan->id == id)
2218 return vlan;
2220 vlan = qemu_mallocz(sizeof(VLANState));
2221 if (!vlan)
2222 return NULL;
2223 vlan->id = id;
2224 vlan->next = NULL;
2225 pvlan = &first_vlan;
2226 while (*pvlan != NULL)
2227 pvlan = &(*pvlan)->next;
2228 *pvlan = vlan;
2229 return vlan;
2232 VLANClientState *qemu_new_vlan_client(VLANState *vlan,
2233 IOReadHandler *fd_read,
2234 IOCanRWHandler *fd_can_read,
2235 void *opaque)
2237 VLANClientState *vc, **pvc;
2238 vc = qemu_mallocz(sizeof(VLANClientState));
2239 if (!vc)
2240 return NULL;
2241 vc->fd_read = fd_read;
2242 vc->fd_can_read = fd_can_read;
2243 vc->opaque = opaque;
2244 vc->vlan = vlan;
2246 vc->next = NULL;
2247 pvc = &vlan->first_client;
2248 while (*pvc != NULL)
2249 pvc = &(*pvc)->next;
2250 *pvc = vc;
2251 return vc;
2254 int qemu_can_send_packet(VLANClientState *vc1)
2256 VLANState *vlan = vc1->vlan;
2257 VLANClientState *vc;
2259 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2260 if (vc != vc1) {
2261 if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
2262 return 0;
2265 return 1;
2268 void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
2270 VLANState *vlan = vc1->vlan;
2271 VLANClientState *vc;
2273 #if 0
2274 printf("vlan %d send:\n", vlan->id);
2275 hex_dump(stdout, buf, size);
2276 #endif
2277 for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
2278 if (vc != vc1) {
2279 vc->fd_read(vc->opaque, buf, size);
2284 #if defined(CONFIG_SLIRP)
2286 /* slirp network adapter */
2288 static int slirp_inited;
2289 static VLANClientState *slirp_vc;
2291 int slirp_can_output(void)
2293 return !slirp_vc || qemu_can_send_packet(slirp_vc);
2296 void slirp_output(const uint8_t *pkt, int pkt_len)
2298 #if 0
2299 printf("slirp output:\n");
2300 hex_dump(stdout, pkt, pkt_len);
2301 #endif
2302 if (!slirp_vc)
2303 return;
2304 qemu_send_packet(slirp_vc, pkt, pkt_len);
2307 static void slirp_receive(void *opaque, const uint8_t *buf, int size)
2309 #if 0
2310 printf("slirp input:\n");
2311 hex_dump(stdout, buf, size);
2312 #endif
2313 slirp_input(buf, size);
2316 static int net_slirp_init(VLANState *vlan)
2318 if (!slirp_inited) {
2319 slirp_inited = 1;
2320 slirp_init();
2322 slirp_vc = qemu_new_vlan_client(vlan,
2323 slirp_receive, NULL, NULL);
2324 snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
2325 return 0;
2328 static void net_slirp_redir(const char *redir_str)
2330 int is_udp;
2331 char buf[256], *r;
2332 const char *p;
2333 struct in_addr guest_addr;
2334 int host_port, guest_port;
2336 if (!slirp_inited) {
2337 slirp_inited = 1;
2338 slirp_init();
2341 p = redir_str;
2342 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2343 goto fail;
2344 if (!strcmp(buf, "tcp")) {
2345 is_udp = 0;
2346 } else if (!strcmp(buf, "udp")) {
2347 is_udp = 1;
2348 } else {
2349 goto fail;
2352 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2353 goto fail;
2354 host_port = strtol(buf, &r, 0);
2355 if (r == buf)
2356 goto fail;
2358 if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
2359 goto fail;
2360 if (buf[0] == '\0') {
2361 pstrcpy(buf, sizeof(buf), "10.0.2.15");
2363 if (!inet_aton(buf, &guest_addr))
2364 goto fail;
2366 guest_port = strtol(p, &r, 0);
2367 if (r == p)
2368 goto fail;
2370 if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
2371 fprintf(stderr, "qemu: could not set up redirection\n");
2372 exit(1);
2374 return;
2375 fail:
2376 fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
2377 exit(1);
2380 #ifndef _WIN32
2382 char smb_dir[1024];
2384 static void smb_exit(void)
2386 DIR *d;
2387 struct dirent *de;
2388 char filename[1024];
2390 /* erase all the files in the directory */
2391 d = opendir(smb_dir);
2392 for(;;) {
2393 de = readdir(d);
2394 if (!de)
2395 break;
2396 if (strcmp(de->d_name, ".") != 0 &&
2397 strcmp(de->d_name, "..") != 0) {
2398 snprintf(filename, sizeof(filename), "%s/%s",
2399 smb_dir, de->d_name);
2400 unlink(filename);
2403 closedir(d);
2404 rmdir(smb_dir);
2407 /* automatic user mode samba server configuration */
2408 void net_slirp_smb(const char *exported_dir)
2410 char smb_conf[1024];
2411 char smb_cmdline[1024];
2412 FILE *f;
2414 if (!slirp_inited) {
2415 slirp_inited = 1;
2416 slirp_init();
2419 /* XXX: better tmp dir construction */
2420 snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
2421 if (mkdir(smb_dir, 0700) < 0) {
2422 fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
2423 exit(1);
2425 snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
2427 f = fopen(smb_conf, "w");
2428 if (!f) {
2429 fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
2430 exit(1);
2432 fprintf(f,
2433 "[global]\n"
2434 "private dir=%s\n"
2435 "smb ports=0\n"
2436 "socket address=127.0.0.1\n"
2437 "pid directory=%s\n"
2438 "lock directory=%s\n"
2439 "log file=%s/log.smbd\n"
2440 "smb passwd file=%s/smbpasswd\n"
2441 "security = share\n"
2442 "[qemu]\n"
2443 "path=%s\n"
2444 "read only=no\n"
2445 "guest ok=yes\n",
2446 smb_dir,
2447 smb_dir,
2448 smb_dir,
2449 smb_dir,
2450 smb_dir,
2451 exported_dir
2453 fclose(f);
2454 atexit(smb_exit);
2456 snprintf(smb_cmdline, sizeof(smb_cmdline), "/usr/sbin/smbd -s %s",
2457 smb_conf);
2459 slirp_add_exec(0, smb_cmdline, 4, 139);
2462 #endif /* !defined(_WIN32) */
2464 #endif /* CONFIG_SLIRP */
2466 #if !defined(_WIN32)
2468 typedef struct TAPState {
2469 VLANClientState *vc;
2470 int fd;
2471 } TAPState;
2473 static void tap_receive(void *opaque, const uint8_t *buf, int size)
2475 TAPState *s = opaque;
2476 int ret;
2477 for(;;) {
2478 ret = write(s->fd, buf, size);
2479 if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
2480 } else {
2481 break;
2486 static void tap_send(void *opaque)
2488 TAPState *s = opaque;
2489 uint8_t buf[4096];
2490 int size;
2492 size = read(s->fd, buf, sizeof(buf));
2493 if (size > 0) {
2494 qemu_send_packet(s->vc, buf, size);
2498 /* fd support */
2500 static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
2502 TAPState *s;
2504 s = qemu_mallocz(sizeof(TAPState));
2505 if (!s)
2506 return NULL;
2507 s->fd = fd;
2508 s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
2509 qemu_set_fd_handler(s->fd, tap_send, NULL, s);
2510 snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
2511 return s;
2514 #ifdef _BSD
2515 static int tap_open(char *ifname, int ifname_size)
2517 int fd;
2518 char *dev;
2519 struct stat s;
2521 fd = open("/dev/tap", O_RDWR);
2522 if (fd < 0) {
2523 fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
2524 return -1;
2527 fstat(fd, &s);
2528 dev = devname(s.st_rdev, S_IFCHR);
2529 pstrcpy(ifname, ifname_size, dev);
2531 fcntl(fd, F_SETFL, O_NONBLOCK);
2532 return fd;
2534 #else
2535 static int tap_open(char *ifname, int ifname_size)
2537 struct ifreq ifr;
2538 int fd, ret;
2540 fd = open("/dev/net/tun", O_RDWR);
2541 if (fd < 0) {
2542 fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
2543 return -1;
2545 memset(&ifr, 0, sizeof(ifr));
2546 ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
2547 if (ifname[0] != '\0')
2548 pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
2549 else
2550 pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
2551 ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
2552 if (ret != 0) {
2553 fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
2554 close(fd);
2555 return -1;
2557 pstrcpy(ifname, ifname_size, ifr.ifr_name);
2558 fcntl(fd, F_SETFL, O_NONBLOCK);
2559 return fd;
2561 #endif
2563 static int net_tap_init(VLANState *vlan, const char *ifname1,
2564 const char *setup_script)
2566 TAPState *s;
2567 int pid, status, fd;
2568 char *args[3];
2569 char **parg;
2570 char ifname[128];
2572 if (ifname1 != NULL)
2573 pstrcpy(ifname, sizeof(ifname), ifname1);
2574 else
2575 ifname[0] = '\0';
2576 fd = tap_open(ifname, sizeof(ifname));
2577 if (fd < 0)
2578 return -1;
2580 if (!setup_script)
2581 setup_script = "";
2582 if (setup_script[0] != '\0') {
2583 /* try to launch network init script */
2584 pid = fork();
2585 if (pid >= 0) {
2586 if (pid == 0) {
2587 parg = args;
2588 *parg++ = (char *)setup_script;
2589 *parg++ = ifname;
2590 *parg++ = NULL;
2591 execv(setup_script, args);
2592 _exit(1);
2594 while (waitpid(pid, &status, 0) != pid);
2595 if (!WIFEXITED(status) ||
2596 WEXITSTATUS(status) != 0) {
2597 fprintf(stderr, "%s: could not launch network script\n",
2598 setup_script);
2599 return -1;
2603 s = net_tap_fd_init(vlan, fd);
2604 if (!s)
2605 return -1;
2606 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2607 "tap: ifname=%s setup_script=%s", ifname, setup_script);
2608 return 0;
2611 #endif /* !_WIN32 */
2613 /* network connection */
2614 typedef struct NetSocketState {
2615 VLANClientState *vc;
2616 int fd;
2617 int state; /* 0 = getting length, 1 = getting data */
2618 int index;
2619 int packet_len;
2620 uint8_t buf[4096];
2621 struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
2622 } NetSocketState;
2624 typedef struct NetSocketListenState {
2625 VLANState *vlan;
2626 int fd;
2627 } NetSocketListenState;
2629 /* XXX: we consider we can send the whole packet without blocking */
2630 static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
2632 NetSocketState *s = opaque;
2633 uint32_t len;
2634 len = htonl(size);
2636 send_all(s->fd, (const uint8_t *)&len, sizeof(len));
2637 send_all(s->fd, buf, size);
2640 static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
2642 NetSocketState *s = opaque;
2643 sendto(s->fd, buf, size, 0,
2644 (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
2647 static void net_socket_send(void *opaque)
2649 NetSocketState *s = opaque;
2650 int l, size, err;
2651 uint8_t buf1[4096];
2652 const uint8_t *buf;
2654 size = recv(s->fd, buf1, sizeof(buf1), 0);
2655 if (size < 0) {
2656 err = socket_error();
2657 if (err != EWOULDBLOCK)
2658 goto eoc;
2659 } else if (size == 0) {
2660 /* end of connection */
2661 eoc:
2662 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2663 closesocket(s->fd);
2664 return;
2666 buf = buf1;
2667 while (size > 0) {
2668 /* reassemble a packet from the network */
2669 switch(s->state) {
2670 case 0:
2671 l = 4 - s->index;
2672 if (l > size)
2673 l = size;
2674 memcpy(s->buf + s->index, buf, l);
2675 buf += l;
2676 size -= l;
2677 s->index += l;
2678 if (s->index == 4) {
2679 /* got length */
2680 s->packet_len = ntohl(*(uint32_t *)s->buf);
2681 s->index = 0;
2682 s->state = 1;
2684 break;
2685 case 1:
2686 l = s->packet_len - s->index;
2687 if (l > size)
2688 l = size;
2689 memcpy(s->buf + s->index, buf, l);
2690 s->index += l;
2691 buf += l;
2692 size -= l;
2693 if (s->index >= s->packet_len) {
2694 qemu_send_packet(s->vc, s->buf, s->packet_len);
2695 s->index = 0;
2696 s->state = 0;
2698 break;
2703 static void net_socket_send_dgram(void *opaque)
2705 NetSocketState *s = opaque;
2706 int size;
2708 size = recv(s->fd, s->buf, sizeof(s->buf), 0);
2709 if (size < 0)
2710 return;
2711 if (size == 0) {
2712 /* end of connection */
2713 qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2714 return;
2716 qemu_send_packet(s->vc, s->buf, size);
2719 static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
2721 struct ip_mreq imr;
2722 int fd;
2723 int val, ret;
2724 if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
2725 fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
2726 inet_ntoa(mcastaddr->sin_addr),
2727 (int)ntohl(mcastaddr->sin_addr.s_addr));
2728 return -1;
2731 fd = socket(PF_INET, SOCK_DGRAM, 0);
2732 if (fd < 0) {
2733 perror("socket(PF_INET, SOCK_DGRAM)");
2734 return -1;
2737 val = 1;
2738 ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
2739 (const char *)&val, sizeof(val));
2740 if (ret < 0) {
2741 perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
2742 goto fail;
2745 ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
2746 if (ret < 0) {
2747 perror("bind");
2748 goto fail;
2751 /* Add host to multicast group */
2752 imr.imr_multiaddr = mcastaddr->sin_addr;
2753 imr.imr_interface.s_addr = htonl(INADDR_ANY);
2755 ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
2756 (const char *)&imr, sizeof(struct ip_mreq));
2757 if (ret < 0) {
2758 perror("setsockopt(IP_ADD_MEMBERSHIP)");
2759 goto fail;
2762 /* Force mcast msgs to loopback (eg. several QEMUs in same host */
2763 val = 1;
2764 ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
2765 (const char *)&val, sizeof(val));
2766 if (ret < 0) {
2767 perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
2768 goto fail;
2771 socket_set_nonblock(fd);
2772 return fd;
2773 fail:
2774 if (fd>=0) close(fd);
2775 return -1;
2778 static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
2779 int is_connected)
2781 struct sockaddr_in saddr;
2782 int newfd;
2783 socklen_t saddr_len;
2784 NetSocketState *s;
2786 /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
2787 * Because this may be "shared" socket from a "master" process, datagrams would be recv()
2788 * by ONLY ONE process: we must "clone" this dgram socket --jjo
2791 if (is_connected) {
2792 if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
2793 /* must be bound */
2794 if (saddr.sin_addr.s_addr==0) {
2795 fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
2796 fd);
2797 return NULL;
2799 /* clone dgram socket */
2800 newfd = net_socket_mcast_create(&saddr);
2801 if (newfd < 0) {
2802 /* error already reported by net_socket_mcast_create() */
2803 close(fd);
2804 return NULL;
2806 /* clone newfd to fd, close newfd */
2807 dup2(newfd, fd);
2808 close(newfd);
2810 } else {
2811 fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
2812 fd, strerror(errno));
2813 return NULL;
2817 s = qemu_mallocz(sizeof(NetSocketState));
2818 if (!s)
2819 return NULL;
2820 s->fd = fd;
2822 s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
2823 qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
2825 /* mcast: save bound address as dst */
2826 if (is_connected) s->dgram_dst=saddr;
2828 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2829 "socket: fd=%d (%s mcast=%s:%d)",
2830 fd, is_connected? "cloned" : "",
2831 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2832 return s;
2835 static void net_socket_connect(void *opaque)
2837 NetSocketState *s = opaque;
2838 qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
2841 static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
2842 int is_connected)
2844 NetSocketState *s;
2845 s = qemu_mallocz(sizeof(NetSocketState));
2846 if (!s)
2847 return NULL;
2848 s->fd = fd;
2849 s->vc = qemu_new_vlan_client(vlan,
2850 net_socket_receive, NULL, s);
2851 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2852 "socket: fd=%d", fd);
2853 if (is_connected) {
2854 net_socket_connect(s);
2855 } else {
2856 qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
2858 return s;
2861 static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
2862 int is_connected)
2864 int so_type=-1, optlen=sizeof(so_type);
2866 if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
2867 fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
2868 return NULL;
2870 switch(so_type) {
2871 case SOCK_DGRAM:
2872 return net_socket_fd_init_dgram(vlan, fd, is_connected);
2873 case SOCK_STREAM:
2874 return net_socket_fd_init_stream(vlan, fd, is_connected);
2875 default:
2876 /* who knows ... this could be a eg. a pty, do warn and continue as stream */
2877 fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
2878 return net_socket_fd_init_stream(vlan, fd, is_connected);
2880 return NULL;
2883 static void net_socket_accept(void *opaque)
2885 NetSocketListenState *s = opaque;
2886 NetSocketState *s1;
2887 struct sockaddr_in saddr;
2888 socklen_t len;
2889 int fd;
2891 for(;;) {
2892 len = sizeof(saddr);
2893 fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
2894 if (fd < 0 && errno != EINTR) {
2895 return;
2896 } else if (fd >= 0) {
2897 break;
2900 s1 = net_socket_fd_init(s->vlan, fd, 1);
2901 if (!s1) {
2902 close(fd);
2903 } else {
2904 snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
2905 "socket: connection from %s:%d",
2906 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2910 static int net_socket_listen_init(VLANState *vlan, const char *host_str)
2912 NetSocketListenState *s;
2913 int fd, val, ret;
2914 struct sockaddr_in saddr;
2916 if (parse_host_port(&saddr, host_str) < 0)
2917 return -1;
2919 s = qemu_mallocz(sizeof(NetSocketListenState));
2920 if (!s)
2921 return -1;
2923 fd = socket(PF_INET, SOCK_STREAM, 0);
2924 if (fd < 0) {
2925 perror("socket");
2926 return -1;
2928 socket_set_nonblock(fd);
2930 /* allow fast reuse */
2931 val = 1;
2932 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2934 ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2935 if (ret < 0) {
2936 perror("bind");
2937 return -1;
2939 ret = listen(fd, 0);
2940 if (ret < 0) {
2941 perror("listen");
2942 return -1;
2944 s->vlan = vlan;
2945 s->fd = fd;
2946 qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
2947 return 0;
2950 static int net_socket_connect_init(VLANState *vlan, const char *host_str)
2952 NetSocketState *s;
2953 int fd, connected, ret, err;
2954 struct sockaddr_in saddr;
2956 if (parse_host_port(&saddr, host_str) < 0)
2957 return -1;
2959 fd = socket(PF_INET, SOCK_STREAM, 0);
2960 if (fd < 0) {
2961 perror("socket");
2962 return -1;
2964 socket_set_nonblock(fd);
2966 connected = 0;
2967 for(;;) {
2968 ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
2969 if (ret < 0) {
2970 err = socket_error();
2971 if (err == EINTR || err == EWOULDBLOCK) {
2972 } else if (err == EINPROGRESS) {
2973 break;
2974 } else {
2975 perror("connect");
2976 closesocket(fd);
2977 return -1;
2979 } else {
2980 connected = 1;
2981 break;
2984 s = net_socket_fd_init(vlan, fd, connected);
2985 if (!s)
2986 return -1;
2987 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
2988 "socket: connect to %s:%d",
2989 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
2990 return 0;
2993 static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
2995 NetSocketState *s;
2996 int fd;
2997 struct sockaddr_in saddr;
2999 if (parse_host_port(&saddr, host_str) < 0)
3000 return -1;
3003 fd = net_socket_mcast_create(&saddr);
3004 if (fd < 0)
3005 return -1;
3007 s = net_socket_fd_init(vlan, fd, 0);
3008 if (!s)
3009 return -1;
3011 s->dgram_dst = saddr;
3013 snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3014 "socket: mcast=%s:%d",
3015 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3016 return 0;
3020 static int get_param_value(char *buf, int buf_size,
3021 const char *tag, const char *str)
3023 const char *p;
3024 char *q;
3025 char option[128];
3027 p = str;
3028 for(;;) {
3029 q = option;
3030 while (*p != '\0' && *p != '=') {
3031 if ((q - option) < sizeof(option) - 1)
3032 *q++ = *p;
3033 p++;
3035 *q = '\0';
3036 if (*p != '=')
3037 break;
3038 p++;
3039 if (!strcmp(tag, option)) {
3040 q = buf;
3041 while (*p != '\0' && *p != ',') {
3042 if ((q - buf) < buf_size - 1)
3043 *q++ = *p;
3044 p++;
3046 *q = '\0';
3047 return q - buf;
3048 } else {
3049 while (*p != '\0' && *p != ',') {
3050 p++;
3053 if (*p != ',')
3054 break;
3055 p++;
3057 return 0;
3060 int net_client_init(const char *str)
3062 const char *p;
3063 char *q;
3064 char device[64];
3065 char buf[1024];
3066 int vlan_id, ret;
3067 VLANState *vlan;
3069 p = str;
3070 q = device;
3071 while (*p != '\0' && *p != ',') {
3072 if ((q - device) < sizeof(device) - 1)
3073 *q++ = *p;
3074 p++;
3076 *q = '\0';
3077 if (*p == ',')
3078 p++;
3079 vlan_id = 0;
3080 if (get_param_value(buf, sizeof(buf), "vlan", p)) {
3081 vlan_id = strtol(buf, NULL, 0);
3083 vlan = qemu_find_vlan(vlan_id);
3084 if (!vlan) {
3085 fprintf(stderr, "Could not create vlan %d\n", vlan_id);
3086 return -1;
3088 if (!strcmp(device, "nic")) {
3089 NICInfo *nd;
3090 uint8_t *macaddr;
3092 if (nb_nics >= MAX_NICS) {
3093 fprintf(stderr, "Too Many NICs\n");
3094 return -1;
3096 nd = &nd_table[nb_nics];
3097 macaddr = nd->macaddr;
3098 macaddr[0] = 0x52;
3099 macaddr[1] = 0x54;
3100 macaddr[2] = 0x00;
3101 macaddr[3] = 0x12;
3102 macaddr[4] = 0x34;
3103 macaddr[5] = 0x56 + nb_nics;
3105 if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
3106 if (parse_macaddr(macaddr, buf) < 0) {
3107 fprintf(stderr, "invalid syntax for ethernet address\n");
3108 return -1;
3111 if (get_param_value(buf, sizeof(buf), "model", p)) {
3112 nd->model = strdup(buf);
3114 nd->vlan = vlan;
3115 nb_nics++;
3116 ret = 0;
3117 } else
3118 if (!strcmp(device, "none")) {
3119 /* does nothing. It is needed to signal that no network cards
3120 are wanted */
3121 ret = 0;
3122 } else
3123 #ifdef CONFIG_SLIRP
3124 if (!strcmp(device, "user")) {
3125 if (get_param_value(buf, sizeof(buf), "hostname", p)) {
3126 if (strlen(buf) > 32)
3127 buf[32] = 0;
3128 strcpy(slirp_hostname, buf);
3130 ret = net_slirp_init(vlan);
3131 } else
3132 #endif
3133 #ifdef _WIN32
3134 if (!strcmp(device, "tap")) {
3135 char ifname[64];
3136 if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
3137 fprintf(stderr, "tap: no interface name\n");
3138 return -1;
3140 ret = tap_win32_init(vlan, ifname);
3141 } else
3142 #else
3143 if (!strcmp(device, "tap")) {
3144 char ifname[64];
3145 char setup_script[1024];
3146 int fd;
3147 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3148 fd = strtol(buf, NULL, 0);
3149 ret = -1;
3150 if (net_tap_fd_init(vlan, fd))
3151 ret = 0;
3152 } else {
3153 get_param_value(ifname, sizeof(ifname), "ifname", p);
3154 if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
3155 pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
3157 ret = net_tap_init(vlan, ifname, setup_script);
3159 } else
3160 #endif
3161 if (!strcmp(device, "socket")) {
3162 if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
3163 int fd;
3164 fd = strtol(buf, NULL, 0);
3165 ret = -1;
3166 if (net_socket_fd_init(vlan, fd, 1))
3167 ret = 0;
3168 } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
3169 ret = net_socket_listen_init(vlan, buf);
3170 } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
3171 ret = net_socket_connect_init(vlan, buf);
3172 } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
3173 ret = net_socket_mcast_init(vlan, buf);
3174 } else {
3175 fprintf(stderr, "Unknown socket options: %s\n", p);
3176 return -1;
3178 } else
3180 fprintf(stderr, "Unknown network device: %s\n", device);
3181 return -1;
3183 if (ret < 0) {
3184 fprintf(stderr, "Could not initialize device '%s'\n", device);
3187 return ret;
3190 void do_info_network(void)
3192 VLANState *vlan;
3193 VLANClientState *vc;
3195 for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3196 term_printf("VLAN %d devices:\n", vlan->id);
3197 for(vc = vlan->first_client; vc != NULL; vc = vc->next)
3198 term_printf(" %s\n", vc->info_str);
3202 /***********************************************************/
3203 /* USB devices */
3205 static int usb_device_add(const char *devname)
3207 const char *p;
3208 USBDevice *dev;
3209 int i;
3211 if (!vm_usb_hub)
3212 return -1;
3213 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3214 if (!vm_usb_ports[i]->dev)
3215 break;
3217 if (i == MAX_VM_USB_PORTS)
3218 return -1;
3220 if (strstart(devname, "host:", &p)) {
3221 dev = usb_host_device_open(p);
3222 if (!dev)
3223 return -1;
3224 } else if (!strcmp(devname, "mouse")) {
3225 dev = usb_mouse_init();
3226 if (!dev)
3227 return -1;
3228 } else if (!strcmp(devname, "tablet")) {
3229 dev = usb_tablet_init();
3230 if (!dev)
3231 return -1;
3232 } else {
3233 return -1;
3235 usb_attach(vm_usb_ports[i], dev);
3236 return 0;
3239 static int usb_device_del(const char *devname)
3241 USBDevice *dev;
3242 int bus_num, addr, i;
3243 const char *p;
3245 if (!vm_usb_hub)
3246 return -1;
3248 p = strchr(devname, '.');
3249 if (!p)
3250 return -1;
3251 bus_num = strtoul(devname, NULL, 0);
3252 addr = strtoul(p + 1, NULL, 0);
3253 if (bus_num != 0)
3254 return -1;
3255 for(i = 0;i < MAX_VM_USB_PORTS; i++) {
3256 dev = vm_usb_ports[i]->dev;
3257 if (dev && dev->addr == addr)
3258 break;
3260 if (i == MAX_VM_USB_PORTS)
3261 return -1;
3262 usb_attach(vm_usb_ports[i], NULL);
3263 return 0;
3266 void do_usb_add(const char *devname)
3268 int ret;
3269 ret = usb_device_add(devname);
3270 if (ret < 0)
3271 term_printf("Could not add USB device '%s'\n", devname);
3274 void do_usb_del(const char *devname)
3276 int ret;
3277 ret = usb_device_del(devname);
3278 if (ret < 0)
3279 term_printf("Could not remove USB device '%s'\n", devname);
3282 void usb_info(void)
3284 USBDevice *dev;
3285 int i;
3286 const char *speed_str;
3288 if (!vm_usb_hub) {
3289 term_printf("USB support not enabled\n");
3290 return;
3293 for(i = 0; i < MAX_VM_USB_PORTS; i++) {
3294 dev = vm_usb_ports[i]->dev;
3295 if (dev) {
3296 term_printf("Hub port %d:\n", i);
3297 switch(dev->speed) {
3298 case USB_SPEED_LOW:
3299 speed_str = "1.5";
3300 break;
3301 case USB_SPEED_FULL:
3302 speed_str = "12";
3303 break;
3304 case USB_SPEED_HIGH:
3305 speed_str = "480";
3306 break;
3307 default:
3308 speed_str = "?";
3309 break;
3311 term_printf(" Device %d.%d, speed %s Mb/s\n",
3312 0, dev->addr, speed_str);
3317 /***********************************************************/
3318 /* pid file */
3320 static char *pid_filename;
3322 /* Remove PID file. Called on normal exit */
3324 static void remove_pidfile(void)
3326 unlink (pid_filename);
3329 static void create_pidfile(const char *filename)
3331 struct stat pidstat;
3332 FILE *f;
3334 /* Try to write our PID to the named file */
3335 if (stat(filename, &pidstat) < 0) {
3336 if (errno == ENOENT) {
3337 if ((f = fopen (filename, "w")) == NULL) {
3338 perror("Opening pidfile");
3339 exit(1);
3341 fprintf(f, "%d\n", getpid());
3342 fclose(f);
3343 pid_filename = qemu_strdup(filename);
3344 if (!pid_filename) {
3345 fprintf(stderr, "Could not save PID filename");
3346 exit(1);
3348 atexit(remove_pidfile);
3350 } else {
3351 fprintf(stderr, "%s already exists. Remove it and try again.\n",
3352 filename);
3353 exit(1);
3357 /***********************************************************/
3358 /* dumb display */
3360 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
3364 static void dumb_resize(DisplayState *ds, int w, int h)
3368 static void dumb_refresh(DisplayState *ds)
3370 vga_hw_update();
3373 void dumb_display_init(DisplayState *ds)
3375 ds->data = NULL;
3376 ds->linesize = 0;
3377 ds->depth = 0;
3378 ds->dpy_update = dumb_update;
3379 ds->dpy_resize = dumb_resize;
3380 ds->dpy_refresh = dumb_refresh;
3383 #if !defined(CONFIG_SOFTMMU)
3384 /***********************************************************/
3385 /* cpu signal handler */
3386 static void host_segv_handler(int host_signum, siginfo_t *info,
3387 void *puc)
3389 if (cpu_signal_handler(host_signum, info, puc))
3390 return;
3391 if (stdio_nb_clients > 0)
3392 term_exit();
3393 abort();
3395 #endif
3397 /***********************************************************/
3398 /* I/O handling */
3400 #define MAX_IO_HANDLERS 64
3402 typedef struct IOHandlerRecord {
3403 int fd;
3404 IOCanRWHandler *fd_read_poll;
3405 IOHandler *fd_read;
3406 IOHandler *fd_write;
3407 void *opaque;
3408 /* temporary data */
3409 struct pollfd *ufd;
3410 struct IOHandlerRecord *next;
3411 } IOHandlerRecord;
3413 static IOHandlerRecord *first_io_handler;
3415 /* XXX: fd_read_poll should be suppressed, but an API change is
3416 necessary in the character devices to suppress fd_can_read(). */
3417 int qemu_set_fd_handler2(int fd,
3418 IOCanRWHandler *fd_read_poll,
3419 IOHandler *fd_read,
3420 IOHandler *fd_write,
3421 void *opaque)
3423 IOHandlerRecord **pioh, *ioh;
3425 if (!fd_read && !fd_write) {
3426 pioh = &first_io_handler;
3427 for(;;) {
3428 ioh = *pioh;
3429 if (ioh == NULL)
3430 break;
3431 if (ioh->fd == fd) {
3432 *pioh = ioh->next;
3433 qemu_free(ioh);
3434 break;
3436 pioh = &ioh->next;
3438 } else {
3439 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
3440 if (ioh->fd == fd)
3441 goto found;
3443 ioh = qemu_mallocz(sizeof(IOHandlerRecord));
3444 if (!ioh)
3445 return -1;
3446 ioh->next = first_io_handler;
3447 first_io_handler = ioh;
3448 found:
3449 ioh->fd = fd;
3450 ioh->fd_read_poll = fd_read_poll;
3451 ioh->fd_read = fd_read;
3452 ioh->fd_write = fd_write;
3453 ioh->opaque = opaque;
3455 return 0;
3458 int qemu_set_fd_handler(int fd,
3459 IOHandler *fd_read,
3460 IOHandler *fd_write,
3461 void *opaque)
3463 return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
3466 /***********************************************************/
3467 /* Polling handling */
3469 typedef struct PollingEntry {
3470 PollingFunc *func;
3471 void *opaque;
3472 struct PollingEntry *next;
3473 } PollingEntry;
3475 static PollingEntry *first_polling_entry;
3477 int qemu_add_polling_cb(PollingFunc *func, void *opaque)
3479 PollingEntry **ppe, *pe;
3480 pe = qemu_mallocz(sizeof(PollingEntry));
3481 if (!pe)
3482 return -1;
3483 pe->func = func;
3484 pe->opaque = opaque;
3485 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
3486 *ppe = pe;
3487 return 0;
3490 void qemu_del_polling_cb(PollingFunc *func, void *opaque)
3492 PollingEntry **ppe, *pe;
3493 for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
3494 pe = *ppe;
3495 if (pe->func == func && pe->opaque == opaque) {
3496 *ppe = pe->next;
3497 qemu_free(pe);
3498 break;
3503 /***********************************************************/
3504 /* savevm/loadvm support */
3506 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
3508 fwrite(buf, 1, size, f);
3511 void qemu_put_byte(QEMUFile *f, int v)
3513 fputc(v, f);
3516 void qemu_put_be16(QEMUFile *f, unsigned int v)
3518 qemu_put_byte(f, v >> 8);
3519 qemu_put_byte(f, v);
3522 void qemu_put_be32(QEMUFile *f, unsigned int v)
3524 qemu_put_byte(f, v >> 24);
3525 qemu_put_byte(f, v >> 16);
3526 qemu_put_byte(f, v >> 8);
3527 qemu_put_byte(f, v);
3530 void qemu_put_be64(QEMUFile *f, uint64_t v)
3532 qemu_put_be32(f, v >> 32);
3533 qemu_put_be32(f, v);
3536 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
3538 return fread(buf, 1, size, f);
3541 int qemu_get_byte(QEMUFile *f)
3543 int v;
3544 v = fgetc(f);
3545 if (v == EOF)
3546 return 0;
3547 else
3548 return v;
3551 unsigned int qemu_get_be16(QEMUFile *f)
3553 unsigned int v;
3554 v = qemu_get_byte(f) << 8;
3555 v |= qemu_get_byte(f);
3556 return v;
3559 unsigned int qemu_get_be32(QEMUFile *f)
3561 unsigned int v;
3562 v = qemu_get_byte(f) << 24;
3563 v |= qemu_get_byte(f) << 16;
3564 v |= qemu_get_byte(f) << 8;
3565 v |= qemu_get_byte(f);
3566 return v;
3569 uint64_t qemu_get_be64(QEMUFile *f)
3571 uint64_t v;
3572 v = (uint64_t)qemu_get_be32(f) << 32;
3573 v |= qemu_get_be32(f);
3574 return v;
3577 int64_t qemu_ftell(QEMUFile *f)
3579 return ftell(f);
3582 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
3584 if (fseek(f, pos, whence) < 0)
3585 return -1;
3586 return ftell(f);
3589 typedef struct SaveStateEntry {
3590 char idstr[256];
3591 int instance_id;
3592 int version_id;
3593 SaveStateHandler *save_state;
3594 LoadStateHandler *load_state;
3595 void *opaque;
3596 struct SaveStateEntry *next;
3597 } SaveStateEntry;
3599 static SaveStateEntry *first_se;
3601 int register_savevm(const char *idstr,
3602 int instance_id,
3603 int version_id,
3604 SaveStateHandler *save_state,
3605 LoadStateHandler *load_state,
3606 void *opaque)
3608 SaveStateEntry *se, **pse;
3610 se = qemu_malloc(sizeof(SaveStateEntry));
3611 if (!se)
3612 return -1;
3613 pstrcpy(se->idstr, sizeof(se->idstr), idstr);
3614 se->instance_id = instance_id;
3615 se->version_id = version_id;
3616 se->save_state = save_state;
3617 se->load_state = load_state;
3618 se->opaque = opaque;
3619 se->next = NULL;
3621 /* add at the end of list */
3622 pse = &first_se;
3623 while (*pse != NULL)
3624 pse = &(*pse)->next;
3625 *pse = se;
3626 return 0;
3629 #define QEMU_VM_FILE_MAGIC 0x5145564d
3630 #define QEMU_VM_FILE_VERSION 0x00000001
3632 int qemu_savevm(const char *filename)
3634 SaveStateEntry *se;
3635 QEMUFile *f;
3636 int len, len_pos, cur_pos, saved_vm_running, ret;
3638 saved_vm_running = vm_running;
3639 vm_stop(0);
3641 f = fopen(filename, "wb");
3642 if (!f) {
3643 ret = -1;
3644 goto the_end;
3647 qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
3648 qemu_put_be32(f, QEMU_VM_FILE_VERSION);
3650 for(se = first_se; se != NULL; se = se->next) {
3651 /* ID string */
3652 len = strlen(se->idstr);
3653 qemu_put_byte(f, len);
3654 qemu_put_buffer(f, se->idstr, len);
3656 qemu_put_be32(f, se->instance_id);
3657 qemu_put_be32(f, se->version_id);
3659 /* record size: filled later */
3660 len_pos = ftell(f);
3661 qemu_put_be32(f, 0);
3663 se->save_state(f, se->opaque);
3665 /* fill record size */
3666 cur_pos = ftell(f);
3667 len = ftell(f) - len_pos - 4;
3668 fseek(f, len_pos, SEEK_SET);
3669 qemu_put_be32(f, len);
3670 fseek(f, cur_pos, SEEK_SET);
3673 fclose(f);
3674 ret = 0;
3675 the_end:
3676 if (saved_vm_running)
3677 vm_start();
3678 return ret;
3681 static SaveStateEntry *find_se(const char *idstr, int instance_id)
3683 SaveStateEntry *se;
3685 for(se = first_se; se != NULL; se = se->next) {
3686 if (!strcmp(se->idstr, idstr) &&
3687 instance_id == se->instance_id)
3688 return se;
3690 return NULL;
3693 int qemu_loadvm(const char *filename)
3695 SaveStateEntry *se;
3696 QEMUFile *f;
3697 int len, cur_pos, ret, instance_id, record_len, version_id;
3698 int saved_vm_running;
3699 unsigned int v;
3700 char idstr[256];
3702 saved_vm_running = vm_running;
3703 vm_stop(0);
3705 f = fopen(filename, "rb");
3706 if (!f) {
3707 ret = -1;
3708 goto the_end;
3711 v = qemu_get_be32(f);
3712 if (v != QEMU_VM_FILE_MAGIC)
3713 goto fail;
3714 v = qemu_get_be32(f);
3715 if (v != QEMU_VM_FILE_VERSION) {
3716 fail:
3717 fclose(f);
3718 ret = -1;
3719 goto the_end;
3721 for(;;) {
3722 len = qemu_get_byte(f);
3723 if (feof(f))
3724 break;
3725 qemu_get_buffer(f, idstr, len);
3726 idstr[len] = '\0';
3727 instance_id = qemu_get_be32(f);
3728 version_id = qemu_get_be32(f);
3729 record_len = qemu_get_be32(f);
3730 #if 0
3731 printf("idstr=%s instance=0x%x version=%d len=%d\n",
3732 idstr, instance_id, version_id, record_len);
3733 #endif
3734 cur_pos = ftell(f);
3735 se = find_se(idstr, instance_id);
3736 if (!se) {
3737 fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
3738 instance_id, idstr);
3739 } else {
3740 ret = se->load_state(f, se->opaque, version_id);
3741 if (ret < 0) {
3742 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
3743 instance_id, idstr);
3746 /* always seek to exact end of record */
3747 qemu_fseek(f, cur_pos + record_len, SEEK_SET);
3749 fclose(f);
3750 ret = 0;
3751 the_end:
3752 if (saved_vm_running)
3753 vm_start();
3754 return ret;
3757 /***********************************************************/
3758 /* cpu save/restore */
3760 #if defined(TARGET_I386)
3762 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
3764 qemu_put_be32(f, dt->selector);
3765 qemu_put_betl(f, dt->base);
3766 qemu_put_be32(f, dt->limit);
3767 qemu_put_be32(f, dt->flags);
3770 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
3772 dt->selector = qemu_get_be32(f);
3773 dt->base = qemu_get_betl(f);
3774 dt->limit = qemu_get_be32(f);
3775 dt->flags = qemu_get_be32(f);
3778 void cpu_save(QEMUFile *f, void *opaque)
3780 CPUState *env = opaque;
3781 uint16_t fptag, fpus, fpuc, fpregs_format;
3782 uint32_t hflags;
3783 int i;
3785 for(i = 0; i < CPU_NB_REGS; i++)
3786 qemu_put_betls(f, &env->regs[i]);
3787 qemu_put_betls(f, &env->eip);
3788 qemu_put_betls(f, &env->eflags);
3789 hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
3790 qemu_put_be32s(f, &hflags);
3792 /* FPU */
3793 fpuc = env->fpuc;
3794 fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
3795 fptag = 0;
3796 for(i = 0; i < 8; i++) {
3797 fptag |= ((!env->fptags[i]) << i);
3800 qemu_put_be16s(f, &fpuc);
3801 qemu_put_be16s(f, &fpus);
3802 qemu_put_be16s(f, &fptag);
3804 #ifdef USE_X86LDOUBLE
3805 fpregs_format = 0;
3806 #else
3807 fpregs_format = 1;
3808 #endif
3809 qemu_put_be16s(f, &fpregs_format);
3811 for(i = 0; i < 8; i++) {
3812 #ifdef USE_X86LDOUBLE
3814 uint64_t mant;
3815 uint16_t exp;
3816 /* we save the real CPU data (in case of MMX usage only 'mant'
3817 contains the MMX register */
3818 cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
3819 qemu_put_be64(f, mant);
3820 qemu_put_be16(f, exp);
3822 #else
3823 /* if we use doubles for float emulation, we save the doubles to
3824 avoid losing information in case of MMX usage. It can give
3825 problems if the image is restored on a CPU where long
3826 doubles are used instead. */
3827 qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
3828 #endif
3831 for(i = 0; i < 6; i++)
3832 cpu_put_seg(f, &env->segs[i]);
3833 cpu_put_seg(f, &env->ldt);
3834 cpu_put_seg(f, &env->tr);
3835 cpu_put_seg(f, &env->gdt);
3836 cpu_put_seg(f, &env->idt);
3838 qemu_put_be32s(f, &env->sysenter_cs);
3839 qemu_put_be32s(f, &env->sysenter_esp);
3840 qemu_put_be32s(f, &env->sysenter_eip);
3842 qemu_put_betls(f, &env->cr[0]);
3843 qemu_put_betls(f, &env->cr[2]);
3844 qemu_put_betls(f, &env->cr[3]);
3845 qemu_put_betls(f, &env->cr[4]);
3847 for(i = 0; i < 8; i++)
3848 qemu_put_betls(f, &env->dr[i]);
3850 /* MMU */
3851 qemu_put_be32s(f, &env->a20_mask);
3853 /* XMM */
3854 qemu_put_be32s(f, &env->mxcsr);
3855 for(i = 0; i < CPU_NB_REGS; i++) {
3856 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3857 qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3860 #ifdef TARGET_X86_64
3861 qemu_put_be64s(f, &env->efer);
3862 qemu_put_be64s(f, &env->star);
3863 qemu_put_be64s(f, &env->lstar);
3864 qemu_put_be64s(f, &env->cstar);
3865 qemu_put_be64s(f, &env->fmask);
3866 qemu_put_be64s(f, &env->kernelgsbase);
3867 #endif
3870 #ifdef USE_X86LDOUBLE
3871 /* XXX: add that in a FPU generic layer */
3872 union x86_longdouble {
3873 uint64_t mant;
3874 uint16_t exp;
3877 #define MANTD1(fp) (fp & ((1LL << 52) - 1))
3878 #define EXPBIAS1 1023
3879 #define EXPD1(fp) ((fp >> 52) & 0x7FF)
3880 #define SIGND1(fp) ((fp >> 32) & 0x80000000)
3882 static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
3884 int e;
3885 /* mantissa */
3886 p->mant = (MANTD1(temp) << 11) | (1LL << 63);
3887 /* exponent + sign */
3888 e = EXPD1(temp) - EXPBIAS1 + 16383;
3889 e |= SIGND1(temp) >> 16;
3890 p->exp = e;
3892 #endif
3894 int cpu_load(QEMUFile *f, void *opaque, int version_id)
3896 CPUState *env = opaque;
3897 int i, guess_mmx;
3898 uint32_t hflags;
3899 uint16_t fpus, fpuc, fptag, fpregs_format;
3901 if (version_id != 3)
3902 return -EINVAL;
3903 for(i = 0; i < CPU_NB_REGS; i++)
3904 qemu_get_betls(f, &env->regs[i]);
3905 qemu_get_betls(f, &env->eip);
3906 qemu_get_betls(f, &env->eflags);
3907 qemu_get_be32s(f, &hflags);
3909 qemu_get_be16s(f, &fpuc);
3910 qemu_get_be16s(f, &fpus);
3911 qemu_get_be16s(f, &fptag);
3912 qemu_get_be16s(f, &fpregs_format);
3914 /* NOTE: we cannot always restore the FPU state if the image come
3915 from a host with a different 'USE_X86LDOUBLE' define. We guess
3916 if we are in an MMX state to restore correctly in that case. */
3917 guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
3918 for(i = 0; i < 8; i++) {
3919 uint64_t mant;
3920 uint16_t exp;
3922 switch(fpregs_format) {
3923 case 0:
3924 mant = qemu_get_be64(f);
3925 exp = qemu_get_be16(f);
3926 #ifdef USE_X86LDOUBLE
3927 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3928 #else
3929 /* difficult case */
3930 if (guess_mmx)
3931 env->fpregs[i].mmx.MMX_Q(0) = mant;
3932 else
3933 env->fpregs[i].d = cpu_set_fp80(mant, exp);
3934 #endif
3935 break;
3936 case 1:
3937 mant = qemu_get_be64(f);
3938 #ifdef USE_X86LDOUBLE
3940 union x86_longdouble *p;
3941 /* difficult case */
3942 p = (void *)&env->fpregs[i];
3943 if (guess_mmx) {
3944 p->mant = mant;
3945 p->exp = 0xffff;
3946 } else {
3947 fp64_to_fp80(p, mant);
3950 #else
3951 env->fpregs[i].mmx.MMX_Q(0) = mant;
3952 #endif
3953 break;
3954 default:
3955 return -EINVAL;
3959 env->fpuc = fpuc;
3960 /* XXX: restore FPU round state */
3961 env->fpstt = (fpus >> 11) & 7;
3962 env->fpus = fpus & ~0x3800;
3963 fptag ^= 0xff;
3964 for(i = 0; i < 8; i++) {
3965 env->fptags[i] = (fptag >> i) & 1;
3968 for(i = 0; i < 6; i++)
3969 cpu_get_seg(f, &env->segs[i]);
3970 cpu_get_seg(f, &env->ldt);
3971 cpu_get_seg(f, &env->tr);
3972 cpu_get_seg(f, &env->gdt);
3973 cpu_get_seg(f, &env->idt);
3975 qemu_get_be32s(f, &env->sysenter_cs);
3976 qemu_get_be32s(f, &env->sysenter_esp);
3977 qemu_get_be32s(f, &env->sysenter_eip);
3979 qemu_get_betls(f, &env->cr[0]);
3980 qemu_get_betls(f, &env->cr[2]);
3981 qemu_get_betls(f, &env->cr[3]);
3982 qemu_get_betls(f, &env->cr[4]);
3984 for(i = 0; i < 8; i++)
3985 qemu_get_betls(f, &env->dr[i]);
3987 /* MMU */
3988 qemu_get_be32s(f, &env->a20_mask);
3990 qemu_get_be32s(f, &env->mxcsr);
3991 for(i = 0; i < CPU_NB_REGS; i++) {
3992 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
3993 qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
3996 #ifdef TARGET_X86_64
3997 qemu_get_be64s(f, &env->efer);
3998 qemu_get_be64s(f, &env->star);
3999 qemu_get_be64s(f, &env->lstar);
4000 qemu_get_be64s(f, &env->cstar);
4001 qemu_get_be64s(f, &env->fmask);
4002 qemu_get_be64s(f, &env->kernelgsbase);
4003 #endif
4005 /* XXX: compute hflags from scratch, except for CPL and IIF */
4006 env->hflags = hflags;
4007 tlb_flush(env, 1);
4008 return 0;
4011 #elif defined(TARGET_PPC)
4012 void cpu_save(QEMUFile *f, void *opaque)
4016 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4018 return 0;
4021 #elif defined(TARGET_MIPS)
4022 void cpu_save(QEMUFile *f, void *opaque)
4026 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4028 return 0;
4031 #elif defined(TARGET_SPARC)
4032 void cpu_save(QEMUFile *f, void *opaque)
4034 CPUState *env = opaque;
4035 int i;
4036 uint32_t tmp;
4038 for(i = 0; i < 8; i++)
4039 qemu_put_betls(f, &env->gregs[i]);
4040 for(i = 0; i < NWINDOWS * 16; i++)
4041 qemu_put_betls(f, &env->regbase[i]);
4043 /* FPU */
4044 for(i = 0; i < TARGET_FPREGS; i++) {
4045 union {
4046 TARGET_FPREG_T f;
4047 target_ulong i;
4048 } u;
4049 u.f = env->fpr[i];
4050 qemu_put_betl(f, u.i);
4053 qemu_put_betls(f, &env->pc);
4054 qemu_put_betls(f, &env->npc);
4055 qemu_put_betls(f, &env->y);
4056 tmp = GET_PSR(env);
4057 qemu_put_be32(f, tmp);
4058 qemu_put_betls(f, &env->fsr);
4059 qemu_put_betls(f, &env->tbr);
4060 #ifndef TARGET_SPARC64
4061 qemu_put_be32s(f, &env->wim);
4062 /* MMU */
4063 for(i = 0; i < 16; i++)
4064 qemu_put_be32s(f, &env->mmuregs[i]);
4065 #endif
4068 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4070 CPUState *env = opaque;
4071 int i;
4072 uint32_t tmp;
4074 for(i = 0; i < 8; i++)
4075 qemu_get_betls(f, &env->gregs[i]);
4076 for(i = 0; i < NWINDOWS * 16; i++)
4077 qemu_get_betls(f, &env->regbase[i]);
4079 /* FPU */
4080 for(i = 0; i < TARGET_FPREGS; i++) {
4081 union {
4082 TARGET_FPREG_T f;
4083 target_ulong i;
4084 } u;
4085 u.i = qemu_get_betl(f);
4086 env->fpr[i] = u.f;
4089 qemu_get_betls(f, &env->pc);
4090 qemu_get_betls(f, &env->npc);
4091 qemu_get_betls(f, &env->y);
4092 tmp = qemu_get_be32(f);
4093 env->cwp = 0; /* needed to ensure that the wrapping registers are
4094 correctly updated */
4095 PUT_PSR(env, tmp);
4096 qemu_get_betls(f, &env->fsr);
4097 qemu_get_betls(f, &env->tbr);
4098 #ifndef TARGET_SPARC64
4099 qemu_get_be32s(f, &env->wim);
4100 /* MMU */
4101 for(i = 0; i < 16; i++)
4102 qemu_get_be32s(f, &env->mmuregs[i]);
4103 #endif
4104 tlb_flush(env, 1);
4105 return 0;
4108 #elif defined(TARGET_ARM)
4110 /* ??? Need to implement these. */
4111 void cpu_save(QEMUFile *f, void *opaque)
4115 int cpu_load(QEMUFile *f, void *opaque, int version_id)
4117 return 0;
4120 #else
4122 #warning No CPU save/restore functions
4124 #endif
4126 /***********************************************************/
4127 /* ram save/restore */
4129 /* we just avoid storing empty pages */
4130 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
4132 int i, v;
4134 v = buf[0];
4135 for(i = 1; i < len; i++) {
4136 if (buf[i] != v)
4137 goto normal_save;
4139 qemu_put_byte(f, 1);
4140 qemu_put_byte(f, v);
4141 return;
4142 normal_save:
4143 qemu_put_byte(f, 0);
4144 qemu_put_buffer(f, buf, len);
4147 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
4149 int v;
4151 v = qemu_get_byte(f);
4152 switch(v) {
4153 case 0:
4154 if (qemu_get_buffer(f, buf, len) != len)
4155 return -EIO;
4156 break;
4157 case 1:
4158 v = qemu_get_byte(f);
4159 memset(buf, v, len);
4160 break;
4161 default:
4162 return -EINVAL;
4164 return 0;
4167 static void ram_save(QEMUFile *f, void *opaque)
4169 int i;
4170 qemu_put_be32(f, phys_ram_size);
4171 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4172 ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4176 static int ram_load(QEMUFile *f, void *opaque, int version_id)
4178 int i, ret;
4180 if (version_id != 1)
4181 return -EINVAL;
4182 if (qemu_get_be32(f) != phys_ram_size)
4183 return -EINVAL;
4184 for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
4185 ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
4186 if (ret)
4187 return ret;
4189 return 0;
4192 /***********************************************************/
4193 /* machine registration */
4195 QEMUMachine *first_machine = NULL;
4197 int qemu_register_machine(QEMUMachine *m)
4199 QEMUMachine **pm;
4200 pm = &first_machine;
4201 while (*pm != NULL)
4202 pm = &(*pm)->next;
4203 m->next = NULL;
4204 *pm = m;
4205 return 0;
4208 QEMUMachine *find_machine(const char *name)
4210 QEMUMachine *m;
4212 for(m = first_machine; m != NULL; m = m->next) {
4213 if (!strcmp(m->name, name))
4214 return m;
4216 return NULL;
4219 /***********************************************************/
4220 /* main execution loop */
4222 void gui_update(void *opaque)
4224 display_state.dpy_refresh(&display_state);
4225 qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
4228 struct vm_change_state_entry {
4229 VMChangeStateHandler *cb;
4230 void *opaque;
4231 LIST_ENTRY (vm_change_state_entry) entries;
4234 static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
4236 VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
4237 void *opaque)
4239 VMChangeStateEntry *e;
4241 e = qemu_mallocz(sizeof (*e));
4242 if (!e)
4243 return NULL;
4245 e->cb = cb;
4246 e->opaque = opaque;
4247 LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
4248 return e;
4251 void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
4253 LIST_REMOVE (e, entries);
4254 qemu_free (e);
4257 static void vm_state_notify(int running)
4259 VMChangeStateEntry *e;
4261 for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
4262 e->cb(e->opaque, running);
4266 /* XXX: support several handlers */
4267 static VMStopHandler *vm_stop_cb;
4268 static void *vm_stop_opaque;
4270 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
4272 vm_stop_cb = cb;
4273 vm_stop_opaque = opaque;
4274 return 0;
4277 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
4279 vm_stop_cb = NULL;
4282 void vm_start(void)
4284 if (!vm_running) {
4285 cpu_enable_ticks();
4286 vm_running = 1;
4287 vm_state_notify(1);
4291 void vm_stop(int reason)
4293 if (vm_running) {
4294 cpu_disable_ticks();
4295 vm_running = 0;
4296 if (reason != 0) {
4297 if (vm_stop_cb) {
4298 vm_stop_cb(vm_stop_opaque, reason);
4301 vm_state_notify(0);
4305 /* reset/shutdown handler */
4307 typedef struct QEMUResetEntry {
4308 QEMUResetHandler *func;
4309 void *opaque;
4310 struct QEMUResetEntry *next;
4311 } QEMUResetEntry;
4313 static QEMUResetEntry *first_reset_entry;
4314 static int reset_requested;
4315 static int shutdown_requested;
4316 static int powerdown_requested;
4318 void qemu_register_reset(QEMUResetHandler *func, void *opaque)
4320 QEMUResetEntry **pre, *re;
4322 pre = &first_reset_entry;
4323 while (*pre != NULL)
4324 pre = &(*pre)->next;
4325 re = qemu_mallocz(sizeof(QEMUResetEntry));
4326 re->func = func;
4327 re->opaque = opaque;
4328 re->next = NULL;
4329 *pre = re;
4332 void qemu_system_reset(void)
4334 QEMUResetEntry *re;
4336 /* reset all devices */
4337 for(re = first_reset_entry; re != NULL; re = re->next) {
4338 re->func(re->opaque);
4342 void qemu_system_reset_request(void)
4344 reset_requested = 1;
4345 if (cpu_single_env)
4346 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4349 void qemu_system_shutdown_request(void)
4351 shutdown_requested = 1;
4352 if (cpu_single_env)
4353 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4356 void qemu_system_powerdown_request(void)
4358 powerdown_requested = 1;
4359 if (cpu_single_env)
4360 cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
4363 void main_loop_wait(int timeout)
4365 IOHandlerRecord *ioh, *ioh_next;
4366 fd_set rfds, wfds;
4367 int ret, nfds;
4368 struct timeval tv;
4369 PollingEntry *pe;
4372 /* XXX: need to suppress polling by better using win32 events */
4373 ret = 0;
4374 for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
4375 ret |= pe->func(pe->opaque);
4377 #ifdef _WIN32
4378 if (ret == 0 && timeout > 0) {
4379 Sleep(timeout);
4381 #endif
4382 /* poll any events */
4383 /* XXX: separate device handlers from system ones */
4384 nfds = -1;
4385 FD_ZERO(&rfds);
4386 FD_ZERO(&wfds);
4387 for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4388 if (ioh->fd_read &&
4389 (!ioh->fd_read_poll ||
4390 ioh->fd_read_poll(ioh->opaque) != 0)) {
4391 FD_SET(ioh->fd, &rfds);
4392 if (ioh->fd > nfds)
4393 nfds = ioh->fd;
4395 if (ioh->fd_write) {
4396 FD_SET(ioh->fd, &wfds);
4397 if (ioh->fd > nfds)
4398 nfds = ioh->fd;
4402 tv.tv_sec = 0;
4403 #ifdef _WIN32
4404 tv.tv_usec = 0;
4405 #else
4406 tv.tv_usec = timeout * 1000;
4407 #endif
4408 ret = select(nfds + 1, &rfds, &wfds, NULL, &tv);
4409 if (ret > 0) {
4410 /* XXX: better handling of removal */
4411 for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
4412 ioh_next = ioh->next;
4413 if (FD_ISSET(ioh->fd, &rfds)) {
4414 ioh->fd_read(ioh->opaque);
4416 if (FD_ISSET(ioh->fd, &wfds)) {
4417 ioh->fd_write(ioh->opaque);
4421 #ifdef _WIN32
4422 tap_win32_poll();
4423 #endif
4425 #if defined(CONFIG_SLIRP)
4426 /* XXX: merge with the previous select() */
4427 if (slirp_inited) {
4428 fd_set rfds, wfds, xfds;
4429 int nfds;
4430 struct timeval tv;
4432 nfds = -1;
4433 FD_ZERO(&rfds);
4434 FD_ZERO(&wfds);
4435 FD_ZERO(&xfds);
4436 slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
4437 tv.tv_sec = 0;
4438 tv.tv_usec = 0;
4439 ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
4440 if (ret >= 0) {
4441 slirp_select_poll(&rfds, &wfds, &xfds);
4444 #endif
4446 if (vm_running) {
4447 qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
4448 qemu_get_clock(vm_clock));
4449 /* run dma transfers, if any */
4450 DMA_run();
4453 /* real time timers */
4454 qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
4455 qemu_get_clock(rt_clock));
4458 static CPUState *cur_cpu;
4460 int main_loop(void)
4462 int ret, timeout;
4463 #ifdef CONFIG_PROFILER
4464 int64_t ti;
4465 #endif
4466 CPUState *env;
4468 cur_cpu = first_cpu;
4469 for(;;) {
4470 if (vm_running) {
4472 env = cur_cpu;
4473 for(;;) {
4474 /* get next cpu */
4475 env = env->next_cpu;
4476 if (!env)
4477 env = first_cpu;
4478 #ifdef CONFIG_PROFILER
4479 ti = profile_getclock();
4480 #endif
4481 ret = cpu_exec(env);
4482 #ifdef CONFIG_PROFILER
4483 qemu_time += profile_getclock() - ti;
4484 #endif
4485 if (ret != EXCP_HALTED)
4486 break;
4487 /* all CPUs are halted ? */
4488 if (env == cur_cpu) {
4489 ret = EXCP_HLT;
4490 break;
4493 cur_cpu = env;
4495 if (shutdown_requested) {
4496 ret = EXCP_INTERRUPT;
4497 break;
4499 if (reset_requested) {
4500 reset_requested = 0;
4501 qemu_system_reset();
4502 ret = EXCP_INTERRUPT;
4504 if (powerdown_requested) {
4505 powerdown_requested = 0;
4506 qemu_system_powerdown();
4507 ret = EXCP_INTERRUPT;
4509 if (ret == EXCP_DEBUG) {
4510 vm_stop(EXCP_DEBUG);
4512 /* if hlt instruction, we wait until the next IRQ */
4513 /* XXX: use timeout computed from timers */
4514 if (ret == EXCP_HLT)
4515 timeout = 10;
4516 else
4517 timeout = 0;
4518 } else {
4519 timeout = 10;
4521 #ifdef CONFIG_PROFILER
4522 ti = profile_getclock();
4523 #endif
4524 main_loop_wait(timeout);
4525 #ifdef CONFIG_PROFILER
4526 dev_time += profile_getclock() - ti;
4527 #endif
4529 cpu_disable_ticks();
4530 return ret;
4533 void help(void)
4535 printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2005 Fabrice Bellard\n"
4536 "usage: %s [options] [disk_image]\n"
4537 "\n"
4538 "'disk_image' is a raw hard image image for IDE hard disk 0\n"
4539 "\n"
4540 "Standard options:\n"
4541 "-M machine select emulated machine (-M ? for list)\n"
4542 "-fda/-fdb file use 'file' as floppy disk 0/1 image\n"
4543 "-hda/-hdb file use 'file' as IDE hard disk 0/1 image\n"
4544 "-hdc/-hdd file use 'file' as IDE hard disk 2/3 image\n"
4545 "-cdrom file use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
4546 "-boot [a|c|d] boot on floppy (a), hard disk (c) or CD-ROM (d)\n"
4547 "-snapshot write to temporary files instead of disk image files\n"
4548 "-m megs set virtual RAM size to megs MB [default=%d]\n"
4549 "-smp n set the number of CPUs to 'n' [default=1]\n"
4550 "-nographic disable graphical output and redirect serial I/Os to console\n"
4551 #ifndef _WIN32
4552 "-k language use keyboard layout (for example \"fr\" for French)\n"
4553 #endif
4554 #ifdef HAS_AUDIO
4555 "-audio-help print list of audio drivers and their options\n"
4556 "-soundhw c1,... enable audio support\n"
4557 " and only specified sound cards (comma separated list)\n"
4558 " use -soundhw ? to get the list of supported cards\n"
4559 " use -soundhw all to enable all of them\n"
4560 #endif
4561 "-localtime set the real time clock to local time [default=utc]\n"
4562 "-full-screen start in full screen\n"
4563 #ifdef TARGET_I386
4564 "-win2k-hack use it when installing Windows 2000 to avoid a disk full bug\n"
4565 #endif
4566 "-usb enable the USB driver (will be the default soon)\n"
4567 "-usbdevice name add the host or guest USB device 'name'\n"
4568 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4569 "-g WxH[xDEPTH] Set the initial graphical resolution and depth\n"
4570 #endif
4571 "\n"
4572 "Network options:\n"
4573 "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
4574 " create a new Network Interface Card and connect it to VLAN 'n'\n"
4575 #ifdef CONFIG_SLIRP
4576 "-net user[,vlan=n][,hostname=host]\n"
4577 " connect the user mode network stack to VLAN 'n' and send\n"
4578 " hostname 'host' to DHCP clients\n"
4579 #endif
4580 #ifdef _WIN32
4581 "-net tap[,vlan=n],ifname=name\n"
4582 " connect the host TAP network interface to VLAN 'n'\n"
4583 #else
4584 "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
4585 " connect the host TAP network interface to VLAN 'n' and use\n"
4586 " the network script 'file' (default=%s);\n"
4587 " use 'fd=h' to connect to an already opened TAP interface\n"
4588 #endif
4589 "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
4590 " connect the vlan 'n' to another VLAN using a socket connection\n"
4591 "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
4592 " connect the vlan 'n' to multicast maddr and port\n"
4593 "-net none use it alone to have zero network devices; if no -net option\n"
4594 " is provided, the default is '-net nic -net user'\n"
4595 "\n"
4596 #ifdef CONFIG_SLIRP
4597 "-tftp prefix allow tftp access to files starting with prefix [-net user]\n"
4598 #ifndef _WIN32
4599 "-smb dir allow SMB access to files in 'dir' [-net user]\n"
4600 #endif
4601 "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
4602 " redirect TCP or UDP connections from host to guest [-net user]\n"
4603 #endif
4604 "\n"
4605 "Linux boot specific:\n"
4606 "-kernel bzImage use 'bzImage' as kernel image\n"
4607 "-append cmdline use 'cmdline' as kernel command line\n"
4608 "-initrd file use 'file' as initial ram disk\n"
4609 "\n"
4610 "Debug/Expert options:\n"
4611 "-monitor dev redirect the monitor to char device 'dev'\n"
4612 "-serial dev redirect the serial port to char device 'dev'\n"
4613 "-parallel dev redirect the parallel port to char device 'dev'\n"
4614 "-pidfile file Write PID to 'file'\n"
4615 "-S freeze CPU at startup (use 'c' to start execution)\n"
4616 "-s wait gdb connection to port %d\n"
4617 "-p port change gdb connection port\n"
4618 "-d item1,... output log to %s (use -d ? for a list of log items)\n"
4619 "-hdachs c,h,s[,t] force hard disk 0 physical geometry and the optional BIOS\n"
4620 " translation (t=none or lba) (usually qemu can guess them)\n"
4621 "-L path set the directory for the BIOS and VGA BIOS\n"
4622 #ifdef USE_KQEMU
4623 "-no-kqemu disable KQEMU kernel module usage\n"
4624 #endif
4625 #ifdef USE_CODE_COPY
4626 "-no-code-copy disable code copy acceleration\n"
4627 #endif
4628 #ifdef TARGET_I386
4629 "-std-vga simulate a standard VGA card with VESA Bochs Extensions\n"
4630 " (default is CL-GD5446 PCI VGA)\n"
4631 #endif
4632 "-loadvm file start right away with a saved state (loadvm in monitor)\n"
4633 "\n"
4634 "During emulation, the following keys are useful:\n"
4635 "ctrl-alt-f toggle full screen\n"
4636 "ctrl-alt-n switch to virtual console 'n'\n"
4637 "ctrl-alt toggle mouse and keyboard grab\n"
4638 "\n"
4639 "When using -nographic, press 'ctrl-a h' to get some help.\n"
4641 #ifdef CONFIG_SOFTMMU
4642 "qemu",
4643 #else
4644 "qemu-fast",
4645 #endif
4646 DEFAULT_RAM_SIZE,
4647 #ifndef _WIN32
4648 DEFAULT_NETWORK_SCRIPT,
4649 #endif
4650 DEFAULT_GDBSTUB_PORT,
4651 "/tmp/qemu.log");
4652 #ifndef CONFIG_SOFTMMU
4653 printf("\n"
4654 "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
4655 "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
4656 "PC emulation.\n");
4657 #endif
4658 exit(1);
4661 #define HAS_ARG 0x0001
4663 enum {
4664 QEMU_OPTION_h,
4666 QEMU_OPTION_M,
4667 QEMU_OPTION_fda,
4668 QEMU_OPTION_fdb,
4669 QEMU_OPTION_hda,
4670 QEMU_OPTION_hdb,
4671 QEMU_OPTION_hdc,
4672 QEMU_OPTION_hdd,
4673 QEMU_OPTION_cdrom,
4674 QEMU_OPTION_boot,
4675 QEMU_OPTION_snapshot,
4676 QEMU_OPTION_m,
4677 QEMU_OPTION_nographic,
4678 #ifdef HAS_AUDIO
4679 QEMU_OPTION_audio_help,
4680 QEMU_OPTION_soundhw,
4681 #endif
4683 QEMU_OPTION_net,
4684 QEMU_OPTION_tftp,
4685 QEMU_OPTION_smb,
4686 QEMU_OPTION_redir,
4688 QEMU_OPTION_kernel,
4689 QEMU_OPTION_append,
4690 QEMU_OPTION_initrd,
4692 QEMU_OPTION_S,
4693 QEMU_OPTION_s,
4694 QEMU_OPTION_p,
4695 QEMU_OPTION_d,
4696 QEMU_OPTION_hdachs,
4697 QEMU_OPTION_L,
4698 QEMU_OPTION_no_code_copy,
4699 QEMU_OPTION_k,
4700 QEMU_OPTION_localtime,
4701 QEMU_OPTION_cirrusvga,
4702 QEMU_OPTION_g,
4703 QEMU_OPTION_std_vga,
4704 QEMU_OPTION_monitor,
4705 QEMU_OPTION_serial,
4706 QEMU_OPTION_parallel,
4707 QEMU_OPTION_loadvm,
4708 QEMU_OPTION_full_screen,
4709 QEMU_OPTION_pidfile,
4710 QEMU_OPTION_no_kqemu,
4711 QEMU_OPTION_kernel_kqemu,
4712 QEMU_OPTION_win2k_hack,
4713 QEMU_OPTION_usb,
4714 QEMU_OPTION_usbdevice,
4715 QEMU_OPTION_smp,
4718 typedef struct QEMUOption {
4719 const char *name;
4720 int flags;
4721 int index;
4722 } QEMUOption;
4724 const QEMUOption qemu_options[] = {
4725 { "h", 0, QEMU_OPTION_h },
4727 { "M", HAS_ARG, QEMU_OPTION_M },
4728 { "fda", HAS_ARG, QEMU_OPTION_fda },
4729 { "fdb", HAS_ARG, QEMU_OPTION_fdb },
4730 { "hda", HAS_ARG, QEMU_OPTION_hda },
4731 { "hdb", HAS_ARG, QEMU_OPTION_hdb },
4732 { "hdc", HAS_ARG, QEMU_OPTION_hdc },
4733 { "hdd", HAS_ARG, QEMU_OPTION_hdd },
4734 { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
4735 { "boot", HAS_ARG, QEMU_OPTION_boot },
4736 { "snapshot", 0, QEMU_OPTION_snapshot },
4737 { "m", HAS_ARG, QEMU_OPTION_m },
4738 { "nographic", 0, QEMU_OPTION_nographic },
4739 { "k", HAS_ARG, QEMU_OPTION_k },
4740 #ifdef HAS_AUDIO
4741 { "audio-help", 0, QEMU_OPTION_audio_help },
4742 { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
4743 #endif
4745 { "net", HAS_ARG, QEMU_OPTION_net},
4746 #ifdef CONFIG_SLIRP
4747 { "tftp", HAS_ARG, QEMU_OPTION_tftp },
4748 #ifndef _WIN32
4749 { "smb", HAS_ARG, QEMU_OPTION_smb },
4750 #endif
4751 { "redir", HAS_ARG, QEMU_OPTION_redir },
4752 #endif
4754 { "kernel", HAS_ARG, QEMU_OPTION_kernel },
4755 { "append", HAS_ARG, QEMU_OPTION_append },
4756 { "initrd", HAS_ARG, QEMU_OPTION_initrd },
4758 { "S", 0, QEMU_OPTION_S },
4759 { "s", 0, QEMU_OPTION_s },
4760 { "p", HAS_ARG, QEMU_OPTION_p },
4761 { "d", HAS_ARG, QEMU_OPTION_d },
4762 { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
4763 { "L", HAS_ARG, QEMU_OPTION_L },
4764 { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
4765 #ifdef USE_KQEMU
4766 { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
4767 { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
4768 #endif
4769 #if defined(TARGET_PPC) || defined(TARGET_SPARC)
4770 { "g", 1, QEMU_OPTION_g },
4771 #endif
4772 { "localtime", 0, QEMU_OPTION_localtime },
4773 { "std-vga", 0, QEMU_OPTION_std_vga },
4774 { "monitor", 1, QEMU_OPTION_monitor },
4775 { "serial", 1, QEMU_OPTION_serial },
4776 { "parallel", 1, QEMU_OPTION_parallel },
4777 { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
4778 { "full-screen", 0, QEMU_OPTION_full_screen },
4779 { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
4780 { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
4781 { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
4782 { "smp", HAS_ARG, QEMU_OPTION_smp },
4784 /* temporary options */
4785 { "usb", 0, QEMU_OPTION_usb },
4786 { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
4787 { NULL },
4790 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
4792 /* this stack is only used during signal handling */
4793 #define SIGNAL_STACK_SIZE 32768
4795 static uint8_t *signal_stack;
4797 #endif
4799 /* password input */
4801 static BlockDriverState *get_bdrv(int index)
4803 BlockDriverState *bs;
4805 if (index < 4) {
4806 bs = bs_table[index];
4807 } else if (index < 6) {
4808 bs = fd_table[index - 4];
4809 } else {
4810 bs = NULL;
4812 return bs;
4815 static void read_passwords(void)
4817 BlockDriverState *bs;
4818 int i, j;
4819 char password[256];
4821 for(i = 0; i < 6; i++) {
4822 bs = get_bdrv(i);
4823 if (bs && bdrv_is_encrypted(bs)) {
4824 term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
4825 for(j = 0; j < 3; j++) {
4826 monitor_readline("Password: ",
4827 1, password, sizeof(password));
4828 if (bdrv_set_key(bs, password) == 0)
4829 break;
4830 term_printf("invalid password\n");
4836 /* XXX: currently we cannot use simultaneously different CPUs */
4837 void register_machines(void)
4839 #if defined(TARGET_I386)
4840 qemu_register_machine(&pc_machine);
4841 qemu_register_machine(&isapc_machine);
4842 #elif defined(TARGET_PPC)
4843 qemu_register_machine(&heathrow_machine);
4844 qemu_register_machine(&core99_machine);
4845 qemu_register_machine(&prep_machine);
4846 #elif defined(TARGET_MIPS)
4847 qemu_register_machine(&mips_machine);
4848 #elif defined(TARGET_SPARC)
4849 #ifdef TARGET_SPARC64
4850 qemu_register_machine(&sun4u_machine);
4851 #else
4852 qemu_register_machine(&sun4m_machine);
4853 #endif
4854 #elif defined(TARGET_ARM)
4855 qemu_register_machine(&integratorcp926_machine);
4856 qemu_register_machine(&integratorcp1026_machine);
4857 qemu_register_machine(&versatilepb_machine);
4858 #else
4859 #error unsupported CPU
4860 #endif
4863 #ifdef HAS_AUDIO
4864 struct soundhw soundhw[] = {
4866 "sb16",
4867 "Creative Sound Blaster 16",
4870 { .init_isa = SB16_init }
4873 #ifdef CONFIG_ADLIB
4875 "adlib",
4876 #ifdef HAS_YMF262
4877 "Yamaha YMF262 (OPL3)",
4878 #else
4879 "Yamaha YM3812 (OPL2)",
4880 #endif
4883 { .init_isa = Adlib_init }
4885 #endif
4887 #ifdef CONFIG_GUS
4889 "gus",
4890 "Gravis Ultrasound GF1",
4893 { .init_isa = GUS_init }
4895 #endif
4898 "es1370",
4899 "ENSONIQ AudioPCI ES1370",
4902 { .init_pci = es1370_init }
4905 { NULL, NULL, 0, 0, { NULL } }
4908 static void select_soundhw (const char *optarg)
4910 struct soundhw *c;
4912 if (*optarg == '?') {
4913 show_valid_cards:
4915 printf ("Valid sound card names (comma separated):\n");
4916 for (c = soundhw; c->name; ++c) {
4917 printf ("%-11s %s\n", c->name, c->descr);
4919 printf ("\n-soundhw all will enable all of the above\n");
4920 exit (*optarg != '?');
4922 else {
4923 size_t l;
4924 const char *p;
4925 char *e;
4926 int bad_card = 0;
4928 if (!strcmp (optarg, "all")) {
4929 for (c = soundhw; c->name; ++c) {
4930 c->enabled = 1;
4932 return;
4935 p = optarg;
4936 while (*p) {
4937 e = strchr (p, ',');
4938 l = !e ? strlen (p) : (size_t) (e - p);
4940 for (c = soundhw; c->name; ++c) {
4941 if (!strncmp (c->name, p, l)) {
4942 c->enabled = 1;
4943 break;
4947 if (!c->name) {
4948 if (l > 80) {
4949 fprintf (stderr,
4950 "Unknown sound card name (too big to show)\n");
4952 else {
4953 fprintf (stderr, "Unknown sound card name `%.*s'\n",
4954 (int) l, p);
4956 bad_card = 1;
4958 p += l + (e != NULL);
4961 if (bad_card)
4962 goto show_valid_cards;
4965 #endif
4967 #define MAX_NET_CLIENTS 32
4969 int main(int argc, char **argv)
4971 #ifdef CONFIG_GDBSTUB
4972 int use_gdbstub, gdbstub_port;
4973 #endif
4974 int i, cdrom_index;
4975 int snapshot, linux_boot;
4976 const char *initrd_filename;
4977 const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
4978 const char *kernel_filename, *kernel_cmdline;
4979 DisplayState *ds = &display_state;
4980 int cyls, heads, secs, translation;
4981 int start_emulation = 1;
4982 char net_clients[MAX_NET_CLIENTS][256];
4983 int nb_net_clients;
4984 int optind;
4985 const char *r, *optarg;
4986 CharDriverState *monitor_hd;
4987 char monitor_device[128];
4988 char serial_devices[MAX_SERIAL_PORTS][128];
4989 int serial_device_index;
4990 char parallel_devices[MAX_PARALLEL_PORTS][128];
4991 int parallel_device_index;
4992 const char *loadvm = NULL;
4993 QEMUMachine *machine;
4994 char usb_devices[MAX_VM_USB_PORTS][128];
4995 int usb_devices_index;
4997 LIST_INIT (&vm_change_state_head);
4998 #if !defined(CONFIG_SOFTMMU)
4999 /* we never want that malloc() uses mmap() */
5000 mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
5001 #endif
5002 register_machines();
5003 machine = first_machine;
5004 initrd_filename = NULL;
5005 for(i = 0; i < MAX_FD; i++)
5006 fd_filename[i] = NULL;
5007 for(i = 0; i < MAX_DISKS; i++)
5008 hd_filename[i] = NULL;
5009 ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
5010 vga_ram_size = VGA_RAM_SIZE;
5011 bios_size = BIOS_SIZE;
5012 #ifdef CONFIG_GDBSTUB
5013 use_gdbstub = 0;
5014 gdbstub_port = DEFAULT_GDBSTUB_PORT;
5015 #endif
5016 snapshot = 0;
5017 nographic = 0;
5018 kernel_filename = NULL;
5019 kernel_cmdline = "";
5020 #ifdef TARGET_PPC
5021 cdrom_index = 1;
5022 #else
5023 cdrom_index = 2;
5024 #endif
5025 cyls = heads = secs = 0;
5026 translation = BIOS_ATA_TRANSLATION_AUTO;
5027 pstrcpy(monitor_device, sizeof(monitor_device), "vc");
5029 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
5030 for(i = 1; i < MAX_SERIAL_PORTS; i++)
5031 serial_devices[i][0] = '\0';
5032 serial_device_index = 0;
5034 pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
5035 for(i = 1; i < MAX_PARALLEL_PORTS; i++)
5036 parallel_devices[i][0] = '\0';
5037 parallel_device_index = 0;
5039 usb_devices_index = 0;
5041 nb_net_clients = 0;
5043 nb_nics = 0;
5044 /* default mac address of the first network interface */
5046 optind = 1;
5047 for(;;) {
5048 if (optind >= argc)
5049 break;
5050 r = argv[optind];
5051 if (r[0] != '-') {
5052 hd_filename[0] = argv[optind++];
5053 } else {
5054 const QEMUOption *popt;
5056 optind++;
5057 popt = qemu_options;
5058 for(;;) {
5059 if (!popt->name) {
5060 fprintf(stderr, "%s: invalid option -- '%s'\n",
5061 argv[0], r);
5062 exit(1);
5064 if (!strcmp(popt->name, r + 1))
5065 break;
5066 popt++;
5068 if (popt->flags & HAS_ARG) {
5069 if (optind >= argc) {
5070 fprintf(stderr, "%s: option '%s' requires an argument\n",
5071 argv[0], r);
5072 exit(1);
5074 optarg = argv[optind++];
5075 } else {
5076 optarg = NULL;
5079 switch(popt->index) {
5080 case QEMU_OPTION_M:
5081 machine = find_machine(optarg);
5082 if (!machine) {
5083 QEMUMachine *m;
5084 printf("Supported machines are:\n");
5085 for(m = first_machine; m != NULL; m = m->next) {
5086 printf("%-10s %s%s\n",
5087 m->name, m->desc,
5088 m == first_machine ? " (default)" : "");
5090 exit(1);
5092 break;
5093 case QEMU_OPTION_initrd:
5094 initrd_filename = optarg;
5095 break;
5096 case QEMU_OPTION_hda:
5097 case QEMU_OPTION_hdb:
5098 case QEMU_OPTION_hdc:
5099 case QEMU_OPTION_hdd:
5101 int hd_index;
5102 hd_index = popt->index - QEMU_OPTION_hda;
5103 hd_filename[hd_index] = optarg;
5104 if (hd_index == cdrom_index)
5105 cdrom_index = -1;
5107 break;
5108 case QEMU_OPTION_snapshot:
5109 snapshot = 1;
5110 break;
5111 case QEMU_OPTION_hdachs:
5113 const char *p;
5114 p = optarg;
5115 cyls = strtol(p, (char **)&p, 0);
5116 if (cyls < 1 || cyls > 16383)
5117 goto chs_fail;
5118 if (*p != ',')
5119 goto chs_fail;
5120 p++;
5121 heads = strtol(p, (char **)&p, 0);
5122 if (heads < 1 || heads > 16)
5123 goto chs_fail;
5124 if (*p != ',')
5125 goto chs_fail;
5126 p++;
5127 secs = strtol(p, (char **)&p, 0);
5128 if (secs < 1 || secs > 63)
5129 goto chs_fail;
5130 if (*p == ',') {
5131 p++;
5132 if (!strcmp(p, "none"))
5133 translation = BIOS_ATA_TRANSLATION_NONE;
5134 else if (!strcmp(p, "lba"))
5135 translation = BIOS_ATA_TRANSLATION_LBA;
5136 else if (!strcmp(p, "auto"))
5137 translation = BIOS_ATA_TRANSLATION_AUTO;
5138 else
5139 goto chs_fail;
5140 } else if (*p != '\0') {
5141 chs_fail:
5142 fprintf(stderr, "qemu: invalid physical CHS format\n");
5143 exit(1);
5146 break;
5147 case QEMU_OPTION_nographic:
5148 pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
5149 pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
5150 nographic = 1;
5151 break;
5152 case QEMU_OPTION_kernel:
5153 kernel_filename = optarg;
5154 break;
5155 case QEMU_OPTION_append:
5156 kernel_cmdline = optarg;
5157 break;
5158 case QEMU_OPTION_cdrom:
5159 if (cdrom_index >= 0) {
5160 hd_filename[cdrom_index] = optarg;
5162 break;
5163 case QEMU_OPTION_boot:
5164 boot_device = optarg[0];
5165 if (boot_device != 'a' &&
5166 #ifdef TARGET_SPARC
5167 // Network boot
5168 boot_device != 'n' &&
5169 #endif
5170 boot_device != 'c' && boot_device != 'd') {
5171 fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
5172 exit(1);
5174 break;
5175 case QEMU_OPTION_fda:
5176 fd_filename[0] = optarg;
5177 break;
5178 case QEMU_OPTION_fdb:
5179 fd_filename[1] = optarg;
5180 break;
5181 case QEMU_OPTION_no_code_copy:
5182 code_copy_enabled = 0;
5183 break;
5184 case QEMU_OPTION_net:
5185 if (nb_net_clients >= MAX_NET_CLIENTS) {
5186 fprintf(stderr, "qemu: too many network clients\n");
5187 exit(1);
5189 pstrcpy(net_clients[nb_net_clients],
5190 sizeof(net_clients[0]),
5191 optarg);
5192 nb_net_clients++;
5193 break;
5194 #ifdef CONFIG_SLIRP
5195 case QEMU_OPTION_tftp:
5196 tftp_prefix = optarg;
5197 break;
5198 #ifndef _WIN32
5199 case QEMU_OPTION_smb:
5200 net_slirp_smb(optarg);
5201 break;
5202 #endif
5203 case QEMU_OPTION_redir:
5204 net_slirp_redir(optarg);
5205 break;
5206 #endif
5207 #ifdef HAS_AUDIO
5208 case QEMU_OPTION_audio_help:
5209 AUD_help ();
5210 exit (0);
5211 break;
5212 case QEMU_OPTION_soundhw:
5213 select_soundhw (optarg);
5214 break;
5215 #endif
5216 case QEMU_OPTION_h:
5217 help();
5218 break;
5219 case QEMU_OPTION_m:
5220 ram_size = atoi(optarg) * 1024 * 1024;
5221 if (ram_size <= 0)
5222 help();
5223 if (ram_size > PHYS_RAM_MAX_SIZE) {
5224 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
5225 PHYS_RAM_MAX_SIZE / (1024 * 1024));
5226 exit(1);
5228 break;
5229 case QEMU_OPTION_d:
5231 int mask;
5232 CPULogItem *item;
5234 mask = cpu_str_to_log_mask(optarg);
5235 if (!mask) {
5236 printf("Log items (comma separated):\n");
5237 for(item = cpu_log_items; item->mask != 0; item++) {
5238 printf("%-10s %s\n", item->name, item->help);
5240 exit(1);
5242 cpu_set_log(mask);
5244 break;
5245 #ifdef CONFIG_GDBSTUB
5246 case QEMU_OPTION_s:
5247 use_gdbstub = 1;
5248 break;
5249 case QEMU_OPTION_p:
5250 gdbstub_port = atoi(optarg);
5251 break;
5252 #endif
5253 case QEMU_OPTION_L:
5254 bios_dir = optarg;
5255 break;
5256 case QEMU_OPTION_S:
5257 start_emulation = 0;
5258 break;
5259 case QEMU_OPTION_k:
5260 keyboard_layout = optarg;
5261 break;
5262 case QEMU_OPTION_localtime:
5263 rtc_utc = 0;
5264 break;
5265 case QEMU_OPTION_cirrusvga:
5266 cirrus_vga_enabled = 1;
5267 break;
5268 case QEMU_OPTION_std_vga:
5269 cirrus_vga_enabled = 0;
5270 break;
5271 case QEMU_OPTION_g:
5273 const char *p;
5274 int w, h, depth;
5275 p = optarg;
5276 w = strtol(p, (char **)&p, 10);
5277 if (w <= 0) {
5278 graphic_error:
5279 fprintf(stderr, "qemu: invalid resolution or depth\n");
5280 exit(1);
5282 if (*p != 'x')
5283 goto graphic_error;
5284 p++;
5285 h = strtol(p, (char **)&p, 10);
5286 if (h <= 0)
5287 goto graphic_error;
5288 if (*p == 'x') {
5289 p++;
5290 depth = strtol(p, (char **)&p, 10);
5291 if (depth != 8 && depth != 15 && depth != 16 &&
5292 depth != 24 && depth != 32)
5293 goto graphic_error;
5294 } else if (*p == '\0') {
5295 depth = graphic_depth;
5296 } else {
5297 goto graphic_error;
5300 graphic_width = w;
5301 graphic_height = h;
5302 graphic_depth = depth;
5304 break;
5305 case QEMU_OPTION_monitor:
5306 pstrcpy(monitor_device, sizeof(monitor_device), optarg);
5307 break;
5308 case QEMU_OPTION_serial:
5309 if (serial_device_index >= MAX_SERIAL_PORTS) {
5310 fprintf(stderr, "qemu: too many serial ports\n");
5311 exit(1);
5313 pstrcpy(serial_devices[serial_device_index],
5314 sizeof(serial_devices[0]), optarg);
5315 serial_device_index++;
5316 break;
5317 case QEMU_OPTION_parallel:
5318 if (parallel_device_index >= MAX_PARALLEL_PORTS) {
5319 fprintf(stderr, "qemu: too many parallel ports\n");
5320 exit(1);
5322 pstrcpy(parallel_devices[parallel_device_index],
5323 sizeof(parallel_devices[0]), optarg);
5324 parallel_device_index++;
5325 break;
5326 case QEMU_OPTION_loadvm:
5327 loadvm = optarg;
5328 break;
5329 case QEMU_OPTION_full_screen:
5330 full_screen = 1;
5331 break;
5332 case QEMU_OPTION_pidfile:
5333 create_pidfile(optarg);
5334 break;
5335 #ifdef TARGET_I386
5336 case QEMU_OPTION_win2k_hack:
5337 win2k_install_hack = 1;
5338 break;
5339 #endif
5340 #ifdef USE_KQEMU
5341 case QEMU_OPTION_no_kqemu:
5342 kqemu_allowed = 0;
5343 break;
5344 case QEMU_OPTION_kernel_kqemu:
5345 kqemu_allowed = 2;
5346 break;
5347 #endif
5348 case QEMU_OPTION_usb:
5349 usb_enabled = 1;
5350 break;
5351 case QEMU_OPTION_usbdevice:
5352 usb_enabled = 1;
5353 if (usb_devices_index >= MAX_VM_USB_PORTS) {
5354 fprintf(stderr, "Too many USB devices\n");
5355 exit(1);
5357 pstrcpy(usb_devices[usb_devices_index],
5358 sizeof(usb_devices[usb_devices_index]),
5359 optarg);
5360 usb_devices_index++;
5361 break;
5362 case QEMU_OPTION_smp:
5363 smp_cpus = atoi(optarg);
5364 if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
5365 fprintf(stderr, "Invalid number of CPUs\n");
5366 exit(1);
5368 break;
5373 #ifdef USE_KQEMU
5374 if (smp_cpus > 1)
5375 kqemu_allowed = 0;
5376 #endif
5377 linux_boot = (kernel_filename != NULL);
5379 if (!linux_boot &&
5380 hd_filename[0] == '\0' &&
5381 (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
5382 fd_filename[0] == '\0')
5383 help();
5385 /* boot to cd by default if no hard disk */
5386 if (hd_filename[0] == '\0' && boot_device == 'c') {
5387 if (fd_filename[0] != '\0')
5388 boot_device = 'a';
5389 else
5390 boot_device = 'd';
5393 #if !defined(CONFIG_SOFTMMU)
5394 /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
5396 static uint8_t stdout_buf[4096];
5397 setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
5399 #else
5400 setvbuf(stdout, NULL, _IOLBF, 0);
5401 #endif
5403 #ifdef _WIN32
5404 socket_init();
5405 #endif
5407 /* init network clients */
5408 if (nb_net_clients == 0) {
5409 /* if no clients, we use a default config */
5410 pstrcpy(net_clients[0], sizeof(net_clients[0]),
5411 "nic");
5412 pstrcpy(net_clients[1], sizeof(net_clients[0]),
5413 "user");
5414 nb_net_clients = 2;
5417 for(i = 0;i < nb_net_clients; i++) {
5418 if (net_client_init(net_clients[i]) < 0)
5419 exit(1);
5422 /* init the memory */
5423 phys_ram_size = ram_size + vga_ram_size + bios_size;
5425 #ifdef CONFIG_SOFTMMU
5426 phys_ram_base = qemu_vmalloc(phys_ram_size);
5427 if (!phys_ram_base) {
5428 fprintf(stderr, "Could not allocate physical memory\n");
5429 exit(1);
5431 #else
5432 /* as we must map the same page at several addresses, we must use
5433 a fd */
5435 const char *tmpdir;
5437 tmpdir = getenv("QEMU_TMPDIR");
5438 if (!tmpdir)
5439 tmpdir = "/tmp";
5440 snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
5441 if (mkstemp(phys_ram_file) < 0) {
5442 fprintf(stderr, "Could not create temporary memory file '%s'\n",
5443 phys_ram_file);
5444 exit(1);
5446 phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
5447 if (phys_ram_fd < 0) {
5448 fprintf(stderr, "Could not open temporary memory file '%s'\n",
5449 phys_ram_file);
5450 exit(1);
5452 ftruncate(phys_ram_fd, phys_ram_size);
5453 unlink(phys_ram_file);
5454 phys_ram_base = mmap(get_mmap_addr(phys_ram_size),
5455 phys_ram_size,
5456 PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED,
5457 phys_ram_fd, 0);
5458 if (phys_ram_base == MAP_FAILED) {
5459 fprintf(stderr, "Could not map physical memory\n");
5460 exit(1);
5463 #endif
5465 /* we always create the cdrom drive, even if no disk is there */
5466 bdrv_init();
5467 if (cdrom_index >= 0) {
5468 bs_table[cdrom_index] = bdrv_new("cdrom");
5469 bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
5472 /* open the virtual block devices */
5473 for(i = 0; i < MAX_DISKS; i++) {
5474 if (hd_filename[i]) {
5475 if (!bs_table[i]) {
5476 char buf[64];
5477 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
5478 bs_table[i] = bdrv_new(buf);
5480 if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
5481 fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
5482 hd_filename[i]);
5483 exit(1);
5485 if (i == 0 && cyls != 0) {
5486 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
5487 bdrv_set_translation_hint(bs_table[i], translation);
5492 /* we always create at least one floppy disk */
5493 fd_table[0] = bdrv_new("fda");
5494 bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
5496 for(i = 0; i < MAX_FD; i++) {
5497 if (fd_filename[i]) {
5498 if (!fd_table[i]) {
5499 char buf[64];
5500 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
5501 fd_table[i] = bdrv_new(buf);
5502 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
5504 if (fd_filename[i] != '\0') {
5505 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
5506 fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
5507 fd_filename[i]);
5508 exit(1);
5514 /* init USB devices */
5515 if (usb_enabled) {
5516 vm_usb_hub = usb_hub_init(vm_usb_ports, MAX_VM_USB_PORTS);
5517 for(i = 0; i < usb_devices_index; i++) {
5518 if (usb_device_add(usb_devices[i]) < 0) {
5519 fprintf(stderr, "Warning: could not add USB device %s\n",
5520 usb_devices[i]);
5525 register_savevm("timer", 0, 1, timer_save, timer_load, NULL);
5526 register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
5528 init_ioports();
5529 cpu_calibrate_ticks();
5531 /* terminal init */
5532 if (nographic) {
5533 dumb_display_init(ds);
5534 } else {
5535 #if defined(CONFIG_SDL)
5536 sdl_display_init(ds, full_screen);
5537 #elif defined(CONFIG_COCOA)
5538 cocoa_display_init(ds, full_screen);
5539 #else
5540 dumb_display_init(ds);
5541 #endif
5544 monitor_hd = qemu_chr_open(monitor_device);
5545 if (!monitor_hd) {
5546 fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
5547 exit(1);
5549 monitor_init(monitor_hd, !nographic);
5551 for(i = 0; i < MAX_SERIAL_PORTS; i++) {
5552 if (serial_devices[i][0] != '\0') {
5553 serial_hds[i] = qemu_chr_open(serial_devices[i]);
5554 if (!serial_hds[i]) {
5555 fprintf(stderr, "qemu: could not open serial device '%s'\n",
5556 serial_devices[i]);
5557 exit(1);
5559 if (!strcmp(serial_devices[i], "vc"))
5560 qemu_chr_printf(serial_hds[i], "serial%d console\n", i);
5564 for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
5565 if (parallel_devices[i][0] != '\0') {
5566 parallel_hds[i] = qemu_chr_open(parallel_devices[i]);
5567 if (!parallel_hds[i]) {
5568 fprintf(stderr, "qemu: could not open parallel device '%s'\n",
5569 parallel_devices[i]);
5570 exit(1);
5572 if (!strcmp(parallel_devices[i], "vc"))
5573 qemu_chr_printf(parallel_hds[i], "parallel%d console\n", i);
5577 /* setup cpu signal handlers for MMU / self modifying code handling */
5578 #if !defined(CONFIG_SOFTMMU)
5580 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5582 stack_t stk;
5583 signal_stack = memalign(16, SIGNAL_STACK_SIZE);
5584 stk.ss_sp = signal_stack;
5585 stk.ss_size = SIGNAL_STACK_SIZE;
5586 stk.ss_flags = 0;
5588 if (sigaltstack(&stk, NULL) < 0) {
5589 perror("sigaltstack");
5590 exit(1);
5593 #endif
5595 struct sigaction act;
5597 sigfillset(&act.sa_mask);
5598 act.sa_flags = SA_SIGINFO;
5599 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5600 act.sa_flags |= SA_ONSTACK;
5601 #endif
5602 act.sa_sigaction = host_segv_handler;
5603 sigaction(SIGSEGV, &act, NULL);
5604 sigaction(SIGBUS, &act, NULL);
5605 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
5606 sigaction(SIGFPE, &act, NULL);
5607 #endif
5609 #endif
5611 #ifndef _WIN32
5613 struct sigaction act;
5614 sigfillset(&act.sa_mask);
5615 act.sa_flags = 0;
5616 act.sa_handler = SIG_IGN;
5617 sigaction(SIGPIPE, &act, NULL);
5619 #endif
5620 init_timers();
5622 machine->init(ram_size, vga_ram_size, boot_device,
5623 ds, fd_filename, snapshot,
5624 kernel_filename, kernel_cmdline, initrd_filename);
5626 gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
5627 qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
5629 #ifdef CONFIG_GDBSTUB
5630 if (use_gdbstub) {
5631 if (gdbserver_start(gdbstub_port) < 0) {
5632 fprintf(stderr, "Could not open gdbserver socket on port %d\n",
5633 gdbstub_port);
5634 exit(1);
5635 } else {
5636 printf("Waiting gdb connection on port %d\n", gdbstub_port);
5638 } else
5639 #endif
5640 if (loadvm)
5641 qemu_loadvm(loadvm);
5644 /* XXX: simplify init */
5645 read_passwords();
5646 if (start_emulation) {
5647 vm_start();
5650 main_loop();
5651 quit_timers();
5652 return 0;