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